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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1395  ! raeburn     4: # $Id: loncommon.pm,v 1.1394 2022/10/29 17:44:05 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.1383    raeburn    64: use Apache::lonnavmaps();
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.1395  ! raeburn    75: use LONCAPA::map();
1.1328    raeburn    76: use HTTP::Request;
1.657     raeburn    77: use DateTime::TimeZone;
1.1241    raeburn    78: use DateTime::Locale;
1.1220    raeburn    79: use Encode();
1.1091    foxr       80: use Text::Aspell;
1.1094    raeburn    81: use Authen::Captcha;
                     82: use Captcha::reCAPTCHA;
1.1234    raeburn    83: use JSON::DWIW;
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.1337    raeburn   439:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
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.1337    raeburn   454:         if (courseadv == 'condition') {
                    455:             if (document.getElementById('courseadv')) {
                    456:                 courseadv = document.getElementById('courseadv').value;
                    457:             }
                    458:         }
                    459:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       460:         var title = 'Student_Browser';
1.74      www       461:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    462:         options += ',width=700,height=600';
                    463:         stdeditbrowser = open(url,title,options,'1');
                    464:         stdeditbrowser.focus();
                    465:     }
1.824     bisitz    466: // ]]>
1.74      www       467: </script>
                    468: ENDSTDBRW
                    469: }
1.42      matthew   470: 
1.1003    www       471: sub resourcebrowser_javascript {
                    472:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       473:    return (<<'ENDRESBRW');
1.1003    www       474: <script type="text/javascript" language="Javascript">
                    475: // <![CDATA[
                    476:     var reseditbrowser;
1.1004    www       477:     function openresbrowser(formname,reslink) {
1.1005    www       478:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       479:         var title = 'Resource_Browser';
                    480:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       481:         options += ',width=700,height=500';
1.1004    www       482:         reseditbrowser = open(url,title,options,'1');
                    483:         reseditbrowser.focus();
1.1003    www       484:     }
                    485: // ]]>
                    486: </script>
1.1004    www       487: ENDRESBRW
1.1003    www       488: }
                    489: 
1.74      www       490: sub selectstudent_link {
1.1337    raeburn   491:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       492:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    493:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    494:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  495:    if ($env{'request.course.id'}) {  
1.302     albertel  496:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    497: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    498: 					'/'.$env{'request.course.sec'})) {
1.111     www       499: 	   return '';
                    500:        }
1.999     www       501:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   502:        if ($courseadv eq 'only') {
                    503:            $callargs .= ",'',1,'$courseadv'";
                    504:        } elsif ($courseadv eq 'none') {
                    505:            $callargs .= ",'','','$courseadv'";
                    506:        } elsif ($courseadv eq 'condition') {
                    507:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   508:        }
                    509:        return '<span class="LC_nobreak">'.
                    510:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    511:               &mt('Select User').'</a></span>';
1.74      www       512:    }
1.258     albertel  513:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       514:        $callargs .= ",'',1"; 
1.793     raeburn   515:        return '<span class="LC_nobreak">'.
                    516:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    517:               &mt('Select User').'</a></span>';
1.111     www       518:    }
                    519:    return '';
1.91      www       520: }
                    521: 
1.1004    www       522: sub selectresource_link {
                    523:    my ($form,$reslink,$arg)=@_;
                    524:    
                    525:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    526:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    527:    unless ($env{'request.course.id'}) { return $arg; }
                    528:    return '<span class="LC_nobreak">'.
                    529:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    530:               $arg.'</a></span>';
                    531: }
                    532: 
                    533: 
                    534: 
1.653     raeburn   535: sub authorbrowser_javascript {
                    536:     return <<"ENDAUTHORBRW";
1.776     bisitz    537: <script type="text/javascript" language="JavaScript">
1.824     bisitz    538: // <![CDATA[
1.653     raeburn   539: var stdeditbrowser;
                    540: 
                    541: function openauthorbrowser(formname,udom) {
                    542:     var url = '/adm/pickauthor?';
                    543:     url += 'form='+formname+'&roledom='+udom;
                    544:     var title = 'Author_Browser';
                    545:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    546:     options += ',width=700,height=600';
                    547:     stdeditbrowser = open(url,title,options,'1');
                    548:     stdeditbrowser.focus();
                    549: }
                    550: 
1.824     bisitz    551: // ]]>
1.653     raeburn   552: </script>
                    553: ENDAUTHORBRW
                    554: }
                    555: 
1.91      www       556: sub coursebrowser_javascript {
1.1116    raeburn   557:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   558:         $credits_element,$instcode) = @_;
1.932     raeburn   559:     my $wintitle = 'Course_Browser';
1.931     raeburn   560:     if ($crstype eq 'Community') {
1.932     raeburn   561:         $wintitle = 'Community_Browser';
1.909     raeburn   562:     }
1.876     raeburn   563:     my $id_functions = &javascript_index_functions();
                    564:     my $output = '
1.776     bisitz    565: <script type="text/javascript" language="JavaScript">
1.824     bisitz    566: // <![CDATA[
1.468     raeburn   567:     var stdeditbrowser;'."\n";
1.876     raeburn   568: 
                    569:     $output .= <<"ENDSTDBRW";
1.909     raeburn   570:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       571:         var url = '/adm/pickcourse?';
1.895     raeburn   572:         var formid = getFormIdByName(formname);
1.876     raeburn   573:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  574:         if (domainfilter != null) {
                    575:            if (domainfilter != '') {
                    576:                url += 'domainfilter='+domainfilter+'&';
                    577: 	   }
                    578:         }
1.91      www       579:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  580: 	                            '&cdomelement='+udom+
                    581:                                     '&cnameelement='+desc;
1.468     raeburn   582:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   583:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   584:                 url += '&roleelement='+extra_element;
                    585:                 if (domainfilter == null || domainfilter == '') {
                    586:                     url += '&domainfilter='+extra_element;
                    587:                 }
1.234     raeburn   588:             }
1.468     raeburn   589:             else {
                    590:                 if (formname == 'portform') {
                    591:                     url += '&setroles='+extra_element;
1.800     raeburn   592:                 } else {
                    593:                     if (formname == 'rules') {
                    594:                         url += '&fixeddom='+extra_element; 
                    595:                     }
1.468     raeburn   596:                 }
                    597:             }     
1.230     raeburn   598:         }
1.909     raeburn   599:         if (type != null && type != '') {
                    600:             url += '&type='+type;
                    601:         }
                    602:         if (type_elem != null && type_elem != '') {
                    603:             url += '&typeelement='+type_elem;
                    604:         }
1.872     raeburn   605:         if (formname == 'ccrs') {
                    606:             var ownername = document.forms[formid].ccuname.value;
                    607:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   608:             url += '&cloner='+ownername+':'+ownerdom;
                    609:             if (type == 'Course') {
                    610:                 url += '&crscode='+document.forms[formid].crscode.value;
                    611:             }
1.1221    raeburn   612:         }
                    613:         if (formname == 'requestcrs') {
                    614:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   615:         }
1.293     raeburn   616:         if (multflag !=null && multflag != '') {
                    617:             url += '&multiple='+multflag;
                    618:         }
1.909     raeburn   619:         var title = '$wintitle';
1.91      www       620:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    621:         options += ',width=700,height=600';
                    622:         stdeditbrowser = open(url,title,options,'1');
                    623:         stdeditbrowser.focus();
                    624:     }
1.876     raeburn   625: $id_functions
                    626: ENDSTDBRW
1.1116    raeburn   627:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    628:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    629:                                       $credits_element);
1.876     raeburn   630:     }
                    631:     $output .= '
                    632: // ]]>
                    633: </script>';
                    634:     return $output;
                    635: }
                    636: 
                    637: sub javascript_index_functions {
                    638:     return <<"ENDJS";
                    639: 
                    640: function getFormIdByName(formname) {
                    641:     for (var i=0;i<document.forms.length;i++) {
                    642:         if (document.forms[i].name == formname) {
                    643:             return i;
                    644:         }
                    645:     }
                    646:     return -1;
                    647: }
                    648: 
                    649: function getIndexByName(formid,item) {
                    650:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    651:         if (document.forms[formid].elements[i].name == item) {
                    652:             return i;
                    653:         }
                    654:     }
                    655:     return -1;
                    656: }
1.468     raeburn   657: 
1.876     raeburn   658: function getDomainFromSelectbox(formname,udom) {
                    659:     var userdom;
                    660:     var formid = getFormIdByName(formname);
                    661:     if (formid > -1) {
                    662:         var domid = getIndexByName(formid,udom);
                    663:         if (domid > -1) {
                    664:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    665:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    666:             }
                    667:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    668:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   669:             }
                    670:         }
                    671:     }
1.876     raeburn   672:     return userdom;
                    673: }
                    674: 
                    675: ENDJS
1.468     raeburn   676: 
1.876     raeburn   677: }
                    678: 
1.1017    raeburn   679: sub javascript_array_indexof {
1.1018    raeburn   680:     return <<ENDJS;
1.1017    raeburn   681: <script type="text/javascript" language="JavaScript">
                    682: // <![CDATA[
                    683: 
                    684: if (!Array.prototype.indexOf) {
                    685:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    686:         "use strict";
                    687:         if (this === void 0 || this === null) {
                    688:             throw new TypeError();
                    689:         }
                    690:         var t = Object(this);
                    691:         var len = t.length >>> 0;
                    692:         if (len === 0) {
                    693:             return -1;
                    694:         }
                    695:         var n = 0;
                    696:         if (arguments.length > 0) {
                    697:             n = Number(arguments[1]);
1.1088    foxr      698:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   699:                 n = 0;
                    700:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    701:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    702:             }
                    703:         }
                    704:         if (n >= len) {
                    705:             return -1;
                    706:         }
                    707:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    708:         for (; k < len; k++) {
                    709:             if (k in t && t[k] === searchElement) {
                    710:                 return k;
                    711:             }
                    712:         }
                    713:         return -1;
                    714:     }
                    715: }
                    716: 
                    717: // ]]>
                    718: </script>
                    719: 
                    720: ENDJS
                    721: 
                    722: }
                    723: 
1.876     raeburn   724: sub userbrowser_javascript {
                    725:     my $id_functions = &javascript_index_functions();
                    726:     return <<"ENDUSERBRW";
                    727: 
1.888     raeburn   728: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   729:     var url = '/adm/pickuser?';
                    730:     var userdom = getDomainFromSelectbox(formname,udom);
                    731:     if (userdom != null) {
                    732:        if (userdom != '') {
                    733:            url += 'srchdom='+userdom+'&';
                    734:        }
                    735:     }
                    736:     url += 'form=' + formname + '&unameelement='+uname+
                    737:                                 '&udomelement='+udom+
                    738:                                 '&ulastelement='+ulast+
                    739:                                 '&ufirstelement='+ufirst+
                    740:                                 '&uemailelement='+uemail+
1.881     raeburn   741:                                 '&hideudomelement='+hideudom+
                    742:                                 '&coursedom='+crsdom;
1.888     raeburn   743:     if ((caller != null) && (caller != undefined)) {
                    744:         url += '&caller='+caller;
                    745:     }
1.876     raeburn   746:     var title = 'User_Browser';
                    747:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    748:     options += ',width=700,height=600';
                    749:     var stdeditbrowser = open(url,title,options,'1');
                    750:     stdeditbrowser.focus();
                    751: }
                    752: 
1.888     raeburn   753: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   754:     var formid = getFormIdByName(formname);
                    755:     if (formid > -1) {
1.888     raeburn   756:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   757:         var domid = getIndexByName(formid,udom);
                    758:         var hidedomid = getIndexByName(formid,origdom);
                    759:         if (hidedomid > -1) {
                    760:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   761:             var unameval = document.forms[formid].elements[unameid].value;
                    762:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    763:                 if (domid > -1) {
                    764:                     var slct = document.forms[formid].elements[domid];
                    765:                     if (slct.type == 'select-one') {
                    766:                         var i;
                    767:                         for (i=0;i<slct.length;i++) {
                    768:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    769:                         }
                    770:                     }
                    771:                     if (slct.type == 'hidden') {
                    772:                         slct.value = fixeddom;
1.876     raeburn   773:                     }
                    774:                 }
1.468     raeburn   775:             }
                    776:         }
                    777:     }
1.876     raeburn   778:     return;
                    779: }
                    780: 
                    781: $id_functions
                    782: ENDUSERBRW
1.468     raeburn   783: }
                    784: 
                    785: sub setsec_javascript {
1.1116    raeburn   786:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   787:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    788:         $communityrolestr);
                    789:     if ($role_element ne '') {
                    790:         my @allroles = ('st','ta','ep','in','ad');
                    791:         foreach my $crstype ('Course','Community') {
                    792:             if ($crstype eq 'Community') {
                    793:                 foreach my $role (@allroles) {
                    794:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    795:                 }
                    796:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    797:             } else {
                    798:                 foreach my $role (@allroles) {
                    799:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    800:                 }
                    801:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    802:             }
                    803:         }
                    804:         $rolestr = '"'.join('","',@allroles).'"';
                    805:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    806:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    807:     }
1.468     raeburn   808:     my $setsections = qq|
                    809: function setSect(sectionlist) {
1.629     raeburn   810:     var sectionsArray = new Array();
                    811:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    812:         sectionsArray = sectionlist.split(",");
                    813:     }
1.468     raeburn   814:     var numSections = sectionsArray.length;
                    815:     document.$formname.$sec_element.length = 0;
                    816:     if (numSections == 0) {
                    817:         document.$formname.$sec_element.multiple=false;
                    818:         document.$formname.$sec_element.size=1;
                    819:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    820:     } else {
                    821:         if (numSections == 1) {
                    822:             document.$formname.$sec_element.multiple=false;
                    823:             document.$formname.$sec_element.size=1;
                    824:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    825:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    826:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    827:         } else {
                    828:             for (var i=0; i<numSections; i++) {
                    829:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    830:             }
                    831:             document.$formname.$sec_element.multiple=true
                    832:             if (numSections < 3) {
                    833:                 document.$formname.$sec_element.size=numSections;
                    834:             } else {
                    835:                 document.$formname.$sec_element.size=3;
                    836:             }
                    837:             document.$formname.$sec_element.options[0].selected = false
                    838:         }
                    839:     }
1.91      www       840: }
1.905     raeburn   841: 
                    842: function setRole(crstype) {
1.468     raeburn   843: |;
1.905     raeburn   844:     if ($role_element eq '') {
                    845:         $setsections .= '    return;
                    846: }
                    847: ';
                    848:     } else {
                    849:         $setsections .= qq|
                    850:     var elementLength = document.$formname.$role_element.length;
                    851:     var allroles = Array($rolestr);
                    852:     var courserolenames = Array($courserolestr);
                    853:     var communityrolenames = Array($communityrolestr);
                    854:     if (elementLength != undefined) {
                    855:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    856:             if (crstype == 'Course') {
                    857:                 return;
                    858:             } else {
                    859:                 allroles[5] = 'co';
                    860:                 for (var i=0; i<6; i++) {
                    861:                     document.$formname.$role_element.options[i].value = allroles[i];
                    862:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    863:                 }
                    864:             }
                    865:         } else {
                    866:             if (crstype == 'Community') {
                    867:                 return;
                    868:             } else {
                    869:                 allroles[5] = 'cc';
                    870:                 for (var i=0; i<6; i++) {
                    871:                     document.$formname.$role_element.options[i].value = allroles[i];
                    872:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    873:                 }
                    874:             }
                    875:         }
                    876:     }
                    877:     return;
                    878: }
                    879: |;
                    880:     }
1.1116    raeburn   881:     if ($credits_element) {
                    882:         $setsections .= qq|
                    883: function setCredits(defaultcredits) {
                    884:     document.$formname.$credits_element.value = defaultcredits;
                    885:     return;
                    886: }
                    887: |;
                    888:     }
1.468     raeburn   889:     return $setsections;
                    890: }
                    891: 
1.91      www       892: sub selectcourse_link {
1.909     raeburn   893:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    894:        $typeelement) = @_;
                    895:    my $type = $selecttype;
1.871     raeburn   896:    my $linktext = &mt('Select Course');
                    897:    if ($selecttype eq 'Community') {
1.909     raeburn   898:        $linktext = &mt('Select Community');
1.1239    raeburn   899:    } elsif ($selecttype eq 'Placement') {
                    900:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   901:    } elsif ($selecttype eq 'Course/Community') {
                    902:        $linktext = &mt('Select Course/Community');
1.909     raeburn   903:        $type = '';
1.1019    raeburn   904:    } elsif ($selecttype eq 'Select') {
                    905:        $linktext = &mt('Select');
                    906:        $type = '';
1.871     raeburn   907:    }
1.787     bisitz    908:    return '<span class="LC_nobreak">'
                    909:          ."<a href='"
                    910:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    911:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   912:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   913:          ."'>".$linktext.'</a>'
1.787     bisitz    914:          .'</span>';
1.74      www       915: }
1.42      matthew   916: 
1.653     raeburn   917: sub selectauthor_link {
                    918:    my ($form,$udom)=@_;
                    919:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    920:           &mt('Select Author').'</a>';
                    921: }
                    922: 
1.876     raeburn   923: sub selectuser_link {
1.881     raeburn   924:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   925:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   926:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   927:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   928:            ');">'.$linktext.'</a>';
1.876     raeburn   929: }
                    930: 
1.273     raeburn   931: sub check_uncheck_jscript {
                    932:     my $jscript = <<"ENDSCRT";
                    933: function checkAll(field) {
                    934:     if (field.length > 0) {
                    935:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   936:             if (!field[i].disabled) { 
                    937:                 field[i].checked = true;
                    938:             }
1.273     raeburn   939:         }
                    940:     } else {
1.1093    raeburn   941:         if (!field.disabled) { 
                    942:             field.checked = true;
                    943:         }
1.273     raeburn   944:     }
                    945: }
                    946:  
                    947: function uncheckAll(field) {
                    948:     if (field.length > 0) {
                    949:         for (i = 0; i < field.length; i++) {
                    950:             field[i].checked = false ;
1.543     albertel  951:         }
                    952:     } else {
1.273     raeburn   953:         field.checked = false ;
                    954:     }
                    955: }
                    956: ENDSCRT
                    957:     return $jscript;
                    958: }
                    959: 
1.656     www       960: sub select_timezone {
1.1387    raeburn   961:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    962:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   963:    if ($includeempty) {
                    964:        $output .= '<option value=""';
                    965:        if (($selected eq '') || ($selected eq 'local')) {
                    966:            $output .= ' selected="selected" ';
                    967:        }
                    968:        $output .= '> </option>';
                    969:    }
1.657     raeburn   970:    my @timezones = DateTime::TimeZone->all_names;
                    971:    foreach my $tzone (@timezones) {
                    972:        $output.= '<option value="'.$tzone.'"';
                    973:        if ($tzone eq $selected) {
                    974:            $output.=' selected="selected"';
                    975:        }
                    976:        $output.=">$tzone</option>\n";
1.656     www       977:    }
                    978:    $output.="</select>";
                    979:    return $output;
                    980: }
1.273     raeburn   981: 
1.687     raeburn   982: sub select_datelocale {
1.1256    raeburn   983:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    984:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   985:     if ($includeempty) {
                    986:         $output .= '<option value=""';
                    987:         if ($selected eq '') {
                    988:             $output .= ' selected="selected" ';
                    989:         }
                    990:         $output .= '> </option>';
                    991:     }
1.1241    raeburn   992:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   993:     my (@possibles,%locale_names);
1.1241    raeburn   994:     my @locales = DateTime::Locale->ids();
                    995:     foreach my $id (@locales) {
                    996:         if ($id ne '') {
                    997:             my ($en_terr,$native_terr);
                    998:             my $loc = DateTime::Locale->load($id);
                    999:             if (ref($loc)) {
                   1000:                 $en_terr = $loc->name();
                   1001:                 $native_terr = $loc->native_name();
1.687     raeburn  1002:                 if (grep(/^en$/,@languages) || !@languages) {
                   1003:                     if ($en_terr ne '') {
                   1004:                         $locale_names{$id} = '('.$en_terr.')';
                   1005:                     } elsif ($native_terr ne '') {
                   1006:                         $locale_names{$id} = $native_terr;
                   1007:                     }
                   1008:                 } else {
                   1009:                     if ($native_terr ne '') {
                   1010:                         $locale_names{$id} = $native_terr.' ';
                   1011:                     } elsif ($en_terr ne '') {
                   1012:                         $locale_names{$id} = '('.$en_terr.')';
                   1013:                     }
                   1014:                 }
1.1220    raeburn  1015:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1016:                 push(@possibles,$id);
                   1017:             } 
1.687     raeburn  1018:         }
                   1019:     }
                   1020:     foreach my $item (sort(@possibles)) {
                   1021:         $output.= '<option value="'.$item.'"';
                   1022:         if ($item eq $selected) {
                   1023:             $output.=' selected="selected"';
                   1024:         }
                   1025:         $output.=">$item";
                   1026:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1027:             $output.='  '.$locale_names{$item};
1.687     raeburn  1028:         }
                   1029:         $output.="</option>\n";
                   1030:     }
                   1031:     $output.="</select>";
                   1032:     return $output;
                   1033: }
                   1034: 
1.792     raeburn  1035: sub select_language {
1.1256    raeburn  1036:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1037:     my %langchoices;
                   1038:     if ($includeempty) {
1.1117    raeburn  1039:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1040:     }
                   1041:     foreach my $id (&languageids()) {
                   1042:         my $code = &supportedlanguagecode($id);
                   1043:         if ($code) {
                   1044:             $langchoices{$code} = &plainlanguagedescription($id);
                   1045:         }
                   1046:     }
1.1117    raeburn  1047:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1048:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1049: }
                   1050: 
1.42      matthew  1051: =pod
1.36      matthew  1052: 
1.1088    foxr     1053: 
                   1054: =item * &list_languages()
                   1055: 
                   1056: Returns an array reference that is suitable for use in language prompters.
                   1057: Each array element is itself a two element array.  The first element
                   1058: is the language code.  The second element a descsriptiuon of the 
                   1059: language itself.  This is suitable for use in e.g.
                   1060: &Apache::edit::select_arg (once dereferenced that is).
                   1061: 
                   1062: =cut 
                   1063: 
                   1064: sub list_languages {
                   1065:     my @lang_choices;
                   1066: 
                   1067:     foreach my $id (&languageids()) {
                   1068: 	my $code = &supportedlanguagecode($id);
                   1069: 	if ($code) {
                   1070: 	    my $selector    = $supported_codes{$id};
                   1071: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1072: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1073: 	}
                   1074:     }
                   1075:     return \@lang_choices;
                   1076: }
                   1077: 
                   1078: =pod
                   1079: 
1.648     raeburn  1080: =item * &linked_select_forms(...)
1.36      matthew  1081: 
                   1082: linked_select_forms returns a string containing a <script></script> block
                   1083: and html for two <select> menus.  The select menus will be linked in that
                   1084: changing the value of the first menu will result in new values being placed
                   1085: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1086: order unless a defined order is provided.
1.36      matthew  1087: 
                   1088: linked_select_forms takes the following ordered inputs:
                   1089: 
                   1090: =over 4
                   1091: 
1.112     bowersj2 1092: =item * $formname, the name of the <form> tag
1.36      matthew  1093: 
1.112     bowersj2 1094: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1095: 
1.112     bowersj2 1096: =item * $firstdefault, the default value for the first menu
1.36      matthew  1097: 
1.112     bowersj2 1098: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1099: 
1.112     bowersj2 1100: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1101: 
1.112     bowersj2 1102: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1103: 
1.609     raeburn  1104: =item * $menuorder, the order of values in the first menu
                   1105: 
1.1115    raeburn  1106: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1107:         event for the first <select> tag
                   1108: 
                   1109: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1110:         event for the second <select> tag
                   1111: 
1.1245    raeburn  1112: =item * $suffix, to differentiate separate uses of select2data javascript
                   1113:         objects in a page.
                   1114: 
1.41      ng       1115: =back 
                   1116: 
1.36      matthew  1117: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1118: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1119: values for the first select menu.  The text that coincides with the 
1.41      ng       1120: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1121: and text for the second menu are given in the hash pointed to by 
                   1122: $menu{$choice1}->{'select2'}.  
                   1123: 
1.112     bowersj2 1124:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1125:                        default => "B3",
                   1126:                        select2 => { 
                   1127:                            B1 => "Choice B1",
                   1128:                            B2 => "Choice B2",
                   1129:                            B3 => "Choice B3",
                   1130:                            B4 => "Choice B4"
1.609     raeburn  1131:                            },
                   1132:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1133:                    },
                   1134:                A2 => { text =>"Choice A2" ,
                   1135:                        default => "C2",
                   1136:                        select2 => { 
                   1137:                            C1 => "Choice C1",
                   1138:                            C2 => "Choice C2",
                   1139:                            C3 => "Choice C3"
1.609     raeburn  1140:                            },
                   1141:                        order => ['C2','C1','C3'],
1.112     bowersj2 1142:                    },
                   1143:                A3 => { text =>"Choice A3" ,
                   1144:                        default => "D6",
                   1145:                        select2 => { 
                   1146:                            D1 => "Choice D1",
                   1147:                            D2 => "Choice D2",
                   1148:                            D3 => "Choice D3",
                   1149:                            D4 => "Choice D4",
                   1150:                            D5 => "Choice D5",
                   1151:                            D6 => "Choice D6",
                   1152:                            D7 => "Choice D7"
1.609     raeburn  1153:                            },
                   1154:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1155:                    }
                   1156:                );
1.36      matthew  1157: 
                   1158: =cut
                   1159: 
                   1160: sub linked_select_forms {
                   1161:     my ($formname,
                   1162:         $middletext,
                   1163:         $firstdefault,
                   1164:         $firstselectname,
                   1165:         $secondselectname, 
1.609     raeburn  1166:         $hashref,
                   1167:         $menuorder,
1.1115    raeburn  1168:         $onchangefirst,
1.1245    raeburn  1169:         $onchangesecond,
                   1170:         $suffix
1.36      matthew  1171:         ) = @_;
                   1172:     my $second = "document.$formname.$secondselectname";
                   1173:     my $first = "document.$formname.$firstselectname";
                   1174:     # output the javascript to do the changing
                   1175:     my $result = '';
1.776     bisitz   1176:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1177:     $result.="// <![CDATA[\n";
1.1245    raeburn  1178:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1179:     $" = '","';
                   1180:     my $debug = '';
                   1181:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1182:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1183:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1184:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1185:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1186:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1187:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1188:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1189:         }
1.36      matthew  1190:         $result.="\"@s2values\");\n";
1.1245    raeburn  1191:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1192:         my @s2texts;
                   1193:         foreach my $value (@s2values) {
1.1263    raeburn  1194:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1195:         }
                   1196:         $result.="\"@s2texts\");\n";
                   1197:     }
                   1198:     $"=' ';
                   1199:     $result.= <<"END";
                   1200: 
1.1245    raeburn  1201: function select1${suffix}_changed() {
1.36      matthew  1202:     // Determine new choice
1.1245    raeburn  1203:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1204:     // update select2
1.1245    raeburn  1205:     var values     = select2data${suffix}[newvalue].values;
                   1206:     var texts      = select2data${suffix}[newvalue].texts;
                   1207:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1208:     var i;
                   1209:     // out with the old
1.1245    raeburn  1210:     $second.options.length = 0;
                   1211:     // in with the new
1.36      matthew  1212:     for (i=0;i<values.length; i++) {
                   1213:         $second.options[i] = new Option(values[i]);
1.143     matthew  1214:         $second.options[i].value = values[i];
1.36      matthew  1215:         $second.options[i].text = texts[i];
                   1216:         if (values[i] == select2def) {
                   1217:             $second.options[i].selected = true;
                   1218:         }
                   1219:     }
                   1220: }
1.824     bisitz   1221: // ]]>
1.36      matthew  1222: </script>
                   1223: END
                   1224:     # output the initial values for the selection lists
1.1245    raeburn  1225:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1226:     my @order = sort(keys(%{$hashref}));
                   1227:     if (ref($menuorder) eq 'ARRAY') {
                   1228:         @order = @{$menuorder};
                   1229:     }
                   1230:     foreach my $value (@order) {
1.36      matthew  1231:         $result.="    <option value=\"$value\" ";
1.253     albertel 1232:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1233:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1234:     }
                   1235:     $result .= "</select>\n";
                   1236:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1237:     $result .= $middletext;
1.1115    raeburn  1238:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1239:     if ($onchangesecond) {
                   1240:         $result .= ' onchange="'.$onchangesecond.'"';
                   1241:     }
                   1242:     $result .= ">\n";
1.36      matthew  1243:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1244:     
                   1245:     my @secondorder = sort(keys(%select2));
                   1246:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1247:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1248:     }
                   1249:     foreach my $value (@secondorder) {
1.36      matthew  1250:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1251:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1252:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1253:     }
                   1254:     $result .= "</select>\n";
                   1255:     #    return $debug;
                   1256:     return $result;
                   1257: }   #  end of sub linked_select_forms {
                   1258: 
1.45      matthew  1259: =pod
1.44      bowersj2 1260: 
1.1381    raeburn  1261: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1262: 
1.112     bowersj2 1263: Returns a string corresponding to an HTML link to the given help
                   1264: $topic, where $topic corresponds to the name of a .tex file in
                   1265: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1266: spaces. 
                   1267: 
                   1268: $text will optionally be linked to the same topic, allowing you to
                   1269: link text in addition to the graphic. If you do not want to link
                   1270: text, but wish to specify one of the later parameters, pass an
                   1271: empty string. 
                   1272: 
                   1273: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1274: the link will not open a new window. If false, the link will open
                   1275: a new window using Javascript. (Default is false.) 
                   1276: 
                   1277: $width and $height are optional numerical parameters that will
                   1278: override the width and height of the popped up window, which may
1.973     raeburn  1279: be useful for certain help topics with big pictures included.
                   1280: 
                   1281: $imgid is the id of the img tag used for the help icon. This may be
                   1282: used in a javascript call to switch the image src.  See 
                   1283: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1284: 
1.1381    raeburn  1285: $links_target will optionally be set to a target (_top, _parent or _self).
                   1286: 
1.44      bowersj2 1287: =cut
                   1288: 
                   1289: sub help_open_topic {
1.1381    raeburn  1290:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1291:     $text = "" if (not defined $text);
1.44      bowersj2 1292:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1293:     $width = 500 if (not defined $width);
1.44      bowersj2 1294:     $height = 400 if (not defined $height);
                   1295:     my $filename = $topic;
                   1296:     $filename =~ s/ /_/g;
                   1297: 
1.48      bowersj2 1298:     my $template = "";
                   1299:     my $link;
1.572     banghart 1300:     
1.159     www      1301:     $topic=~s/\W/\_/g;
1.44      bowersj2 1302: 
1.572     banghart 1303:     if (!$stayOnPage) {
1.1033    www      1304: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1305:     } elsif ($stayOnPage eq 'popup') {
                   1306:         $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 1307:     } else {
1.48      bowersj2 1308: 	$link = "/adm/help/${filename}.hlp";
                   1309:     }
                   1310: 
                   1311:     # Add the text
1.1314    raeburn  1312:     my $target = ' target="_top"';
1.1381    raeburn  1313:     if ($links_target) {
                   1314:         $target = ' target="'.$links_target.'"';
                   1315:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1316:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1317:         $target = '';
1.1378    raeburn  1318:     }
1.1380    raeburn  1319:     if ($text ne "") {
1.763     bisitz   1320: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1321:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1322:                   .$text.'</a>';
1.48      bowersj2 1323:     }
                   1324: 
1.763     bisitz   1325:     # (Always) Add the graphic
1.179     matthew  1326:     my $title = &mt('Online Help');
1.667     raeburn  1327:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1328:     if ($imgid ne '') {
                   1329:         $imgid = ' id="'.$imgid.'"';
                   1330:     }
1.1314    raeburn  1331:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1332:               .'<img src="'.$helpicon.'" border="0"'
                   1333:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1334:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1335:               .' /></a>';
                   1336:     if ($text ne "") {	
                   1337:         $template.='</span>';
                   1338:     }
1.44      bowersj2 1339:     return $template;
                   1340: 
1.106     bowersj2 1341: }
                   1342: 
                   1343: # This is a quicky function for Latex cheatsheet editing, since it 
                   1344: # appears in at least four places
                   1345: sub helpLatexCheatsheet {
1.1037    www      1346:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1347:     my $out;
1.106     bowersj2 1348:     my $addOther = '';
1.732     raeburn  1349:     if ($topic) {
1.1037    www      1350: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1351:     }
                   1352:     $out = '<span>' # Start cheatsheet
                   1353: 	  .$addOther
                   1354:           .'<span>'
1.1037    www      1355: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1356: 	  .'</span> <span>'
1.1037    www      1357: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1358: 	  .'</span>';
1.732     raeburn  1359:     unless ($not_author) {
1.1186    kruse    1360:         $out .= '<span>'
                   1361:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1362:                .'</span> <span>'
                   1363:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1364: 	       .'</span>';
1.732     raeburn  1365:     }
1.763     bisitz   1366:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1367:     return $out;
1.172     www      1368: }
                   1369: 
1.430     albertel 1370: sub general_help {
                   1371:     my $helptopic='Student_Intro';
                   1372:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1373: 	$helptopic='Authoring_Intro';
1.907     raeburn  1374:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1375: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1376:     } elsif ($env{'request.role'}=~/^dc/) {
                   1377:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1378:     }
                   1379:     return $helptopic;
                   1380: }
                   1381: 
                   1382: sub update_help_link {
                   1383:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1384:     my $origurl = $ENV{'REQUEST_URI'};
                   1385:     $origurl=~s|^/~|/priv/|;
                   1386:     my $timestamp = time;
                   1387:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1388:         $$datum = &escape($$datum);
                   1389:     }
                   1390: 
                   1391:     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";
                   1392:     my $output .= <<"ENDOUTPUT";
                   1393: <script type="text/javascript">
1.824     bisitz   1394: // <![CDATA[
1.430     albertel 1395: banner_link = '$banner_link';
1.824     bisitz   1396: // ]]>
1.430     albertel 1397: </script>
                   1398: ENDOUTPUT
                   1399:     return $output;
                   1400: }
                   1401: 
                   1402: # now just updates the help link and generates a blue icon
1.193     raeburn  1403: sub help_open_menu {
1.1381    raeburn  1404:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1405: 	= @_;    
1.949     droeschl 1406:     $stayOnPage = 1;
1.430     albertel 1407:     my $output;
                   1408:     if ($component_help) {
                   1409: 	if (!$text) {
                   1410: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1411: 				       $width,$height,'',$links_target);
1.430     albertel 1412: 	} else {
                   1413: 	    my $help_text;
                   1414: 	    $help_text=&unescape($topic);
                   1415: 	    $output='<table><tr><td>'.
                   1416: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1417: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1418: 	}
                   1419:     }
                   1420:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1421:     return $output.$banner_link;
                   1422: }
                   1423: 
                   1424: sub top_nav_help {
1.1369    raeburn  1425:     my ($text,$linkattr) = @_;
1.436     albertel 1426:     $text = &mt($text);
1.949     droeschl 1427:     my $stay_on_page = 1;
                   1428: 
1.1168    raeburn  1429:     my ($link,$banner_link);
                   1430:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1431:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1432: 	                         : "javascript:helpMenu('open')";
                   1433:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1434:     }
1.201     raeburn  1435:     my $title = &mt('Get help');
1.1168    raeburn  1436:     if ($link) {
                   1437:         return <<"END";
1.436     albertel 1438: $banner_link
1.1369    raeburn  1439: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1440: END
1.1168    raeburn  1441:     } else {
                   1442:         return '&nbsp;'.$text.'&nbsp;';
                   1443:     }
1.436     albertel 1444: }
                   1445: 
                   1446: sub help_menu_js {
1.1154    raeburn  1447:     my ($httphost) = @_;
1.949     droeschl 1448:     my $stayOnPage = 1;
1.436     albertel 1449:     my $width = 620;
                   1450:     my $height = 600;
1.430     albertel 1451:     my $helptopic=&general_help();
1.1154    raeburn  1452:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1453:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1454:     my $start_page =
                   1455:         &Apache::loncommon::start_page('Help Menu', undef,
                   1456: 				       {'frameset'    => 1,
                   1457: 					'js_ready'    => 1,
1.1154    raeburn  1458:                                         'use_absolute' => $httphost,
1.331     albertel 1459: 					'add_entries' => {
1.1168    raeburn  1460: 					    'border' => '0', 
1.579     raeburn  1461: 					    'rows'   => "110,*",},});
1.331     albertel 1462:     my $end_page =
                   1463:         &Apache::loncommon::end_page({'frameset' => 1,
                   1464: 				      'js_ready' => 1,});
                   1465: 
1.436     albertel 1466:     my $template .= <<"ENDTEMPLATE";
                   1467: <script type="text/javascript">
1.877     bisitz   1468: // <![CDATA[
1.253     albertel 1469: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1470: var banner_link = '';
1.243     raeburn  1471: function helpMenu(target) {
                   1472:     var caller = this;
                   1473:     if (target == 'open') {
                   1474:         var newWindow = null;
                   1475:         try {
1.262     albertel 1476:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1477:         }
                   1478:         catch(error) {
                   1479:             writeHelp(caller);
                   1480:             return;
                   1481:         }
                   1482:         if (newWindow) {
                   1483:             caller = newWindow;
                   1484:         }
1.193     raeburn  1485:     }
1.243     raeburn  1486:     writeHelp(caller);
                   1487:     return;
                   1488: }
                   1489: function writeHelp(caller) {
1.1168    raeburn  1490:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1491:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1492:     caller.document.close();
                   1493:     caller.focus();
1.193     raeburn  1494: }
1.877     bisitz   1495: // END LON-CAPA Internal -->
1.253     albertel 1496: // ]]>
1.436     albertel 1497: </script>
1.193     raeburn  1498: ENDTEMPLATE
                   1499:     return $template;
                   1500: }
                   1501: 
1.172     www      1502: sub help_open_bug {
                   1503:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1504:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1505:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1506:     $text = "" if (not defined $text);
                   1507: 	$stayOnPage=1;
1.184     albertel 1508:     $width = 600 if (not defined $width);
                   1509:     $height = 600 if (not defined $height);
1.172     www      1510: 
                   1511:     $topic=~s/\W+/\+/g;
                   1512:     my $link='';
                   1513:     my $template='';
1.379     albertel 1514:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1515: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1516:     if (!$stayOnPage)
                   1517:     {
                   1518: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1519:     }
                   1520:     else
                   1521:     {
                   1522: 	$link = $url;
                   1523:     }
1.1314    raeburn  1524: 
1.1382    raeburn  1525:     my $target = '_top';
                   1526:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1527:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1528:         $target = '_blank';
1.1378    raeburn  1529:     }
1.1382    raeburn  1530: 
1.172     www      1531:     # Add the text
                   1532:     if ($text ne "")
                   1533:     {
                   1534: 	$template .= 
                   1535:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1536:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1537:     }
                   1538: 
                   1539:     # Add the graphic
1.179     matthew  1540:     my $title = &mt('Report a Bug');
1.215     albertel 1541:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1542:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1543:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1544: ENDTEMPLATE
                   1545:     if ($text ne '') { $template.='</td></tr></table>' };
                   1546:     return $template;
                   1547: 
                   1548: }
                   1549: 
                   1550: sub help_open_faq {
                   1551:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1552:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1553:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1554:     $text = "" if (not defined $text);
                   1555: 	$stayOnPage=1;
                   1556:     $width = 350 if (not defined $width);
                   1557:     $height = 400 if (not defined $height);
                   1558: 
                   1559:     $topic=~s/\W+/\+/g;
                   1560:     my $link='';
                   1561:     my $template='';
                   1562:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1563:     if (!$stayOnPage)
                   1564:     {
                   1565: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1566:     }
                   1567:     else
                   1568:     {
                   1569: 	$link = $url;
                   1570:     }
                   1571: 
                   1572:     # Add the text
                   1573:     if ($text ne "")
                   1574:     {
                   1575: 	$template .= 
1.173     www      1576:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1577:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1578:     }
                   1579: 
                   1580:     # Add the graphic
1.179     matthew  1581:     my $title = &mt('View the FAQ');
1.215     albertel 1582:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1583:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1584:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1585: ENDTEMPLATE
                   1586:     if ($text ne '') { $template.='</td></tr></table>' };
                   1587:     return $template;
                   1588: 
1.44      bowersj2 1589: }
1.37      matthew  1590: 
1.180     matthew  1591: ###############################################################
                   1592: ###############################################################
                   1593: 
1.45      matthew  1594: =pod
                   1595: 
1.648     raeburn  1596: =item * &change_content_javascript():
1.256     matthew  1597: 
                   1598: This and the next function allow you to create small sections of an
                   1599: otherwise static HTML page that you can update on the fly with
                   1600: Javascript, even in Netscape 4.
                   1601: 
                   1602: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1603: must be written to the HTML page once. It will prove the Javascript
                   1604: function "change(name, content)". Calling the change function with the
                   1605: name of the section 
                   1606: you want to update, matching the name passed to C<changable_area>, and
                   1607: the new content you want to put in there, will put the content into
                   1608: that area.
                   1609: 
                   1610: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1611: to contain room for the original contents. You need to "make space"
                   1612: for whatever changes you wish to make, and be B<sure> to check your
                   1613: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1614: it's adequate for updating a one-line status display, but little more.
                   1615: This script will set the space to 100% width, so you only need to
                   1616: worry about height in Netscape 4.
                   1617: 
                   1618: Modern browsers are much less limiting, and if you can commit to the
                   1619: user not using Netscape 4, this feature may be used freely with
                   1620: pretty much any HTML.
                   1621: 
                   1622: =cut
                   1623: 
                   1624: sub change_content_javascript {
                   1625:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1626:     if ($env{'browser.type'} eq 'netscape' &&
                   1627: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1628: 	return (<<NETSCAPE4);
                   1629: 	function change(name, content) {
                   1630: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1631: 	    doc.open();
                   1632: 	    doc.write(content);
                   1633: 	    doc.close();
                   1634: 	}
                   1635: NETSCAPE4
                   1636:     } else {
                   1637: 	# Otherwise, we need to use semi-standards-compliant code
                   1638: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1639: 	# is really scary, and every useful browser supports it
                   1640: 	return (<<DOMBASED);
                   1641: 	function change(name, content) {
                   1642: 	    element = document.getElementById(name);
                   1643: 	    element.innerHTML = content;
                   1644: 	}
                   1645: DOMBASED
                   1646:     }
                   1647: }
                   1648: 
                   1649: =pod
                   1650: 
1.648     raeburn  1651: =item * &changable_area($name,$origContent):
1.256     matthew  1652: 
                   1653: This provides a "changable area" that can be modified on the fly via
                   1654: the Javascript code provided in C<change_content_javascript>. $name is
                   1655: the name you will use to reference the area later; do not repeat the
                   1656: same name on a given HTML page more then once. $origContent is what
                   1657: the area will originally contain, which can be left blank.
                   1658: 
                   1659: =cut
                   1660: 
                   1661: sub changable_area {
                   1662:     my ($name, $origContent) = @_;
                   1663: 
1.258     albertel 1664:     if ($env{'browser.type'} eq 'netscape' &&
                   1665: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1666: 	# If this is netscape 4, we need to use the Layer tag
                   1667: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1668:     } else {
                   1669: 	return "<span id='$name'>$origContent</span>";
                   1670:     }
                   1671: }
                   1672: 
                   1673: =pod
                   1674: 
1.648     raeburn  1675: =item * &viewport_geometry_js 
1.590     raeburn  1676: 
                   1677: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1678: 
                   1679: =cut
                   1680: 
                   1681: 
                   1682: sub viewport_geometry_js { 
                   1683:     return <<"GEOMETRY";
                   1684: var Geometry = {};
                   1685: function init_geometry() {
                   1686:     if (Geometry.init) { return };
                   1687:     Geometry.init=1;
                   1688:     if (window.innerHeight) {
                   1689:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1690:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1691:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1692:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1693:     }
                   1694:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1695:         Geometry.getViewportHeight =
                   1696:             function() { return document.documentElement.clientHeight; };
                   1697:         Geometry.getViewportWidth =
                   1698:             function() { return document.documentElement.clientWidth; };
                   1699: 
                   1700:         Geometry.getHorizontalScroll =
                   1701:             function() { return document.documentElement.scrollLeft; };
                   1702:         Geometry.getVerticalScroll =
                   1703:             function() { return document.documentElement.scrollTop; };
                   1704:     }
                   1705:     else if (document.body.clientHeight) {
                   1706:         Geometry.getViewportHeight =
                   1707:             function() { return document.body.clientHeight; };
                   1708:         Geometry.getViewportWidth =
                   1709:             function() { return document.body.clientWidth; };
                   1710:         Geometry.getHorizontalScroll =
                   1711:             function() { return document.body.scrollLeft; };
                   1712:         Geometry.getVerticalScroll =
                   1713:             function() { return document.body.scrollTop; };
                   1714:     }
                   1715: }
                   1716: 
                   1717: GEOMETRY
                   1718: }
                   1719: 
                   1720: =pod
                   1721: 
1.648     raeburn  1722: =item * &viewport_size_js()
1.590     raeburn  1723: 
                   1724: 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. 
                   1725: 
                   1726: =cut
                   1727: 
                   1728: sub viewport_size_js {
                   1729:     my $geometry = &viewport_geometry_js();
                   1730:     return <<"DIMS";
                   1731: 
                   1732: $geometry
                   1733: 
                   1734: function getViewportDims(width,height) {
                   1735:     init_geometry();
                   1736:     width.value = Geometry.getViewportWidth();
                   1737:     height.value = Geometry.getViewportHeight();
                   1738:     return;
                   1739: }
                   1740: 
                   1741: DIMS
                   1742: }
                   1743: 
                   1744: =pod
                   1745: 
1.648     raeburn  1746: =item * &resize_textarea_js()
1.565     albertel 1747: 
                   1748: emits the needed javascript to resize a textarea to be as big as possible
                   1749: 
                   1750: creates a function resize_textrea that takes two IDs first should be
                   1751: the id of the element to resize, second should be the id of a div that
                   1752: surrounds everything that comes after the textarea, this routine needs
                   1753: to be attached to the <body> for the onload and onresize events.
                   1754: 
1.648     raeburn  1755: =back
1.565     albertel 1756: 
                   1757: =cut
                   1758: 
                   1759: sub resize_textarea_js {
1.590     raeburn  1760:     my $geometry = &viewport_geometry_js();
1.565     albertel 1761:     return <<"RESIZE";
                   1762:     <script type="text/javascript">
1.824     bisitz   1763: // <![CDATA[
1.590     raeburn  1764: $geometry
1.565     albertel 1765: 
1.588     albertel 1766: function getX(element) {
                   1767:     var x = 0;
                   1768:     while (element) {
                   1769: 	x += element.offsetLeft;
                   1770: 	element = element.offsetParent;
                   1771:     }
                   1772:     return x;
                   1773: }
                   1774: function getY(element) {
                   1775:     var y = 0;
                   1776:     while (element) {
                   1777: 	y += element.offsetTop;
                   1778: 	element = element.offsetParent;
                   1779:     }
                   1780:     return y;
                   1781: }
                   1782: 
                   1783: 
1.565     albertel 1784: function resize_textarea(textarea_id,bottom_id) {
                   1785:     init_geometry();
                   1786:     var textarea        = document.getElementById(textarea_id);
                   1787:     //alert(textarea);
                   1788: 
1.588     albertel 1789:     var textarea_top    = getY(textarea);
1.565     albertel 1790:     var textarea_height = textarea.offsetHeight;
                   1791:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1792:     var bottom_top      = getY(bottom);
1.565     albertel 1793:     var bottom_height   = bottom.offsetHeight;
                   1794:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1795:     var fudge           = 23;
1.565     albertel 1796:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1797:     if (new_height < 300) {
                   1798: 	new_height = 300;
                   1799:     }
                   1800:     textarea.style.height=new_height+'px';
                   1801: }
1.824     bisitz   1802: // ]]>
1.565     albertel 1803: </script>
                   1804: RESIZE
                   1805: 
                   1806: }
                   1807: 
1.1205    golterma 1808: sub colorfuleditor_js {
1.1248    raeburn  1809:     my $browse_or_search;
                   1810:     my $respath;
                   1811:     my ($cnum,$cdom) = &crsauthor_url();
                   1812:     if ($cnum) {
                   1813:         $respath = "/res/$cdom/$cnum/";
                   1814:         my %js_lt = &Apache::lonlocal::texthash(
                   1815:             sunm => 'Sub-directory name',
                   1816:             save => 'Save page to make this permanent',
                   1817:         );
                   1818:         &js_escape(\%js_lt);
                   1819:         $browse_or_search = <<"END";
                   1820: 
                   1821:     function toggleChooser(form,element,titleid,only,search) {
                   1822:         var disp = 'none';
                   1823:         if (document.getElementById('chooser_'+element)) {
                   1824:             var curr = document.getElementById('chooser_'+element).style.display;
                   1825:             if (curr == 'none') {
                   1826:                 disp='inline';
                   1827:                 if (form.elements['chooser_'+element].length) {
                   1828:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1829:                         form.elements['chooser_'+element][i].checked = false;
                   1830:                     }
                   1831:                 }
                   1832:                 toggleResImport(form,element);
                   1833:             }
                   1834:             document.getElementById('chooser_'+element).style.display = disp;
                   1835:         }
                   1836:     }
                   1837: 
                   1838:     function toggleCrsFile(form,element,numdirs) {
                   1839:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1840:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1841:             if (curr == 'none') {
                   1842:                 if (numdirs) {
                   1843:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1844:                     if (numdirs > 1) {
                   1845:                         window['select1'+element+'_changed']();
                   1846:                     }
                   1847:                 }
                   1848:             } 
                   1849:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1850:             
                   1851:         }
                   1852:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1853:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1854:             if (document.getElementById('uploadcrsres_'+element)) {
                   1855:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1856:             }
                   1857:         }
                   1858:         return;
                   1859:     }
                   1860: 
                   1861:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1862:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1863:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1864:         }
                   1865:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1866:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1867:             if (curr == 'none') {
                   1868:                 if (numcrsdirs) {
                   1869:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1870:                    form.elements['newsubdir_'+element][0].checked = true;
                   1871:                    toggleNewsubdir(form,element);
                   1872:                 }
                   1873:             }
                   1874:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1875:         }
                   1876:         return;
                   1877:     }
                   1878: 
                   1879:     function toggleResImport(form,element) {
                   1880:         var choices = new Array('crsres','upload');
                   1881:         for (var i=0; i<choices.length; i++) {
                   1882:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1883:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1884:             }
                   1885:         }
                   1886:     }
                   1887: 
                   1888:     function toggleNewsubdir(form,element) {
                   1889:         var newsub = form.elements['newsubdir_'+element];
                   1890:         if (newsub) {
                   1891:             if (newsub.length) {
                   1892:                 for (var j=0; j<newsub.length; j++) {
                   1893:                     if (newsub[j].checked) {
                   1894:                         if (document.getElementById('newsubdirname_'+element)) {
                   1895:                             if (newsub[j].value == '1') {
                   1896:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1897:                                 if (document.getElementById('newsubdir_'+element)) {
                   1898:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1899:                                 }
                   1900:                             } else {
                   1901:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1902:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1903:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1904:                             }
                   1905:                         }
                   1906:                         break; 
                   1907:                     }
                   1908:                 }
                   1909:             }
                   1910:         }
                   1911:     }
                   1912: 
                   1913:     function updateCrsFile(form,element) {
                   1914:         var directory = form.elements['coursepath_'+element];
                   1915:         var filename = form.elements['coursefile_'+element];
                   1916:         var path = directory.options[directory.selectedIndex].value;
                   1917:         var file = filename.options[filename.selectedIndex].value;
                   1918:         form.elements[element].value = '$respath';
                   1919:         if (path == '/') {
                   1920:             form.elements[element].value += file;
                   1921:         } else {
                   1922:             form.elements[element].value += path+'/'+file;
                   1923:         }
                   1924:         unClean();
                   1925:         if (document.getElementById('previewimg_'+element)) {
                   1926:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1927:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1928:         }
                   1929:         if (document.getElementById('showimg_'+element)) {
                   1930:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1931:         }
                   1932:         toggleChooser(form,element);
                   1933:         return;
                   1934:     }
                   1935: 
                   1936:     function uploadDone(suffix,name) {
                   1937:         if (name) {
                   1938: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1939:             unClean();
                   1940:             toggleChooser(document.forms["lonhomework"],suffix);
                   1941:         }
                   1942:     }
                   1943: 
                   1944: \$(document).ready(function(){
                   1945: 
                   1946:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1947:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1948:             var buttonId = this.id;
                   1949:             var suffix = buttonId.toString();
                   1950:             suffix = suffix.replace(/^crsupload_/,'');
                   1951:             event.preventDefault();
                   1952:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1953:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1954:             \$(this.form).submit();
                   1955:             document.lonhomework.target = '';
                   1956:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1957:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1958:             }
                   1959:             return false;
                   1960:         }
                   1961:     });
                   1962: });
                   1963: END
                   1964:     }
1.1205    golterma 1965:     return <<"COLORFULEDIT"
                   1966: <script type="text/javascript">
                   1967: // <![CDATA[>
                   1968:     function fold_box(curDepth, lastresource){
                   1969: 
                   1970:     // we need a list because there can be several blocks you need to fold in one tag
                   1971:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1972:     // but there is only one folding button per tag
                   1973:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1974: 
                   1975:         if(block.item(0).style.display == 'none'){
                   1976: 
                   1977:             foldbutton.value = '@{[&mt("Hide")]}';
                   1978:             for (i = 0; i < block.length; i++){
                   1979:                 block.item(i).style.display = '';
                   1980:             }
                   1981:         }else{
                   1982: 
                   1983:             foldbutton.value = '@{[&mt("Show")]}';
                   1984:             for (i = 0; i < block.length; i++){
                   1985:                 // block.item(i).style.visibility = 'collapse';
                   1986:                 block.item(i).style.display = 'none';
                   1987:             }
                   1988:         };
                   1989:         saveState(lastresource);
                   1990:     }
                   1991: 
                   1992:     function saveState (lastresource) {
                   1993: 
                   1994:         var tag_list = getTagList();
                   1995:         if(tag_list != null){
                   1996:             var timestamp = new Date().getTime();
                   1997:             var key = lastresource;
                   1998: 
                   1999:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2000:             // starting with timestamp
                   2001:             var value = timestamp+';';
                   2002: 
                   2003:             // building the list of key-value pairs
                   2004:             for(var i = 0; i < tag_list.length; i++){
                   2005:                 value += tag_list[i]+',';
                   2006:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2007:             }
                   2008: 
                   2009:             // only iterate whole storage if nothing to override
                   2010:             if(localStorage.getItem(key) == null){        
                   2011: 
                   2012:                 // prevent storage from growing large
                   2013:                 if(localStorage.length > 50){
                   2014:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2015:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2016:                     var oldest_key;
                   2017:                     
                   2018:                     for(var i = 1; i < localStorage.length; i++){
                   2019:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2020:                             oldest_key = localStorage.key(i);
                   2021:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2022:                         }
                   2023:                     }
                   2024:                     localStorage.removeItem(oldest_key);
                   2025:                 }
                   2026:             }
                   2027:             localStorage.setItem(key,value);
                   2028:         }
                   2029:     }
                   2030: 
                   2031:     // restore folding status of blocks (on page load)
                   2032:     function restoreState (lastresource) {
                   2033:         if(localStorage.getItem(lastresource) != null){
                   2034:             var key = lastresource;
                   2035:             var value = localStorage.getItem(key);
                   2036:             var regex_delTimestamp = /^\d+;/;
                   2037: 
                   2038:             value.replace(regex_delTimestamp, '');
                   2039: 
                   2040:             var valueArr = value.split(';');
                   2041:             var pairs;
                   2042:             var elements;
                   2043:             for (var i = 0; i < valueArr.length; i++){
                   2044:                 pairs = valueArr[i].split(',');
                   2045:                 elements = document.getElementsByName(pairs[0]);
                   2046: 
                   2047:                 for (var j = 0; j < elements.length; j++){  
                   2048:                     elements[j].style.display = pairs[1];
                   2049:                     if (pairs[1] == "none"){
                   2050:                         var regex_id = /([_\\d]+)\$/;
                   2051:                         regex_id.exec(pairs[0]);
                   2052:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2053:                     }
                   2054:                 }
                   2055:             }
                   2056:         }
                   2057:     }
                   2058: 
                   2059:     function getTagList () {
                   2060:         
                   2061:         var stringToSearch = document.lonhomework.innerHTML;
                   2062: 
                   2063:         var ret = new Array();
                   2064:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2065:         var tag_list = stringToSearch.match(regex_findBlock);
                   2066: 
                   2067:         if(tag_list != null){
                   2068:             for(var i = 0; i < tag_list.length; i++){            
                   2069:                 ret.push(tag_list[i].replace(/"/, ''));
                   2070:             }
                   2071:         }
                   2072:         return ret;
                   2073:     }
                   2074: 
                   2075:     function saveScrollPosition (resource) {
                   2076:         var tag_list = getTagList();
                   2077: 
                   2078:         // we dont always want to jump to the first block
                   2079:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2080:         if(\$(window).scrollTop() > 170){
                   2081:             if(tag_list != null){
                   2082:                 var result;
                   2083:                 for(var i = 0; i < tag_list.length; i++){
                   2084:                     if(isElementInViewport(tag_list[i])){
                   2085:                         result += tag_list[i]+';';
                   2086:                     }
                   2087:                 }
                   2088:                 sessionStorage.setItem('anchor_'+resource, result);
                   2089:             }
                   2090:         } else {
                   2091:             // we dont need to save zero, just delete the item to leave everything tidy
                   2092:             sessionStorage.removeItem('anchor_'+resource);
                   2093:         }
                   2094:     }
                   2095: 
                   2096:     function restoreScrollPosition(resource){
                   2097: 
                   2098:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2099:         if(elem != null){
                   2100:             var tag_list = elem.split(';');
                   2101:             var elem_list;
                   2102: 
                   2103:             for(var i = 0; i < tag_list.length; i++){
                   2104:                 elem_list = document.getElementsByName(tag_list[i]);
                   2105:                 
                   2106:                 if(elem_list.length > 0){
                   2107:                     elem = elem_list[0];
                   2108:                     break;
                   2109:                 }
                   2110:             }
                   2111:             elem.scrollIntoView();
                   2112:         }
                   2113:     }
                   2114: 
                   2115:     function isElementInViewport(el) {
                   2116: 
                   2117:         // change to last element instead of first
                   2118:         var elem = document.getElementsByName(el);
                   2119:         var rect = elem[0].getBoundingClientRect();
                   2120: 
                   2121:         return (
                   2122:             rect.top >= 0 &&
                   2123:             rect.left >= 0 &&
                   2124:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2125:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2126:         );
                   2127:     }
                   2128:     
                   2129:     function autosize(depth){
                   2130:         var cmInst = window['cm'+depth];
                   2131:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2132: 
                   2133:         // is fixed size, switching to dynamic
                   2134:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2135:             cmInst.setSize("","auto");
                   2136:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2137:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2138: 
                   2139:         // is dynamic size, switching to fixed
                   2140:         } else {
                   2141:             cmInst.setSize("","300px");
                   2142:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2143:             sessionStorage.removeItem("autosized_"+depth);
                   2144:         }
                   2145:     }
                   2146: 
1.1248    raeburn  2147: $browse_or_search
1.1205    golterma 2148: 
                   2149: // ]]>
                   2150: </script>
                   2151: COLORFULEDIT
                   2152: }
                   2153: 
                   2154: sub xmleditor_js {
                   2155:     return <<XMLEDIT
                   2156: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2157: <script type="text/javascript">
                   2158: // <![CDATA[>
                   2159: 
                   2160:     function saveScrollPosition (resource) {
                   2161: 
                   2162:         var scrollPos = \$(window).scrollTop();
                   2163:         sessionStorage.setItem(resource,scrollPos);
                   2164:     }
                   2165: 
                   2166:     function restoreScrollPosition(resource){
                   2167: 
                   2168:         var scrollPos = sessionStorage.getItem(resource);
                   2169:         \$(window).scrollTop(scrollPos);
                   2170:     }
                   2171: 
                   2172:     // unless internet explorer
                   2173:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2174: 
                   2175:         \$(document).ready(function() {
                   2176:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2177:         });
                   2178:     }
                   2179: 
                   2180:     // inserts text at cursor position into codemirror (xml editor only)
                   2181:     function insertText(text){
                   2182:         cm.focus();
                   2183:         var curPos = cm.getCursor();
                   2184:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2185:     }
                   2186: // ]]>
                   2187: </script>
                   2188: XMLEDIT
                   2189: }
                   2190: 
                   2191: sub insert_folding_button {
                   2192:     my $curDepth = $Apache::lonxml::curdepth;
                   2193:     my $lastresource = $env{'request.ambiguous'};
                   2194: 
                   2195:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2196:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2197: }
                   2198: 
1.1248    raeburn  2199: sub crsauthor_url {
                   2200:     my ($url) = @_;
                   2201:     if ($url eq '') {
                   2202:         $url = $ENV{'REQUEST_URI'};
                   2203:     }
                   2204:     my ($cnum,$cdom);
                   2205:     if ($env{'request.course.id'}) {
                   2206:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2207:         if ($audom ne '' && $auname ne '') {
                   2208:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2209:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2210:                 $cnum = $auname;
                   2211:                 $cdom = $audom;
                   2212:             }
                   2213:         }
                   2214:     }
                   2215:     return ($cnum,$cdom);
                   2216: }
                   2217: 
                   2218: sub import_crsauthor_form {
1.1265    raeburn  2219:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2220:     return (0) unless ($env{'request.course.id'});
                   2221:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2222:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2223:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2224:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2225:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2226:     my @ids=&Apache::lonnet::current_machine_ids();
                   2227:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2228:     
                   2229:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2230:         $is_home = 1;
                   2231:     }
                   2232:     $relpath = "/priv/$cdom/$cnum";
                   2233:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2234:     my %lt = &Apache::lonlocal::texthash (
                   2235:         fnam => 'Filename',
                   2236:         dire => 'Directory',
                   2237:     );
                   2238:     my $numdirs = scalar(keys(%files));
                   2239:     my (%possexts,$singledir,@singledirfiles);
                   2240:     if ($only) {
                   2241:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2242:     }
                   2243:     my (%nonemptydirs,$possdirs);
                   2244:     if ($numdirs > 1) {
                   2245:         my @order;
                   2246:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2247:             if (ref($files{$key}) eq 'HASH') {
                   2248:                 my $shown = $key;
                   2249:                 if ($key eq '') {
                   2250:                     $shown = '/';
                   2251:                 }
                   2252:                 my @ordered = ();
                   2253:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2254:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2255:                     if ($only) {
                   2256:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2257:                         unless ($possexts{lc($ext)}) {
                   2258:                             next;
                   2259:                         }
                   2260:                     }
                   2261:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2262:                     push(@ordered,$file);
                   2263:                 }
                   2264:                 if (@ordered) {
                   2265:                     push(@order,$key);
                   2266:                     $nonemptydirs{$key} = 1;
                   2267:                     $selimport_menus{$key}->{'text'} = $shown;
                   2268:                     $selimport_menus{$key}->{'default'} = '';
                   2269:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2270:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2271:                 }
                   2272:             }
                   2273:         }
                   2274:         $possdirs = scalar(keys(%nonemptydirs));
                   2275:         if ($possdirs > 1) {
                   2276:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2277:             $output = $lt{'dire'}.
                   2278:                       &linked_select_forms($form,'<br />'.
                   2279:                                            $lt{'fnam'},'',
                   2280:                                            $firstselectname,$secondselectname,
                   2281:                                            \%selimport_menus,\@order,
                   2282:                                            $onchangefirst,'',$suffix).'<br />';
                   2283:         } elsif ($possdirs == 1) {
                   2284:             $singledir = (keys(%nonemptydirs))[0];
                   2285:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2286:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2287:             }
                   2288:             delete($selimport_menus{$singledir});
                   2289:         }
                   2290:     } elsif ($numdirs == 1) {
                   2291:         $singledir = (keys(%files))[0];
                   2292:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2293:             if ($only) {
                   2294:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2295:                 unless ($possexts{lc($ext)}) {
                   2296:                     next;
                   2297:                 }
1.1315    raeburn  2298:             } else {
                   2299:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2300:             }
                   2301:             push(@singledirfiles,$file);
                   2302:         }
                   2303:         if (@singledirfiles) {
1.1315    raeburn  2304:             $possdirs = 1;
1.1248    raeburn  2305:         }
                   2306:     }
                   2307:     if (($possdirs == 1) && (@singledirfiles)) {
                   2308:         my $showdir = $singledir;
                   2309:         if ($singledir eq '') {
                   2310:             $showdir = '/';
                   2311:         }
                   2312:         $output = $lt{'dire'}.
                   2313:                   '<select name="'.$firstselectname.'">'.
                   2314:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2315:                   '</select><br />'.
                   2316:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2317:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2318:         foreach my $file (@singledirfiles) {
                   2319:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2320:         }
                   2321:         $output .= '</select><br />'."\n";
                   2322:     }
                   2323:     return ($possdirs,$output);
                   2324: }
                   2325: 
1.565     albertel 2326: =pod
                   2327: 
1.256     matthew  2328: =head1 Excel and CSV file utility routines
                   2329: 
                   2330: =cut
                   2331: 
                   2332: ###############################################################
                   2333: ###############################################################
                   2334: 
                   2335: =pod
                   2336: 
1.1162    raeburn  2337: =over 4
                   2338: 
1.648     raeburn  2339: =item * &csv_translate($text) 
1.37      matthew  2340: 
1.185     www      2341: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2342: format.
                   2343: 
                   2344: =cut
                   2345: 
1.180     matthew  2346: ###############################################################
                   2347: ###############################################################
1.37      matthew  2348: sub csv_translate {
                   2349:     my $text = shift;
                   2350:     $text =~ s/\"/\"\"/g;
1.209     albertel 2351:     $text =~ s/\n/ /g;
1.37      matthew  2352:     return $text;
                   2353: }
1.180     matthew  2354: 
                   2355: ###############################################################
                   2356: ###############################################################
                   2357: 
                   2358: =pod
                   2359: 
1.648     raeburn  2360: =item * &define_excel_formats()
1.180     matthew  2361: 
                   2362: Define some commonly used Excel cell formats.
                   2363: 
                   2364: Currently supported formats:
                   2365: 
                   2366: =over 4
                   2367: 
                   2368: =item header
                   2369: 
                   2370: =item bold
                   2371: 
                   2372: =item h1
                   2373: 
                   2374: =item h2
                   2375: 
                   2376: =item h3
                   2377: 
1.256     matthew  2378: =item h4
                   2379: 
                   2380: =item i
                   2381: 
1.180     matthew  2382: =item date
                   2383: 
                   2384: =back
                   2385: 
                   2386: Inputs: $workbook
                   2387: 
                   2388: Returns: $format, a hash reference.
                   2389: 
1.1057    foxr     2390: 
1.180     matthew  2391: =cut
                   2392: 
                   2393: ###############################################################
                   2394: ###############################################################
                   2395: sub define_excel_formats {
                   2396:     my ($workbook) = @_;
                   2397:     my $format;
                   2398:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2399:                                                 bottom    => 1,
                   2400:                                                 align     => 'center');
                   2401:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2402:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2403:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2404:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2405:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2406:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2407:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2408:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2409:     return $format;
                   2410: }
                   2411: 
                   2412: ###############################################################
                   2413: ###############################################################
1.113     bowersj2 2414: 
                   2415: =pod
                   2416: 
1.648     raeburn  2417: =item * &create_workbook()
1.255     matthew  2418: 
                   2419: Create an Excel worksheet.  If it fails, output message on the
                   2420: request object and return undefs.
                   2421: 
                   2422: Inputs: Apache request object
                   2423: 
                   2424: Returns (undef) on failure, 
                   2425:     Excel worksheet object, scalar with filename, and formats 
                   2426:     from &Apache::loncommon::define_excel_formats on success
                   2427: 
                   2428: =cut
                   2429: 
                   2430: ###############################################################
                   2431: ###############################################################
                   2432: sub create_workbook {
                   2433:     my ($r) = @_;
                   2434:         #
                   2435:     # Create the excel spreadsheet
                   2436:     my $filename = '/prtspool/'.
1.258     albertel 2437:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2438:         time.'_'.rand(1000000000).'.xls';
                   2439:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2440:     if (! defined($workbook)) {
                   2441:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2442:         $r->print(
                   2443:             '<p class="LC_error">'
                   2444:            .&mt('Problems occurred in creating the new Excel file.')
                   2445:            .' '.&mt('This error has been logged.')
                   2446:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2447:            .'</p>'
                   2448:         );
1.255     matthew  2449:         return (undef);
                   2450:     }
                   2451:     #
1.1014    foxr     2452:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2453:     #
                   2454:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2455:     return ($workbook,$filename,$format);
                   2456: }
                   2457: 
                   2458: ###############################################################
                   2459: ###############################################################
                   2460: 
                   2461: =pod
                   2462: 
1.648     raeburn  2463: =item * &create_text_file()
1.113     bowersj2 2464: 
1.542     raeburn  2465: Create a file to write to and eventually make available to the user.
1.256     matthew  2466: If file creation fails, outputs an error message on the request object and 
                   2467: return undefs.
1.113     bowersj2 2468: 
1.256     matthew  2469: Inputs: Apache request object, and file suffix
1.113     bowersj2 2470: 
1.256     matthew  2471: Returns (undef) on failure, 
                   2472:     Filehandle and filename on success.
1.113     bowersj2 2473: 
                   2474: =cut
                   2475: 
1.256     matthew  2476: ###############################################################
                   2477: ###############################################################
                   2478: sub create_text_file {
                   2479:     my ($r,$suffix) = @_;
                   2480:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2481:     my $fh;
                   2482:     my $filename = '/prtspool/'.
1.258     albertel 2483:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2484:         time.'_'.rand(1000000000).'.'.$suffix;
                   2485:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2486:     if (! defined($fh)) {
                   2487:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2488:         $r->print(
                   2489:             '<p class="LC_error">'
                   2490:            .&mt('Problems occurred in creating the output file.')
                   2491:            .' '.&mt('This error has been logged.')
                   2492:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2493:            .'</p>'
                   2494:         );
1.113     bowersj2 2495:     }
1.256     matthew  2496:     return ($fh,$filename)
1.113     bowersj2 2497: }
                   2498: 
                   2499: 
1.256     matthew  2500: =pod 
1.113     bowersj2 2501: 
                   2502: =back
                   2503: 
                   2504: =cut
1.37      matthew  2505: 
                   2506: ###############################################################
1.33      matthew  2507: ##        Home server <option> list generating code          ##
                   2508: ###############################################################
1.35      matthew  2509: 
1.169     www      2510: # ------------------------------------------
                   2511: 
                   2512: sub domain_select {
1.1289    raeburn  2513:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2514:     my @possdoms;
                   2515:     if (ref($incdoms) eq 'ARRAY') {
                   2516:         @possdoms = @{$incdoms};
                   2517:     } else {
                   2518:         @possdoms = &Apache::lonnet::all_domains();
                   2519:     }
                   2520: 
1.169     www      2521:     my %domains=map { 
1.514     albertel 2522: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2523:     } @possdoms;
                   2524: 
                   2525:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2526:         foreach my $dom (@{$excdoms}) {
                   2527:             delete($domains{$dom});
                   2528:         }
                   2529:     }
                   2530: 
1.169     www      2531:     if ($multiple) {
                   2532: 	$domains{''}=&mt('Any domain');
1.550     albertel 2533: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2534: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2535:     } else {
1.550     albertel 2536: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2537: 	return &select_form($name,$value,\%domains);
1.169     www      2538:     }
                   2539: }
                   2540: 
1.282     albertel 2541: #-------------------------------------------
                   2542: 
                   2543: =pod
                   2544: 
1.519     raeburn  2545: =head1 Routines for form select boxes
                   2546: 
                   2547: =over 4
                   2548: 
1.648     raeburn  2549: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2550: 
                   2551: Returns a string containing a <select> element int multiple mode
                   2552: 
                   2553: 
                   2554: Args:
                   2555:   $name - name of the <select> element
1.506     raeburn  2556:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2557:   $size - number of rows long the select element is
1.283     albertel 2558:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2559:           (shown text should already have been &mt())
1.506     raeburn  2560:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2561: 
1.282     albertel 2562: =cut
                   2563: 
                   2564: #-------------------------------------------
1.169     www      2565: sub multiple_select_form {
1.284     albertel 2566:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2567:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2568:     my $output='';
1.191     matthew  2569:     if (! defined($size)) {
                   2570:         $size = 4;
1.283     albertel 2571:         if (scalar(keys(%$hash))<4) {
                   2572:             $size = scalar(keys(%$hash));
1.191     matthew  2573:         }
                   2574:     }
1.734     bisitz   2575:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2576:     my @order;
1.506     raeburn  2577:     if (ref($order) eq 'ARRAY')  {
                   2578:         @order = @{$order};
                   2579:     } else {
                   2580:         @order = sort(keys(%$hash));
1.501     banghart 2581:     }
                   2582:     if (exists($$hash{'select_form_order'})) {
                   2583:         @order = @{$$hash{'select_form_order'}};
                   2584:     }
                   2585:         
1.284     albertel 2586:     foreach my $key (@order) {
1.356     albertel 2587:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2588:         $output.='selected="selected" ' if ($selected{$key});
                   2589:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2590:     }
                   2591:     $output.="</select>\n";
                   2592:     return $output;
                   2593: }
                   2594: 
1.88      www      2595: #-------------------------------------------
                   2596: 
                   2597: =pod
                   2598: 
1.1254    raeburn  2599: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2600: 
                   2601: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2602: allow a user to select options from a ref to a hash containing:
                   2603: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2604: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2605: An optional arg -- $readonly -- if true will cause the select form
                   2606: to be disabled, e.g., for the case where an instructor has a section-
                   2607: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2608: 
1.88      www      2609: See lonrights.pm for an example invocation and use.
                   2610: 
                   2611: =cut
                   2612: 
                   2613: #-------------------------------------------
                   2614: sub select_form {
1.1228    raeburn  2615:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2616:     return unless (ref($hashref) eq 'HASH');
                   2617:     if ($onchange) {
                   2618:         $onchange = ' onchange="'.$onchange.'"';
                   2619:     }
1.1228    raeburn  2620:     my $disabled;
                   2621:     if ($readonly) {
                   2622:         $disabled = ' disabled="disabled"';
                   2623:     }
                   2624:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2625:     my @keys;
1.970     raeburn  2626:     if (exists($hashref->{'select_form_order'})) {
                   2627: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2628:     } else {
1.970     raeburn  2629: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2630:     }
1.356     albertel 2631:     foreach my $key (@keys) {
                   2632:         $selectform.=
                   2633: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2634:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2635:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2636:     }
                   2637:     $selectform.="</select>";
                   2638:     return $selectform;
                   2639: }
                   2640: 
1.475     www      2641: # For display filters
                   2642: 
                   2643: sub display_filter {
1.1074    raeburn  2644:     my ($context) = @_;
1.475     www      2645:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2646:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2647:     my $phraseinput = 'hidden';
                   2648:     my $includeinput = 'hidden';
                   2649:     my ($checked,$includetypestext);
                   2650:     if ($env{'form.displayfilter'} eq 'containing') {
                   2651:         $phraseinput = 'text'; 
                   2652:         if ($context eq 'parmslog') {
                   2653:             $includeinput = 'checkbox';
                   2654:             if ($env{'form.includetypes'}) {
                   2655:                 $checked = ' checked="checked"';
                   2656:             }
                   2657:             $includetypestext = &mt('Include parameter types');
                   2658:         }
                   2659:     } else {
                   2660:         $includetypestext = '&nbsp;';
                   2661:     }
                   2662:     my ($additional,$secondid,$thirdid);
                   2663:     if ($context eq 'parmslog') {
                   2664:         $additional = 
                   2665:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2666:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2667:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2668:             '</label>';
                   2669:         $secondid = 'includetypes';
                   2670:         $thirdid = 'includetypestext';
                   2671:     }
                   2672:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2673:                                                     '$secondid','$thirdid')";
                   2674:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2675: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2676: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2677: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2678:            &mt('Filter: [_1]',
1.477     www      2679: 	   &select_form($env{'form.displayfilter'},
                   2680: 			'displayfilter',
1.970     raeburn  2681: 			{'currentfolder' => 'Current folder/page',
1.477     www      2682: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2683: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2684: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2685:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2686:                          '" />'.$additional;
                   2687: }
                   2688: 
                   2689: sub display_filter_js {
                   2690:     my $includetext = &mt('Include parameter types');
                   2691:     return <<"ENDJS";
                   2692:   
                   2693: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2694:     var firstType = 'hidden';
                   2695:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2696:         firstType = 'text';
                   2697:     }
                   2698:     firstObject = document.getElementById(firstid);
                   2699:     if (typeof(firstObject) == 'object') {
                   2700:         if (firstObject.type != firstType) {
                   2701:             changeInputType(firstObject,firstType);
                   2702:         }
                   2703:     }
                   2704:     if (context == 'parmslog') {
                   2705:         var secondType = 'hidden';
                   2706:         if (firstType == 'text') {
                   2707:             secondType = 'checkbox';
                   2708:         }
                   2709:         secondObject = document.getElementById(secondid);  
                   2710:         if (typeof(secondObject) == 'object') {
                   2711:             if (secondObject.type != secondType) {
                   2712:                 changeInputType(secondObject,secondType);
                   2713:             }
                   2714:         }
                   2715:         var textItem = document.getElementById(thirdid);
                   2716:         var currtext = textItem.innerHTML;
                   2717:         var newtext;
                   2718:         if (firstType == 'text') {
                   2719:             newtext = '$includetext';
                   2720:         } else {
                   2721:             newtext = '&nbsp;';
                   2722:         }
                   2723:         if (currtext != newtext) {
                   2724:             textItem.innerHTML = newtext;
                   2725:         }
                   2726:     }
                   2727:     return;
                   2728: }
                   2729: 
                   2730: function changeInputType(oldObject,newType) {
                   2731:     var newObject = document.createElement('input');
                   2732:     newObject.type = newType;
                   2733:     if (oldObject.size) {
                   2734:         newObject.size = oldObject.size;
                   2735:     }
                   2736:     if (oldObject.value) {
                   2737:         newObject.value = oldObject.value;
                   2738:     }
                   2739:     if (oldObject.name) {
                   2740:         newObject.name = oldObject.name;
                   2741:     }
                   2742:     if (oldObject.id) {
                   2743:         newObject.id = oldObject.id;
                   2744:     }
                   2745:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2746:     return;
                   2747: }
                   2748: 
                   2749: ENDJS
1.475     www      2750: }
                   2751: 
1.167     www      2752: sub gradeleveldescription {
                   2753:     my $gradelevel=shift;
                   2754:     my %gradelevels=(0 => 'Not specified',
                   2755: 		     1 => 'Grade 1',
                   2756: 		     2 => 'Grade 2',
                   2757: 		     3 => 'Grade 3',
                   2758: 		     4 => 'Grade 4',
                   2759: 		     5 => 'Grade 5',
                   2760: 		     6 => 'Grade 6',
                   2761: 		     7 => 'Grade 7',
                   2762: 		     8 => 'Grade 8',
                   2763: 		     9 => 'Grade 9',
                   2764: 		     10 => 'Grade 10',
                   2765: 		     11 => 'Grade 11',
                   2766: 		     12 => 'Grade 12',
                   2767: 		     13 => 'Grade 13',
                   2768: 		     14 => '100 Level',
                   2769: 		     15 => '200 Level',
                   2770: 		     16 => '300 Level',
                   2771: 		     17 => '400 Level',
                   2772: 		     18 => 'Graduate Level');
                   2773:     return &mt($gradelevels{$gradelevel});
                   2774: }
                   2775: 
1.163     www      2776: sub select_level_form {
                   2777:     my ($deflevel,$name)=@_;
                   2778:     unless ($deflevel) { $deflevel=0; }
1.167     www      2779:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2780:     for (my $i=0; $i<=18; $i++) {
                   2781:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2782:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2783:                 ">".&gradeleveldescription($i)."</option>\n";
                   2784:     }
                   2785:     $selectform.="</select>";
                   2786:     return $selectform;
1.163     www      2787: }
1.167     www      2788: 
1.35      matthew  2789: #-------------------------------------------
                   2790: 
1.45      matthew  2791: =pod
                   2792: 
1.1256    raeburn  2793: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2794: 
                   2795: Returns a string containing a <select name='$name' size='1'> form to 
                   2796: allow a user to select the domain to preform an operation in.  
                   2797: See loncreateuser.pm for an example invocation and use.
                   2798: 
1.90      www      2799: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2800: selected");
                   2801: 
1.743     raeburn  2802: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2803: 
1.910     raeburn  2804: 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.
                   2805: 
1.1121    raeburn  2806: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2807: 
                   2808: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2809: 
1.1256    raeburn  2810: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2811: 
1.35      matthew  2812: =cut
                   2813: 
                   2814: #-------------------------------------------
1.34      matthew  2815: sub select_dom_form {
1.1256    raeburn  2816:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2817:     if ($onchange) {
1.874     raeburn  2818:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2819:     }
1.1256    raeburn  2820:     if ($disabled) {
                   2821:         $disabled = ' disabled="disabled"';
                   2822:     }
1.1121    raeburn  2823:     my (@domains,%exclude);
1.910     raeburn  2824:     if (ref($incdoms) eq 'ARRAY') {
                   2825:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2826:     } else {
                   2827:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2828:     }
1.90      www      2829:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2830:     if (ref($excdoms) eq 'ARRAY') {
                   2831:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2832:     }
1.1256    raeburn  2833:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2834:     foreach my $dom (@domains) {
1.1121    raeburn  2835:         next if ($exclude{$dom});
1.356     albertel 2836:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2837:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2838:         if ($showdomdesc) {
                   2839:             if ($dom ne '') {
                   2840:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2841:                 if ($domdesc ne '') {
                   2842:                     $selectdomain .= ' ('.$domdesc.')';
                   2843:                 }
                   2844:             } 
                   2845:         }
                   2846:         $selectdomain .= "</option>\n";
1.34      matthew  2847:     }
                   2848:     $selectdomain.="</select>";
                   2849:     return $selectdomain;
                   2850: }
                   2851: 
1.35      matthew  2852: #-------------------------------------------
                   2853: 
1.45      matthew  2854: =pod
                   2855: 
1.648     raeburn  2856: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2857: 
1.586     raeburn  2858: input: 4 arguments (two required, two optional) - 
                   2859:     $domain - domain of new user
                   2860:     $name - name of form element
                   2861:     $default - Value of 'default' causes a default item to be first 
                   2862:                             option, and selected by default. 
                   2863:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2864:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2865: output: returns 2 items: 
1.586     raeburn  2866: (a) form element which contains either:
                   2867:    (i) <select name="$name">
                   2868:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2869:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2870:        </select>
                   2871:        form item if there are multiple library servers in $domain, or
                   2872:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2873:        if there is only one library server in $domain.
                   2874: 
                   2875: (b) number of library servers found.
                   2876: 
                   2877: See loncreateuser.pm for example of use.
1.35      matthew  2878: 
                   2879: =cut
                   2880: 
                   2881: #-------------------------------------------
1.586     raeburn  2882: sub home_server_form_item {
                   2883:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2884:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2885:     my $result;
                   2886:     my $numlib = keys(%servers);
                   2887:     if ($numlib > 1) {
                   2888:         $result .= '<select name="'.$name.'" />'."\n";
                   2889:         if ($default) {
1.804     bisitz   2890:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2891:                        '</option>'."\n";
                   2892:         }
                   2893:         foreach my $hostid (sort(keys(%servers))) {
                   2894:             $result.= '<option value="'.$hostid.'">'.
                   2895: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2896:         }
                   2897:         $result .= '</select>'."\n";
                   2898:     } elsif ($numlib == 1) {
                   2899:         my $hostid;
                   2900:         foreach my $item (keys(%servers)) {
                   2901:             $hostid = $item;
                   2902:         }
                   2903:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2904:                    $hostid.'" />';
                   2905:                    if (!$hide) {
                   2906:                        $result .= $hostid.' '.$servers{$hostid};
                   2907:                    }
                   2908:                    $result .= "\n";
                   2909:     } elsif ($default) {
                   2910:         $result .= '<input type="hidden" name="'.$name.
                   2911:                    '" value="default" />';
                   2912:                    if (!$hide) {
                   2913:                        $result .= &mt('default');
                   2914:                    }
                   2915:                    $result .= "\n";
1.33      matthew  2916:     }
1.586     raeburn  2917:     return ($result,$numlib);
1.33      matthew  2918: }
1.112     bowersj2 2919: 
                   2920: =pod
                   2921: 
1.534     albertel 2922: =back 
                   2923: 
1.112     bowersj2 2924: =cut
1.87      matthew  2925: 
                   2926: ###############################################################
1.112     bowersj2 2927: ##                  Decoding User Agent                      ##
1.87      matthew  2928: ###############################################################
                   2929: 
                   2930: =pod
                   2931: 
1.112     bowersj2 2932: =head1 Decoding the User Agent
                   2933: 
                   2934: =over 4
                   2935: 
                   2936: =item * &decode_user_agent()
1.87      matthew  2937: 
                   2938: Inputs: $r
                   2939: 
                   2940: Outputs:
                   2941: 
                   2942: =over 4
                   2943: 
1.112     bowersj2 2944: =item * $httpbrowser
1.87      matthew  2945: 
1.112     bowersj2 2946: =item * $clientbrowser
1.87      matthew  2947: 
1.112     bowersj2 2948: =item * $clientversion
1.87      matthew  2949: 
1.112     bowersj2 2950: =item * $clientmathml
1.87      matthew  2951: 
1.112     bowersj2 2952: =item * $clientunicode
1.87      matthew  2953: 
1.112     bowersj2 2954: =item * $clientos
1.87      matthew  2955: 
1.1137    raeburn  2956: =item * $clientmobile
                   2957: 
1.1141    raeburn  2958: =item * $clientinfo
                   2959: 
1.1194    raeburn  2960: =item * $clientosversion
                   2961: 
1.87      matthew  2962: =back
                   2963: 
1.157     matthew  2964: =back 
                   2965: 
1.87      matthew  2966: =cut
                   2967: 
                   2968: ###############################################################
                   2969: ###############################################################
                   2970: sub decode_user_agent {
1.247     albertel 2971:     my ($r)=@_;
1.87      matthew  2972:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2973:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2974:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2975:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2976:     my $clientbrowser='unknown';
                   2977:     my $clientversion='0';
                   2978:     my $clientmathml='';
                   2979:     my $clientunicode='0';
1.1137    raeburn  2980:     my $clientmobile=0;
1.1194    raeburn  2981:     my $clientosversion='';
1.87      matthew  2982:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2983:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2984: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2985: 	    $clientbrowser=$bname;
                   2986:             $httpbrowser=~/$vreg/i;
                   2987: 	    $clientversion=$1;
                   2988:             $clientmathml=($clientversion>=$minv);
                   2989:             $clientunicode=($clientversion>=$univ);
                   2990: 	}
                   2991:     }
                   2992:     my $clientos='unknown';
1.1141    raeburn  2993:     my $clientinfo;
1.87      matthew  2994:     if (($httpbrowser=~/linux/i) ||
                   2995:         ($httpbrowser=~/unix/i) ||
                   2996:         ($httpbrowser=~/ux/i) ||
                   2997:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2998:     if (($httpbrowser=~/vax/i) ||
                   2999:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3000:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3001:     if (($httpbrowser=~/mac/i) ||
                   3002:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3003:     if ($httpbrowser=~/win/i) {
                   3004:         $clientos='win';
                   3005:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3006:             $clientosversion = $1;
                   3007:         }
                   3008:     }
1.87      matthew  3009:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3010:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3011:         $clientmobile=lc($1);
                   3012:     }
1.1141    raeburn  3013:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3014:         $clientinfo = 'firefox-'.$1;
                   3015:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3016:         $clientinfo = 'chromeframe-'.$1;
                   3017:     }
1.87      matthew  3018:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3019:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3020:             $clientosversion);
1.87      matthew  3021: }
                   3022: 
1.32      matthew  3023: ###############################################################
                   3024: ##    Authentication changing form generation subroutines    ##
                   3025: ###############################################################
                   3026: ##
                   3027: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3028: ## hash, and have reasonable default values.
                   3029: ##
                   3030: ##    formname = the name given in the <form> tag.
1.35      matthew  3031: #-------------------------------------------
                   3032: 
1.45      matthew  3033: =pod
                   3034: 
1.112     bowersj2 3035: =head1 Authentication Routines
                   3036: 
                   3037: =over 4
                   3038: 
1.648     raeburn  3039: =item * &authform_xxxxxx()
1.35      matthew  3040: 
                   3041: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3042: handle some of the conveniences required for authentication forms.  
                   3043: This is not an optimal method, but it works.  
                   3044: 
                   3045: =over 4
                   3046: 
1.112     bowersj2 3047: =item * authform_header
1.35      matthew  3048: 
1.112     bowersj2 3049: =item * authform_authorwarning
1.35      matthew  3050: 
1.112     bowersj2 3051: =item * authform_nochange
1.35      matthew  3052: 
1.112     bowersj2 3053: =item * authform_kerberos
1.35      matthew  3054: 
1.112     bowersj2 3055: =item * authform_internal
1.35      matthew  3056: 
1.112     bowersj2 3057: =item * authform_filesystem
1.35      matthew  3058: 
1.1310    raeburn  3059: =item * authform_lti
                   3060: 
1.35      matthew  3061: =back
                   3062: 
1.648     raeburn  3063: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3064: 
1.35      matthew  3065: =cut
                   3066: 
                   3067: #-------------------------------------------
1.32      matthew  3068: sub authform_header{  
                   3069:     my %in = (
                   3070:         formname => 'cu',
1.80      albertel 3071:         kerb_def_dom => '',
1.32      matthew  3072:         @_,
                   3073:     );
                   3074:     $in{'formname'} = 'document.' . $in{'formname'};
                   3075:     my $result='';
1.80      albertel 3076: 
                   3077: #---------------------------------------------- Code for upper case translation
                   3078:     my $Javascript_toUpperCase;
                   3079:     unless ($in{kerb_def_dom}) {
                   3080:         $Javascript_toUpperCase =<<"END";
                   3081:         switch (choice) {
                   3082:            case 'krb': currentform.elements[choicearg].value =
                   3083:                currentform.elements[choicearg].value.toUpperCase();
                   3084:                break;
                   3085:            default:
                   3086:         }
                   3087: END
                   3088:     } else {
                   3089:         $Javascript_toUpperCase = "";
                   3090:     }
                   3091: 
1.165     raeburn  3092:     my $radioval = "'nochange'";
1.591     raeburn  3093:     if (defined($in{'curr_authtype'})) {
                   3094:         if ($in{'curr_authtype'} ne '') {
                   3095:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3096:         }
1.174     matthew  3097:     }
1.165     raeburn  3098:     my $argfield = 'null';
1.591     raeburn  3099:     if (defined($in{'mode'})) {
1.165     raeburn  3100:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3101:             if (defined($in{'curr_autharg'})) {
                   3102:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3103:                     $argfield = "'$in{'curr_autharg'}'";
                   3104:                 }
                   3105:             }
                   3106:         }
                   3107:     }
                   3108: 
1.32      matthew  3109:     $result.=<<"END";
                   3110: var current = new Object();
1.165     raeburn  3111: current.radiovalue = $radioval;
                   3112: current.argfield = $argfield;
1.32      matthew  3113: 
                   3114: function changed_radio(choice,currentform) {
                   3115:     var choicearg = choice + 'arg';
                   3116:     // If a radio button in changed, we need to change the argfield
                   3117:     if (current.radiovalue != choice) {
                   3118:         current.radiovalue = choice;
                   3119:         if (current.argfield != null) {
                   3120:             currentform.elements[current.argfield].value = '';
                   3121:         }
                   3122:         if (choice == 'nochange') {
                   3123:             current.argfield = null;
                   3124:         } else {
                   3125:             current.argfield = choicearg;
                   3126:             switch(choice) {
                   3127:                 case 'krb': 
                   3128:                     currentform.elements[current.argfield].value = 
                   3129:                         "$in{'kerb_def_dom'}";
                   3130:                 break;
                   3131:               default:
                   3132:                 break;
                   3133:             }
                   3134:         }
                   3135:     }
                   3136:     return;
                   3137: }
1.22      www      3138: 
1.32      matthew  3139: function changed_text(choice,currentform) {
                   3140:     var choicearg = choice + 'arg';
                   3141:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3142:         $Javascript_toUpperCase
1.32      matthew  3143:         // clear old field
                   3144:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3145:             currentform.elements[current.argfield].value = '';
                   3146:         }
                   3147:         current.argfield = choicearg;
                   3148:     }
                   3149:     set_auth_radio_buttons(choice,currentform);
                   3150:     return;
1.20      www      3151: }
1.32      matthew  3152: 
                   3153: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3154:     var numauthchoices = currentform.login.length;
                   3155:     if (typeof numauthchoices  == "undefined") {
                   3156:         return;
                   3157:     } 
1.32      matthew  3158:     var i=0;
1.986     raeburn  3159:     while (i < numauthchoices) {
1.32      matthew  3160:         if (currentform.login[i].value == newvalue) { break; }
                   3161:         i++;
                   3162:     }
1.986     raeburn  3163:     if (i == numauthchoices) {
1.32      matthew  3164:         return;
                   3165:     }
                   3166:     current.radiovalue = newvalue;
                   3167:     currentform.login[i].checked = true;
                   3168:     return;
                   3169: }
                   3170: END
                   3171:     return $result;
                   3172: }
                   3173: 
1.1106    raeburn  3174: sub authform_authorwarning {
1.32      matthew  3175:     my $result='';
1.144     matthew  3176:     $result='<i>'.
                   3177:         &mt('As a general rule, only authors or co-authors should be '.
                   3178:             'filesystem authenticated '.
                   3179:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3180:     return $result;
                   3181: }
                   3182: 
1.1106    raeburn  3183: sub authform_nochange {
1.32      matthew  3184:     my %in = (
                   3185:               formname => 'document.cu',
                   3186:               kerb_def_dom => 'MSU.EDU',
                   3187:               @_,
                   3188:           );
1.1106    raeburn  3189:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3190:     my $result;
1.1104    raeburn  3191:     if (!$authnum) {
1.1105    raeburn  3192:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3193:     } else {
                   3194:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3195:                   '<input type="radio" name="login" value="nochange" '.
                   3196:                   'checked="checked" onclick="'.
1.281     albertel 3197:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3198: 	    '</label>';
1.586     raeburn  3199:     }
1.32      matthew  3200:     return $result;
                   3201: }
                   3202: 
1.591     raeburn  3203: sub authform_kerberos {
1.32      matthew  3204:     my %in = (
                   3205:               formname => 'document.cu',
                   3206:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3207:               kerb_def_auth => 'krb4',
1.32      matthew  3208:               @_,
                   3209:               );
1.586     raeburn  3210:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3211:         $autharg,$jscall,$disabled);
1.1106    raeburn  3212:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3213:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3214:        $check5 = ' checked="checked"';
1.80      albertel 3215:     } else {
1.772     bisitz   3216:        $check4 = ' checked="checked"';
1.80      albertel 3217:     }
1.1259    raeburn  3218:     if ($in{'readonly'}) {
                   3219:         $disabled = ' disabled="disabled"';
                   3220:     }
1.165     raeburn  3221:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3222:     if (defined($in{'curr_authtype'})) {
                   3223:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3224:             $krbcheck = ' checked="checked"';
1.623     raeburn  3225:             if (defined($in{'mode'})) {
                   3226:                 if ($in{'mode'} eq 'modifyuser') {
                   3227:                     $krbcheck = '';
                   3228:                 }
                   3229:             }
1.591     raeburn  3230:             if (defined($in{'curr_kerb_ver'})) {
                   3231:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3232:                     $check5 = ' checked="checked"';
1.591     raeburn  3233:                     $check4 = '';
                   3234:                 } else {
1.772     bisitz   3235:                     $check4 = ' checked="checked"';
1.591     raeburn  3236:                     $check5 = '';
                   3237:                 }
1.586     raeburn  3238:             }
1.591     raeburn  3239:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3240:                 $krbarg = $in{'curr_autharg'};
                   3241:             }
1.586     raeburn  3242:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3243:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3244:                     $result = 
                   3245:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3246:         $in{'curr_autharg'},$krbver);
                   3247:                 } else {
                   3248:                     $result =
                   3249:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3250:                 }
                   3251:                 return $result; 
                   3252:             }
                   3253:         }
                   3254:     } else {
                   3255:         if ($authnum == 1) {
1.784     bisitz   3256:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3257:         }
                   3258:     }
1.586     raeburn  3259:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3260:         return;
1.587     raeburn  3261:     } elsif ($authtype eq '') {
1.591     raeburn  3262:         if (defined($in{'mode'})) {
1.587     raeburn  3263:             if ($in{'mode'} eq 'modifycourse') {
                   3264:                 if ($authnum == 1) {
1.1259    raeburn  3265:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3266:                 }
                   3267:             }
                   3268:         }
1.586     raeburn  3269:     }
                   3270:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3271:     if ($authtype eq '') {
                   3272:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3273:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3274:                     $krbcheck.$disabled.' />';
1.586     raeburn  3275:     }
                   3276:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3277:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3278:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3279:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3280:          $in{'curr_authtype'} eq 'krb4')) {
                   3281:         $result .= &mt
1.144     matthew  3282:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3283:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3284:          '<label>'.$authtype,
1.281     albertel 3285:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3286:              'value="'.$krbarg.'" '.
1.1259    raeburn  3287:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3288:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3289:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3290: 	 '</label>');
1.586     raeburn  3291:     } elsif ($can_assign{'krb4'}) {
                   3292:         $result .= &mt
                   3293:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3294:          '[_3] Version 4 [_4]',
                   3295:          '<label>'.$authtype,
                   3296:          '</label><input type="text" size="10" name="krbarg" '.
                   3297:              'value="'.$krbarg.'" '.
1.1259    raeburn  3298:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3299:          '<label><input type="hidden" name="krbver" value="4" />',
                   3300:          '</label>');
                   3301:     } elsif ($can_assign{'krb5'}) {
                   3302:         $result .= &mt
                   3303:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3304:          '[_3] Version 5 [_4]',
                   3305:          '<label>'.$authtype,
                   3306:          '</label><input type="text" size="10" name="krbarg" '.
                   3307:              'value="'.$krbarg.'" '.
1.1259    raeburn  3308:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3309:          '<label><input type="hidden" name="krbver" value="5" />',
                   3310:          '</label>');
                   3311:     }
1.32      matthew  3312:     return $result;
                   3313: }
                   3314: 
1.1106    raeburn  3315: sub authform_internal {
1.586     raeburn  3316:     my %in = (
1.32      matthew  3317:                 formname => 'document.cu',
                   3318:                 kerb_def_dom => 'MSU.EDU',
                   3319:                 @_,
                   3320:                 );
1.1259    raeburn  3321:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3322:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3323:     if ($in{'readonly'}) {
                   3324:         $disabled = ' disabled="disabled"';
                   3325:     }
1.591     raeburn  3326:     if (defined($in{'curr_authtype'})) {
                   3327:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3328:             if ($can_assign{'int'}) {
1.772     bisitz   3329:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3330:                 if (defined($in{'mode'})) {
                   3331:                     if ($in{'mode'} eq 'modifyuser') {
                   3332:                         $intcheck = '';
                   3333:                     }
                   3334:                 }
1.591     raeburn  3335:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3336:                     $intarg = $in{'curr_autharg'};
                   3337:                 }
                   3338:             } else {
                   3339:                 $result = &mt('Currently internally authenticated.');
                   3340:                 return $result;
1.165     raeburn  3341:             }
                   3342:         }
1.586     raeburn  3343:     } else {
                   3344:         if ($authnum == 1) {
1.784     bisitz   3345:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3346:         }
                   3347:     }
                   3348:     if (!$can_assign{'int'}) {
                   3349:         return;
1.587     raeburn  3350:     } elsif ($authtype eq '') {
1.591     raeburn  3351:         if (defined($in{'mode'})) {
1.587     raeburn  3352:             if ($in{'mode'} eq 'modifycourse') {
                   3353:                 if ($authnum == 1) {
1.1259    raeburn  3354:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3355:                 }
                   3356:             }
                   3357:         }
1.165     raeburn  3358:     }
1.586     raeburn  3359:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3360:     if ($authtype eq '') {
                   3361:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3362:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3363:     }
1.605     bisitz   3364:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3365:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3366:     $result = &mt
1.144     matthew  3367:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3368:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3369:     $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  3370:     return $result;
                   3371: }
                   3372: 
1.1104    raeburn  3373: sub authform_local {
1.32      matthew  3374:     my %in = (
                   3375:               formname => 'document.cu',
                   3376:               kerb_def_dom => 'MSU.EDU',
                   3377:               @_,
                   3378:               );
1.1259    raeburn  3379:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3380:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3381:     if ($in{'readonly'}) {
                   3382:         $disabled = ' disabled="disabled"';
                   3383:     } 
1.591     raeburn  3384:     if (defined($in{'curr_authtype'})) {
                   3385:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3386:             if ($can_assign{'loc'}) {
1.772     bisitz   3387:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3388:                 if (defined($in{'mode'})) {
                   3389:                     if ($in{'mode'} eq 'modifyuser') {
                   3390:                         $loccheck = '';
                   3391:                     }
                   3392:                 }
1.591     raeburn  3393:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3394:                     $locarg = $in{'curr_autharg'};
                   3395:                 }
                   3396:             } else {
                   3397:                 $result = &mt('Currently using local (institutional) authentication.');
                   3398:                 return $result;
1.165     raeburn  3399:             }
                   3400:         }
1.586     raeburn  3401:     } else {
                   3402:         if ($authnum == 1) {
1.784     bisitz   3403:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3404:         }
                   3405:     }
                   3406:     if (!$can_assign{'loc'}) {
                   3407:         return;
1.587     raeburn  3408:     } elsif ($authtype eq '') {
1.591     raeburn  3409:         if (defined($in{'mode'})) {
1.587     raeburn  3410:             if ($in{'mode'} eq 'modifycourse') {
                   3411:                 if ($authnum == 1) {
1.1259    raeburn  3412:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3413:                 }
                   3414:             }
                   3415:         }
1.165     raeburn  3416:     }
1.586     raeburn  3417:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3418:     if ($authtype eq '') {
                   3419:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3420:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3421:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3422:     }
                   3423:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3424:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3425:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3426:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3427:     return $result;
                   3428: }
                   3429: 
1.1106    raeburn  3430: sub authform_filesystem {
1.32      matthew  3431:     my %in = (
                   3432:               formname => 'document.cu',
                   3433:               kerb_def_dom => 'MSU.EDU',
                   3434:               @_,
                   3435:               );
1.1259    raeburn  3436:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3437:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3438:     if ($in{'readonly'}) {
                   3439:         $disabled = ' disabled="disabled"';
                   3440:     }
1.591     raeburn  3441:     if (defined($in{'curr_authtype'})) {
                   3442:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3443:             if ($can_assign{'fsys'}) {
1.772     bisitz   3444:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3445:                 if (defined($in{'mode'})) {
                   3446:                     if ($in{'mode'} eq 'modifyuser') {
                   3447:                         $fsyscheck = '';
                   3448:                     }
                   3449:                 }
1.586     raeburn  3450:             } else {
                   3451:                 $result = &mt('Currently Filesystem Authenticated.');
                   3452:                 return $result;
1.1259    raeburn  3453:             }
1.586     raeburn  3454:         }
                   3455:     } else {
                   3456:         if ($authnum == 1) {
1.784     bisitz   3457:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3458:         }
                   3459:     }
                   3460:     if (!$can_assign{'fsys'}) {
                   3461:         return;
1.587     raeburn  3462:     } elsif ($authtype eq '') {
1.591     raeburn  3463:         if (defined($in{'mode'})) {
1.587     raeburn  3464:             if ($in{'mode'} eq 'modifycourse') {
                   3465:                 if ($authnum == 1) {
1.1259    raeburn  3466:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3467:                 }
                   3468:             }
                   3469:         }
1.586     raeburn  3470:     }
                   3471:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3472:     if ($authtype eq '') {
                   3473:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3474:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3475:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3476:     }
1.1310    raeburn  3477:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3478:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3479:     $result = &mt
1.144     matthew  3480:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3481:          '<label>'.$authtype,'</label>'.$autharg);
                   3482:     return $result;
                   3483: }
                   3484: 
                   3485: sub authform_lti {
                   3486:     my %in = (
                   3487:               formname => 'document.cu',
                   3488:               kerb_def_dom => 'MSU.EDU',
                   3489:               @_,
                   3490:               );
                   3491:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3492:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3493:     if ($in{'readonly'}) {
                   3494:         $disabled = ' disabled="disabled"';
                   3495:     }
                   3496:     if (defined($in{'curr_authtype'})) {
                   3497:         if ($in{'curr_authtype'} eq 'lti') {
                   3498:             if ($can_assign{'lti'}) {
                   3499:                 $lticheck = 'checked="checked" ';
                   3500:                 if (defined($in{'mode'})) {
                   3501:                     if ($in{'mode'} eq 'modifyuser') {
                   3502:                         $lticheck = '';
                   3503:                     }
                   3504:                 }
                   3505:             } else {
                   3506:                 $result = &mt('Currently LTI Authenticated.');
                   3507:                 return $result;
                   3508:             }
                   3509:         }
                   3510:     } else {
                   3511:         if ($authnum == 1) {
                   3512:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3513:         }
                   3514:     }
                   3515:     if (!$can_assign{'lti'}) {
                   3516:         return;
                   3517:     } elsif ($authtype eq '') {
                   3518:         if (defined($in{'mode'})) {
                   3519:             if ($in{'mode'} eq 'modifycourse') {
                   3520:                 if ($authnum == 1) {
                   3521:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3522:                 }
                   3523:             }
                   3524:         }
                   3525:     }
                   3526:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3527:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3528:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3529:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3530:                     $jscall.'"'.$disabled.' />';
                   3531:     }
                   3532:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3533:     if ($authtype) {
                   3534:         $result = &mt('[_1] LTI Authenticated',
                   3535:                       '<label>'.$authtype.'</label>'.$autharg);
                   3536:     } else {
                   3537:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3538:                   $autharg;
                   3539:     }
1.32      matthew  3540:     return $result;
                   3541: }
                   3542: 
1.586     raeburn  3543: sub get_assignable_auth {
                   3544:     my ($dom) = @_;
                   3545:     if ($dom eq '') {
                   3546:         $dom = $env{'request.role.domain'};
                   3547:     }
                   3548:     my %can_assign = (
                   3549:                           krb4 => 1,
                   3550:                           krb5 => 1,
                   3551:                           int  => 1,
                   3552:                           loc  => 1,
1.1310    raeburn  3553:                           lti  => 1,
1.586     raeburn  3554:                      );
                   3555:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3556:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3557:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3558:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3559:             my $context;
                   3560:             if ($env{'request.role'} =~ /^au/) {
                   3561:                 $context = 'author';
1.1259    raeburn  3562:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3563:                 $context = 'domain';
                   3564:             } elsif ($env{'request.course.id'}) {
                   3565:                 $context = 'course';
                   3566:             }
                   3567:             if ($context) {
                   3568:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3569:                    %can_assign = %{$authhash->{$context}}; 
                   3570:                 }
                   3571:             }
                   3572:         }
                   3573:     }
                   3574:     my $authnum = 0;
                   3575:     foreach my $key (keys(%can_assign)) {
                   3576:         if ($can_assign{$key}) {
                   3577:             $authnum ++;
                   3578:         }
                   3579:     }
                   3580:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3581:         $authnum --;
                   3582:     }
                   3583:     return ($authnum,%can_assign);
                   3584: }
                   3585: 
1.1331    raeburn  3586: sub check_passwd_rules {
                   3587:     my ($domain,$plainpass) = @_;
                   3588:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3589:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3590:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3591:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3592:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3593:             if ($passwdconf{'min'} > $min) {
                   3594:                 $min = $passwdconf{'min'};
                   3595:             }
1.1331    raeburn  3596:         }
                   3597:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3598:             $max = $passwdconf{'max'};
                   3599:         }
                   3600:         @chars = @{$passwdconf{'chars'}};
                   3601:     }
                   3602:     if (($min) && (length($plainpass) < $min)) {
                   3603:         push(@brokerule,'min');
                   3604:     }
                   3605:     if (($max) && (length($plainpass) > $max)) {
                   3606:         push(@brokerule,'max');
                   3607:     }
                   3608:     if (@chars) {
                   3609:         my %rules;
                   3610:         map { $rules{$_} = 1; } @chars;
                   3611:         if ($rules{'uc'}) {
                   3612:             unless ($plainpass =~ /[A-Z]/) {
                   3613:                 push(@brokerule,'uc');
                   3614:             }
                   3615:         }
                   3616:         if ($rules{'lc'}) {
1.1332    raeburn  3617:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3618:                 push(@brokerule,'lc');
                   3619:             }
                   3620:         }
                   3621:         if ($rules{'num'}) {
                   3622:             unless ($plainpass =~ /\d/) {
                   3623:                 push(@brokerule,'num');
                   3624:             }
                   3625:         }
                   3626:         if ($rules{'spec'}) {
                   3627:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3628:                 push(@brokerule,'spec');
                   3629:             }
                   3630:         }
                   3631:     }
                   3632:     if (@brokerule) {
                   3633:         my %rulenames = &Apache::lonlocal::texthash(
                   3634:             uc   => 'At least one upper case letter',
                   3635:             lc   => 'At least one lower case letter',
                   3636:             num  => 'At least one number',
                   3637:             spec => 'At least one non-alphanumeric',
                   3638:         );
                   3639:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3640:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3641:         $rulenames{'num'} .= ': 0123456789';
                   3642:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3643:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3644:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3645:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3646:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3647:             if (grep(/^$rule$/,@brokerule)) {
                   3648:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3649:             }
                   3650:         }
                   3651:         $warning .= '</ul>';
                   3652:     }
1.1332    raeburn  3653:     if (wantarray) {
                   3654:         return @brokerule;
                   3655:     }
1.1331    raeburn  3656:     return $warning;
                   3657: }
                   3658: 
1.1376    raeburn  3659: sub passwd_validation_js {
1.1377    raeburn  3660:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3661:     my (%passwdconf,$alertmsg);
                   3662:     if ($context eq 'linkprot') {
                   3663:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3664:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3665:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3666:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3667:             }
                   3668:         }
                   3669:         if ($id eq 'add') {
                   3670:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3671:         } elsif ($id =~ /^\d+$/) {
                   3672:             my $pos = $id+1;
                   3673:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3674:         } else {
                   3675:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3676:         }
                   3677:     } else {
                   3678:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3679:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3680:     }
1.1376    raeburn  3681:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3682:     $numrules = 0;
                   3683:     $min = $Apache::lonnet::passwdmin;
                   3684:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3685:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3686:             if ($passwdconf{'min'} > $min) {
                   3687:                 $min = $passwdconf{'min'};
                   3688:             }
                   3689:         }
                   3690:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3691:             $max = $passwdconf{'max'};
                   3692:             $numrules ++;
                   3693:         }
                   3694:         @chars = @{$passwdconf{'chars'}};
                   3695:         if (@chars) {
                   3696:             $numrules ++;
                   3697:         }
                   3698:     }
                   3699:     if ($min > 0) {
                   3700:         $numrules ++;
                   3701:     }
                   3702:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3703:         if ($min) {
                   3704:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3705:         }
                   3706:         if ($max) {
                   3707:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3708:         }
                   3709:         my (@charalerts,@charrules);
                   3710:         if (@chars) {
                   3711:             if (grep(/^uc$/,@chars)) {
                   3712:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3713:                 push(@charrules,'uc');
                   3714:             }
                   3715:             if (grep(/^lc$/,@chars)) {
                   3716:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3717:                 push(@charrules,'lc');
                   3718:             }
                   3719:             if (grep(/^num$/,@chars)) {
                   3720:                 push(@charalerts,&mt('contain at least one number'));
                   3721:                 push(@charrules,'num');
                   3722:             }
                   3723:             if (grep(/^spec$/,@chars)) {
                   3724:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3725:                 push(@charrules,'spec');
                   3726:             }
                   3727:         }
                   3728:         $intargjs = qq|            var rulesmsg = '';\n|.
                   3729:                     qq|            var currpwval = $currpasswdval;\n|;
                   3730:             if ($min) {
                   3731:                 $intargjs .= qq|
                   3732:             if (currpwval.length < $min) {
                   3733:                 rulesmsg += ' - $alert{min}';
                   3734:             }
                   3735: |;
                   3736:             }
                   3737:             if ($max) {
                   3738:                 $intargjs .= qq|
                   3739:             if (currpwval.length > $max) {
                   3740:                 rulesmsg += ' - $alert{max}';
                   3741:             }
                   3742: |;
                   3743:             }
                   3744:             if (@chars > 0) {
                   3745:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3746:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3747:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3748:                              qq|            var charrules = new Array($charrulestr);\n|.
                   3749:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3750:                 my %rules;
                   3751:                 map { $rules{$_} = 1; } @chars;
                   3752:                 if ($rules{'uc'}) {
                   3753:                     $intargjs .= qq|
                   3754:             var ucRegExp = /[A-Z]/;
                   3755:             if (!ucRegExp.test(currpwval)) {
                   3756:                 brokerules.push('uc');
                   3757:             }
                   3758: |;
                   3759:                 }
                   3760:                 if ($rules{'lc'}) {
                   3761:                     $intargjs .= qq|
                   3762:             var lcRegExp = /[a-z]/;
                   3763:             if (!lcRegExp.test(currpwval)) {
                   3764:                 brokerules.push('lc');
                   3765:             }
                   3766: |;
                   3767:                 }
                   3768:                 if ($rules{'num'}) {
                   3769:                      $intargjs .= qq|
                   3770:             var numRegExp = /[0-9]/;
                   3771:             if (!numRegExp.test(currpwval)) {
                   3772:                 brokerules.push('num');
                   3773:             }
                   3774: |;
                   3775:                 }
                   3776:                 if ($rules{'spec'}) {
                   3777:                      $intargjs .= q|
                   3778:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3779:             if (!specRegExp.test(currpwval)) {
                   3780:                 brokerules.push('spec');
                   3781:             }
                   3782: |;
                   3783:                 }
                   3784:                 $intargjs .= qq|
                   3785:             if (brokerules.length > 0) {
                   3786:                 for (var i=0; i<brokerules.length; i++) {
                   3787:                     for (var j=0; j<charrules.length; j++) {
                   3788:                         if (brokerules[i] == charrules[j]) {
                   3789:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3790:                             break;
                   3791:                         }
                   3792:                     }
                   3793:                 }
                   3794:             }
                   3795: |;
                   3796:             }
                   3797:             $intargjs .= qq|
                   3798:             if (rulesmsg != '') {
                   3799:                 rulesmsg = '$alertmsg'+rulesmsg;
                   3800:                 alert(rulesmsg);
                   3801:                 return false;
                   3802:             }
                   3803: |;
                   3804:     }
                   3805:     return ($numrules,$intargjs);
                   3806: }
                   3807: 
1.80      albertel 3808: ###############################################################
                   3809: ##    Get Kerberos Defaults for Domain                 ##
                   3810: ###############################################################
                   3811: ##
                   3812: ## Returns default kerberos version and an associated argument
                   3813: ## as listed in file domain.tab. If not listed, provides
                   3814: ## appropriate default domain and kerberos version.
                   3815: ##
                   3816: #-------------------------------------------
                   3817: 
                   3818: =pod
                   3819: 
1.648     raeburn  3820: =item * &get_kerberos_defaults()
1.80      albertel 3821: 
                   3822: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3823: version and domain. If not found, it defaults to version 4 and the 
                   3824: domain of the server.
1.80      albertel 3825: 
1.648     raeburn  3826: =over 4
                   3827: 
1.80      albertel 3828: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3829: 
1.648     raeburn  3830: =back
                   3831: 
                   3832: =back
                   3833: 
1.80      albertel 3834: =cut
                   3835: 
                   3836: #-------------------------------------------
                   3837: sub get_kerberos_defaults {
                   3838:     my $domain=shift;
1.641     raeburn  3839:     my ($krbdef,$krbdefdom);
                   3840:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3841:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3842:         $krbdef = $domdefaults{'auth_def'};
                   3843:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3844:     } else {
1.80      albertel 3845:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3846:         my $krbdefdom=$1;
                   3847:         $krbdefdom=~tr/a-z/A-Z/;
                   3848:         $krbdef = "krb4";
                   3849:     }
                   3850:     return ($krbdef,$krbdefdom);
                   3851: }
1.112     bowersj2 3852: 
1.32      matthew  3853: 
1.46      matthew  3854: ###############################################################
                   3855: ##                Thesaurus Functions                        ##
                   3856: ###############################################################
1.20      www      3857: 
1.46      matthew  3858: =pod
1.20      www      3859: 
1.112     bowersj2 3860: =head1 Thesaurus Functions
                   3861: 
                   3862: =over 4
                   3863: 
1.648     raeburn  3864: =item * &initialize_keywords()
1.46      matthew  3865: 
                   3866: Initializes the package variable %Keywords if it is empty.  Uses the
                   3867: package variable $thesaurus_db_file.
                   3868: 
                   3869: =cut
                   3870: 
                   3871: ###################################################
                   3872: 
                   3873: sub initialize_keywords {
                   3874:     return 1 if (scalar keys(%Keywords));
                   3875:     # If we are here, %Keywords is empty, so fill it up
                   3876:     #   Make sure the file we need exists...
                   3877:     if (! -e $thesaurus_db_file) {
                   3878:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3879:                                  " failed because it does not exist");
                   3880:         return 0;
                   3881:     }
                   3882:     #   Set up the hash as a database
                   3883:     my %thesaurus_db;
                   3884:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3885:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3886:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3887:                                  $thesaurus_db_file);
                   3888:         return 0;
                   3889:     } 
                   3890:     #  Get the average number of appearances of a word.
                   3891:     my $avecount = $thesaurus_db{'average.count'};
                   3892:     #  Put keywords (those that appear > average) into %Keywords
                   3893:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3894:         my ($count,undef) = split /:/,$data;
                   3895:         $Keywords{$word}++ if ($count > $avecount);
                   3896:     }
                   3897:     untie %thesaurus_db;
                   3898:     # Remove special values from %Keywords.
1.356     albertel 3899:     foreach my $value ('total.count','average.count') {
                   3900:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3901:   }
1.46      matthew  3902:     return 1;
                   3903: }
                   3904: 
                   3905: ###################################################
                   3906: 
                   3907: =pod
                   3908: 
1.648     raeburn  3909: =item * &keyword($word)
1.46      matthew  3910: 
                   3911: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3912: than the average number of times in the thesaurus database.  Calls 
                   3913: &initialize_keywords
                   3914: 
                   3915: =cut
                   3916: 
                   3917: ###################################################
1.20      www      3918: 
                   3919: sub keyword {
1.46      matthew  3920:     return if (!&initialize_keywords());
                   3921:     my $word=lc(shift());
                   3922:     $word=~s/\W//g;
                   3923:     return exists($Keywords{$word});
1.20      www      3924: }
1.46      matthew  3925: 
                   3926: ###############################################################
                   3927: 
                   3928: =pod 
1.20      www      3929: 
1.648     raeburn  3930: =item * &get_related_words()
1.46      matthew  3931: 
1.160     matthew  3932: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3933: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3934: will be returned.  The order of the words returned is determined by the
                   3935: database which holds them.
                   3936: 
                   3937: Uses global $thesaurus_db_file.
                   3938: 
1.1057    foxr     3939: 
1.46      matthew  3940: =cut
                   3941: 
                   3942: ###############################################################
                   3943: sub get_related_words {
                   3944:     my $keyword = shift;
                   3945:     my %thesaurus_db;
                   3946:     if (! -e $thesaurus_db_file) {
                   3947:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3948:                                  "failed because the file does not exist");
                   3949:         return ();
                   3950:     }
                   3951:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3952:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3953:         return ();
                   3954:     } 
                   3955:     my @Words=();
1.429     www      3956:     my $count=0;
1.46      matthew  3957:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3958: 	# The first element is the number of times
                   3959: 	# the word appears.  We do not need it now.
1.429     www      3960: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3961: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3962: 	my $threshold=$mostfrequentcount/10;
                   3963:         foreach my $possibleword (@RelatedWords) {
                   3964:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3965:             if ($wordcount>$threshold) {
                   3966: 		push(@Words,$word);
                   3967:                 $count++;
                   3968:                 if ($count>10) { last; }
                   3969: 	    }
1.20      www      3970:         }
                   3971:     }
1.46      matthew  3972:     untie %thesaurus_db;
                   3973:     return @Words;
1.14      harris41 3974: }
1.1090    foxr     3975: ###############################################################
                   3976: #
                   3977: #  Spell checking
                   3978: #
                   3979: 
                   3980: =pod
                   3981: 
1.1142    raeburn  3982: =back
                   3983: 
1.1090    foxr     3984: =head1 Spell checking
                   3985: 
                   3986: =over 4
                   3987: 
                   3988: =item * &check_spelling($wordlist $language)
                   3989: 
                   3990: Takes a string containing words and feeds it to an external
                   3991: spellcheck program via a pipeline. Returns a string containing
                   3992: them mis-spelled words.
                   3993: 
                   3994: Parameters:
                   3995: 
                   3996: =over 4
                   3997: 
                   3998: =item - $wordlist
                   3999: 
                   4000: String that will be fed into the spellcheck program.
                   4001: 
                   4002: =item - $language
                   4003: 
                   4004: Language string that specifies the language for which the spell
                   4005: check will be performed.
                   4006: 
                   4007: =back
                   4008: 
                   4009: =back
                   4010: 
                   4011: Note: This sub assumes that aspell is installed.
                   4012: 
                   4013: 
                   4014: =cut
                   4015: 
1.46      matthew  4016: 
1.1090    foxr     4017: sub check_spelling {
                   4018:     my ($wordlist, $language) = @_;
1.1091    foxr     4019:     my @misspellings;
                   4020:     
                   4021:     # Generate the speller and set the langauge.
                   4022:     # if explicitly selected:
1.1090    foxr     4023: 
1.1091    foxr     4024:     my $speller = Text::Aspell->new;
1.1090    foxr     4025:     if ($language) {
1.1091    foxr     4026: 	$speller->set_option('lang', $language);
1.1090    foxr     4027:     }
                   4028: 
1.1091    foxr     4029:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4030: 
1.1091    foxr     4031:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4032: 
1.1091    foxr     4033:     foreach my $word (@words) {
                   4034: 	if(! $speller->check($word)) {
                   4035: 	    push(@misspellings, $word);
1.1090    foxr     4036: 	}
                   4037:     }
1.1091    foxr     4038:     return join(' ', @misspellings);
                   4039:     
1.1090    foxr     4040: }
                   4041: 
1.61      www      4042: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4043: =pod
                   4044: 
1.112     bowersj2 4045: =head1 User Name Functions
                   4046: 
                   4047: =over 4
                   4048: 
1.648     raeburn  4049: =item * &plainname($uname,$udom,$first)
1.81      albertel 4050: 
1.112     bowersj2 4051: Takes a users logon name and returns it as a string in
1.226     albertel 4052: "first middle last generation" form 
                   4053: if $first is set to 'lastname' then it returns it as
                   4054: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4055: 
                   4056: =cut
1.61      www      4057: 
1.295     www      4058: 
1.81      albertel 4059: ###############################################################
1.61      www      4060: sub plainname {
1.226     albertel 4061:     my ($uname,$udom,$first)=@_;
1.537     albertel 4062:     return if (!defined($uname) || !defined($udom));
1.295     www      4063:     my %names=&getnames($uname,$udom);
1.226     albertel 4064:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4065: 					  $names{'middlename'},
                   4066: 					  $names{'lastname'},
                   4067: 					  $names{'generation'},$first);
                   4068:     $name=~s/^\s+//;
1.62      www      4069:     $name=~s/\s+$//;
                   4070:     $name=~s/\s+/ /g;
1.353     albertel 4071:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4072:     return $name;
1.61      www      4073: }
1.66      www      4074: 
                   4075: # -------------------------------------------------------------------- Nickname
1.81      albertel 4076: =pod
                   4077: 
1.648     raeburn  4078: =item * &nickname($uname,$udom)
1.81      albertel 4079: 
                   4080: Gets a users name and returns it as a string as
                   4081: 
                   4082: "&quot;nickname&quot;"
1.66      www      4083: 
1.81      albertel 4084: if the user has a nickname or
                   4085: 
                   4086: "first middle last generation"
                   4087: 
                   4088: if the user does not
                   4089: 
                   4090: =cut
1.66      www      4091: 
                   4092: sub nickname {
                   4093:     my ($uname,$udom)=@_;
1.537     albertel 4094:     return if (!defined($uname) || !defined($udom));
1.295     www      4095:     my %names=&getnames($uname,$udom);
1.68      albertel 4096:     my $name=$names{'nickname'};
1.66      www      4097:     if ($name) {
                   4098:        $name='&quot;'.$name.'&quot;'; 
                   4099:     } else {
                   4100:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4101: 	     $names{'lastname'}.' '.$names{'generation'};
                   4102:        $name=~s/\s+$//;
                   4103:        $name=~s/\s+/ /g;
                   4104:     }
                   4105:     return $name;
                   4106: }
                   4107: 
1.295     www      4108: sub getnames {
                   4109:     my ($uname,$udom)=@_;
1.537     albertel 4110:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4111:     if ($udom eq 'public' && $uname eq 'public') {
                   4112: 	return ('lastname' => &mt('Public'));
                   4113:     }
1.295     www      4114:     my $id=$uname.':'.$udom;
                   4115:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4116:     if ($cached) {
                   4117: 	return %{$names};
                   4118:     } else {
                   4119: 	my %loadnames=&Apache::lonnet::get('environment',
                   4120:                     ['firstname','middlename','lastname','generation','nickname'],
                   4121: 					 $udom,$uname);
                   4122: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4123: 	return %loadnames;
                   4124:     }
                   4125: }
1.61      www      4126: 
1.542     raeburn  4127: # -------------------------------------------------------------------- getemails
1.648     raeburn  4128: 
1.542     raeburn  4129: =pod
                   4130: 
1.648     raeburn  4131: =item * &getemails($uname,$udom)
1.542     raeburn  4132: 
                   4133: Gets a user's email information and returns it as a hash with keys:
                   4134: notification, critnotification, permanentemail
                   4135: 
                   4136: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4137: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4138:  
1.648     raeburn  4139: 
1.542     raeburn  4140: =cut
                   4141: 
1.648     raeburn  4142: 
1.466     albertel 4143: sub getemails {
                   4144:     my ($uname,$udom)=@_;
                   4145:     if ($udom eq 'public' && $uname eq 'public') {
                   4146: 	return;
                   4147:     }
1.467     www      4148:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4149:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4150:     my $id=$uname.':'.$udom;
                   4151:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4152:     if ($cached) {
                   4153: 	return %{$names};
                   4154:     } else {
                   4155: 	my %loadnames=&Apache::lonnet::get('environment',
                   4156:                     			   ['notification','critnotification',
                   4157: 					    'permanentemail'],
                   4158: 					   $udom,$uname);
                   4159: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4160: 	return %loadnames;
                   4161:     }
                   4162: }
                   4163: 
1.551     albertel 4164: sub flush_email_cache {
                   4165:     my ($uname,$udom)=@_;
                   4166:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4167:     if (!$uname) { $uname=$env{'user.name'};   }
                   4168:     return if ($udom eq 'public' && $uname eq 'public');
                   4169:     my $id=$uname.':'.$udom;
                   4170:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4171: }
                   4172: 
1.728     raeburn  4173: # -------------------------------------------------------------------- getlangs
                   4174: 
                   4175: =pod
                   4176: 
                   4177: =item * &getlangs($uname,$udom)
                   4178: 
                   4179: Gets a user's language preference and returns it as a hash with key:
                   4180: language.
                   4181: 
                   4182: =cut
                   4183: 
                   4184: 
                   4185: sub getlangs {
                   4186:     my ($uname,$udom) = @_;
                   4187:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4188:     if (!$uname) { $uname=$env{'user.name'};   }
                   4189:     my $id=$uname.':'.$udom;
                   4190:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4191:     if ($cached) {
                   4192:         return %{$langs};
                   4193:     } else {
                   4194:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4195:                                            $udom,$uname);
                   4196:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4197:         return %loadlangs;
                   4198:     }
                   4199: }
                   4200: 
                   4201: sub flush_langs_cache {
                   4202:     my ($uname,$udom)=@_;
                   4203:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4204:     if (!$uname) { $uname=$env{'user.name'};   }
                   4205:     return if ($udom eq 'public' && $uname eq 'public');
                   4206:     my $id=$uname.':'.$udom;
                   4207:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4208: }
                   4209: 
1.61      www      4210: # ------------------------------------------------------------------ Screenname
1.81      albertel 4211: 
                   4212: =pod
                   4213: 
1.648     raeburn  4214: =item * &screenname($uname,$udom)
1.81      albertel 4215: 
                   4216: Gets a users screenname and returns it as a string
                   4217: 
                   4218: =cut
1.61      www      4219: 
                   4220: sub screenname {
                   4221:     my ($uname,$udom)=@_;
1.258     albertel 4222:     if ($uname eq $env{'user.name'} &&
                   4223: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4224:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4225:     return $names{'screenname'};
1.62      www      4226: }
                   4227: 
1.212     albertel 4228: 
1.802     bisitz   4229: # ------------------------------------------------------------- Confirm Wrapper
                   4230: =pod
                   4231: 
1.1142    raeburn  4232: =item * &confirmwrapper($message)
1.802     bisitz   4233: 
                   4234: Wrap messages about completion of operation in box
                   4235: 
                   4236: =cut
                   4237: 
                   4238: sub confirmwrapper {
                   4239:     my ($message)=@_;
                   4240:     if ($message) {
                   4241:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4242:                .$message."\n"
                   4243:                .'</div>'."\n";
                   4244:     } else {
                   4245:         return $message;
                   4246:     }
                   4247: }
                   4248: 
1.62      www      4249: # ------------------------------------------------------------- Message Wrapper
                   4250: 
                   4251: sub messagewrapper {
1.369     www      4252:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4253:     return 
1.441     albertel 4254:         '<a href="/adm/email?compose=individual&amp;'.
                   4255:         'recname='.$username.'&amp;recdom='.$domain.
                   4256: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4257:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4258: }
1.802     bisitz   4259: 
1.74      www      4260: # --------------------------------------------------------------- Notes Wrapper
                   4261: 
                   4262: sub noteswrapper {
                   4263:     my ($link,$un,$do)=@_;
                   4264:     return 
1.896     amueller 4265: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4266: }
1.802     bisitz   4267: 
1.62      www      4268: # ------------------------------------------------------------- Aboutme Wrapper
                   4269: 
                   4270: sub aboutmewrapper {
1.1070    raeburn  4271:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4272:     if (!defined($username)  && !defined($domain)) {
                   4273:         return;
                   4274:     }
1.1096    raeburn  4275:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4276: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4277: }
                   4278: 
                   4279: # ------------------------------------------------------------ Syllabus Wrapper
                   4280: 
                   4281: sub syllabuswrapper {
1.707     bisitz   4282:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4283:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4284: }
1.14      harris41 4285: 
1.802     bisitz   4286: # -----------------------------------------------------------------------------
                   4287: 
1.208     matthew  4288: sub track_student_link {
1.887     raeburn  4289:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4290:     my $link ="/adm/trackstudent?";
1.208     matthew  4291:     my $title = 'View recent activity';
                   4292:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4293:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4294:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4295:         $title .= ' of this student';
1.268     albertel 4296:     } 
1.208     matthew  4297:     if (defined($target) && $target !~ /^\s*$/) {
                   4298:         $target = qq{target="$target"};
                   4299:     } else {
                   4300:         $target = '';
                   4301:     }
1.268     albertel 4302:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4303:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4304:     $title = &mt($title);
                   4305:     $linktext = &mt($linktext);
1.448     albertel 4306:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4307: 	&help_open_topic('View_recent_activity');
1.208     matthew  4308: }
                   4309: 
1.781     raeburn  4310: sub slot_reservations_link {
                   4311:     my ($linktext,$sname,$sdom,$target) = @_;
                   4312:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4313:     my $title = 'View slot reservation history';
                   4314:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4315:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4316:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4317:         $title .= ' of this student';
                   4318:     }
                   4319:     if (defined($target) && $target !~ /^\s*$/) {
                   4320:         $target = qq{target="$target"};
                   4321:     } else {
                   4322:         $target = '';
                   4323:     }
                   4324:     $title = &mt($title);
                   4325:     $linktext = &mt($linktext);
                   4326:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4327: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4328: 
                   4329: }
                   4330: 
1.508     www      4331: # ===================================================== Display a student photo
                   4332: 
                   4333: 
1.509     albertel 4334: sub student_image_tag {
1.508     www      4335:     my ($domain,$user)=@_;
                   4336:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4337:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4338: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4339:     } else {
                   4340: 	return '';
                   4341:     }
                   4342: }
                   4343: 
1.112     bowersj2 4344: =pod
                   4345: 
                   4346: =back
                   4347: 
                   4348: =head1 Access .tab File Data
                   4349: 
                   4350: =over 4
                   4351: 
1.648     raeburn  4352: =item * &languageids() 
1.112     bowersj2 4353: 
                   4354: returns list of all language ids
                   4355: 
                   4356: =cut
                   4357: 
1.14      harris41 4358: sub languageids {
1.16      harris41 4359:     return sort(keys(%language));
1.14      harris41 4360: }
                   4361: 
1.112     bowersj2 4362: =pod
                   4363: 
1.648     raeburn  4364: =item * &languagedescription() 
1.112     bowersj2 4365: 
                   4366: returns description of a specified language id
                   4367: 
                   4368: =cut
                   4369: 
1.14      harris41 4370: sub languagedescription {
1.125     www      4371:     my $code=shift;
                   4372:     return  ($supported_language{$code}?'* ':'').
                   4373:             $language{$code}.
1.126     www      4374: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4375: }
                   4376: 
1.1048    foxr     4377: =pod
                   4378: 
                   4379: =item * &plainlanguagedescription
                   4380: 
                   4381: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4382: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4383: 
                   4384: =cut
                   4385: 
1.145     www      4386: sub plainlanguagedescription {
                   4387:     my $code=shift;
                   4388:     return $language{$code};
                   4389: }
                   4390: 
1.1048    foxr     4391: =pod
                   4392: 
                   4393: =item * &supportedlanguagecode
                   4394: 
                   4395: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4396: code.
                   4397: 
                   4398: =cut
                   4399: 
1.145     www      4400: sub supportedlanguagecode {
                   4401:     my $code=shift;
                   4402:     return $supported_language{$code};
1.97      www      4403: }
                   4404: 
1.112     bowersj2 4405: =pod
                   4406: 
1.1048    foxr     4407: =item * &latexlanguage()
                   4408: 
                   4409: Given a language key code returns the correspondnig language to use
                   4410: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4411: is no supported hyphenation for the language code.
                   4412: 
                   4413: =cut
                   4414: 
                   4415: sub latexlanguage {
                   4416:     my $code = shift;
                   4417:     return $latex_language{$code};
                   4418: }
                   4419: 
                   4420: =pod
                   4421: 
                   4422: =item * &latexhyphenation()
                   4423: 
                   4424: Same as above but what's supplied is the language as it might be stored
                   4425: in the metadata.
                   4426: 
                   4427: =cut
                   4428: 
                   4429: sub latexhyphenation {
                   4430:     my $key = shift;
                   4431:     return $latex_language_bykey{$key};
                   4432: }
                   4433: 
                   4434: =pod
                   4435: 
1.648     raeburn  4436: =item * &copyrightids() 
1.112     bowersj2 4437: 
                   4438: returns list of all copyrights
                   4439: 
                   4440: =cut
                   4441: 
                   4442: sub copyrightids {
                   4443:     return sort(keys(%cprtag));
                   4444: }
                   4445: 
                   4446: =pod
                   4447: 
1.648     raeburn  4448: =item * &copyrightdescription() 
1.112     bowersj2 4449: 
                   4450: returns description of a specified copyright id
                   4451: 
                   4452: =cut
                   4453: 
                   4454: sub copyrightdescription {
1.166     www      4455:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4456: }
1.197     matthew  4457: 
                   4458: =pod
                   4459: 
1.648     raeburn  4460: =item * &source_copyrightids() 
1.192     taceyjo1 4461: 
                   4462: returns list of all source copyrights
                   4463: 
                   4464: =cut
                   4465: 
                   4466: sub source_copyrightids {
                   4467:     return sort(keys(%scprtag));
                   4468: }
                   4469: 
                   4470: =pod
                   4471: 
1.648     raeburn  4472: =item * &source_copyrightdescription() 
1.192     taceyjo1 4473: 
                   4474: returns description of a specified source copyright id
                   4475: 
                   4476: =cut
                   4477: 
                   4478: sub source_copyrightdescription {
                   4479:     return &mt($scprtag{shift(@_)});
                   4480: }
1.112     bowersj2 4481: 
                   4482: =pod
                   4483: 
1.648     raeburn  4484: =item * &filecategories() 
1.112     bowersj2 4485: 
                   4486: returns list of all file categories
                   4487: 
                   4488: =cut
                   4489: 
                   4490: sub filecategories {
                   4491:     return sort(keys(%category_extensions));
                   4492: }
                   4493: 
                   4494: =pod
                   4495: 
1.648     raeburn  4496: =item * &filecategorytypes() 
1.112     bowersj2 4497: 
                   4498: returns list of file types belonging to a given file
                   4499: category
                   4500: 
                   4501: =cut
                   4502: 
                   4503: sub filecategorytypes {
1.356     albertel 4504:     my ($cat) = @_;
1.1248    raeburn  4505:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4506:         return @{$category_extensions{lc($cat)}};
                   4507:     } else {
                   4508:         return ();
                   4509:     }
1.112     bowersj2 4510: }
                   4511: 
                   4512: =pod
                   4513: 
1.648     raeburn  4514: =item * &fileembstyle() 
1.112     bowersj2 4515: 
                   4516: returns embedding style for a specified file type
                   4517: 
                   4518: =cut
                   4519: 
                   4520: sub fileembstyle {
                   4521:     return $fe{lc(shift(@_))};
1.169     www      4522: }
                   4523: 
1.351     www      4524: sub filemimetype {
                   4525:     return $fm{lc(shift(@_))};
                   4526: }
                   4527: 
1.169     www      4528: 
                   4529: sub filecategoryselect {
                   4530:     my ($name,$value)=@_;
1.189     matthew  4531:     return &select_form($value,$name,
1.970     raeburn  4532:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4533: }
                   4534: 
                   4535: =pod
                   4536: 
1.648     raeburn  4537: =item * &filedescription() 
1.112     bowersj2 4538: 
                   4539: returns description for a specified file type
                   4540: 
                   4541: =cut
                   4542: 
                   4543: sub filedescription {
1.188     matthew  4544:     my $file_description = $fd{lc(shift())};
                   4545:     $file_description =~ s:([\[\]]):~$1:g;
                   4546:     return &mt($file_description);
1.112     bowersj2 4547: }
                   4548: 
                   4549: =pod
                   4550: 
1.648     raeburn  4551: =item * &filedescriptionex() 
1.112     bowersj2 4552: 
                   4553: returns description for a specified file type with
                   4554: extra formatting
                   4555: 
                   4556: =cut
                   4557: 
                   4558: sub filedescriptionex {
                   4559:     my $ex=shift;
1.188     matthew  4560:     my $file_description = $fd{lc($ex)};
                   4561:     $file_description =~ s:([\[\]]):~$1:g;
                   4562:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4563: }
                   4564: 
                   4565: # End of .tab access
                   4566: =pod
                   4567: 
                   4568: =back
                   4569: 
                   4570: =cut
                   4571: 
                   4572: # ------------------------------------------------------------------ File Types
                   4573: sub fileextensions {
                   4574:     return sort(keys(%fe));
                   4575: }
                   4576: 
1.97      www      4577: # ----------------------------------------------------------- Display Languages
                   4578: # returns a hash with all desired display languages
                   4579: #
                   4580: 
                   4581: sub display_languages {
                   4582:     my %languages=();
1.695     raeburn  4583:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4584: 	$languages{$lang}=1;
1.97      www      4585:     }
                   4586:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4587:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4588: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4589: 	    $languages{$lang}=1;
1.97      www      4590:         }
                   4591:     }
                   4592:     return %languages;
1.14      harris41 4593: }
                   4594: 
1.582     albertel 4595: sub languages {
                   4596:     my ($possible_langs) = @_;
1.695     raeburn  4597:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4598:     if (!ref($possible_langs)) {
                   4599: 	if( wantarray ) {
                   4600: 	    return @preferred_langs;
                   4601: 	} else {
                   4602: 	    return $preferred_langs[0];
                   4603: 	}
                   4604:     }
                   4605:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4606:     my @preferred_possibilities;
                   4607:     foreach my $preferred_lang (@preferred_langs) {
                   4608: 	if (exists($possibilities{$preferred_lang})) {
                   4609: 	    push(@preferred_possibilities, $preferred_lang);
                   4610: 	}
                   4611:     }
                   4612:     if( wantarray ) {
                   4613: 	return @preferred_possibilities;
                   4614:     }
                   4615:     return $preferred_possibilities[0];
                   4616: }
                   4617: 
1.742     raeburn  4618: sub user_lang {
                   4619:     my ($touname,$toudom,$fromcid) = @_;
                   4620:     my @userlangs;
                   4621:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4622:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4623:                     $env{'course.'.$fromcid.'.languages'}));
                   4624:     } else {
                   4625:         my %langhash = &getlangs($touname,$toudom);
                   4626:         if ($langhash{'languages'} ne '') {
                   4627:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4628:         } else {
                   4629:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4630:             if ($domdefs{'lang_def'} ne '') {
                   4631:                 @userlangs = ($domdefs{'lang_def'});
                   4632:             }
                   4633:         }
                   4634:     }
                   4635:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4636:     my $user_lh = Apache::localize->get_handle(@languages);
                   4637:     return $user_lh;
                   4638: }
                   4639: 
                   4640: 
1.112     bowersj2 4641: ###############################################################
                   4642: ##               Student Answer Attempts                     ##
                   4643: ###############################################################
                   4644: 
                   4645: =pod
                   4646: 
                   4647: =head1 Alternate Problem Views
                   4648: 
                   4649: =over 4
                   4650: 
1.648     raeburn  4651: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4652:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4653: 
                   4654: Return string with previous attempt on problem. Arguments:
                   4655: 
                   4656: =over 4
                   4657: 
                   4658: =item * $symb: Problem, including path
                   4659: 
                   4660: =item * $username: username of the desired student
                   4661: 
                   4662: =item * $domain: domain of the desired student
1.14      harris41 4663: 
1.112     bowersj2 4664: =item * $course: Course ID
1.14      harris41 4665: 
1.112     bowersj2 4666: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4667:     something
1.14      harris41 4668: 
1.112     bowersj2 4669: =item * $regexp: if string matches this regexp, the string will be
                   4670:     sent to $gradesub
1.14      harris41 4671: 
1.112     bowersj2 4672: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4673: 
1.1199    raeburn  4674: =item * $usec: section of the desired student
                   4675: 
                   4676: =item * $identifier: counter for student (multiple students one problem) or 
                   4677:     problem (one student; whole sequence).
                   4678: 
1.112     bowersj2 4679: =back
1.14      harris41 4680: 
1.112     bowersj2 4681: The output string is a table containing all desired attempts, if any.
1.16      harris41 4682: 
1.112     bowersj2 4683: =cut
1.1       albertel 4684: 
                   4685: sub get_previous_attempt {
1.1199    raeburn  4686:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4687:   my $prevattempts='';
1.43      ng       4688:   no strict 'refs';
1.1       albertel 4689:   if ($symb) {
1.3       albertel 4690:     my (%returnhash)=
                   4691:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4692:     if ($returnhash{'version'}) {
                   4693:       my %lasthash=();
                   4694:       my $version;
                   4695:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4696:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4697:             if ($key =~ /\.rawrndseed$/) {
                   4698:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4699:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4700:             } else {
                   4701:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4702:             }
1.19      harris41 4703:         }
1.1       albertel 4704:       }
1.596     albertel 4705:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4706:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4707:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4708:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4709:       foreach my $key (sort(keys(%lasthash))) {
                   4710: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4711: 	if ($#parts > 0) {
1.31      albertel 4712: 	  my $data=$parts[-1];
1.989     raeburn  4713:           next if ($data eq 'foilorder');
1.31      albertel 4714: 	  pop(@parts);
1.1010    www      4715:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4716:           if ($data eq 'type') {
                   4717:               unless ($showsurv) {
                   4718:                   my $id = join(',',@parts);
                   4719:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4720:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4721:                       $lasthidden{$ign.'.'.$id} = 1;
                   4722:                   }
1.945     raeburn  4723:               }
1.1199    raeburn  4724:               if ($identifier ne '') {
                   4725:                   my $id = join(',',@parts);
                   4726:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4727:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4728:                       $hidestatus{$ign.'.'.$id} = 1;
                   4729:                   }
                   4730:               }
                   4731:           } elsif ($data eq 'regrader') {
                   4732:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4733:                   my $id = join(',',@parts);
                   4734:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4735:               }
1.1010    www      4736:           } 
1.31      albertel 4737: 	} else {
1.41      ng       4738: 	  if ($#parts == 0) {
                   4739: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4740: 	  } else {
                   4741: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4742: 	  }
1.31      albertel 4743: 	}
1.16      harris41 4744:       }
1.596     albertel 4745:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4746:       if ($getattempt eq '') {
1.1199    raeburn  4747:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4748:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4749:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4750:                 foreach my $id (keys(%regraded)) {
                   4751:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4752:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4753:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4754:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4755:                     }
                   4756:                 }
                   4757:             }
1.1200    raeburn  4758:         }
                   4759: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4760:             my (@hidden,@unsolved);
1.945     raeburn  4761:             if (%typeparts) {
                   4762:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4763:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4764:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4765:                         push(@hidden,$id);
1.1199    raeburn  4766:                     } elsif ($identifier ne '') {
                   4767:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4768:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4769:                                 ($hidestatus{$id})) {
1.1200    raeburn  4770:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4771:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4772:                                 push(@{$solved{$id}},$version);
                   4773:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4774:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4775:                                 my $skip;
                   4776:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4777:                                     foreach my $reset (@{$resets{$id}}) {
                   4778:                                         if ($reset > $solved{$id}[-1]) {
                   4779:                                             $skip=1;
                   4780:                                             last;
                   4781:                                         }
                   4782:                                     }
                   4783:                                 }
                   4784:                                 unless ($skip) {
                   4785:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4786:                                     push(@unsolved,$partslist);
                   4787:                                 }
                   4788:                             }
                   4789:                         }
1.945     raeburn  4790:                     }
                   4791:                 }
                   4792:             }
                   4793:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4794:                            '<td>'.&mt('Transaction [_1]',$version);
                   4795:             if (@unsolved) {
                   4796:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4797:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4798:                                  &mt('Hide').'</label></span>';
                   4799:             }
                   4800:             $prevattempts .= '</td>';
1.945     raeburn  4801:             if (@hidden) {
                   4802:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4803:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4804:                     my $hide;
                   4805:                     foreach my $id (@hidden) {
                   4806:                         if ($key =~ /^\Q$id\E/) {
                   4807:                             $hide = 1;
                   4808:                             last;
                   4809:                         }
                   4810:                     }
                   4811:                     if ($hide) {
                   4812:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4813:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4814:                             my $value = &format_previous_attempt_value($key,
                   4815:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4816:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4817:                         } else {
                   4818:                             $prevattempts.='<td>&nbsp;</td>';
                   4819:                         }
                   4820:                     } else {
                   4821:                         if ($key =~ /\./) {
1.1212    raeburn  4822:                             my $value = $returnhash{$version.':'.$key};
                   4823:                             if ($key =~ /\.rndseed$/) {
                   4824:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4825:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4826:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4827:                                 }
                   4828:                             }
                   4829:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4830:                                            '&nbsp;</td>';
1.945     raeburn  4831:                         } else {
                   4832:                             $prevattempts.='<td>&nbsp;</td>';
                   4833:                         }
                   4834:                     }
                   4835:                 }
                   4836:             } else {
                   4837: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4838:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4839:                     my $value = $returnhash{$version.':'.$key};
                   4840:                     if ($key =~ /\.rndseed$/) {
                   4841:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4842:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4843:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4844:                         }
                   4845:                     }
                   4846:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4847:                                    '&nbsp;</td>';
1.945     raeburn  4848: 	        }
                   4849:             }
                   4850: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4851: 	 }
1.1       albertel 4852:       }
1.945     raeburn  4853:       my @currhidden = keys(%lasthidden);
1.596     albertel 4854:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4855:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4856:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4857:           if (%typeparts) {
                   4858:               my $hidden;
                   4859:               foreach my $id (@currhidden) {
                   4860:                   if ($key =~ /^\Q$id\E/) {
                   4861:                       $hidden = 1;
                   4862:                       last;
                   4863:                   }
                   4864:               }
                   4865:               if ($hidden) {
                   4866:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4867:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4868:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4869:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4870:                           $value = &$gradesub($value);
                   4871:                       }
1.1173    kruse    4872:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4873:                   } else {
                   4874:                       $prevattempts.='<td>&nbsp;</td>';
                   4875:                   }
                   4876:               } else {
                   4877:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4878:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4879:                       $value = &$gradesub($value);
                   4880:                   }
1.1173    kruse    4881:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4882:               }
                   4883:           } else {
                   4884: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4885: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4886:                   $value = &$gradesub($value);
                   4887:               }
1.1173    kruse    4888: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4889:           }
1.16      harris41 4890:       }
1.596     albertel 4891:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4892:     } else {
1.1305    raeburn  4893:       my $msg;
                   4894:       if ($symb =~ /ext\.tool$/) {
                   4895:           $msg = &mt('No grade passed back.');
                   4896:       } else {
                   4897:           $msg = &mt('Nothing submitted - no attempts.');
                   4898:       }
1.596     albertel 4899:       $prevattempts=
                   4900: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4901: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4902: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4903:     }
                   4904:   } else {
1.596     albertel 4905:     $prevattempts=
                   4906: 	  &start_data_table().&start_data_table_row().
                   4907: 	  '<td>'.&mt('No data.').'</td>'.
                   4908: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4909:   }
1.10      albertel 4910: }
                   4911: 
1.581     albertel 4912: sub format_previous_attempt_value {
                   4913:     my ($key,$value) = @_;
1.1011    www      4914:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4915:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4916:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4917:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4918:     } elsif ($key =~ /answerstring$/) {
                   4919:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4920:         my @answer = %answers;
                   4921:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4922:         my @anskeys = sort(keys(%answers));
                   4923:         if (@anskeys == 1) {
                   4924:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4925:             if ($answer =~ m{\0}) {
                   4926:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4927:             }
                   4928:             my $tag_internal_answer_name = 'INTERNAL';
                   4929:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4930:                 $value = $answer; 
                   4931:             } else {
                   4932:                 $value = $anskeys[0].'='.$answer;
                   4933:             }
                   4934:         } else {
                   4935:             foreach my $ans (@anskeys) {
                   4936:                 my $answer = $answers{$ans};
1.1001    raeburn  4937:                 if ($answer =~ m{\0}) {
                   4938:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4939:                 }
                   4940:                 $value .=  $ans.'='.$answer.'<br />';;
                   4941:             } 
                   4942:         }
1.581     albertel 4943:     } else {
1.1173    kruse    4944:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4945:     }
                   4946:     return $value;
                   4947: }
                   4948: 
                   4949: 
1.107     albertel 4950: sub relative_to_absolute {
                   4951:     my ($url,$output)=@_;
                   4952:     my $parser=HTML::TokeParser->new(\$output);
                   4953:     my $token;
                   4954:     my $thisdir=$url;
                   4955:     my @rlinks=();
                   4956:     while ($token=$parser->get_token) {
                   4957: 	if ($token->[0] eq 'S') {
                   4958: 	    if ($token->[1] eq 'a') {
                   4959: 		if ($token->[2]->{'href'}) {
                   4960: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4961: 		}
                   4962: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4963: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4964: 	    } elsif ($token->[1] eq 'base') {
                   4965: 		$thisdir=$token->[2]->{'href'};
                   4966: 	    }
                   4967: 	}
                   4968:     }
                   4969:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4970:     foreach my $link (@rlinks) {
1.726     raeburn  4971: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4972: 		($link=~/^\//) ||
                   4973: 		($link=~/^javascript:/i) ||
                   4974: 		($link=~/^mailto:/i) ||
                   4975: 		($link=~/^\#/)) {
                   4976: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4977: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4978: 	}
                   4979:     }
                   4980: # -------------------------------------------------- Deal with Applet codebases
                   4981:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4982:     return $output;
                   4983: }
                   4984: 
1.112     bowersj2 4985: =pod
                   4986: 
1.648     raeburn  4987: =item * &get_student_view()
1.112     bowersj2 4988: 
                   4989: show a snapshot of what student was looking at
                   4990: 
                   4991: =cut
                   4992: 
1.10      albertel 4993: sub get_student_view {
1.186     albertel 4994:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4995:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4996:   my (%form);
1.10      albertel 4997:   my @elements=('symb','courseid','domain','username');
                   4998:   foreach my $element (@elements) {
1.186     albertel 4999:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5000:   }
1.186     albertel 5001:   if (defined($moreenv)) {
                   5002:       %form=(%form,%{$moreenv});
                   5003:   }
1.236     albertel 5004:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5005:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5006:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5007:       $feedurl =~ s{^/adm/wrapper}{};
                   5008:   }
1.650     www      5009:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5010:   $userview=~s/\<body[^\>]*\>//gi;
                   5011:   $userview=~s/\<\/body\>//gi;
                   5012:   $userview=~s/\<html\>//gi;
                   5013:   $userview=~s/\<\/html\>//gi;
                   5014:   $userview=~s/\<head\>//gi;
                   5015:   $userview=~s/\<\/head\>//gi;
                   5016:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5017:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5018:   if (wantarray) {
                   5019:      return ($userview,$response);
                   5020:   } else {
                   5021:      return $userview;
                   5022:   }
                   5023: }
                   5024: 
                   5025: sub get_student_view_with_retries {
                   5026:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5027: 
                   5028:     my $ok = 0;                 # True if we got a good response.
                   5029:     my $content;
                   5030:     my $response;
                   5031: 
                   5032:     # Try to get the student_view done. within the retries count:
                   5033:     
                   5034:     do {
                   5035:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5036:          $ok      = $response->is_success;
                   5037:          if (!$ok) {
                   5038:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5039:          }
                   5040:          $retries--;
                   5041:     } while (!$ok && ($retries > 0));
                   5042:     
                   5043:     if (!$ok) {
                   5044:        $content = '';          # On error return an empty content.
                   5045:     }
1.651     www      5046:     if (wantarray) {
                   5047:        return ($content, $response);
                   5048:     } else {
                   5049:        return $content;
                   5050:     }
1.11      albertel 5051: }
                   5052: 
1.1349    raeburn  5053: sub css_links {
                   5054:     my ($currsymb,$level) = @_;
                   5055:     my ($links,@symbs,%cssrefs,%httpref);
                   5056:     if ($level eq 'map') {
                   5057:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5058:         if (ref($navmap)) {
                   5059:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5060:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5061:             foreach my $res (@resources) {
                   5062:                 if (ref($res) && $res->symb()) {
                   5063:                     push(@symbs,$res->symb());
                   5064:                 }
                   5065:             }
                   5066:         }
                   5067:     } else {
                   5068:         @symbs = ($currsymb);
                   5069:     }
                   5070:     foreach my $symb (@symbs) {
                   5071:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5072:         if ($css_href =~ /\S/) {
                   5073:             unless ($css_href =~ m{https?://}) {
                   5074:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5075:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5076:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5077:                 unless ($css_href =~ m{^/}) {
                   5078:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5079:                 }
                   5080:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5081:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5082:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5083:                         my $thisurl = $proburl;
                   5084:                         if ($env{'httpref.'.$proburl}) {
                   5085:                             $thisurl = $env{'httpref.'.$proburl};
                   5086:                         }
                   5087:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5088:                     }
                   5089:                 }
                   5090:             }
                   5091:             $cssrefs{$css_href} = 1;
                   5092:         }
                   5093:     }
                   5094:     if (keys(%httpref)) {
                   5095:         &Apache::lonnet::appenv(\%httpref);
                   5096:     }
                   5097:     if (keys(%cssrefs)) {
                   5098:         foreach my $css_href (keys(%cssrefs)) {
                   5099:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5100:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5101:         }
                   5102:     }
                   5103:     return $links;
                   5104: }
                   5105: 
1.112     bowersj2 5106: =pod
                   5107: 
1.648     raeburn  5108: =item * &get_student_answers() 
1.112     bowersj2 5109: 
                   5110: show a snapshot of how student was answering problem
                   5111: 
                   5112: =cut
                   5113: 
1.11      albertel 5114: sub get_student_answers {
1.100     sakharuk 5115:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5116:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5117:   my (%moreenv);
1.11      albertel 5118:   my @elements=('symb','courseid','domain','username');
                   5119:   foreach my $element (@elements) {
1.186     albertel 5120:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5121:   }
1.186     albertel 5122:   $moreenv{'grade_target'}='answer';
                   5123:   %moreenv=(%form,%moreenv);
1.497     raeburn  5124:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5125:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5126:   return $userview;
1.1       albertel 5127: }
1.116     albertel 5128: 
                   5129: =pod
                   5130: 
                   5131: =item * &submlink()
                   5132: 
1.242     albertel 5133: Inputs: $text $uname $udom $symb $target
1.116     albertel 5134: 
                   5135: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5136: 
                   5137: =cut
                   5138: 
                   5139: ###############################################
                   5140: sub submlink {
1.242     albertel 5141:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5142:     if (!($uname && $udom)) {
                   5143: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5144: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5145: 	if (!$symb) { $symb=$cursymb; }
                   5146:     }
1.254     matthew  5147:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5148:     $symb=&escape($symb);
1.960     bisitz   5149:     if ($target) { $target=" target=\"$target\""; }
                   5150:     return
                   5151:         '<a href="/adm/grades?command=submission'.
                   5152:         '&amp;symb='.$symb.
                   5153:         '&amp;student='.$uname.
                   5154:         '&amp;userdom='.$udom.'"'.
                   5155:         $target.'>'.$text.'</a>';
1.242     albertel 5156: }
                   5157: ##############################################
                   5158: 
                   5159: =pod
                   5160: 
                   5161: =item * &pgrdlink()
                   5162: 
                   5163: Inputs: $text $uname $udom $symb $target
                   5164: 
                   5165: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5166: 
                   5167: =cut
                   5168: 
                   5169: ###############################################
                   5170: sub pgrdlink {
                   5171:     my $link=&submlink(@_);
                   5172:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5173:     return $link;
                   5174: }
                   5175: ##############################################
                   5176: 
                   5177: =pod
                   5178: 
                   5179: =item * &pprmlink()
                   5180: 
                   5181: Inputs: $text $uname $udom $symb $target
                   5182: 
                   5183: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5184: student and a specific resource
1.242     albertel 5185: 
                   5186: =cut
                   5187: 
                   5188: ###############################################
                   5189: sub pprmlink {
                   5190:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5191:     if (!($uname && $udom)) {
                   5192: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5193: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5194: 	if (!$symb) { $symb=$cursymb; }
                   5195:     }
1.254     matthew  5196:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5197:     $symb=&escape($symb);
1.242     albertel 5198:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5199:     return '<a href="/adm/parmset?command=set&amp;'.
                   5200: 	'symb='.$symb.'&amp;uname='.$uname.
                   5201: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5202: }
                   5203: ##############################################
1.37      matthew  5204: 
1.112     bowersj2 5205: =pod
                   5206: 
                   5207: =back
                   5208: 
                   5209: =cut
                   5210: 
1.37      matthew  5211: ###############################################
1.51      www      5212: 
                   5213: 
                   5214: sub timehash {
1.687     raeburn  5215:     my ($thistime) = @_;
                   5216:     my $timezone = &Apache::lonlocal::gettimezone();
                   5217:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5218:                      ->set_time_zone($timezone);
                   5219:     my $wday = $dt->day_of_week();
                   5220:     if ($wday == 7) { $wday = 0; }
                   5221:     return ( 'second' => $dt->second(),
                   5222:              'minute' => $dt->minute(),
                   5223:              'hour'   => $dt->hour(),
                   5224:              'day'     => $dt->day_of_month(),
                   5225:              'month'   => $dt->month(),
                   5226:              'year'    => $dt->year(),
                   5227:              'weekday' => $wday,
                   5228:              'dayyear' => $dt->day_of_year(),
                   5229:              'dlsav'   => $dt->is_dst() );
1.51      www      5230: }
                   5231: 
1.370     www      5232: sub utc_string {
                   5233:     my ($date)=@_;
1.371     www      5234:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5235: }
                   5236: 
1.51      www      5237: sub maketime {
                   5238:     my %th=@_;
1.687     raeburn  5239:     my ($epoch_time,$timezone,$dt);
                   5240:     $timezone = &Apache::lonlocal::gettimezone();
                   5241:     eval {
                   5242:         $dt = DateTime->new( year   => $th{'year'},
                   5243:                              month  => $th{'month'},
                   5244:                              day    => $th{'day'},
                   5245:                              hour   => $th{'hour'},
                   5246:                              minute => $th{'minute'},
                   5247:                              second => $th{'second'},
                   5248:                              time_zone => $timezone,
                   5249:                          );
                   5250:     };
                   5251:     if (!$@) {
                   5252:         $epoch_time = $dt->epoch;
                   5253:         if ($epoch_time) {
                   5254:             return $epoch_time;
                   5255:         }
                   5256:     }
1.51      www      5257:     return POSIX::mktime(
                   5258:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5259:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5260: }
                   5261: 
                   5262: #########################################
1.51      www      5263: 
                   5264: sub findallcourses {
1.482     raeburn  5265:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5266:     my %roles;
                   5267:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5268:     my %courses;
1.51      www      5269:     my $now=time;
1.482     raeburn  5270:     if (!defined($uname)) {
                   5271:         $uname = $env{'user.name'};
                   5272:     }
                   5273:     if (!defined($udom)) {
                   5274:         $udom = $env{'user.domain'};
                   5275:     }
                   5276:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5277:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5278:         if (!%roles) {
                   5279:             %roles = (
                   5280:                        cc => 1,
1.907     raeburn  5281:                        co => 1,
1.482     raeburn  5282:                        in => 1,
                   5283:                        ep => 1,
                   5284:                        ta => 1,
                   5285:                        cr => 1,
                   5286:                        st => 1,
                   5287:              );
                   5288:         }
                   5289:         foreach my $entry (keys(%roleshash)) {
                   5290:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5291:             if ($trole =~ /^cr/) { 
                   5292:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5293:             } else {
                   5294:                 next if (!exists($roles{$trole}));
                   5295:             }
                   5296:             if ($tend) {
                   5297:                 next if ($tend < $now);
                   5298:             }
                   5299:             if ($tstart) {
                   5300:                 next if ($tstart > $now);
                   5301:             }
1.1058    raeburn  5302:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5303:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5304:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5305:             if ($secpart eq '') {
                   5306:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5307:                 $sec = 'none';
1.1058    raeburn  5308:                 $value .= $cnum.'/';
1.482     raeburn  5309:             } else {
                   5310:                 $cnum = $cnumpart;
                   5311:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5312:                 $value .= $cnum.'/'.$sec;
                   5313:             }
                   5314:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5315:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5316:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5317:                 }
                   5318:             } else {
                   5319:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5320:             }
1.482     raeburn  5321:         }
                   5322:     } else {
                   5323:         foreach my $key (keys(%env)) {
1.483     albertel 5324: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5325:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5326: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5327: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5328: 	        next if (%roles && !exists($roles{$role}));
                   5329: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5330:                 my $active=1;
                   5331:                 if ($starttime) {
                   5332: 		    if ($now<$starttime) { $active=0; }
                   5333:                 }
                   5334:                 if ($endtime) {
                   5335:                     if ($now>$endtime) { $active=0; }
                   5336:                 }
                   5337:                 if ($active) {
1.1058    raeburn  5338:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5339:                     if ($sec eq '') {
                   5340:                         $sec = 'none';
1.1058    raeburn  5341:                     } else {
                   5342:                         $value .= $sec;
                   5343:                     }
                   5344:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5345:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5346:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5347:                         }
                   5348:                     } else {
                   5349:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5350:                     }
1.474     raeburn  5351:                 }
                   5352:             }
1.51      www      5353:         }
                   5354:     }
1.474     raeburn  5355:     return %courses;
1.51      www      5356: }
1.37      matthew  5357: 
1.54      www      5358: ###############################################
1.474     raeburn  5359: 
                   5360: sub blockcheck {
1.1372    raeburn  5361:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5362:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5363:         my ($has_evb,$check_ipaccess);
                   5364:         my $dom = $env{'user.domain'};
                   5365:         if ($env{'request.course.id'}) {
                   5366:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5367:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5368:             my $checkrole = "cm./$cdom/$cnum";
                   5369:             my $sec = $env{'request.course.sec'};
                   5370:             if ($sec ne '') {
                   5371:                 $checkrole .= "/$sec";
                   5372:             }
                   5373:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5374:                 ($env{'request.role'} !~ /^st/)) {
                   5375:                 $has_evb = 1;
                   5376:             }
                   5377:             unless ($has_evb) {
                   5378:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5379:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5380:                     if ($udom eq $cdom) {
                   5381:                         $check_ipaccess = 1;
                   5382:                     }
                   5383:                 }
                   5384:             }
1.1375    raeburn  5385:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5386:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5387:             my $checkrole;
                   5388:             if ($env{'request.role.domain'} eq '') {
                   5389:                 $checkrole = "cm./$env{'user.domain'}/";
                   5390:             } else {
                   5391:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5392:             }
                   5393:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5394:                 $has_evb = 1;
                   5395:             }
1.1372    raeburn  5396:         }
                   5397:         unless ($has_evb || $check_ipaccess) {
                   5398:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5399:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5400:                 $dom = $udom;
                   5401:             }
                   5402:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5403:                 $check_ipaccess = 1;
                   5404:             } else {
                   5405:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5406:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5407:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5408:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5409:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5410:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5411:                         $check_ipaccess = 1;
                   5412:                     }
                   5413:                 }
                   5414:             }
                   5415:         }
                   5416:         if ($check_ipaccess) {
                   5417:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5418:             unless (defined($cached)) {
                   5419:                 my %domconfig =
                   5420:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5421:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5422:             }
                   5423:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5424:                 foreach my $id (keys(%{$ipaccessref})) {
                   5425:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5426:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5427:                         if ($range) {
                   5428:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5429:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5430:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5431:                                         return ('','','',$id,$dom);
                   5432:                                         last;
                   5433:                                     }
                   5434:                                 }
                   5435:                             }
                   5436:                         }
                   5437:                     }
                   5438:                 }
                   5439:             }
                   5440:         }
1.1373    raeburn  5441:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5442:             return ();
                   5443:         }
1.1372    raeburn  5444:     }
1.1189    raeburn  5445:     if (defined($udom) && defined($uname)) {
                   5446:         # If uname and udom are for a course, check for blocks in the course.
                   5447:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5448:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5449:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5450:             return ($startblock,$endblock,$triggerblock);
                   5451:         }
                   5452:     } else {
1.490     raeburn  5453:         $udom = $env{'user.domain'};
                   5454:         $uname = $env{'user.name'};
                   5455:     }
                   5456: 
1.502     raeburn  5457:     my $startblock = 0;
                   5458:     my $endblock = 0;
1.1062    raeburn  5459:     my $triggerblock = '';
1.1373    raeburn  5460:     my %live_courses;
                   5461:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5462:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5463:     }
1.474     raeburn  5464: 
1.490     raeburn  5465:     # If uname is for a user, and activity is course-specific, i.e.,
                   5466:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5467: 
1.490     raeburn  5468:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5469:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5470:          $activity eq 'search' || $activity eq 'reinit' ||
                   5471:          $activity eq 'alert') &&
1.1189    raeburn  5472:         ($env{'request.course.id'})) {
1.490     raeburn  5473:         foreach my $key (keys(%live_courses)) {
                   5474:             if ($key ne $env{'request.course.id'}) {
                   5475:                 delete($live_courses{$key});
                   5476:             }
                   5477:         }
                   5478:     }
                   5479: 
                   5480:     my $otheruser = 0;
                   5481:     my %own_courses;
                   5482:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5483:         # Resource belongs to user other than current user.
                   5484:         $otheruser = 1;
                   5485:         # Gather courses for current user
                   5486:         %own_courses = 
                   5487:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5488:     }
                   5489: 
                   5490:     # Gather active course roles - course coordinator, instructor, 
                   5491:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5492: 
                   5493:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5494:         my ($cdom,$cnum);
                   5495:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5496:             $cdom = $env{'course.'.$course.'.domain'};
                   5497:             $cnum = $env{'course.'.$course.'.num'};
                   5498:         } else {
1.490     raeburn  5499:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5500:         }
                   5501:         my $no_ownblock = 0;
                   5502:         my $no_userblock = 0;
1.533     raeburn  5503:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5504:             # Check if current user has 'evb' priv for this
                   5505:             if (defined($own_courses{$course})) {
                   5506:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5507:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5508:                     if ($sec ne 'none') {
                   5509:                         $checkrole .= '/'.$sec;
                   5510:                     }
                   5511:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5512:                         $no_ownblock = 1;
                   5513:                         last;
                   5514:                     }
                   5515:                 }
                   5516:             }
                   5517:             # if they have 'evb' priv and are currently not playing student
                   5518:             next if (($no_ownblock) &&
                   5519:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5520:         }
1.474     raeburn  5521:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5522:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5523:             if ($sec ne 'none') {
1.482     raeburn  5524:                 $checkrole .= '/'.$sec;
1.474     raeburn  5525:             }
1.490     raeburn  5526:             if ($otheruser) {
                   5527:                 # Resource belongs to user other than current user.
                   5528:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5529:                 my (%allroles,%userroles);
                   5530:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5531:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5532:                         my ($trole,$tdom,$tnum,$tsec);
                   5533:                         if ($entry =~ /^cr/) {
                   5534:                             ($trole,$tdom,$tnum,$tsec) = 
                   5535:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5536:                         } else {
                   5537:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5538:                         }
                   5539:                         my ($spec,$area,$trest);
                   5540:                         $area = '/'.$tdom.'/'.$tnum;
                   5541:                         $trest = $tnum;
                   5542:                         if ($tsec ne '') {
                   5543:                             $area .= '/'.$tsec;
                   5544:                             $trest .= '/'.$tsec;
                   5545:                         }
                   5546:                         $spec = $trole.'.'.$area;
                   5547:                         if ($trole =~ /^cr/) {
                   5548:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5549:                                                               $tdom,$spec,$trest,$area);
                   5550:                         } else {
                   5551:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5552:                                                                 $tdom,$spec,$trest,$area);
                   5553:                         }
                   5554:                     }
1.1276    raeburn  5555:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5556:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5557:                         if ($1) {
                   5558:                             $no_userblock = 1;
                   5559:                             last;
                   5560:                         }
1.486     raeburn  5561:                     }
                   5562:                 }
1.490     raeburn  5563:             } else {
                   5564:                 # Resource belongs to current user
                   5565:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5566:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5567:                     $no_ownblock = 1;
                   5568:                     last;
                   5569:                 }
1.474     raeburn  5570:             }
                   5571:         }
                   5572:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5573:         next if (($no_ownblock) &&
1.491     albertel 5574:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5575:         next if ($no_userblock);
1.474     raeburn  5576: 
1.1303    raeburn  5577:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5578:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5579: 
1.1062    raeburn  5580:         my ($start,$end,$trigger) = 
1.1347    raeburn  5581:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5582:         if (($start != 0) && 
                   5583:             (($startblock == 0) || ($startblock > $start))) {
                   5584:             $startblock = $start;
1.1062    raeburn  5585:             if ($trigger ne '') {
                   5586:                 $triggerblock = $trigger;
                   5587:             }
1.502     raeburn  5588:         }
                   5589:         if (($end != 0)  &&
                   5590:             (($endblock == 0) || ($endblock < $end))) {
                   5591:             $endblock = $end;
1.1062    raeburn  5592:             if ($trigger ne '') {
                   5593:                 $triggerblock = $trigger;
                   5594:             }
1.502     raeburn  5595:         }
1.490     raeburn  5596:     }
1.1062    raeburn  5597:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5598: }
                   5599: 
                   5600: sub get_blocks {
1.1347    raeburn  5601:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5602:     my $startblock = 0;
                   5603:     my $endblock = 0;
1.1062    raeburn  5604:     my $triggerblock = '';
1.490     raeburn  5605:     my $course = $cdom.'_'.$cnum;
                   5606:     $setters->{$course} = {};
                   5607:     $setters->{$course}{'staff'} = [];
                   5608:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5609:     $setters->{$course}{'triggers'} = [];
                   5610:     my (@blockers,%triggered);
                   5611:     my $now = time;
                   5612:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5613:     if ($activity eq 'docs') {
1.1348    raeburn  5614:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5615:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5616:             $blocked = 1;
                   5617:             $nosymbcache = 1;
1.1348    raeburn  5618:             $noenccheck = 1;
1.1347    raeburn  5619:         }
1.1348    raeburn  5620:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5621:         foreach my $block (@blockers) {
                   5622:             if ($block =~ /^firstaccess____(.+)$/) {
                   5623:                 my $item = $1;
                   5624:                 my $type = 'map';
                   5625:                 my $timersymb = $item;
                   5626:                 if ($item eq 'course') {
                   5627:                     $type = 'course';
                   5628:                 } elsif ($item =~ /___\d+___/) {
                   5629:                     $type = 'resource';
                   5630:                 } else {
                   5631:                     $timersymb = &Apache::lonnet::symbread($item);
                   5632:                 }
                   5633:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5634:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5635:                 $triggered{$block} = {
                   5636:                                        start => $start,
                   5637:                                        end   => $end,
                   5638:                                        type  => $type,
                   5639:                                      };
                   5640:             }
                   5641:         }
                   5642:     } else {
                   5643:         foreach my $block (keys(%commblocks)) {
                   5644:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5645:                 my ($start,$end) = ($1,$2);
                   5646:                 if ($start <= time && $end >= time) {
                   5647:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5648:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5649:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5650:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5651:                                     push(@blockers,$block);
                   5652:                                 }
                   5653:                             }
                   5654:                         }
                   5655:                     }
                   5656:                 }
                   5657:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5658:                 my $item = $1;
                   5659:                 my $timersymb = $item; 
                   5660:                 my $type = 'map';
                   5661:                 if ($item eq 'course') {
                   5662:                     $type = 'course';
                   5663:                 } elsif ($item =~ /___\d+___/) {
                   5664:                     $type = 'resource';
                   5665:                 } else {
                   5666:                     $timersymb = &Apache::lonnet::symbread($item);
                   5667:                 }
                   5668:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5669:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5670:                 if ($start && $end) {
                   5671:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5672:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5673:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5674:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5675:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5676:                                         push(@blockers,$block);
                   5677:                                         $triggered{$block} = {
                   5678:                                                                start => $start,
                   5679:                                                                end   => $end,
                   5680:                                                                type  => $type,
                   5681:                                                              };
                   5682:                                     }
                   5683:                                 }
                   5684:                             }
1.1062    raeburn  5685:                         }
                   5686:                     }
1.490     raeburn  5687:                 }
1.1062    raeburn  5688:             }
                   5689:         }
                   5690:     }
                   5691:     foreach my $blocker (@blockers) {
                   5692:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5693:             &parse_block_record($commblocks{$blocker});
                   5694:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5695:         my ($start,$end,$triggertype);
                   5696:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5697:             ($start,$end) = ($1,$2);
                   5698:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5699:             $start = $triggered{$blocker}{'start'};
                   5700:             $end = $triggered{$blocker}{'end'};
                   5701:             $triggertype = $triggered{$blocker}{'type'};
                   5702:         }
                   5703:         if ($start) {
                   5704:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5705:             if ($triggertype) {
                   5706:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5707:             } else {
                   5708:                 push(@{$$setters{$course}{'triggers'}},0);
                   5709:             }
                   5710:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5711:                 $startblock = $start;
                   5712:                 if ($triggertype) {
                   5713:                     $triggerblock = $blocker;
1.474     raeburn  5714:                 }
                   5715:             }
1.1062    raeburn  5716:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5717:                $endblock = $end;
                   5718:                if ($triggertype) {
                   5719:                    $triggerblock = $blocker;
                   5720:                }
                   5721:             }
1.474     raeburn  5722:         }
                   5723:     }
1.1062    raeburn  5724:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5725: }
                   5726: 
                   5727: sub parse_block_record {
                   5728:     my ($record) = @_;
                   5729:     my ($setuname,$setudom,$title,$blocks);
                   5730:     if (ref($record) eq 'HASH') {
                   5731:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5732:         $title = &unescape($record->{'event'});
                   5733:         $blocks = $record->{'blocks'};
                   5734:     } else {
                   5735:         my @data = split(/:/,$record,3);
                   5736:         if (scalar(@data) eq 2) {
                   5737:             $title = $data[1];
                   5738:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5739:         } else {
                   5740:             ($setuname,$setudom,$title) = @data;
                   5741:         }
                   5742:         $blocks = { 'com' => 'on' };
                   5743:     }
                   5744:     return ($setuname,$setudom,$title,$blocks);
                   5745: }
                   5746: 
1.854     kalberla 5747: sub blocking_status {
1.1372    raeburn  5748:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5749:     my %setters;
1.890     droeschl 5750: 
1.1061    raeburn  5751: # check for active blocking
1.1372    raeburn  5752:     if ($clientip eq '') {
                   5753:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5754:     }
                   5755:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5756:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5757:     my $blocked = 0;
1.1372    raeburn  5758:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5759:         $blocked = 1;
                   5760:     }
1.890     droeschl 5761: 
1.1061    raeburn  5762: # caller just wants to know whether a block is active
                   5763:     if (!wantarray) { return $blocked; }
                   5764: 
                   5765: # build a link to a popup window containing the details
                   5766:     my $querystring  = "?activity=$activity";
1.1351    raeburn  5767: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5768:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  5769:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5770:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5771:     } elsif ($activity eq 'docs') {
1.1347    raeburn  5772:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5773:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5774:         if ($symb) {
                   5775:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5776:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5777:         }
1.1062    raeburn  5778:     }
1.1061    raeburn  5779: 
                   5780:     my $output .= <<'END_MYBLOCK';
                   5781: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5782:     var options = "width=" + w + ",height=" + h + ",";
                   5783:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5784:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5785:     var newWin = window.open(url, wdwName, options);
                   5786:     newWin.focus();
                   5787: }
1.890     droeschl 5788: END_MYBLOCK
1.854     kalberla 5789: 
1.1061    raeburn  5790:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5791:   
1.1061    raeburn  5792:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5793:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5794:     my $class = 'LC_comblock';
1.1062    raeburn  5795:     if ($activity eq 'docs') {
                   5796:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5797:         $class = '';
1.1063    raeburn  5798:     } elsif ($activity eq 'printout') {
                   5799:         $text = &mt('Printing Blocked');
1.1232    raeburn  5800:     } elsif ($activity eq 'passwd') {
                   5801:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5802:     } elsif ($activity eq 'grades') {
                   5803:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5804:     } elsif ($activity eq 'search') {
                   5805:         $text = &mt('Search Blocked');
1.1282    raeburn  5806:     } elsif ($activity eq 'alert') {
                   5807:         $text = &mt('Checking Critical Messages Blocked');
                   5808:     } elsif ($activity eq 'reinit') {
                   5809:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  5810:     } elsif ($activity eq 'about') {
                   5811:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  5812:     } elsif ($activity eq 'wishlist') {
                   5813:         $text = &mt('Access to Stored Links Blocked');
                   5814:     } elsif ($activity eq 'annotate') {
                   5815:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5816:     }
1.1061    raeburn  5817:     $output .= <<"END_BLOCK";
1.1217    raeburn  5818: <div class='$class'>
1.869     kalberla 5819:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5820:   title='$text'>
                   5821:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5822:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5823:   title='$text'>$text</a>
1.867     kalberla 5824: </div>
                   5825: 
                   5826: END_BLOCK
1.474     raeburn  5827: 
1.1061    raeburn  5828:     return ($blocked, $output);
1.854     kalberla 5829: }
1.490     raeburn  5830: 
1.60      matthew  5831: ###############################################
                   5832: 
1.682     raeburn  5833: sub check_ip_acc {
1.1201    raeburn  5834:     my ($acc,$clientip)=@_;
1.682     raeburn  5835:     &Apache::lonxml::debug("acc is $acc");
                   5836:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5837:         return 1;
                   5838:     }
1.1339    raeburn  5839:     my ($ip,$allowed);
                   5840:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5841:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5842:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5843:     } else {
1.1350    raeburn  5844:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5845:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  5846:     }
1.682     raeburn  5847: 
                   5848:     my $name;
1.1219    raeburn  5849:     my %access = (
                   5850:                      allowfrom => 1,
                   5851:                      denyfrom  => 0,
                   5852:                  );
                   5853:     my @allows;
                   5854:     my @denies;
                   5855:     foreach my $item (split(',',$acc)) {
                   5856:         $item =~ s/^\s*//;
                   5857:         $item =~ s/\s*$//;
                   5858:         my $pattern;
                   5859:         if ($item =~ /^\!(.+)$/) {
                   5860:             push(@denies,$1);
                   5861:         } else {
                   5862:             push(@allows,$item);
                   5863:         }
                   5864:    }
                   5865:    my $numdenies = scalar(@denies);
                   5866:    my $numallows = scalar(@allows);
                   5867:    my $count = 0;
                   5868:    foreach my $pattern (@denies,@allows) {
                   5869:         $count ++; 
                   5870:         my $acctype = 'allowfrom';
                   5871:         if ($count <= $numdenies) {
                   5872:             $acctype = 'denyfrom';
                   5873:         }
1.682     raeburn  5874:         if ($pattern =~ /\*$/) {
                   5875:             #35.8.*
                   5876:             $pattern=~s/\*//;
1.1219    raeburn  5877:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5878:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5879:             #35.8.3.[34-56]
                   5880:             my $low=$2;
                   5881:             my $high=$3;
                   5882:             $pattern=$1;
                   5883:             if ($ip =~ /^\Q$pattern\E/) {
                   5884:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5885:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5886:             }
                   5887:         } elsif ($pattern =~ /^\*/) {
                   5888:             #*.msu.edu
                   5889:             $pattern=~s/\*//;
                   5890:             if (!defined($name)) {
                   5891:                 use Socket;
                   5892:                 my $netaddr=inet_aton($ip);
                   5893:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5894:             }
1.1219    raeburn  5895:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5896:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5897:             #127.0.0.1
1.1219    raeburn  5898:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5899:         } else {
                   5900:             #some.name.com
                   5901:             if (!defined($name)) {
                   5902:                 use Socket;
                   5903:                 my $netaddr=inet_aton($ip);
                   5904:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5905:             }
1.1219    raeburn  5906:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5907:         }
                   5908:         if ($allowed =~ /^(0|1)$/) { last; }
                   5909:     }
                   5910:     if ($allowed eq '') {
                   5911:         if ($numdenies && !$numallows) {
                   5912:             $allowed = 1;
                   5913:         } else {
                   5914:             $allowed = 0;
1.682     raeburn  5915:         }
                   5916:     }
                   5917:     return $allowed;
                   5918: }
                   5919: 
                   5920: ###############################################
                   5921: 
1.60      matthew  5922: =pod
                   5923: 
1.112     bowersj2 5924: =head1 Domain Template Functions
                   5925: 
                   5926: =over 4
                   5927: 
                   5928: =item * &determinedomain()
1.60      matthew  5929: 
                   5930: Inputs: $domain (usually will be undef)
                   5931: 
1.63      www      5932: Returns: Determines which domain should be used for designs
1.60      matthew  5933: 
                   5934: =cut
1.54      www      5935: 
1.60      matthew  5936: ###############################################
1.63      www      5937: sub determinedomain {
                   5938:     my $domain=shift;
1.531     albertel 5939:     if (! $domain) {
1.60      matthew  5940:         # Determine domain if we have not been given one
1.893     raeburn  5941:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5942:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5943:         if ($env{'request.role.domain'}) { 
                   5944:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5945:         }
                   5946:     }
1.63      www      5947:     return $domain;
                   5948: }
                   5949: ###############################################
1.517     raeburn  5950: 
1.518     albertel 5951: sub devalidate_domconfig_cache {
                   5952:     my ($udom)=@_;
                   5953:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5954: }
                   5955: 
                   5956: # ---------------------- Get domain configuration for a domain
                   5957: sub get_domainconf {
                   5958:     my ($udom) = @_;
                   5959:     my $cachetime=1800;
                   5960:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5961:     if (defined($cached)) { return %{$result}; }
                   5962: 
                   5963:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5964: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5965:     my (%designhash,%legacy);
1.518     albertel 5966:     if (keys(%domconfig) > 0) {
                   5967:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5968:             if (keys(%{$domconfig{'login'}})) {
                   5969:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5970:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5971:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5972:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5973:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5974:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5975:                                         if ($key eq 'loginvia') {
                   5976:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5977:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5978:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5979:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5980: 
                   5981:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5982:                                                 } else {
                   5983:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5984:                                                 }
1.948     raeburn  5985:                                             }
1.1208    raeburn  5986:                                         } elsif ($key eq 'headtag') {
                   5987:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5988:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5989:                                             }
1.946     raeburn  5990:                                         }
1.1208    raeburn  5991:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5992:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5993:                                         }
1.946     raeburn  5994:                                     }
                   5995:                                 }
                   5996:                             }
1.1366    raeburn  5997:                         } elsif ($key eq 'saml') {
                   5998:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5999:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6000:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6001:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6002:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6003:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6004:                                         }
                   6005:                                     }
                   6006:                                 }
                   6007:                             }
1.946     raeburn  6008:                         } else {
                   6009:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6010:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6011:                                     $domconfig{'login'}{$key}{$img};
                   6012:                             }
1.699     raeburn  6013:                         }
                   6014:                     } else {
                   6015:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6016:                     }
1.632     raeburn  6017:                 }
                   6018:             } else {
                   6019:                 $legacy{'login'} = 1;
1.518     albertel 6020:             }
1.632     raeburn  6021:         } else {
                   6022:             $legacy{'login'} = 1;
1.518     albertel 6023:         }
                   6024:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6025:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6026:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6027:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6028:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6029:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6030:                         }
1.518     albertel 6031:                     }
                   6032:                 }
1.632     raeburn  6033:             } else {
                   6034:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6035:             }
1.632     raeburn  6036:         } else {
                   6037:             $legacy{'rolecolors'} = 1;
1.518     albertel 6038:         }
1.948     raeburn  6039:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6040:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6041:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6042:             }
                   6043:         }
1.632     raeburn  6044:         if (keys(%legacy) > 0) {
                   6045:             my %legacyhash = &get_legacy_domconf($udom);
                   6046:             foreach my $item (keys(%legacyhash)) {
                   6047:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6048:                     if ($legacy{'login'}) { 
                   6049:                         $designhash{$item} = $legacyhash{$item};
                   6050:                     }
                   6051:                 } else {
                   6052:                     if ($legacy{'rolecolors'}) {
                   6053:                         $designhash{$item} = $legacyhash{$item};
                   6054:                     }
1.518     albertel 6055:                 }
                   6056:             }
                   6057:         }
1.632     raeburn  6058:     } else {
                   6059:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6060:     }
                   6061:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6062: 				  $cachetime);
                   6063:     return %designhash;
                   6064: }
                   6065: 
1.632     raeburn  6066: sub get_legacy_domconf {
                   6067:     my ($udom) = @_;
                   6068:     my %legacyhash;
                   6069:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6070:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6071:     if (-e $designfile) {
1.1317    raeburn  6072:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6073:             while (my $line = <$fh>) {
                   6074:                 next if ($line =~ /^\#/);
                   6075:                 chomp($line);
                   6076:                 my ($key,$val)=(split(/\=/,$line));
                   6077:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6078:             }
                   6079:             close($fh);
                   6080:         }
                   6081:     }
1.1026    raeburn  6082:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6083:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6084:     }
                   6085:     return %legacyhash;
                   6086: }
                   6087: 
1.63      www      6088: =pod
                   6089: 
1.112     bowersj2 6090: =item * &domainlogo()
1.63      www      6091: 
                   6092: Inputs: $domain (usually will be undef)
                   6093: 
                   6094: Returns: A link to a domain logo, if the domain logo exists.
                   6095: If the domain logo does not exist, a description of the domain.
                   6096: 
                   6097: =cut
1.112     bowersj2 6098: 
1.63      www      6099: ###############################################
                   6100: sub domainlogo {
1.517     raeburn  6101:     my $domain = &determinedomain(shift);
1.518     albertel 6102:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6103:     # See if there is a logo
                   6104:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6105:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6106:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6107: 	    if ($imgsrc =~ m{^/res/}) {
                   6108: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6109: 		&Apache::lonnet::repcopy($local_name);
                   6110: 	    }
                   6111: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6112:         }
                   6113:         my $alttext = $domain;
                   6114:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6115:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6116:         }
                   6117:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6118:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6119:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6120:     } else {
1.60      matthew  6121:         return '';
1.59      www      6122:     }
                   6123: }
1.63      www      6124: ##############################################
                   6125: 
                   6126: =pod
                   6127: 
1.112     bowersj2 6128: =item * &designparm()
1.63      www      6129: 
                   6130: Inputs: $which parameter; $domain (usually will be undef)
                   6131: 
                   6132: Returns: value of designparamter $which
                   6133: 
                   6134: =cut
1.112     bowersj2 6135: 
1.397     albertel 6136: 
1.400     albertel 6137: ##############################################
1.397     albertel 6138: sub designparm {
                   6139:     my ($which,$domain)=@_;
                   6140:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6141:         return $env{'environment.color.'.$which};
1.96      www      6142:     }
1.63      www      6143:     $domain=&determinedomain($domain);
1.1016    raeburn  6144:     my %domdesign;
                   6145:     unless ($domain eq 'public') {
                   6146:         %domdesign = &get_domainconf($domain);
                   6147:     }
1.520     raeburn  6148:     my $output;
1.517     raeburn  6149:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6150:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6151:     } else {
1.520     raeburn  6152:         $output = $defaultdesign{$which};
                   6153:     }
                   6154:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6155:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6156:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6157:             if ($output =~ m{^/res/}) {
                   6158:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6159:                 &Apache::lonnet::repcopy($local_name);
                   6160:             }
1.520     raeburn  6161:             $output = &lonhttpdurl($output);
                   6162:         }
1.63      www      6163:     }
1.520     raeburn  6164:     return $output;
1.63      www      6165: }
1.59      www      6166: 
1.822     bisitz   6167: ##############################################
                   6168: =pod
                   6169: 
1.832     bisitz   6170: =item * &authorspace()
                   6171: 
1.1028    raeburn  6172: Inputs: $url (usually will be undef).
1.832     bisitz   6173: 
1.1132    raeburn  6174: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6175:          directory being viewed (or for which action is being taken). 
                   6176:          If $url is provided, and begins /priv/<domain>/<uname>
                   6177:          the path will be that portion of the $context argument.
                   6178:          Otherwise the path will be for the author space of the current
                   6179:          user when the current role is author, or for that of the 
                   6180:          co-author/assistant co-author space when the current role 
                   6181:          is co-author or assistant co-author.
1.832     bisitz   6182: 
                   6183: =cut
                   6184: 
                   6185: sub authorspace {
1.1028    raeburn  6186:     my ($url) = @_;
                   6187:     if ($url ne '') {
                   6188:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6189:            return $1;
                   6190:         }
                   6191:     }
1.832     bisitz   6192:     my $caname = '';
1.1024    www      6193:     my $cadom = '';
1.1028    raeburn  6194:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6195:         ($cadom,$caname) =
1.832     bisitz   6196:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6197:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6198:         $caname = $env{'user.name'};
1.1024    www      6199:         $cadom = $env{'user.domain'};
1.832     bisitz   6200:     }
1.1028    raeburn  6201:     if (($caname ne '') && ($cadom ne '')) {
                   6202:         return "/priv/$cadom/$caname/";
                   6203:     }
                   6204:     return;
1.832     bisitz   6205: }
                   6206: 
                   6207: ##############################################
                   6208: =pod
                   6209: 
1.822     bisitz   6210: =item * &head_subbox()
                   6211: 
                   6212: Inputs: $content (contains HTML code with page functions, etc.)
                   6213: 
                   6214: Returns: HTML div with $content
                   6215:          To be included in page header
                   6216: 
                   6217: =cut
                   6218: 
                   6219: sub head_subbox {
                   6220:     my ($content)=@_;
                   6221:     my $output =
1.993     raeburn  6222:         '<div class="LC_head_subbox">'
1.822     bisitz   6223:        .$content
                   6224:        .'</div>'
                   6225: }
                   6226: 
                   6227: ##############################################
                   6228: =pod
                   6229: 
                   6230: =item * &CSTR_pageheader()
                   6231: 
1.1026    raeburn  6232: Input: (optional) filename from which breadcrumb trail is built.
                   6233:        In most cases no input as needed, as $env{'request.filename'}
                   6234:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6235:        frameset flag
                   6236:        If page header is being requested for use in a frameset, then
                   6237:        the second (option) argument -- frameset will be true, and
                   6238:        the target attribute set for links should be target="_parent".
1.822     bisitz   6239: 
                   6240: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6241:          To be included on Authoring Space pages
1.822     bisitz   6242: 
                   6243: =cut
                   6244: 
                   6245: sub CSTR_pageheader {
1.1379    raeburn  6246:     my ($trailfile,$frameset) = @_;
1.1026    raeburn  6247:     if ($trailfile eq '') {
                   6248:         $trailfile = $env{'request.filename'};
                   6249:     }
                   6250: 
                   6251: # this is for resources; directories have customtitle, and crumbs
                   6252: # and select recent are created in lonpubdir.pm
                   6253: 
                   6254:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6255:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6256:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6257:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6258:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6259: 
                   6260:     my $parentpath = '';
                   6261:     my $lastitem = '';
                   6262:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6263:         $parentpath = $1;
                   6264:         $lastitem = $2;
                   6265:     } else {
                   6266:         $lastitem = $thisdisfn;
                   6267:     }
1.921     bisitz   6268: 
1.1246    raeburn  6269:     my ($crsauthor,$title);
                   6270:     if (($env{'request.course.id'}) &&
                   6271:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6272:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6273:         $crsauthor = 1;
                   6274:         $title = &mt('Course Authoring Space');
                   6275:     } else {
                   6276:         $title = &mt('Authoring Space');
                   6277:     }
                   6278: 
1.1379    raeburn  6279:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6280:     if ($frameset) {
                   6281:         $target = ' target="_parent"';
                   6282:         $crumbtarget = '_parent';
                   6283:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6284:         $target = '';
                   6285:         $crumbtarget = '';
1.1379    raeburn  6286:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6287:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6288:         $crumbtarget = $env{'request.deeplink.target'};
                   6289:     }
1.1313    raeburn  6290: 
1.921     bisitz   6291:     my $output =
1.822     bisitz   6292:          '<div>'
                   6293:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6294:         .'<b>'.$title.'</b> '
1.1314    raeburn  6295:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6296:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6297: 
                   6298:     if ($lastitem) {
                   6299:         $output .=
                   6300:              '<span class="LC_filename">'
                   6301:             .$lastitem
                   6302:             .'</span>';
                   6303:     }
1.1245    raeburn  6304: 
1.1246    raeburn  6305:     if ($crsauthor) {
1.1379    raeburn  6306:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6307:     } else {
                   6308:         $output .=
                   6309:              '<br />'
1.1314    raeburn  6310:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6311:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6312:             .'</form>'
1.1379    raeburn  6313:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6314:     }
                   6315:     $output .= '</div>';
1.921     bisitz   6316: 
                   6317:     return $output;
1.822     bisitz   6318: }
                   6319: 
1.60      matthew  6320: ###############################################
                   6321: ###############################################
                   6322: 
                   6323: =pod
                   6324: 
1.112     bowersj2 6325: =back
                   6326: 
1.549     albertel 6327: =head1 HTML Helpers
1.112     bowersj2 6328: 
                   6329: =over 4
                   6330: 
                   6331: =item * &bodytag()
1.60      matthew  6332: 
                   6333: Returns a uniform header for LON-CAPA web pages.
                   6334: 
                   6335: Inputs: 
                   6336: 
1.112     bowersj2 6337: =over 4
                   6338: 
                   6339: =item * $title, A title to be displayed on the page.
                   6340: 
                   6341: =item * $function, the current role (can be undef).
                   6342: 
                   6343: =item * $addentries, extra parameters for the <body> tag.
                   6344: 
                   6345: =item * $bodyonly, if defined, only return the <body> tag.
                   6346: 
                   6347: =item * $domain, if defined, force a given domain.
                   6348: 
                   6349: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6350:             text interface only)
1.60      matthew  6351: 
1.814     bisitz   6352: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6353:                      navigational links
1.317     albertel 6354: 
1.338     albertel 6355: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6356: 
1.460     albertel 6357: =item * $args, optional argument valid values are
                   6358:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6359:             use_absolute     -> for external resource or syllabus, this will
                   6360:                                 contain https://<hostname> if server uses
                   6361:                                 https (as per hosts.tab), but request is for http
                   6362:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6363: 
1.1096    raeburn  6364: =item * $advtoolsref, optional argument, ref to an array containing
                   6365:             inlineremote items to be added in "Functions" menu below
                   6366:             breadcrumbs.
                   6367: 
1.1316    raeburn  6368: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6369:             course, if LON-CAPA is in LTI Provider context. Value is
                   6370:             the scope of use, i.e., launch was for access to a single, a map
                   6371:             or the entire course.
                   6372: 
                   6373: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6374:             context, this will contain the URL for the landing item in
                   6375:             the course, after launch from an LTI Consumer
                   6376: 
1.1318    raeburn  6377: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6378:             context, this will contain a reference to hash of items
                   6379:             to be included in the page header and/or inline menu.
                   6380: 
1.1385    raeburn  6381: =item * $menucoll, optional argument, if specific menu collection is in
                   6382:             effect, either set as the default for the course, or set for
                   6383:             the deeplink paramater for $env{'request.deeplink.login'}
                   6384:             then $menucoll will be the number of that collection. 
                   6385: 
                   6386: =item * $menuref, optional argument, reference to a hash, containing the
                   6387:             menu options included for the menu in effect, based on the
                   6388:             configuration for the numbered menu collection in use.  
                   6389: 
                   6390: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6391:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6392:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6393:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6394:             being called a second time.
                   6395: 
1.112     bowersj2 6396: =back
                   6397: 
1.60      matthew  6398: Returns: A uniform header for LON-CAPA web pages.  
                   6399: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6400: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6401: other decorations will be returned.
                   6402: 
                   6403: =cut
                   6404: 
1.54      www      6405: sub bodytag {
1.831     bisitz   6406:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6407:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6408:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6409: 
1.954     raeburn  6410:     my $public;
                   6411:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6412:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6413:         $public = 1;
                   6414:     }
1.460     albertel 6415:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6416:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6417:     my $hostname = $args->{'hostname'};
1.339     albertel 6418: 
1.183     matthew  6419:     $function = &get_users_function() if (!$function);
1.339     albertel 6420:     my $img =    &designparm($function.'.img',$domain);
                   6421:     my $font =   &designparm($function.'.font',$domain);
                   6422:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6423: 
1.803     bisitz   6424:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6425: 		   'bgcolor' => $pgbg,
1.339     albertel 6426: 		   'text'    => $font,
                   6427:                    'alink'   => &designparm($function.'.alink',$domain),
                   6428: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6429: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6430:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6431: 
1.63      www      6432:  # role and realm
1.1178    raeburn  6433:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6434:     if ($realm) {
                   6435:         $realm = '/'.$realm;
                   6436:     }
1.1357    raeburn  6437:     if ($role eq 'ca') {
1.479     albertel 6438:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6439:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6440:     } 
1.55      www      6441: # realm
1.1357    raeburn  6442:     my ($cid,$sec);
1.258     albertel 6443:     if ($env{'request.course.id'}) {
1.1357    raeburn  6444:         $cid = $env{'request.course.id'};
                   6445:         if ($env{'request.course.sec'}) {
                   6446:             $sec = $env{'request.course.sec'};
                   6447:         }
                   6448:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6449:         if (&Apache::lonnet::is_course($1,$2)) {
                   6450:             $cid = $1.'_'.$2;
                   6451:             $sec = $3;
                   6452:         }
                   6453:     }
                   6454:     if ($cid) {
1.378     raeburn  6455:         if ($env{'request.role'} !~ /^cr/) {
                   6456:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6457:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6458:             if ($env{'request.role.desc'}) {
                   6459:                 $role = $env{'request.role.desc'};
                   6460:             } else {
                   6461:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6462:             }
1.1257    raeburn  6463:         } else {
                   6464:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6465:         }
1.1357    raeburn  6466:         if ($sec) {
                   6467:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6468:         }   
1.1357    raeburn  6469: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6470:     } else {
                   6471:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6472:     }
1.433     albertel 6473: 
1.359     albertel 6474:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6475: 
1.438     albertel 6476:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6477: 
1.101     www      6478: # construct main body tag
1.359     albertel 6479:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6480: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6481: 
1.1131    raeburn  6482:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6483: 
1.1130    raeburn  6484:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6485:         return $bodytag;
1.1130    raeburn  6486:     }
1.359     albertel 6487: 
1.954     raeburn  6488:     if ($public) {
1.433     albertel 6489: 	undef($role);
                   6490:     }
1.1318    raeburn  6491: 
1.1359    raeburn  6492:     my $showcrstitle = 1;
1.1357    raeburn  6493:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6494:         if (ref($ltimenu) eq 'HASH') {
                   6495:             unless ($ltimenu->{'role'}) {
                   6496:                 undef($role);
                   6497:             }
                   6498:             unless ($ltimenu->{'coursetitle'}) {
                   6499:                 $realm='&nbsp;';
1.1359    raeburn  6500:                 $showcrstitle = 0;
                   6501:             }
                   6502:         }
                   6503:     } elsif (($cid) && ($menucoll)) {
                   6504:         if (ref($menuref) eq 'HASH') {
                   6505:             unless ($menuref->{'role'}) {
                   6506:                 undef($role);
                   6507:             }
                   6508:             unless ($menuref->{'crs'}) {
                   6509:                 $realm='&nbsp;';
                   6510:                 $showcrstitle = 0;
1.1318    raeburn  6511:             }
                   6512:         }
                   6513:     }
                   6514: 
1.762     bisitz   6515:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6516:     #
                   6517:     # Extra info if you are the DC
                   6518:     my $dc_info = '';
1.1359    raeburn  6519:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6520:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6521:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6522:         $dc_info =~ s/\s+$//;
1.359     albertel 6523:     }
                   6524: 
1.1237    raeburn  6525:     my $crstype;
1.1357    raeburn  6526:     if ($cid) {
                   6527:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6528:     } elsif ($args->{'crstype'}) {
                   6529:         $crstype = $args->{'crstype'};
                   6530:     }
                   6531:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6532:         undef($role);
                   6533:     } else {
1.1242    raeburn  6534:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6535:     }
1.853     droeschl 6536: 
1.903     droeschl 6537:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6538: 
                   6539:         #    if ($env{'request.state'} eq 'construct') {
                   6540:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6541:         #    }
                   6542: 
1.1130    raeburn  6543:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6544:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6545: 
1.1318    raeburn  6546:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6547:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  6548:                                                               $args->{'links_disabled'},
                   6549:                                                               $args->{'links_target'});
1.359     albertel 6550: 
1.1318    raeburn  6551:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6552:                 if ($dc_info) {
                   6553:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6554:                 }
                   6555:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6556:                                <em>$realm</em> $dc_info</div>|;
                   6557:                 return $bodytag;
                   6558:             }
1.894     droeschl 6559: 
1.1318    raeburn  6560:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6561:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6562:             }
1.916     droeschl 6563: 
1.1318    raeburn  6564:             $bodytag .= $right;
1.852     droeschl 6565: 
1.1318    raeburn  6566:             if ($dc_info) {
                   6567:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6568:             }
                   6569:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6570:         }
1.916     droeschl 6571: 
1.1169    raeburn  6572:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6573:         if ($args->{'no_secondary_menu'}) {
                   6574:             return $bodytag;
                   6575:         }
1.1169    raeburn  6576:         #don't show menus for public users
1.954     raeburn  6577:         if (!$public){
1.1318    raeburn  6578:             unless ($args->{'no_inline_menu'}) {
                   6579:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6580:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6581:                                                             $menucoll,$menuref,
1.1380    raeburn  6582:                                                             $args->{'links_disabled'},
                   6583:                                                             $args->{'links_target'});
1.1318    raeburn  6584:             }
1.903     droeschl 6585:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6586:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6587:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6588:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  6589:                                 $args->{'bread_crumbs'},'','',$hostname,
                   6590:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6591:             } elsif ($forcereg) {
                   6592:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  6593:                                 $args->{'group'},$args->{'hide_buttons'},
                   6594:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6595:             } else {
                   6596:                 $bodytag .= 
                   6597:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6598:                                                         $forcereg,$args->{'group'},
                   6599:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6600:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6601:             }
1.903     droeschl 6602:         }else{
                   6603:             # this is to seperate menu from content when there's no secondary
                   6604:             # menu. Especially needed for public accessible ressources.
                   6605:             $bodytag .= '<hr style="clear:both" />';
                   6606:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6607:         }
1.903     droeschl 6608: 
1.235     raeburn  6609:         return $bodytag;
1.182     matthew  6610: }
                   6611: 
1.917     raeburn  6612: sub dc_courseid_toggle {
                   6613:     my ($dc_info) = @_;
1.980     raeburn  6614:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6615:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6616:            &mt('(More ...)').'</a></span>'.
                   6617:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6618: }
                   6619: 
1.330     albertel 6620: sub make_attr_string {
                   6621:     my ($register,$attr_ref) = @_;
                   6622: 
                   6623:     if ($attr_ref && !ref($attr_ref)) {
                   6624: 	die("addentries Must be a hash ref ".
                   6625: 	    join(':',caller(1))." ".
                   6626: 	    join(':',caller(0))." ");
                   6627:     }
                   6628: 
                   6629:     if ($register) {
1.339     albertel 6630: 	my ($on_load,$on_unload);
                   6631: 	foreach my $key (keys(%{$attr_ref})) {
                   6632: 	    if      (lc($key) eq 'onload') {
                   6633: 		$on_load.=$attr_ref->{$key}.';';
                   6634: 		delete($attr_ref->{$key});
                   6635: 
                   6636: 	    } elsif (lc($key) eq 'onunload') {
                   6637: 		$on_unload.=$attr_ref->{$key}.';';
                   6638: 		delete($attr_ref->{$key});
                   6639: 	    }
                   6640: 	}
1.953     droeschl 6641: 	$attr_ref->{'onload'}  = $on_load;
                   6642: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6643:     }
1.339     albertel 6644: 
1.330     albertel 6645:     my $attr_string;
1.1159    raeburn  6646:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6647: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6648:     }
                   6649:     return $attr_string;
                   6650: }
                   6651: 
                   6652: 
1.182     matthew  6653: ###############################################
1.251     albertel 6654: ###############################################
                   6655: 
                   6656: =pod
                   6657: 
                   6658: =item * &endbodytag()
                   6659: 
                   6660: Returns a uniform footer for LON-CAPA web pages.
                   6661: 
1.635     raeburn  6662: Inputs: 1 - optional reference to an args hash
                   6663: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6664: a 'Continue' link is not displayed if the page contains an
                   6665: internal redirect in the <head></head> section,
                   6666: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6667: 
                   6668: =cut
                   6669: 
                   6670: sub endbodytag {
1.635     raeburn  6671:     my ($args) = @_;
1.1080    raeburn  6672:     my $endbodytag;
                   6673:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6674:         $endbodytag='</body>';
                   6675:     }
1.315     albertel 6676:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6677:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  6678:             my ($endbodyjs,$idattr);
                   6679:             if ($env{'internal.head.to_opener'}) {
                   6680:                 my $linkid = 'LC_continue_link';
                   6681:                 $idattr = ' id="'.$linkid.'"';
                   6682:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6683:                 $endbodyjs=<<ENDJS;
                   6684: <script type="text/javascript">
                   6685: // <![CDATA[
                   6686: function ebFunction(evt) {
                   6687:     evt.preventDefault();
                   6688:     var dest = '$redirect_for_js';
                   6689:     if (window.opener != null && !window.opener.closed) {
                   6690:         window.opener.location.href=dest;
                   6691:         window.close();
                   6692:     } else {
                   6693:         window.location.href=dest;
                   6694:     }
                   6695:     return false;
                   6696: }
                   6697: 
                   6698: \$(document).ready(function () {
                   6699:   if (document.getElementById('$linkid')) {
                   6700:     var clickelem = document.getElementById('$linkid');
                   6701:     clickelem.addEventListener('click',ebFunction,false);
                   6702:   }
                   6703: });
                   6704: // ]]>
                   6705: </script>
                   6706: ENDJS
                   6707:             }
1.635     raeburn  6708: 	    $endbodytag=
1.1386    raeburn  6709: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6710: 	        &mt('Continue').'</a>'.
                   6711: 	        $endbodytag;
                   6712:         }
1.315     albertel 6713:     }
1.251     albertel 6714:     return $endbodytag;
                   6715: }
                   6716: 
1.352     albertel 6717: =pod
                   6718: 
                   6719: =item * &standard_css()
                   6720: 
                   6721: Returns a style sheet
                   6722: 
                   6723: Inputs: (all optional)
                   6724:             domain         -> force to color decorate a page for a specific
                   6725:                                domain
                   6726:             function       -> force usage of a specific rolish color scheme
                   6727:             bgcolor        -> override the default page bgcolor
                   6728: 
                   6729: =cut
                   6730: 
1.343     albertel 6731: sub standard_css {
1.345     albertel 6732:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6733:     $function  = &get_users_function() if (!$function);
                   6734:     my $img    = &designparm($function.'.img',   $domain);
                   6735:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6736:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6737:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6738: #second colour for later usage
1.345     albertel 6739:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6740:     my $pgbg_or_bgcolor =
                   6741: 	         $bgcolor ||
1.352     albertel 6742: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6743:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6744:     my $alink  = &designparm($function.'.alink', $domain);
                   6745:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6746:     my $link   = &designparm($function.'.link',  $domain);
                   6747: 
1.602     albertel 6748:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6749:     my $mono                 = 'monospace';
1.850     bisitz   6750:     my $data_table_head      = $sidebg;
                   6751:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6752:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6753:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6754:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6755:     my $mail_new             = '#FFBB77';
                   6756:     my $mail_new_hover       = '#DD9955';
                   6757:     my $mail_read            = '#BBBB77';
                   6758:     my $mail_read_hover      = '#999944';
                   6759:     my $mail_replied         = '#AAAA88';
                   6760:     my $mail_replied_hover   = '#888855';
                   6761:     my $mail_other           = '#99BBBB';
                   6762:     my $mail_other_hover     = '#669999';
1.391     albertel 6763:     my $table_header         = '#DDDDDD';
1.489     raeburn  6764:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6765:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6766:     my $button_hover         = '#BF2317';
1.392     albertel 6767: 
1.608     albertel 6768:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6769:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6770:                                              : '0 3px 0 4px';
1.448     albertel 6771: 
1.523     albertel 6772: 
1.343     albertel 6773:     return <<END;
1.947     droeschl 6774: 
                   6775: /* needed for iframe to allow 100% height in FF */
                   6776: body, html { 
                   6777:     margin: 0;
                   6778:     padding: 0 0.5%;
                   6779:     height: 99%; /* to avoid scrollbars */
                   6780: }
                   6781: 
1.795     www      6782: body {
1.911     bisitz   6783:   font-family: $sans;
                   6784:   line-height:130%;
                   6785:   font-size:0.83em;
                   6786:   color:$font;
1.795     www      6787: }
                   6788: 
1.959     onken    6789: a:focus,
                   6790: a:focus img {
1.795     www      6791:   color: red;
                   6792: }
1.698     harmsja  6793: 
1.911     bisitz   6794: form, .inline {
                   6795:   display: inline;
1.795     www      6796: }
1.721     harmsja  6797: 
1.795     www      6798: .LC_right {
1.911     bisitz   6799:   text-align:right;
1.795     www      6800: }
                   6801: 
                   6802: .LC_middle {
1.911     bisitz   6803:   vertical-align:middle;
1.795     www      6804: }
1.721     harmsja  6805: 
1.1130    raeburn  6806: .LC_floatleft {
                   6807:   float: left;
                   6808: }
                   6809: 
                   6810: .LC_floatright {
                   6811:   float: right;
                   6812: }
                   6813: 
1.911     bisitz   6814: .LC_400Box {
                   6815:   width:400px;
                   6816: }
1.721     harmsja  6817: 
1.947     droeschl 6818: .LC_iframecontainer {
                   6819:     width: 98%;
                   6820:     margin: 0;
                   6821:     position: fixed;
                   6822:     top: 8.5em;
                   6823:     bottom: 0;
                   6824: }
                   6825: 
                   6826: .LC_iframecontainer iframe{
                   6827:     border: none;
                   6828:     width: 100%;
                   6829:     height: 100%;
                   6830: }
                   6831: 
1.778     bisitz   6832: .LC_filename {
                   6833:   font-family: $mono;
                   6834:   white-space:pre;
1.921     bisitz   6835:   font-size: 120%;
1.778     bisitz   6836: }
                   6837: 
                   6838: .LC_fileicon {
                   6839:   border: none;
                   6840:   height: 1.3em;
                   6841:   vertical-align: text-bottom;
                   6842:   margin-right: 0.3em;
                   6843:   text-decoration:none;
                   6844: }
                   6845: 
1.1008    www      6846: .LC_setting {
                   6847:   text-decoration:underline;
                   6848: }
                   6849: 
1.350     albertel 6850: .LC_error {
                   6851:   color: red;
                   6852: }
1.795     www      6853: 
1.1097    bisitz   6854: .LC_warning {
                   6855:   color: darkorange;
                   6856: }
                   6857: 
1.457     albertel 6858: .LC_diff_removed {
1.733     bisitz   6859:   color: red;
1.394     albertel 6860: }
1.532     albertel 6861: 
                   6862: .LC_info,
1.457     albertel 6863: .LC_success,
                   6864: .LC_diff_added {
1.350     albertel 6865:   color: green;
                   6866: }
1.795     www      6867: 
1.802     bisitz   6868: div.LC_confirm_box {
                   6869:   background-color: #FAFAFA;
                   6870:   border: 1px solid $lg_border_color;
                   6871:   margin-right: 0;
                   6872:   padding: 5px;
                   6873: }
                   6874: 
                   6875: div.LC_confirm_box .LC_error img,
                   6876: div.LC_confirm_box .LC_success img {
                   6877:   vertical-align: middle;
                   6878: }
                   6879: 
1.1242    raeburn  6880: .LC_maxwidth {
                   6881:   max-width: 100%;
                   6882:   height: auto;
                   6883: }
                   6884: 
1.1243    raeburn  6885: .LC_textsize_mobile {
                   6886:   \@media only screen and (max-device-width: 480px) {
                   6887:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6888:   }
                   6889: }
                   6890: 
1.440     albertel 6891: .LC_icon {
1.771     droeschl 6892:   border: none;
1.790     droeschl 6893:   vertical-align: middle;
1.771     droeschl 6894: }
                   6895: 
1.543     albertel 6896: .LC_docs_spacer {
                   6897:   width: 25px;
                   6898:   height: 1px;
1.771     droeschl 6899:   border: none;
1.543     albertel 6900: }
1.346     albertel 6901: 
1.532     albertel 6902: .LC_internal_info {
1.735     bisitz   6903:   color: #999999;
1.532     albertel 6904: }
                   6905: 
1.794     www      6906: .LC_discussion {
1.1050    www      6907:   background: $data_table_dark;
1.911     bisitz   6908:   border: 1px solid black;
                   6909:   margin: 2px;
1.794     www      6910: }
                   6911: 
                   6912: .LC_disc_action_left {
1.1050    www      6913:   background: $sidebg;
1.911     bisitz   6914:   text-align: left;
1.1050    www      6915:   padding: 4px;
                   6916:   margin: 2px;
1.794     www      6917: }
                   6918: 
                   6919: .LC_disc_action_right {
1.1050    www      6920:   background: $sidebg;
1.911     bisitz   6921:   text-align: right;
1.1050    www      6922:   padding: 4px;
                   6923:   margin: 2px;
1.794     www      6924: }
                   6925: 
                   6926: .LC_disc_new_item {
1.911     bisitz   6927:   background: white;
                   6928:   border: 2px solid red;
1.1050    www      6929:   margin: 4px;
                   6930:   padding: 4px;
1.794     www      6931: }
                   6932: 
                   6933: .LC_disc_old_item {
1.911     bisitz   6934:   background: white;
1.1050    www      6935:   margin: 4px;
                   6936:   padding: 4px;
1.794     www      6937: }
                   6938: 
1.458     albertel 6939: table.LC_pastsubmission {
                   6940:   border: 1px solid black;
                   6941:   margin: 2px;
                   6942: }
                   6943: 
1.924     bisitz   6944: table#LC_menubuttons {
1.345     albertel 6945:   width: 100%;
                   6946:   background: $pgbg;
1.392     albertel 6947:   border: 2px;
1.402     albertel 6948:   border-collapse: separate;
1.803     bisitz   6949:   padding: 0;
1.345     albertel 6950: }
1.392     albertel 6951: 
1.801     tempelho 6952: table#LC_title_bar a {
                   6953:   color: $fontmenu;
                   6954: }
1.836     bisitz   6955: 
1.807     droeschl 6956: table#LC_title_bar {
1.819     tempelho 6957:   clear: both;
1.836     bisitz   6958:   display: none;
1.807     droeschl 6959: }
                   6960: 
1.795     www      6961: table#LC_title_bar,
1.933     droeschl 6962: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6963: table#LC_title_bar.LC_with_remote {
1.359     albertel 6964:   width: 100%;
1.392     albertel 6965:   border-color: $pgbg;
                   6966:   border-style: solid;
                   6967:   border-width: $border;
1.379     albertel 6968:   background: $pgbg;
1.801     tempelho 6969:   color: $fontmenu;
1.392     albertel 6970:   border-collapse: collapse;
1.803     bisitz   6971:   padding: 0;
1.819     tempelho 6972:   margin: 0;
1.359     albertel 6973: }
1.795     www      6974: 
1.933     droeschl 6975: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6976:     margin: 0;
                   6977:     padding: 0;
1.933     droeschl 6978:     position: relative;
                   6979:     list-style: none;
1.913     droeschl 6980: }
1.933     droeschl 6981: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6982:     display: inline;
                   6983: }
1.933     droeschl 6984: 
                   6985: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6986:     padding: 0;
1.933     droeschl 6987:     margin: 0;
                   6988:     float: left;
1.913     droeschl 6989: }
1.933     droeschl 6990: .LC_breadcrumb_tools_tools {
                   6991:     padding: 0;
                   6992:     margin: 0;
1.913     droeschl 6993:     float: right;
                   6994: }
                   6995: 
1.1240    raeburn  6996: .LC_placement_prog {
                   6997:     padding-right: 20px;
                   6998:     font-weight: bold;
                   6999:     font-size: 90%;
                   7000: }
                   7001: 
1.359     albertel 7002: table#LC_title_bar td {
                   7003:   background: $tabbg;
                   7004: }
1.795     www      7005: 
1.911     bisitz   7006: table#LC_menubuttons img {
1.803     bisitz   7007:   border: none;
1.346     albertel 7008: }
1.795     www      7009: 
1.842     droeschl 7010: .LC_breadcrumbs_component {
1.911     bisitz   7011:   float: right;
                   7012:   margin: 0 1em;
1.357     albertel 7013: }
1.842     droeschl 7014: .LC_breadcrumbs_component img {
1.911     bisitz   7015:   vertical-align: middle;
1.777     tempelho 7016: }
1.795     www      7017: 
1.1243    raeburn  7018: .LC_breadcrumbs_hoverable {
                   7019:   background: $sidebg;
                   7020: }
                   7021: 
1.383     albertel 7022: td.LC_table_cell_checkbox {
                   7023:   text-align: center;
                   7024: }
1.795     www      7025: 
                   7026: .LC_fontsize_small {
1.911     bisitz   7027:   font-size: 70%;
1.705     tempelho 7028: }
                   7029: 
1.844     bisitz   7030: #LC_breadcrumbs {
1.911     bisitz   7031:   clear:both;
                   7032:   background: $sidebg;
                   7033:   border-bottom: 1px solid $lg_border_color;
                   7034:   line-height: 2.5em;
1.933     droeschl 7035:   overflow: hidden;
1.911     bisitz   7036:   margin: 0;
                   7037:   padding: 0;
1.995     raeburn  7038:   text-align: left;
1.819     tempelho 7039: }
1.862     bisitz   7040: 
1.1098    bisitz   7041: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7042:   clear:both;
                   7043:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7044:   border: 1px solid $sidebg;
1.1098    bisitz   7045:   margin: 0 0 10px 0;
1.966     bisitz   7046:   padding: 3px;
1.995     raeburn  7047:   text-align: left;
1.822     bisitz   7048: }
                   7049: 
1.795     www      7050: .LC_fontsize_medium {
1.911     bisitz   7051:   font-size: 85%;
1.705     tempelho 7052: }
                   7053: 
1.795     www      7054: .LC_fontsize_large {
1.911     bisitz   7055:   font-size: 120%;
1.705     tempelho 7056: }
                   7057: 
1.346     albertel 7058: .LC_menubuttons_inline_text {
                   7059:   color: $font;
1.698     harmsja  7060:   font-size: 90%;
1.701     harmsja  7061:   padding-left:3px;
1.346     albertel 7062: }
                   7063: 
1.934     droeschl 7064: .LC_menubuttons_inline_text img{
                   7065:   vertical-align: middle;
                   7066: }
                   7067: 
1.1051    www      7068: li.LC_menubuttons_inline_text img {
1.951     onken    7069:   cursor:pointer;
1.1002    droeschl 7070:   text-decoration: none;
1.951     onken    7071: }
                   7072: 
1.526     www      7073: .LC_menubuttons_link {
                   7074:   text-decoration: none;
                   7075: }
1.795     www      7076: 
1.522     albertel 7077: .LC_menubuttons_category {
1.521     www      7078:   color: $font;
1.526     www      7079:   background: $pgbg;
1.521     www      7080:   font-size: larger;
                   7081:   font-weight: bold;
                   7082: }
                   7083: 
1.346     albertel 7084: td.LC_menubuttons_text {
1.911     bisitz   7085:   color: $font;
1.346     albertel 7086: }
1.706     harmsja  7087: 
1.346     albertel 7088: .LC_current_location {
                   7089:   background: $tabbg;
                   7090: }
1.795     www      7091: 
1.1286    raeburn  7092: td.LC_zero_height {
                   7093:   line-height: 0; 
                   7094:   cellpadding: 0;
                   7095: }
                   7096: 
1.938     bisitz   7097: table.LC_data_table {
1.347     albertel 7098:   border: 1px solid #000000;
1.402     albertel 7099:   border-collapse: separate;
1.426     albertel 7100:   border-spacing: 1px;
1.610     albertel 7101:   background: $pgbg;
1.347     albertel 7102: }
1.795     www      7103: 
1.422     albertel 7104: .LC_data_table_dense {
                   7105:   font-size: small;
                   7106: }
1.795     www      7107: 
1.507     raeburn  7108: table.LC_nested_outer {
                   7109:   border: 1px solid #000000;
1.589     raeburn  7110:   border-collapse: collapse;
1.803     bisitz   7111:   border-spacing: 0;
1.507     raeburn  7112:   width: 100%;
                   7113: }
1.795     www      7114: 
1.879     raeburn  7115: table.LC_innerpickbox,
1.507     raeburn  7116: table.LC_nested {
1.803     bisitz   7117:   border: none;
1.589     raeburn  7118:   border-collapse: collapse;
1.803     bisitz   7119:   border-spacing: 0;
1.507     raeburn  7120:   width: 100%;
                   7121: }
1.795     www      7122: 
1.911     bisitz   7123: table.LC_data_table tr th,
                   7124: table.LC_calendar tr th,
1.879     raeburn  7125: table.LC_prior_tries tr th,
                   7126: table.LC_innerpickbox tr th {
1.349     albertel 7127:   font-weight: bold;
                   7128:   background-color: $data_table_head;
1.801     tempelho 7129:   color:$fontmenu;
1.701     harmsja  7130:   font-size:90%;
1.347     albertel 7131: }
1.795     www      7132: 
1.879     raeburn  7133: table.LC_innerpickbox tr th,
                   7134: table.LC_innerpickbox tr td {
                   7135:   vertical-align: top;
                   7136: }
                   7137: 
1.711     raeburn  7138: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7139:   background-color: #CCCCCC;
1.711     raeburn  7140:   font-weight: bold;
                   7141:   text-align: left;
                   7142: }
1.795     www      7143: 
1.912     bisitz   7144: table.LC_data_table tr.LC_odd_row > td {
                   7145:   background-color: $data_table_light;
                   7146:   padding: 2px;
                   7147:   vertical-align: top;
                   7148: }
                   7149: 
1.809     bisitz   7150: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7151:   background-color: $data_table_light;
1.912     bisitz   7152:   vertical-align: top;
                   7153: }
                   7154: 
                   7155: table.LC_data_table tr.LC_even_row > td {
                   7156:   background-color: $data_table_dark;
1.425     albertel 7157:   padding: 2px;
1.900     bisitz   7158:   vertical-align: top;
1.347     albertel 7159: }
1.795     www      7160: 
1.809     bisitz   7161: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7162:   background-color: $data_table_dark;
1.900     bisitz   7163:   vertical-align: top;
1.347     albertel 7164: }
1.795     www      7165: 
1.425     albertel 7166: table.LC_data_table tr.LC_data_table_highlight td {
                   7167:   background-color: $data_table_darker;
                   7168: }
1.795     www      7169: 
1.639     raeburn  7170: table.LC_data_table tr td.LC_leftcol_header {
                   7171:   background-color: $data_table_head;
                   7172:   font-weight: bold;
                   7173: }
1.795     www      7174: 
1.451     albertel 7175: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7176: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7177:   font-weight: bold;
                   7178:   font-style: italic;
                   7179:   text-align: center;
                   7180:   padding: 8px;
1.347     albertel 7181: }
1.795     www      7182: 
1.1114    raeburn  7183: table.LC_data_table tr.LC_empty_row td,
                   7184: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7185:   background-color: $sidebg;
                   7186: }
                   7187: 
                   7188: table.LC_nested tr.LC_empty_row td {
                   7189:   background-color: #FFFFFF;
                   7190: }
                   7191: 
1.890     droeschl 7192: table.LC_caption {
                   7193: }
                   7194: 
1.507     raeburn  7195: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7196:   padding: 4ex
                   7197: }
1.795     www      7198: 
1.507     raeburn  7199: table.LC_nested_outer tr th {
                   7200:   font-weight: bold;
1.801     tempelho 7201:   color:$fontmenu;
1.507     raeburn  7202:   background-color: $data_table_head;
1.701     harmsja  7203:   font-size: small;
1.507     raeburn  7204:   border-bottom: 1px solid #000000;
                   7205: }
1.795     www      7206: 
1.507     raeburn  7207: table.LC_nested_outer tr td.LC_subheader {
                   7208:   background-color: $data_table_head;
                   7209:   font-weight: bold;
                   7210:   font-size: small;
                   7211:   border-bottom: 1px solid #000000;
                   7212:   text-align: right;
1.451     albertel 7213: }
1.795     www      7214: 
1.507     raeburn  7215: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7216:   background-color: #CCCCCC;
1.451     albertel 7217:   font-weight: bold;
                   7218:   font-size: small;
1.507     raeburn  7219:   text-align: center;
                   7220: }
1.795     www      7221: 
1.589     raeburn  7222: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7223: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7224:   text-align: left;
1.451     albertel 7225: }
1.795     www      7226: 
1.507     raeburn  7227: table.LC_nested td {
1.735     bisitz   7228:   background-color: #FFFFFF;
1.451     albertel 7229:   font-size: small;
1.507     raeburn  7230: }
1.795     www      7231: 
1.507     raeburn  7232: table.LC_nested_outer tr th.LC_right_item,
                   7233: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7234: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7235: table.LC_nested tr td.LC_right_item {
1.451     albertel 7236:   text-align: right;
                   7237: }
                   7238: 
1.507     raeburn  7239: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7240:   background-color: #EEEEEE;
1.451     albertel 7241: }
                   7242: 
1.473     raeburn  7243: table.LC_createuser {
                   7244: }
                   7245: 
                   7246: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7247:   font-size: small;
1.473     raeburn  7248: }
                   7249: 
                   7250: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7251:   background-color: #CCCCCC;
1.473     raeburn  7252:   font-weight: bold;
                   7253:   text-align: center;
                   7254: }
                   7255: 
1.349     albertel 7256: table.LC_calendar {
                   7257:   border: 1px solid #000000;
                   7258:   border-collapse: collapse;
1.917     raeburn  7259:   width: 98%;
1.349     albertel 7260: }
1.795     www      7261: 
1.349     albertel 7262: table.LC_calendar_pickdate {
                   7263:   font-size: xx-small;
                   7264: }
1.795     www      7265: 
1.349     albertel 7266: table.LC_calendar tr td {
                   7267:   border: 1px solid #000000;
                   7268:   vertical-align: top;
1.917     raeburn  7269:   width: 14%;
1.349     albertel 7270: }
1.795     www      7271: 
1.349     albertel 7272: table.LC_calendar tr td.LC_calendar_day_empty {
                   7273:   background-color: $data_table_dark;
                   7274: }
1.795     www      7275: 
1.779     bisitz   7276: table.LC_calendar tr td.LC_calendar_day_current {
                   7277:   background-color: $data_table_highlight;
1.777     tempelho 7278: }
1.795     www      7279: 
1.938     bisitz   7280: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7281:   background-color: $mail_new;
                   7282: }
1.795     www      7283: 
1.938     bisitz   7284: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7285:   background-color: $mail_new_hover;
                   7286: }
1.795     www      7287: 
1.938     bisitz   7288: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7289:   background-color: $mail_read;
                   7290: }
1.795     www      7291: 
1.938     bisitz   7292: /*
                   7293: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7294:   background-color: $mail_read_hover;
                   7295: }
1.938     bisitz   7296: */
1.795     www      7297: 
1.938     bisitz   7298: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7299:   background-color: $mail_replied;
                   7300: }
1.795     www      7301: 
1.938     bisitz   7302: /*
                   7303: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7304:   background-color: $mail_replied_hover;
                   7305: }
1.938     bisitz   7306: */
1.795     www      7307: 
1.938     bisitz   7308: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7309:   background-color: $mail_other;
                   7310: }
1.795     www      7311: 
1.938     bisitz   7312: /*
                   7313: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7314:   background-color: $mail_other_hover;
                   7315: }
1.938     bisitz   7316: */
1.494     raeburn  7317: 
1.777     tempelho 7318: table.LC_data_table tr > td.LC_browser_file,
                   7319: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7320:   background: #AAEE77;
1.389     albertel 7321: }
1.795     www      7322: 
1.777     tempelho 7323: table.LC_data_table tr > td.LC_browser_file_locked,
                   7324: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7325:   background: #FFAA99;
1.387     albertel 7326: }
1.795     www      7327: 
1.777     tempelho 7328: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7329:   background: #888888;
1.779     bisitz   7330: }
1.795     www      7331: 
1.777     tempelho 7332: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7333: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7334:   background: #F8F866;
1.777     tempelho 7335: }
1.795     www      7336: 
1.696     bisitz   7337: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7338:   background: #E0E8FF;
1.387     albertel 7339: }
1.696     bisitz   7340: 
1.707     bisitz   7341: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7342:   /* background: #77FF77; */
1.707     bisitz   7343: }
1.795     www      7344: 
1.707     bisitz   7345: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7346:   border-right: 8px solid #FFFF77;
1.707     bisitz   7347: }
1.795     www      7348: 
1.707     bisitz   7349: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7350:   border-right: 8px solid #FFAA77;
1.707     bisitz   7351: }
1.795     www      7352: 
1.707     bisitz   7353: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7354:   border-right: 8px solid #FF7777;
1.707     bisitz   7355: }
1.795     www      7356: 
1.707     bisitz   7357: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7358:   border-right: 8px solid #AAFF77;
1.707     bisitz   7359: }
1.795     www      7360: 
1.707     bisitz   7361: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7362:   border-right: 8px solid #11CC55;
1.707     bisitz   7363: }
                   7364: 
1.388     albertel 7365: span.LC_current_location {
1.701     harmsja  7366:   font-size:larger;
1.388     albertel 7367:   background: $pgbg;
                   7368: }
1.387     albertel 7369: 
1.1029    www      7370: span.LC_current_nav_location {
                   7371:   font-weight:bold;
                   7372:   background: $sidebg;
                   7373: }
                   7374: 
1.395     albertel 7375: span.LC_parm_menu_item {
                   7376:   font-size: larger;
                   7377: }
1.795     www      7378: 
1.395     albertel 7379: span.LC_parm_scope_all {
                   7380:   color: red;
                   7381: }
1.795     www      7382: 
1.395     albertel 7383: span.LC_parm_scope_folder {
                   7384:   color: green;
                   7385: }
1.795     www      7386: 
1.395     albertel 7387: span.LC_parm_scope_resource {
                   7388:   color: orange;
                   7389: }
1.795     www      7390: 
1.395     albertel 7391: span.LC_parm_part {
                   7392:   color: blue;
                   7393: }
1.795     www      7394: 
1.911     bisitz   7395: span.LC_parm_folder,
                   7396: span.LC_parm_symb {
1.395     albertel 7397:   font-size: x-small;
                   7398:   font-family: $mono;
                   7399:   color: #AAAAAA;
                   7400: }
                   7401: 
1.977     bisitz   7402: ul.LC_parm_parmlist li {
                   7403:   display: inline-block;
                   7404:   padding: 0.3em 0.8em;
                   7405:   vertical-align: top;
                   7406:   width: 150px;
                   7407:   border-top:1px solid $lg_border_color;
                   7408: }
                   7409: 
1.795     www      7410: td.LC_parm_overview_level_menu,
                   7411: td.LC_parm_overview_map_menu,
                   7412: td.LC_parm_overview_parm_selectors,
                   7413: td.LC_parm_overview_restrictions  {
1.396     albertel 7414:   border: 1px solid black;
                   7415:   border-collapse: collapse;
                   7416: }
1.795     www      7417: 
1.1285    raeburn  7418: span.LC_parm_recursive,
                   7419: td.LC_parm_recursive {
                   7420:   font-weight: bold;
                   7421:   font-size: smaller;
                   7422: }
                   7423: 
1.396     albertel 7424: table.LC_parm_overview_restrictions td {
                   7425:   border-width: 1px 4px 1px 4px;
                   7426:   border-style: solid;
                   7427:   border-color: $pgbg;
                   7428:   text-align: center;
                   7429: }
1.795     www      7430: 
1.396     albertel 7431: table.LC_parm_overview_restrictions th {
                   7432:   background: $tabbg;
                   7433:   border-width: 1px 4px 1px 4px;
                   7434:   border-style: solid;
                   7435:   border-color: $pgbg;
                   7436: }
1.795     www      7437: 
1.398     albertel 7438: table#LC_helpmenu {
1.803     bisitz   7439:   border: none;
1.398     albertel 7440:   height: 55px;
1.803     bisitz   7441:   border-spacing: 0;
1.398     albertel 7442: }
                   7443: 
                   7444: table#LC_helpmenu fieldset legend {
                   7445:   font-size: larger;
                   7446: }
1.795     www      7447: 
1.397     albertel 7448: table#LC_helpmenu_links {
                   7449:   width: 100%;
                   7450:   border: 1px solid black;
                   7451:   background: $pgbg;
1.803     bisitz   7452:   padding: 0;
1.397     albertel 7453:   border-spacing: 1px;
                   7454: }
1.795     www      7455: 
1.397     albertel 7456: table#LC_helpmenu_links tr td {
                   7457:   padding: 1px;
                   7458:   background: $tabbg;
1.399     albertel 7459:   text-align: center;
                   7460:   font-weight: bold;
1.397     albertel 7461: }
1.396     albertel 7462: 
1.795     www      7463: table#LC_helpmenu_links a:link,
                   7464: table#LC_helpmenu_links a:visited,
1.397     albertel 7465: table#LC_helpmenu_links a:active {
                   7466:   text-decoration: none;
                   7467:   color: $font;
                   7468: }
1.795     www      7469: 
1.397     albertel 7470: table#LC_helpmenu_links a:hover {
                   7471:   text-decoration: underline;
                   7472:   color: $vlink;
                   7473: }
1.396     albertel 7474: 
1.417     albertel 7475: .LC_chrt_popup_exists {
                   7476:   border: 1px solid #339933;
                   7477:   margin: -1px;
                   7478: }
1.795     www      7479: 
1.417     albertel 7480: .LC_chrt_popup_up {
                   7481:   border: 1px solid yellow;
                   7482:   margin: -1px;
                   7483: }
1.795     www      7484: 
1.417     albertel 7485: .LC_chrt_popup {
                   7486:   border: 1px solid #8888FF;
                   7487:   background: #CCCCFF;
                   7488: }
1.795     www      7489: 
1.421     albertel 7490: table.LC_pick_box {
                   7491:   border-collapse: separate;
                   7492:   background: white;
                   7493:   border: 1px solid black;
                   7494:   border-spacing: 1px;
                   7495: }
1.795     www      7496: 
1.421     albertel 7497: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7498:   background: $sidebg;
1.421     albertel 7499:   font-weight: bold;
1.900     bisitz   7500:   text-align: left;
1.740     bisitz   7501:   vertical-align: top;
1.421     albertel 7502:   width: 184px;
                   7503:   padding: 8px;
                   7504: }
1.795     www      7505: 
1.579     raeburn  7506: table.LC_pick_box td.LC_pick_box_value {
                   7507:   text-align: left;
                   7508:   padding: 8px;
                   7509: }
1.795     www      7510: 
1.579     raeburn  7511: table.LC_pick_box td.LC_pick_box_select {
                   7512:   text-align: left;
                   7513:   padding: 8px;
                   7514: }
1.795     www      7515: 
1.424     albertel 7516: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7517:   padding: 0;
1.421     albertel 7518:   height: 1px;
                   7519:   background: black;
                   7520: }
1.795     www      7521: 
1.421     albertel 7522: table.LC_pick_box td.LC_pick_box_submit {
                   7523:   text-align: right;
                   7524: }
1.795     www      7525: 
1.579     raeburn  7526: table.LC_pick_box td.LC_evenrow_value {
                   7527:   text-align: left;
                   7528:   padding: 8px;
                   7529:   background-color: $data_table_light;
                   7530: }
1.795     www      7531: 
1.579     raeburn  7532: table.LC_pick_box td.LC_oddrow_value {
                   7533:   text-align: left;
                   7534:   padding: 8px;
                   7535:   background-color: $data_table_light;
                   7536: }
1.795     www      7537: 
1.579     raeburn  7538: span.LC_helpform_receipt_cat {
                   7539:   font-weight: bold;
                   7540: }
1.795     www      7541: 
1.424     albertel 7542: table.LC_group_priv_box {
                   7543:   background: white;
                   7544:   border: 1px solid black;
                   7545:   border-spacing: 1px;
                   7546: }
1.795     www      7547: 
1.424     albertel 7548: table.LC_group_priv_box td.LC_pick_box_title {
                   7549:   background: $tabbg;
                   7550:   font-weight: bold;
                   7551:   text-align: right;
                   7552:   width: 184px;
                   7553: }
1.795     www      7554: 
1.424     albertel 7555: table.LC_group_priv_box td.LC_groups_fixed {
                   7556:   background: $data_table_light;
                   7557:   text-align: center;
                   7558: }
1.795     www      7559: 
1.424     albertel 7560: table.LC_group_priv_box td.LC_groups_optional {
                   7561:   background: $data_table_dark;
                   7562:   text-align: center;
                   7563: }
1.795     www      7564: 
1.424     albertel 7565: table.LC_group_priv_box td.LC_groups_functionality {
                   7566:   background: $data_table_darker;
                   7567:   text-align: center;
                   7568:   font-weight: bold;
                   7569: }
1.795     www      7570: 
1.424     albertel 7571: table.LC_group_priv td {
                   7572:   text-align: left;
1.803     bisitz   7573:   padding: 0;
1.424     albertel 7574: }
                   7575: 
                   7576: .LC_navbuttons {
                   7577:   margin: 2ex 0ex 2ex 0ex;
                   7578: }
1.795     www      7579: 
1.423     albertel 7580: .LC_topic_bar {
                   7581:   font-weight: bold;
                   7582:   background: $tabbg;
1.918     wenzelju 7583:   margin: 1em 0em 1em 2em;
1.805     bisitz   7584:   padding: 3px;
1.918     wenzelju 7585:   font-size: 1.2em;
1.423     albertel 7586: }
1.795     www      7587: 
1.423     albertel 7588: .LC_topic_bar span {
1.918     wenzelju 7589:   left: 0.5em;
                   7590:   position: absolute;
1.423     albertel 7591:   vertical-align: middle;
1.918     wenzelju 7592:   font-size: 1.2em;
1.423     albertel 7593: }
1.795     www      7594: 
1.423     albertel 7595: table.LC_course_group_status {
                   7596:   margin: 20px;
                   7597: }
1.795     www      7598: 
1.423     albertel 7599: table.LC_status_selector td {
                   7600:   vertical-align: top;
                   7601:   text-align: center;
1.424     albertel 7602:   padding: 4px;
                   7603: }
1.795     www      7604: 
1.599     albertel 7605: div.LC_feedback_link {
1.616     albertel 7606:   clear: both;
1.829     kalberla 7607:   background: $sidebg;
1.779     bisitz   7608:   width: 100%;
1.829     kalberla 7609:   padding-bottom: 10px;
                   7610:   border: 1px $tabbg solid;
1.833     kalberla 7611:   height: 22px;
                   7612:   line-height: 22px;
                   7613:   padding-top: 5px;
                   7614: }
                   7615: 
                   7616: div.LC_feedback_link img {
                   7617:   height: 22px;
1.867     kalberla 7618:   vertical-align:middle;
1.829     kalberla 7619: }
                   7620: 
1.911     bisitz   7621: div.LC_feedback_link a {
1.829     kalberla 7622:   text-decoration: none;
1.489     raeburn  7623: }
1.795     www      7624: 
1.867     kalberla 7625: div.LC_comblock {
1.911     bisitz   7626:   display:inline;
1.867     kalberla 7627:   color:$font;
                   7628:   font-size:90%;
                   7629: }
                   7630: 
                   7631: div.LC_feedback_link div.LC_comblock {
                   7632:   padding-left:5px;
                   7633: }
                   7634: 
                   7635: div.LC_feedback_link div.LC_comblock a {
                   7636:   color:$font;
                   7637: }
                   7638: 
1.489     raeburn  7639: span.LC_feedback_link {
1.858     bisitz   7640:   /* background: $feedback_link_bg; */
1.599     albertel 7641:   font-size: larger;
                   7642: }
1.795     www      7643: 
1.599     albertel 7644: span.LC_message_link {
1.858     bisitz   7645:   /* background: $feedback_link_bg; */
1.599     albertel 7646:   font-size: larger;
                   7647:   position: absolute;
                   7648:   right: 1em;
1.489     raeburn  7649: }
1.421     albertel 7650: 
1.515     albertel 7651: table.LC_prior_tries {
1.524     albertel 7652:   border: 1px solid #000000;
                   7653:   border-collapse: separate;
                   7654:   border-spacing: 1px;
1.515     albertel 7655: }
1.523     albertel 7656: 
1.515     albertel 7657: table.LC_prior_tries td {
1.524     albertel 7658:   padding: 2px;
1.515     albertel 7659: }
1.523     albertel 7660: 
                   7661: .LC_answer_correct {
1.795     www      7662:   background: lightgreen;
                   7663:   color: darkgreen;
                   7664:   padding: 6px;
1.523     albertel 7665: }
1.795     www      7666: 
1.523     albertel 7667: .LC_answer_charged_try {
1.797     www      7668:   background: #FFAAAA;
1.795     www      7669:   color: darkred;
                   7670:   padding: 6px;
1.523     albertel 7671: }
1.795     www      7672: 
1.779     bisitz   7673: .LC_answer_not_charged_try,
1.523     albertel 7674: .LC_answer_no_grade,
                   7675: .LC_answer_late {
1.795     www      7676:   background: lightyellow;
1.523     albertel 7677:   color: black;
1.795     www      7678:   padding: 6px;
1.523     albertel 7679: }
1.795     www      7680: 
1.523     albertel 7681: .LC_answer_previous {
1.795     www      7682:   background: lightblue;
                   7683:   color: darkblue;
                   7684:   padding: 6px;
1.523     albertel 7685: }
1.795     www      7686: 
1.779     bisitz   7687: .LC_answer_no_message {
1.777     tempelho 7688:   background: #FFFFFF;
                   7689:   color: black;
1.795     www      7690:   padding: 6px;
1.779     bisitz   7691: }
1.795     www      7692: 
1.1334    raeburn  7693: .LC_answer_unknown,
                   7694: .LC_answer_warning {
1.779     bisitz   7695:   background: orange;
                   7696:   color: black;
1.795     www      7697:   padding: 6px;
1.777     tempelho 7698: }
1.795     www      7699: 
1.529     albertel 7700: span.LC_prior_numerical,
                   7701: span.LC_prior_string,
                   7702: span.LC_prior_custom,
                   7703: span.LC_prior_reaction,
                   7704: span.LC_prior_math {
1.925     bisitz   7705:   font-family: $mono;
1.523     albertel 7706:   white-space: pre;
                   7707: }
                   7708: 
1.525     albertel 7709: span.LC_prior_string {
1.925     bisitz   7710:   font-family: $mono;
1.525     albertel 7711:   white-space: pre;
                   7712: }
                   7713: 
1.523     albertel 7714: table.LC_prior_option {
                   7715:   width: 100%;
                   7716:   border-collapse: collapse;
                   7717: }
1.795     www      7718: 
1.911     bisitz   7719: table.LC_prior_rank,
1.795     www      7720: table.LC_prior_match {
1.528     albertel 7721:   border-collapse: collapse;
                   7722: }
1.795     www      7723: 
1.528     albertel 7724: table.LC_prior_option tr td,
                   7725: table.LC_prior_rank tr td,
                   7726: table.LC_prior_match tr td {
1.524     albertel 7727:   border: 1px solid #000000;
1.515     albertel 7728: }
                   7729: 
1.855     bisitz   7730: .LC_nobreak {
1.544     albertel 7731:   white-space: nowrap;
1.519     raeburn  7732: }
                   7733: 
1.576     raeburn  7734: span.LC_cusr_emph {
                   7735:   font-style: italic;
                   7736: }
                   7737: 
1.633     raeburn  7738: span.LC_cusr_subheading {
                   7739:   font-weight: normal;
                   7740:   font-size: 85%;
                   7741: }
                   7742: 
1.861     bisitz   7743: div.LC_docs_entry_move {
1.859     bisitz   7744:   border: 1px solid #BBBBBB;
1.545     albertel 7745:   background: #DDDDDD;
1.861     bisitz   7746:   width: 22px;
1.859     bisitz   7747:   padding: 1px;
                   7748:   margin: 0;
1.545     albertel 7749: }
                   7750: 
1.861     bisitz   7751: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7752: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7753:   font-size: x-small;
                   7754: }
1.795     www      7755: 
1.861     bisitz   7756: .LC_docs_entry_parameter {
                   7757:   white-space: nowrap;
                   7758: }
                   7759: 
1.544     albertel 7760: .LC_docs_copy {
1.545     albertel 7761:   color: #000099;
1.544     albertel 7762: }
1.795     www      7763: 
1.544     albertel 7764: .LC_docs_cut {
1.545     albertel 7765:   color: #550044;
1.544     albertel 7766: }
1.795     www      7767: 
1.544     albertel 7768: .LC_docs_rename {
1.545     albertel 7769:   color: #009900;
1.544     albertel 7770: }
1.795     www      7771: 
1.544     albertel 7772: .LC_docs_remove {
1.545     albertel 7773:   color: #990000;
                   7774: }
                   7775: 
1.1284    raeburn  7776: .LC_docs_alias {
                   7777:   color: #440055;  
                   7778: }
                   7779: 
1.1286    raeburn  7780: .LC_domprefs_email,
1.1284    raeburn  7781: .LC_docs_alias_name,
1.547     albertel 7782: .LC_docs_reinit_warn,
                   7783: .LC_docs_ext_edit {
                   7784:   font-size: x-small;
                   7785: }
                   7786: 
1.545     albertel 7787: table.LC_docs_adddocs td,
                   7788: table.LC_docs_adddocs th {
                   7789:   border: 1px solid #BBBBBB;
                   7790:   padding: 4px;
                   7791:   background: #DDDDDD;
1.543     albertel 7792: }
                   7793: 
1.584     albertel 7794: table.LC_sty_begin {
                   7795:   background: #BBFFBB;
                   7796: }
1.795     www      7797: 
1.584     albertel 7798: table.LC_sty_end {
                   7799:   background: #FFBBBB;
                   7800: }
                   7801: 
1.589     raeburn  7802: table.LC_double_column {
1.803     bisitz   7803:   border-width: 0;
1.589     raeburn  7804:   border-collapse: collapse;
                   7805:   width: 100%;
                   7806:   padding: 2px;
                   7807: }
                   7808: 
                   7809: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7810:   top: 2px;
1.589     raeburn  7811:   left: 2px;
                   7812:   width: 47%;
                   7813:   vertical-align: top;
                   7814: }
                   7815: 
                   7816: table.LC_double_column tr td.LC_right_col {
                   7817:   top: 2px;
1.779     bisitz   7818:   right: 2px;
1.589     raeburn  7819:   width: 47%;
                   7820:   vertical-align: top;
                   7821: }
                   7822: 
1.591     raeburn  7823: div.LC_left_float {
                   7824:   float: left;
                   7825:   padding-right: 5%;
1.597     albertel 7826:   padding-bottom: 4px;
1.591     raeburn  7827: }
                   7828: 
                   7829: div.LC_clear_float_header {
1.597     albertel 7830:   padding-bottom: 2px;
1.591     raeburn  7831: }
                   7832: 
                   7833: div.LC_clear_float_footer {
1.597     albertel 7834:   padding-top: 10px;
1.591     raeburn  7835:   clear: both;
                   7836: }
                   7837: 
1.597     albertel 7838: div.LC_grade_show_user {
1.941     bisitz   7839: /*  border-left: 5px solid $sidebg; */
                   7840:   border-top: 5px solid #000000;
                   7841:   margin: 50px 0 0 0;
1.936     bisitz   7842:   padding: 15px 0 5px 10px;
1.597     albertel 7843: }
1.795     www      7844: 
1.936     bisitz   7845: div.LC_grade_show_user_odd_row {
1.941     bisitz   7846: /*  border-left: 5px solid #000000; */
                   7847: }
                   7848: 
                   7849: div.LC_grade_show_user div.LC_Box {
                   7850:   margin-right: 50px;
1.597     albertel 7851: }
                   7852: 
                   7853: div.LC_grade_submissions,
                   7854: div.LC_grade_message_center,
1.936     bisitz   7855: div.LC_grade_info_links {
1.597     albertel 7856:   margin: 5px;
                   7857:   width: 99%;
                   7858:   background: #FFFFFF;
                   7859: }
1.795     www      7860: 
1.597     albertel 7861: div.LC_grade_submissions_header,
1.936     bisitz   7862: div.LC_grade_message_center_header {
1.705     tempelho 7863:   font-weight: bold;
                   7864:   font-size: large;
1.597     albertel 7865: }
1.795     www      7866: 
1.597     albertel 7867: div.LC_grade_submissions_body,
1.936     bisitz   7868: div.LC_grade_message_center_body {
1.597     albertel 7869:   border: 1px solid black;
                   7870:   width: 99%;
                   7871:   background: #FFFFFF;
                   7872: }
1.795     www      7873: 
1.613     albertel 7874: table.LC_scantron_action {
                   7875:   width: 100%;
                   7876: }
1.795     www      7877: 
1.613     albertel 7878: table.LC_scantron_action tr th {
1.698     harmsja  7879:   font-weight:bold;
                   7880:   font-style:normal;
1.613     albertel 7881: }
1.795     www      7882: 
1.779     bisitz   7883: .LC_edit_problem_header,
1.614     albertel 7884: div.LC_edit_problem_footer {
1.705     tempelho 7885:   font-weight: normal;
                   7886:   font-size:  medium;
1.602     albertel 7887:   margin: 2px;
1.1060    bisitz   7888:   background-color: $sidebg;
1.600     albertel 7889: }
1.795     www      7890: 
1.600     albertel 7891: div.LC_edit_problem_header,
1.602     albertel 7892: div.LC_edit_problem_header div,
1.614     albertel 7893: div.LC_edit_problem_footer,
                   7894: div.LC_edit_problem_footer div,
1.602     albertel 7895: div.LC_edit_problem_editxml_header,
                   7896: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7897:   z-index: 100;
1.600     albertel 7898: }
1.795     www      7899: 
1.600     albertel 7900: div.LC_edit_problem_header_title {
1.705     tempelho 7901:   font-weight: bold;
                   7902:   font-size: larger;
1.602     albertel 7903:   background: $tabbg;
                   7904:   padding: 3px;
1.1060    bisitz   7905:   margin: 0 0 5px 0;
1.602     albertel 7906: }
1.795     www      7907: 
1.602     albertel 7908: table.LC_edit_problem_header_title {
                   7909:   width: 100%;
1.600     albertel 7910:   background: $tabbg;
1.602     albertel 7911: }
                   7912: 
1.1205    golterma 7913: div.LC_edit_actionbar {
                   7914:     background-color: $sidebg;
1.1218    droeschl 7915:     margin: 0;
                   7916:     padding: 0;
                   7917:     line-height: 200%;
1.602     albertel 7918: }
1.795     www      7919: 
1.1218    droeschl 7920: div.LC_edit_actionbar div{
                   7921:     padding: 0;
                   7922:     margin: 0;
                   7923:     display: inline-block;
1.600     albertel 7924: }
1.795     www      7925: 
1.1124    bisitz   7926: .LC_edit_opt {
                   7927:   padding-left: 1em;
                   7928:   white-space: nowrap;
                   7929: }
                   7930: 
1.1152    golterma 7931: .LC_edit_problem_latexhelper{
                   7932:     text-align: right;
                   7933: }
                   7934: 
                   7935: #LC_edit_problem_colorful div{
                   7936:     margin-left: 40px;
                   7937: }
                   7938: 
1.1205    golterma 7939: #LC_edit_problem_codemirror div{
                   7940:     margin-left: 0px;
                   7941: }
                   7942: 
1.911     bisitz   7943: img.stift {
1.803     bisitz   7944:   border-width: 0;
                   7945:   vertical-align: middle;
1.677     riegler  7946: }
1.680     riegler  7947: 
1.923     bisitz   7948: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7949:   vertical-align: top;
1.777     tempelho 7950: }
1.795     www      7951: 
1.716     raeburn  7952: div.LC_createcourse {
1.911     bisitz   7953:   margin: 10px 10px 10px 10px;
1.716     raeburn  7954: }
                   7955: 
1.917     raeburn  7956: .LC_dccid {
1.1130    raeburn  7957:   float: right;
1.917     raeburn  7958:   margin: 0.2em 0 0 0;
                   7959:   padding: 0;
                   7960:   font-size: 90%;
                   7961:   display:none;
                   7962: }
                   7963: 
1.897     wenzelju 7964: ol.LC_primary_menu a:hover,
1.721     harmsja  7965: ol#LC_MenuBreadcrumbs a:hover,
                   7966: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7967: ul#LC_secondary_menu a:hover,
1.721     harmsja  7968: .LC_FormSectionClearButton input:hover
1.795     www      7969: ul.LC_TabContent   li:hover a {
1.952     onken    7970:   color:$button_hover;
1.911     bisitz   7971:   text-decoration:none;
1.693     droeschl 7972: }
                   7973: 
1.779     bisitz   7974: h1 {
1.911     bisitz   7975:   padding: 0;
                   7976:   line-height:130%;
1.693     droeschl 7977: }
1.698     harmsja  7978: 
1.911     bisitz   7979: h2,
                   7980: h3,
                   7981: h4,
                   7982: h5,
                   7983: h6 {
                   7984:   margin: 5px 0 5px 0;
                   7985:   padding: 0;
                   7986:   line-height:130%;
1.693     droeschl 7987: }
1.795     www      7988: 
                   7989: .LC_hcell {
1.911     bisitz   7990:   padding:3px 15px 3px 15px;
                   7991:   margin: 0;
                   7992:   background-color:$tabbg;
                   7993:   color:$fontmenu;
                   7994:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7995: }
1.795     www      7996: 
1.840     bisitz   7997: .LC_Box > .LC_hcell {
1.911     bisitz   7998:   margin: 0 -10px 10px -10px;
1.835     bisitz   7999: }
                   8000: 
1.721     harmsja  8001: .LC_noBorder {
1.911     bisitz   8002:   border: 0;
1.698     harmsja  8003: }
1.693     droeschl 8004: 
1.721     harmsja  8005: .LC_FormSectionClearButton input {
1.911     bisitz   8006:   background-color:transparent;
                   8007:   border: none;
                   8008:   cursor:pointer;
                   8009:   text-decoration:underline;
1.693     droeschl 8010: }
1.763     bisitz   8011: 
                   8012: .LC_help_open_topic {
1.911     bisitz   8013:   color: #FFFFFF;
                   8014:   background-color: #EEEEFF;
                   8015:   margin: 1px;
                   8016:   padding: 4px;
                   8017:   border: 1px solid #000033;
                   8018:   white-space: nowrap;
                   8019:   /* vertical-align: middle; */
1.759     neumanie 8020: }
1.693     droeschl 8021: 
1.911     bisitz   8022: dl,
                   8023: ul,
                   8024: div,
                   8025: fieldset {
                   8026:   margin: 10px 10px 10px 0;
                   8027:   /* overflow: hidden; */
1.693     droeschl 8028: }
1.795     www      8029: 
1.1211    raeburn  8030: article.geogebraweb div {
                   8031:     margin: 0;
                   8032: }
                   8033: 
1.838     bisitz   8034: fieldset > legend {
1.911     bisitz   8035:   font-weight: bold;
                   8036:   padding: 0 5px 0 5px;
1.838     bisitz   8037: }
                   8038: 
1.813     bisitz   8039: #LC_nav_bar {
1.911     bisitz   8040:   float: left;
1.995     raeburn  8041:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8042:   margin: 0 0 2px 0;
1.807     droeschl 8043: }
                   8044: 
1.916     droeschl 8045: #LC_realm {
                   8046:   margin: 0.2em 0 0 0;
                   8047:   padding: 0;
                   8048:   font-weight: bold;
                   8049:   text-align: center;
1.995     raeburn  8050:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8051: }
                   8052: 
1.911     bisitz   8053: #LC_nav_bar em {
                   8054:   font-weight: bold;
                   8055:   font-style: normal;
1.807     droeschl 8056: }
                   8057: 
1.897     wenzelju 8058: ol.LC_primary_menu {
1.934     droeschl 8059:   margin: 0;
1.1076    raeburn  8060:   padding: 0;
1.807     droeschl 8061: }
                   8062: 
1.852     droeschl 8063: ol#LC_PathBreadcrumbs {
1.911     bisitz   8064:   margin: 0;
1.693     droeschl 8065: }
                   8066: 
1.897     wenzelju 8067: ol.LC_primary_menu li {
1.1076    raeburn  8068:   color: RGB(80, 80, 80);
                   8069:   vertical-align: middle;
                   8070:   text-align: left;
                   8071:   list-style: none;
1.1205    golterma 8072:   position: relative;
1.1076    raeburn  8073:   float: left;
1.1205    golterma 8074:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8075:   line-height: 1.5em;
1.1076    raeburn  8076: }
                   8077: 
1.1205    golterma 8078: ol.LC_primary_menu li a,
                   8079: ol.LC_primary_menu li p {
1.1076    raeburn  8080:   display: block;
                   8081:   margin: 0;
                   8082:   padding: 0 5px 0 10px;
                   8083:   text-decoration: none;
                   8084: }
                   8085: 
1.1205    golterma 8086: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8087:   display: inline-block;
                   8088:   width: 95%;
                   8089:   text-align: left;
                   8090: }
                   8091: 
                   8092: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8093:   display: inline-block;	
                   8094:   width: 5%;
                   8095:   float: right;
                   8096:   text-align: right;
                   8097:   font-size: 70%;
                   8098: }
                   8099: 
                   8100: ol.LC_primary_menu ul {
1.1076    raeburn  8101:   display: none;
1.1205    golterma 8102:   width: 15em;
1.1076    raeburn  8103:   background-color: $data_table_light;
1.1205    golterma 8104:   position: absolute;
                   8105:   top: 100%;
1.1076    raeburn  8106: }
                   8107: 
1.1205    golterma 8108: ol.LC_primary_menu ul ul {
                   8109:   left: 100%;
                   8110:   top: 0;
                   8111: }
                   8112: 
                   8113: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8114:   display: block;
                   8115:   position: absolute;
                   8116:   margin: 0;
                   8117:   padding: 0;
1.1078    raeburn  8118:   z-index: 2;
1.1076    raeburn  8119: }
                   8120: 
                   8121: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8122: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8123:   font-size: 90%;
1.911     bisitz   8124:   vertical-align: top;
1.1076    raeburn  8125:   float: none;
1.1079    raeburn  8126:   border-left: 1px solid black;
                   8127:   border-right: 1px solid black;
1.1205    golterma 8128: /* A dark bottom border to visualize different menu options; 
                   8129: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8130:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8131: }
                   8132: 
1.1205    golterma 8133: ol.LC_primary_menu li li p:hover {
                   8134:   color:$button_hover;
                   8135:   text-decoration:none;
                   8136:   background-color:$data_table_dark;
1.1076    raeburn  8137: }
                   8138: 
                   8139: ol.LC_primary_menu li li a:hover {
                   8140:    color:$button_hover;
                   8141:    background-color:$data_table_dark;
1.693     droeschl 8142: }
                   8143: 
1.1205    golterma 8144: /* Font-size equal to the size of the predecessors*/
                   8145: ol.LC_primary_menu li:hover li li {
                   8146:   font-size: 100%;
                   8147: }
                   8148: 
1.897     wenzelju 8149: ol.LC_primary_menu li img {
1.911     bisitz   8150:   vertical-align: bottom;
1.934     droeschl 8151:   height: 1.1em;
1.1077    raeburn  8152:   margin: 0.2em 0 0 0;
1.693     droeschl 8153: }
                   8154: 
1.897     wenzelju 8155: ol.LC_primary_menu a {
1.911     bisitz   8156:   color: RGB(80, 80, 80);
                   8157:   text-decoration: none;
1.693     droeschl 8158: }
1.795     www      8159: 
1.949     droeschl 8160: ol.LC_primary_menu a.LC_new_message {
                   8161:   font-weight:bold;
                   8162:   color: darkred;
                   8163: }
                   8164: 
1.975     raeburn  8165: ol.LC_docs_parameters {
                   8166:   margin-left: 0;
                   8167:   padding: 0;
                   8168:   list-style: none;
                   8169: }
                   8170: 
                   8171: ol.LC_docs_parameters li {
                   8172:   margin: 0;
                   8173:   padding-right: 20px;
                   8174:   display: inline;
                   8175: }
                   8176: 
1.976     raeburn  8177: ol.LC_docs_parameters li:before {
                   8178:   content: "\\002022 \\0020";
                   8179: }
                   8180: 
                   8181: li.LC_docs_parameters_title {
                   8182:   font-weight: bold;
                   8183: }
                   8184: 
                   8185: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8186:   content: "";
                   8187: }
                   8188: 
1.897     wenzelju 8189: ul#LC_secondary_menu {
1.1107    raeburn  8190:   clear: right;
1.911     bisitz   8191:   color: $fontmenu;
                   8192:   background: $tabbg;
                   8193:   list-style: none;
                   8194:   padding: 0;
                   8195:   margin: 0;
                   8196:   width: 100%;
1.995     raeburn  8197:   text-align: left;
1.1107    raeburn  8198:   float: left;
1.808     droeschl 8199: }
                   8200: 
1.897     wenzelju 8201: ul#LC_secondary_menu li {
1.911     bisitz   8202:   font-weight: bold;
                   8203:   line-height: 1.8em;
1.1107    raeburn  8204:   border-right: 1px solid black;
                   8205:   float: left;
                   8206: }
                   8207: 
                   8208: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8209:   background-color: $data_table_light;
                   8210: }
                   8211: 
                   8212: ul#LC_secondary_menu li a {
1.911     bisitz   8213:   padding: 0 0.8em;
1.1107    raeburn  8214: }
                   8215: 
                   8216: ul#LC_secondary_menu li ul {
                   8217:   display: none;
                   8218: }
                   8219: 
                   8220: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8221:   display: block;
                   8222:   position: absolute;
                   8223:   margin: 0;
                   8224:   padding: 0;
                   8225:   list-style:none;
                   8226:   float: none;
                   8227:   background-color: $data_table_light;
                   8228:   z-index: 2;
                   8229:   margin-left: -1px;
                   8230: }
                   8231: 
                   8232: ul#LC_secondary_menu li ul li {
                   8233:   font-size: 90%;
                   8234:   vertical-align: top;
                   8235:   border-left: 1px solid black;
1.911     bisitz   8236:   border-right: 1px solid black;
1.1119    raeburn  8237:   background-color: $data_table_light;
1.1107    raeburn  8238:   list-style:none;
                   8239:   float: none;
                   8240: }
                   8241: 
                   8242: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8243:   background-color: $data_table_dark;
1.807     droeschl 8244: }
                   8245: 
1.847     tempelho 8246: ul.LC_TabContent {
1.911     bisitz   8247:   display:block;
                   8248:   background: $sidebg;
                   8249:   border-bottom: solid 1px $lg_border_color;
                   8250:   list-style:none;
1.1020    raeburn  8251:   margin: -1px -10px 0 -10px;
1.911     bisitz   8252:   padding: 0;
1.693     droeschl 8253: }
                   8254: 
1.795     www      8255: ul.LC_TabContent li,
                   8256: ul.LC_TabContentBigger li {
1.911     bisitz   8257:   float:left;
1.741     harmsja  8258: }
1.795     www      8259: 
1.897     wenzelju 8260: ul#LC_secondary_menu li a {
1.911     bisitz   8261:   color: $fontmenu;
                   8262:   text-decoration: none;
1.693     droeschl 8263: }
1.795     www      8264: 
1.721     harmsja  8265: ul.LC_TabContent {
1.952     onken    8266:   min-height:20px;
1.721     harmsja  8267: }
1.795     www      8268: 
                   8269: ul.LC_TabContent li {
1.911     bisitz   8270:   vertical-align:middle;
1.959     onken    8271:   padding: 0 16px 0 10px;
1.911     bisitz   8272:   background-color:$tabbg;
                   8273:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8274:   border-left: solid 1px $font;
1.721     harmsja  8275: }
1.795     www      8276: 
1.847     tempelho 8277: ul.LC_TabContent .right {
1.911     bisitz   8278:   float:right;
1.847     tempelho 8279: }
                   8280: 
1.911     bisitz   8281: ul.LC_TabContent li a,
                   8282: ul.LC_TabContent li {
                   8283:   color:rgb(47,47,47);
                   8284:   text-decoration:none;
                   8285:   font-size:95%;
                   8286:   font-weight:bold;
1.952     onken    8287:   min-height:20px;
                   8288: }
                   8289: 
1.959     onken    8290: ul.LC_TabContent li a:hover,
                   8291: ul.LC_TabContent li a:focus {
1.952     onken    8292:   color: $button_hover;
1.959     onken    8293:   background:none;
                   8294:   outline:none;
1.952     onken    8295: }
                   8296: 
                   8297: ul.LC_TabContent li:hover {
                   8298:   color: $button_hover;
                   8299:   cursor:pointer;
1.721     harmsja  8300: }
1.795     www      8301: 
1.911     bisitz   8302: ul.LC_TabContent li.active {
1.952     onken    8303:   color: $font;
1.911     bisitz   8304:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8305:   border-bottom:solid 1px #FFFFFF;
                   8306:   cursor: default;
1.744     ehlerst  8307: }
1.795     www      8308: 
1.959     onken    8309: ul.LC_TabContent li.active a {
                   8310:   color:$font;
                   8311:   background:#FFFFFF;
                   8312:   outline: none;
                   8313: }
1.1047    raeburn  8314: 
                   8315: ul.LC_TabContent li.goback {
                   8316:   float: left;
                   8317:   border-left: none;
                   8318: }
                   8319: 
1.870     tempelho 8320: #maincoursedoc {
1.911     bisitz   8321:   clear:both;
1.870     tempelho 8322: }
                   8323: 
                   8324: ul.LC_TabContentBigger {
1.911     bisitz   8325:   display:block;
                   8326:   list-style:none;
                   8327:   padding: 0;
1.870     tempelho 8328: }
                   8329: 
1.795     www      8330: ul.LC_TabContentBigger li {
1.911     bisitz   8331:   vertical-align:bottom;
                   8332:   height: 30px;
                   8333:   font-size:110%;
                   8334:   font-weight:bold;
                   8335:   color: #737373;
1.841     tempelho 8336: }
                   8337: 
1.957     onken    8338: ul.LC_TabContentBigger li.active {
                   8339:   position: relative;
                   8340:   top: 1px;
                   8341: }
                   8342: 
1.870     tempelho 8343: ul.LC_TabContentBigger li a {
1.911     bisitz   8344:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8345:   height: 30px;
                   8346:   line-height: 30px;
                   8347:   text-align: center;
                   8348:   display: block;
                   8349:   text-decoration: none;
1.958     onken    8350:   outline: none;  
1.741     harmsja  8351: }
1.795     www      8352: 
1.870     tempelho 8353: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8354:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8355:   color:$font;
1.744     ehlerst  8356: }
1.795     www      8357: 
1.870     tempelho 8358: ul.LC_TabContentBigger li b {
1.911     bisitz   8359:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8360:   display: block;
                   8361:   float: left;
                   8362:   padding: 0 30px;
1.957     onken    8363:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8364: }
                   8365: 
1.956     onken    8366: ul.LC_TabContentBigger li:hover b {
                   8367:   color:$button_hover;
                   8368: }
                   8369: 
1.870     tempelho 8370: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8371:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8372:   color:$font;
1.957     onken    8373:   border: 0;
1.741     harmsja  8374: }
1.693     droeschl 8375: 
1.870     tempelho 8376: 
1.862     bisitz   8377: ul.LC_CourseBreadcrumbs {
                   8378:   background: $sidebg;
1.1020    raeburn  8379:   height: 2em;
1.862     bisitz   8380:   padding-left: 10px;
1.1020    raeburn  8381:   margin: 0;
1.862     bisitz   8382:   list-style-position: inside;
                   8383: }
                   8384: 
1.911     bisitz   8385: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8386: ol#LC_PathBreadcrumbs {
1.911     bisitz   8387:   padding-left: 10px;
                   8388:   margin: 0;
1.933     droeschl 8389:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8390: }
                   8391: 
1.911     bisitz   8392: ol#LC_MenuBreadcrumbs li,
                   8393: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8394: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8395:   display: inline;
1.933     droeschl 8396:   white-space: normal;  
1.693     droeschl 8397: }
                   8398: 
1.823     bisitz   8399: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8400: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8401:   text-decoration: none;
                   8402:   font-size:90%;
1.693     droeschl 8403: }
1.795     www      8404: 
1.969     droeschl 8405: ol#LC_MenuBreadcrumbs h1 {
                   8406:   display: inline;
                   8407:   font-size: 90%;
                   8408:   line-height: 2.5em;
                   8409:   margin: 0;
                   8410:   padding: 0;
                   8411: }
                   8412: 
1.795     www      8413: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8414:   text-decoration:none;
                   8415:   font-size:100%;
                   8416:   font-weight:bold;
1.693     droeschl 8417: }
1.795     www      8418: 
1.840     bisitz   8419: .LC_Box {
1.911     bisitz   8420:   border: solid 1px $lg_border_color;
                   8421:   padding: 0 10px 10px 10px;
1.746     neumanie 8422: }
1.795     www      8423: 
1.1020    raeburn  8424: .LC_DocsBox {
                   8425:   border: solid 1px $lg_border_color;
                   8426:   padding: 0 0 10px 10px;
                   8427: }
                   8428: 
1.795     www      8429: .LC_AboutMe_Image {
1.911     bisitz   8430:   float:left;
                   8431:   margin-right:10px;
1.747     neumanie 8432: }
1.795     www      8433: 
                   8434: .LC_Clear_AboutMe_Image {
1.911     bisitz   8435:   clear:left;
1.747     neumanie 8436: }
1.795     www      8437: 
1.721     harmsja  8438: dl.LC_ListStyleClean dt {
1.911     bisitz   8439:   padding-right: 5px;
                   8440:   display: table-header-group;
1.693     droeschl 8441: }
                   8442: 
1.721     harmsja  8443: dl.LC_ListStyleClean dd {
1.911     bisitz   8444:   display: table-row;
1.693     droeschl 8445: }
                   8446: 
1.721     harmsja  8447: .LC_ListStyleClean,
                   8448: .LC_ListStyleSimple,
                   8449: .LC_ListStyleNormal,
1.795     www      8450: .LC_ListStyleSpecial {
1.911     bisitz   8451:   /* display:block; */
                   8452:   list-style-position: inside;
                   8453:   list-style-type: none;
                   8454:   overflow: hidden;
                   8455:   padding: 0;
1.693     droeschl 8456: }
                   8457: 
1.721     harmsja  8458: .LC_ListStyleSimple li,
                   8459: .LC_ListStyleSimple dd,
                   8460: .LC_ListStyleNormal li,
                   8461: .LC_ListStyleNormal dd,
                   8462: .LC_ListStyleSpecial li,
1.795     www      8463: .LC_ListStyleSpecial dd {
1.911     bisitz   8464:   margin: 0;
                   8465:   padding: 5px 5px 5px 10px;
                   8466:   clear: both;
1.693     droeschl 8467: }
                   8468: 
1.721     harmsja  8469: .LC_ListStyleClean li,
                   8470: .LC_ListStyleClean dd {
1.911     bisitz   8471:   padding-top: 0;
                   8472:   padding-bottom: 0;
1.693     droeschl 8473: }
                   8474: 
1.721     harmsja  8475: .LC_ListStyleSimple dd,
1.795     www      8476: .LC_ListStyleSimple li {
1.911     bisitz   8477:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8478: }
                   8479: 
1.721     harmsja  8480: .LC_ListStyleSpecial li,
                   8481: .LC_ListStyleSpecial dd {
1.911     bisitz   8482:   list-style-type: none;
                   8483:   background-color: RGB(220, 220, 220);
                   8484:   margin-bottom: 4px;
1.693     droeschl 8485: }
                   8486: 
1.721     harmsja  8487: table.LC_SimpleTable {
1.911     bisitz   8488:   margin:5px;
                   8489:   border:solid 1px $lg_border_color;
1.795     www      8490: }
1.693     droeschl 8491: 
1.721     harmsja  8492: table.LC_SimpleTable tr {
1.911     bisitz   8493:   padding: 0;
                   8494:   border:solid 1px $lg_border_color;
1.693     droeschl 8495: }
1.795     www      8496: 
                   8497: table.LC_SimpleTable thead {
1.911     bisitz   8498:   background:rgb(220,220,220);
1.693     droeschl 8499: }
                   8500: 
1.721     harmsja  8501: div.LC_columnSection {
1.911     bisitz   8502:   display: block;
                   8503:   clear: both;
                   8504:   overflow: hidden;
                   8505:   margin: 0;
1.693     droeschl 8506: }
                   8507: 
1.721     harmsja  8508: div.LC_columnSection>* {
1.911     bisitz   8509:   float: left;
                   8510:   margin: 10px 20px 10px 0;
                   8511:   overflow:hidden;
1.693     droeschl 8512: }
1.721     harmsja  8513: 
1.795     www      8514: table em {
1.911     bisitz   8515:   font-weight: bold;
                   8516:   font-style: normal;
1.748     schulted 8517: }
1.795     www      8518: 
1.779     bisitz   8519: table.LC_tableBrowseRes,
1.795     www      8520: table.LC_tableOfContent {
1.911     bisitz   8521:   border:none;
                   8522:   border-spacing: 1px;
                   8523:   padding: 3px;
                   8524:   background-color: #FFFFFF;
                   8525:   font-size: 90%;
1.753     droeschl 8526: }
1.789     droeschl 8527: 
1.911     bisitz   8528: table.LC_tableOfContent {
                   8529:   border-collapse: collapse;
1.789     droeschl 8530: }
                   8531: 
1.771     droeschl 8532: table.LC_tableBrowseRes a,
1.768     schulted 8533: table.LC_tableOfContent a {
1.911     bisitz   8534:   background-color: transparent;
                   8535:   text-decoration: none;
1.753     droeschl 8536: }
                   8537: 
1.795     www      8538: table.LC_tableOfContent img {
1.911     bisitz   8539:   border: none;
                   8540:   height: 1.3em;
                   8541:   vertical-align: text-bottom;
                   8542:   margin-right: 0.3em;
1.753     droeschl 8543: }
1.757     schulted 8544: 
1.795     www      8545: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8546:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8547: }
                   8548: 
1.795     www      8549: a#LC_content_toolbar_everything {
1.911     bisitz   8550:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8551: }
                   8552: 
1.795     www      8553: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8554:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8555: }
                   8556: 
1.795     www      8557: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8558:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8559: }
                   8560: 
1.795     www      8561: a#LC_content_toolbar_changefolder {
1.911     bisitz   8562:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8563: }
                   8564: 
1.795     www      8565: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8566:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8567: }
                   8568: 
1.1043    raeburn  8569: a#LC_content_toolbar_edittoplevel {
                   8570:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8571: }
                   8572: 
1.1384    raeburn  8573: a#LC_content_toolbar_printout {
                   8574:   background-image:url(/res/adm/pages/printout.gif);
                   8575: }
                   8576: 
1.795     www      8577: ul#LC_toolbar li a:hover {
1.911     bisitz   8578:   background-position: bottom center;
1.757     schulted 8579: }
                   8580: 
1.795     www      8581: ul#LC_toolbar {
1.911     bisitz   8582:   padding: 0;
                   8583:   margin: 2px;
                   8584:   list-style:none;
                   8585:   position:relative;
                   8586:   background-color:white;
1.1082    raeburn  8587:   overflow: auto;
1.757     schulted 8588: }
                   8589: 
1.795     www      8590: ul#LC_toolbar li {
1.911     bisitz   8591:   border:1px solid white;
                   8592:   padding: 0;
                   8593:   margin: 0;
                   8594:   float: left;
                   8595:   display:inline;
                   8596:   vertical-align:middle;
1.1082    raeburn  8597:   white-space: nowrap;
1.911     bisitz   8598: }
1.757     schulted 8599: 
1.783     amueller 8600: 
1.795     www      8601: a.LC_toolbarItem {
1.911     bisitz   8602:   display:block;
                   8603:   padding: 0;
                   8604:   margin: 0;
                   8605:   height: 32px;
                   8606:   width: 32px;
                   8607:   color:white;
                   8608:   border: none;
                   8609:   background-repeat:no-repeat;
                   8610:   background-color:transparent;
1.757     schulted 8611: }
                   8612: 
1.915     droeschl 8613: ul.LC_funclist {
                   8614:     margin: 0;
                   8615:     padding: 0.5em 1em 0.5em 0;
                   8616: }
                   8617: 
1.933     droeschl 8618: ul.LC_funclist > li:first-child {
                   8619:     font-weight:bold; 
                   8620:     margin-left:0.8em;
                   8621: }
                   8622: 
1.915     droeschl 8623: ul.LC_funclist + ul.LC_funclist {
                   8624:     /* 
                   8625:        left border as a seperator if we have more than
                   8626:        one list 
                   8627:     */
                   8628:     border-left: 1px solid $sidebg;
                   8629:     /* 
                   8630:        this hides the left border behind the border of the 
                   8631:        outer box if element is wrapped to the next 'line' 
                   8632:     */
                   8633:     margin-left: -1px;
                   8634: }
                   8635: 
1.843     bisitz   8636: ul.LC_funclist li {
1.915     droeschl 8637:   display: inline;
1.782     bisitz   8638:   white-space: nowrap;
1.915     droeschl 8639:   margin: 0 0 0 25px;
                   8640:   line-height: 150%;
1.782     bisitz   8641: }
                   8642: 
1.974     wenzelju 8643: .LC_hidden {
                   8644:   display: none;
                   8645: }
                   8646: 
1.1030    www      8647: .LCmodal-overlay {
                   8648: 		position:fixed;
                   8649: 		top:0;
                   8650: 		right:0;
                   8651: 		bottom:0;
                   8652: 		left:0;
                   8653: 		height:100%;
                   8654: 		width:100%;
                   8655: 		margin:0;
                   8656: 		padding:0;
                   8657: 		background:#999;
                   8658: 		opacity:.75;
                   8659: 		filter: alpha(opacity=75);
                   8660: 		-moz-opacity: 0.75;
                   8661: 		z-index:101;
                   8662: }
                   8663: 
                   8664: * html .LCmodal-overlay {   
                   8665: 		position: absolute;
                   8666: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8667: }
                   8668: 
                   8669: .LCmodal-window {
                   8670: 		position:fixed;
                   8671: 		top:50%;
                   8672: 		left:50%;
                   8673: 		margin:0;
                   8674: 		padding:0;
                   8675: 		z-index:102;
                   8676: 	}
                   8677: 
                   8678: * html .LCmodal-window {
                   8679: 		position:absolute;
                   8680: }
                   8681: 
                   8682: .LCclose-window {
                   8683: 		position:absolute;
                   8684: 		width:32px;
                   8685: 		height:32px;
                   8686: 		right:8px;
                   8687: 		top:8px;
                   8688: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8689: 		text-indent:-99999px;
                   8690: 		overflow:hidden;
                   8691: 		cursor:pointer;
                   8692: }
                   8693: 
1.1369    raeburn  8694: .LCisDisabled {
                   8695:   cursor: not-allowed;
                   8696:   opacity: 0.5;
                   8697: }
                   8698: 
                   8699: a[aria-disabled="true"] {
                   8700:   color: currentColor;
                   8701:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8702:   pointer-events: none;
                   8703:   text-decoration: none;
                   8704: }
                   8705: 
1.1335    raeburn  8706: pre.LC_wordwrap {
                   8707:   white-space: pre-wrap;
                   8708:   white-space: -moz-pre-wrap;
                   8709:   white-space: -pre-wrap;
                   8710:   white-space: -o-pre-wrap;
                   8711:   word-wrap: break-word;
                   8712: }
                   8713: 
1.1100    raeburn  8714: /*
1.1231    damieng  8715:   styles used for response display
                   8716: */
                   8717: div.LC_radiofoil, div.LC_rankfoil {
                   8718:   margin: .5em 0em .5em 0em;
                   8719: }
                   8720: table.LC_itemgroup {
                   8721:   margin-top: 1em;
                   8722: }
                   8723: 
                   8724: /*
1.1100    raeburn  8725:   styles used by TTH when "Default set of options to pass to tth/m
                   8726:   when converting TeX" in course settings has been set
                   8727: 
                   8728:   option passed: -t
                   8729: 
                   8730: */
                   8731: 
                   8732: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8733: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8734: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8735: td div.norm {line-height:normal;}
                   8736: 
                   8737: /*
                   8738:   option passed -y3
                   8739: */
                   8740: 
                   8741: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8742: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8743: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8744: 
1.1230    damieng  8745: /*
                   8746:   sections with roles, for content only
                   8747: */
                   8748: section[class^="role-"] {
                   8749:   padding-left: 10px;
                   8750:   padding-right: 5px;
                   8751:   margin-top: 8px;
                   8752:   margin-bottom: 8px;
                   8753:   border: 1px solid #2A4;
                   8754:   border-radius: 5px;
                   8755:   box-shadow: 0px 1px 1px #BBB;
                   8756: }
                   8757: section[class^="role-"]>h1 {
                   8758:   position: relative;
                   8759:   margin: 0px;
                   8760:   padding-top: 10px;
                   8761:   padding-left: 40px;
                   8762: }
                   8763: section[class^="role-"]>h1:before {
                   8764:   position: absolute;
                   8765:   left: -5px;
                   8766:   top: 5px;
                   8767: }
                   8768: section.role-activity>h1:before {
                   8769:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8770: }
                   8771: section.role-advice>h1:before {
                   8772:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8773: }
                   8774: section.role-bibliography>h1:before {
                   8775:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8776: }
                   8777: section.role-citation>h1:before {
                   8778:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8779: }
                   8780: section.role-conclusion>h1:before {
                   8781:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8782: }
                   8783: section.role-definition>h1:before {
                   8784:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8785: }
                   8786: section.role-demonstration>h1:before {
                   8787:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8788: }
                   8789: section.role-example>h1:before {
                   8790:   content:url('/adm/daxe/images/section_icons/example.png');
                   8791: }
                   8792: section.role-explanation>h1:before {
                   8793:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8794: }
                   8795: section.role-introduction>h1:before {
                   8796:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8797: }
                   8798: section.role-method>h1:before {
                   8799:   content:url('/adm/daxe/images/section_icons/method.png');
                   8800: }
                   8801: section.role-more_information>h1:before {
                   8802:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8803: }
                   8804: section.role-objectives>h1:before {
                   8805:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8806: }
                   8807: section.role-prerequisites>h1:before {
                   8808:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8809: }
                   8810: section.role-remark>h1:before {
                   8811:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8812: }
                   8813: section.role-reminder>h1:before {
                   8814:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8815: }
                   8816: section.role-summary>h1:before {
                   8817:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8818: }
                   8819: section.role-syntax>h1:before {
                   8820:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8821: }
                   8822: section.role-warning>h1:before {
                   8823:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8824: }
                   8825: 
1.1269    raeburn  8826: #LC_minitab_header {
                   8827:   float:left;
                   8828:   width:100%;
                   8829:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8830:   font-size:93%;
                   8831:   line-height:normal;
                   8832:   margin: 0.5em 0 0.5em 0;
                   8833: }
                   8834: #LC_minitab_header ul {
                   8835:   margin:0;
                   8836:   padding:10px 10px 0;
                   8837:   list-style:none;
                   8838: }
                   8839: #LC_minitab_header li {
                   8840:   float:left;
                   8841:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8842:   margin:0;
                   8843:   padding:0 0 0 9px;
                   8844: }
                   8845: #LC_minitab_header a {
                   8846:   display:block;
                   8847:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8848:   padding:5px 15px 4px 6px;
                   8849: }
                   8850: #LC_minitab_header #LC_current_minitab {
                   8851:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8852: }
                   8853: #LC_minitab_header #LC_current_minitab a {
                   8854:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8855:   padding-bottom:5px;
                   8856: }
                   8857: 
                   8858: 
1.343     albertel 8859: END
                   8860: }
                   8861: 
1.306     albertel 8862: =pod
                   8863: 
                   8864: =item * &headtag()
                   8865: 
                   8866: Returns a uniform footer for LON-CAPA web pages.
                   8867: 
1.307     albertel 8868: Inputs: $title - optional title for the head
                   8869:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8870:         $args - optional arguments
1.319     albertel 8871:             force_register - if is true call registerurl so the remote is 
                   8872:                              informed
1.415     albertel 8873:             redirect       -> array ref of
                   8874:                                    1- seconds before redirect occurs
                   8875:                                    2- url to redirect to
                   8876:                                    3- whether the side effect should occur
1.315     albertel 8877:                            (side effect of setting 
                   8878:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  8879:                                redirected to)
                   8880:                                    4- whether the redirect target should be
                   8881:                                       the opener of the current (pop-up)
                   8882:                                       window (side effect of setting
                   8883:                                       $env{'internal.head.to_opener'} to
                   8884:                                       1, if true.
1.1388    raeburn  8885:                                    5- whether encrypt check should be skipped
1.352     albertel 8886:             domain         -> force to color decorate a page for a specific
                   8887:                                domain
                   8888:             function       -> force usage of a specific rolish color scheme
                   8889:             bgcolor        -> override the default page bgcolor
1.460     albertel 8890:             no_auto_mt_title
                   8891:                            -> prevent &mt()ing the title arg
1.464     albertel 8892: 
1.306     albertel 8893: =cut
                   8894: 
                   8895: sub headtag {
1.313     albertel 8896:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8897:     
1.363     albertel 8898:     my $function = $args->{'function'} || &get_users_function();
                   8899:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8900:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8901:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8902:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8903: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8904: 		   #time(),
1.418     albertel 8905: 		   $env{'environment.color.timestamp'},
1.363     albertel 8906: 		   $function,$domain,$bgcolor);
                   8907: 
1.369     www      8908:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8909: 
1.308     albertel 8910:     my $result =
                   8911: 	'<head>'.
1.1160    raeburn  8912: 	&font_settings($args);
1.319     albertel 8913: 
1.1188    raeburn  8914:     my $inhibitprint;
                   8915:     if ($args->{'print_suppress'}) {
                   8916:         $inhibitprint = &print_suppression();
                   8917:     }
1.1064    raeburn  8918: 
1.461     albertel 8919:     if (!$args->{'frameset'}) {
                   8920: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8921:     }
1.962     droeschl 8922:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8923:         $result .= Apache::lonxml::display_title();
1.319     albertel 8924:     }
1.436     albertel 8925:     if (!$args->{'no_nav_bar'} 
                   8926: 	&& !$args->{'only_body'}
                   8927: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8928: 	$result .= &help_menu_js($httphost);
1.1032    www      8929:         $result.=&modal_window();
1.1038    www      8930:         $result.=&togglebox_script();
1.1034    www      8931:         $result.=&wishlist_window();
1.1041    www      8932:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8933:     } else {
                   8934:         if ($args->{'add_modal'}) {
                   8935:            $result.=&modal_window();
                   8936:         }
                   8937:         if ($args->{'add_wishlist'}) {
                   8938:            $result.=&wishlist_window();
                   8939:         }
1.1038    www      8940:         if ($args->{'add_togglebox'}) {
                   8941:            $result.=&togglebox_script();
                   8942:         }
1.1041    www      8943:         if ($args->{'add_progressbar'}) {
                   8944:            $result.=&LCprogressbarUpdate_script();
                   8945:         }
1.436     albertel 8946:     }
1.314     albertel 8947:     if (ref($args->{'redirect'})) {
1.1388    raeburn  8948: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   8949:         if (!$skip_enc_check) {
                   8950:             $url = &Apache::lonenc::check_encrypt($url);
                   8951:         }
1.414     albertel 8952: 	if (!$inhibit_continue) {
                   8953: 	    $env{'internal.head.redirect'} = $url;
                   8954: 	}
1.1386    raeburn  8955: 	$result.=<<"ADDMETA";
1.313     albertel 8956: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  8957: ADDMETA
                   8958:         if ($to_opener) {
                   8959:             $env{'internal.head.to_opener'} = 1;
                   8960:             my $dest = &js_escape($url);
                   8961:             my $timeout = int($time * 1000);
                   8962:             $result .=<<"ENDJS";
                   8963: <script type="text/javascript">
                   8964: // <![CDATA[
                   8965: function LC_To_Opener() {
                   8966:     var dest = '$dest';
                   8967:     if (dest != '') {
                   8968:         if (window.opener != null && !window.opener.closed) {
                   8969:             window.opener.location.href=dest;
                   8970:             window.close();
                   8971:         } else {
                   8972:             window.location.href=dest;
                   8973:         }
                   8974:     }
                   8975: }
                   8976: \$(document).ready(function () {
                   8977:     setTimeout('LC_To_Opener()',$timeout);
                   8978: });
                   8979: // ]]>
                   8980: </script>
                   8981: ENDJS
                   8982:         } else {
                   8983:             $result.=<<"ADDMETA";
1.344     albertel 8984: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8985: ADDMETA
1.1386    raeburn  8986:         }
1.1210    raeburn  8987:     } else {
                   8988:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8989:             my $requrl = $env{'request.uri'};
                   8990:             if ($requrl eq '') {
                   8991:                 $requrl = $ENV{'REQUEST_URI'};
                   8992:                 $requrl =~ s/\?.+$//;
                   8993:             }
                   8994:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8995:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8996:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8997:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8998:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8999:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9000:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9001:                     my ($offload,$offloadoth);
1.1210    raeburn  9002:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9003:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9004:                             $offload = 1;
1.1353    raeburn  9005:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9006:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9007:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9008:                                     $offloadoth = 1;
                   9009:                                     $dom_in_use = $env{'user.domain'};
                   9010:                                 }
                   9011:                             }
1.1340    raeburn  9012:                         }
                   9013:                     }
                   9014:                     unless ($offload) {
                   9015:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9016:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9017:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9018:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9019:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9020:                                         $offload = 1;
1.1352    raeburn  9021:                                         $offloadoth = 1;
1.1340    raeburn  9022:                                         $dom_in_use = $env{'user.domain'};
                   9023:                                     }
1.1210    raeburn  9024:                                 }
1.1340    raeburn  9025:                             }
                   9026:                         }
                   9027:                     }
                   9028:                     if ($offload) {
1.1358    raeburn  9029:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9030:                         if (($newserver eq '') && ($offloadoth)) {
                   9031:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9032:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9033:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9034:                             }
                   9035:                         }
1.1340    raeburn  9036:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9037:                             my $numsec = 5;
                   9038:                             my $timeout = $numsec * 1000;
                   9039:                             my ($newurl,$locknum,%locks,$msg);
                   9040:                             if ($env{'request.role.adv'}) {
                   9041:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9042:                             }
                   9043:                             my $disable_submit = 0;
                   9044:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9045:                                 $disable_submit = 1;
                   9046:                             }
                   9047:                             if ($locknum) {
                   9048:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9049:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9050:                                        join(", ",sort(values(%locks)))."\n";
                   9051:                                 if (&show_course()) {
                   9052:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9053:                                 } else {
                   9054:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9055:                                 }
1.1340    raeburn  9056:                             } else {
                   9057:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9058:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9059:                                 }
                   9060:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9061:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9062:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9063:                                     $newurl .= '&role='.$env{'request.role'};
                   9064:                                 }
                   9065:                                 if ($env{'request.symb'}) {
                   9066:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9067:                                     if ($shownsymb =~ m{^/enc/}) {
                   9068:                                         my $reqdmajor = 2;
                   9069:                                         my $reqdminor = 11;
                   9070:                                         my $reqdsubminor = 3;
                   9071:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9072:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9073:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9074:                                         if (($major eq '' && $minor eq '') ||
                   9075:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9076:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9077:                                              ($reqdsubminor > $subminor))))) {
                   9078:                                             undef($shownsymb);
                   9079:                                         }
1.1210    raeburn  9080:                                     }
1.1340    raeburn  9081:                                     if ($shownsymb) {
                   9082:                                         &js_escape(\$shownsymb);
                   9083:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9084:                                     }
1.1340    raeburn  9085:                                 } else {
                   9086:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9087:                                     &js_escape(\$shownurl);
                   9088:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9089:                                 }
1.1340    raeburn  9090:                             }
                   9091:                             &js_escape(\$msg);
                   9092:                             $result.=<<OFFLOAD
1.1210    raeburn  9093: <meta http-equiv="pragma" content="no-cache" />
                   9094: <script type="text/javascript">
1.1215    raeburn  9095: // <![CDATA[
1.1210    raeburn  9096: function LC_Offload_Now() {
                   9097:     var dest = "$newurl";
                   9098:     if (dest != '') {
                   9099:         window.location.href="$newurl";
                   9100:     }
                   9101: }
1.1214    raeburn  9102: \$(document).ready(function () {
                   9103:     window.alert('$msg');
                   9104:     if ($disable_submit) {
1.1210    raeburn  9105:         \$(".LC_hwk_submit").prop("disabled", true);
                   9106:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9107:     }
                   9108:     setTimeout('LC_Offload_Now()', $timeout);
                   9109: });
1.1215    raeburn  9110: // ]]>
1.1210    raeburn  9111: </script>
                   9112: OFFLOAD
                   9113:                         }
                   9114:                     }
                   9115:                 }
                   9116:             }
                   9117:         }
1.313     albertel 9118:     }
1.306     albertel 9119:     if (!defined($title)) {
                   9120: 	$title = 'The LearningOnline Network with CAPA';
                   9121:     }
1.460     albertel 9122:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9123:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9124: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9125:     if (!$args->{'frameset'}) {
                   9126:         $result .= ' /';
                   9127:     }
                   9128:     $result .= '>' 
1.1064    raeburn  9129:         .$inhibitprint
1.414     albertel 9130: 	.$head_extra;
1.1242    raeburn  9131:     my $clientmobile;
                   9132:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9133:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9134:     } else {
                   9135:         $clientmobile = $env{'browser.mobile'};
                   9136:     }
                   9137:     if ($clientmobile) {
1.1137    raeburn  9138:         $result .= '
                   9139: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9140: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9141:     }
1.1278    raeburn  9142:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9143:     return $result.'</head>';
1.306     albertel 9144: }
                   9145: 
                   9146: =pod
                   9147: 
1.340     albertel 9148: =item * &font_settings()
                   9149: 
                   9150: Returns neccessary <meta> to set the proper encoding
                   9151: 
1.1160    raeburn  9152: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9153: 
                   9154: =cut
                   9155: 
                   9156: sub font_settings {
1.1160    raeburn  9157:     my ($args) = @_;
1.340     albertel 9158:     my $headerstring='';
1.1160    raeburn  9159:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9160:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9161:         $headerstring.=
                   9162:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9163:         if (!$args->{'frameset'}) {
                   9164: 	    $headerstring.= ' /';
                   9165:         }
                   9166: 	$headerstring .= '>'."\n";
1.340     albertel 9167:     }
                   9168:     return $headerstring;
                   9169: }
                   9170: 
1.341     albertel 9171: =pod
                   9172: 
1.1064    raeburn  9173: =item * &print_suppression()
                   9174: 
                   9175: In course context returns css which causes the body to be blank when media="print",
                   9176: if printout generation is unavailable for the current resource.
                   9177: 
                   9178: This could be because:
                   9179: 
                   9180: (a) printstartdate is in the future
                   9181: 
                   9182: (b) printenddate is in the past
                   9183: 
                   9184: (c) there is an active exam block with "printout"
                   9185: functionality blocked
                   9186: 
                   9187: Users with pav, pfo or evb privileges are exempt.
                   9188: 
                   9189: Inputs: none
                   9190: 
                   9191: =cut
                   9192: 
                   9193: 
                   9194: sub print_suppression {
                   9195:     my $noprint;
                   9196:     if ($env{'request.course.id'}) {
                   9197:         my $scope = $env{'request.course.id'};
                   9198:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9199:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9200:             return;
                   9201:         }
                   9202:         if ($env{'request.course.sec'} ne '') {
                   9203:             $scope .= "/$env{'request.course.sec'}";
                   9204:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9205:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9206:                 return;
1.1064    raeburn  9207:             }
                   9208:         }
                   9209:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9210:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9211:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9212:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9213:         if ($blocked) {
                   9214:             my $checkrole = "cm./$cdom/$cnum";
                   9215:             if ($env{'request.course.sec'} ne '') {
                   9216:                 $checkrole .= "/$env{'request.course.sec'}";
                   9217:             }
                   9218:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9219:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9220:                 $noprint = 1;
                   9221:             }
                   9222:         }
                   9223:         unless ($noprint) {
                   9224:             my $symb = &Apache::lonnet::symbread();
                   9225:             if ($symb ne '') {
                   9226:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9227:                 if (ref($navmap)) {
                   9228:                     my $res = $navmap->getBySymb($symb);
                   9229:                     if (ref($res)) {
                   9230:                         if (!$res->resprintable()) {
                   9231:                             $noprint = 1;
                   9232:                         }
                   9233:                     }
                   9234:                 }
                   9235:             }
                   9236:         }
                   9237:         if ($noprint) {
                   9238:             return <<"ENDSTYLE";
                   9239: <style type="text/css" media="print">
                   9240:     body { display:none }
                   9241: </style>
                   9242: ENDSTYLE
                   9243:         }
                   9244:     }
                   9245:     return;
                   9246: }
                   9247: 
                   9248: =pod
                   9249: 
1.341     albertel 9250: =item * &xml_begin()
                   9251: 
                   9252: Returns the needed doctype and <html>
                   9253: 
                   9254: Inputs: none
                   9255: 
                   9256: =cut
                   9257: 
                   9258: sub xml_begin {
1.1168    raeburn  9259:     my ($is_frameset) = @_;
1.341     albertel 9260:     my $output='';
                   9261: 
                   9262:     if ($env{'browser.mathml'}) {
                   9263: 	$output='<?xml version="1.0"?>'
                   9264:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9265: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9266:             
                   9267: #	    .'<!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">] >'
                   9268: 	    .'<!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">'
                   9269:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9270: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9271:     } elsif ($is_frameset) {
                   9272:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9273:                 '<html>'."\n";
1.341     albertel 9274:     } else {
1.1168    raeburn  9275: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9276:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9277:     }
                   9278:     return $output;
                   9279: }
1.340     albertel 9280: 
                   9281: =pod
                   9282: 
1.306     albertel 9283: =item * &start_page()
                   9284: 
                   9285: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9286: 
1.648     raeburn  9287: Inputs:
                   9288: 
                   9289: =over 4
                   9290: 
                   9291: $title - optional title for the page
                   9292: 
                   9293: $head_extra - optional extra HTML to incude inside the <head>
                   9294: 
                   9295: $args - additional optional args supported are:
                   9296: 
                   9297: =over 8
                   9298: 
                   9299:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9300:                                     arg on
1.814     bisitz   9301:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9302:              add_entries    -> additional attributes to add to the  <body>
                   9303:              domain         -> force to color decorate a page for a 
1.317     albertel 9304:                                     specific domain
1.648     raeburn  9305:              function       -> force usage of a specific rolish color
1.317     albertel 9306:                                     scheme
1.648     raeburn  9307:              redirect       -> see &headtag()
                   9308:              bgcolor        -> override the default page bg color
                   9309:              js_ready       -> return a string ready for being used in 
1.317     albertel 9310:                                     a javascript writeln
1.648     raeburn  9311:              html_encode    -> return a string ready for being used in 
1.320     albertel 9312:                                     a html attribute
1.648     raeburn  9313:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9314:                                     $forcereg arg
1.648     raeburn  9315:              frameset       -> if true will start with a <frameset>
1.330     albertel 9316:                                     rather than <body>
1.648     raeburn  9317:              skip_phases    -> hash ref of 
1.338     albertel 9318:                                     head -> skip the <html><head> generation
                   9319:                                     body -> skip all <body> generation
1.648     raeburn  9320:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9321:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9322:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9323:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9324:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9325:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9326:                                specific group
                   9327:              use_absolute   -> for request for external resource or syllabus, this
                   9328:                                will contain https://<hostname> if server uses
                   9329:                                https (as per hosts.tab), but request is for http
                   9330:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9331:              links_disabled -> Links in primary and secondary menus are disabled
                   9332:                                (Can enable them once page has loaded - see lonroles.pm
                   9333:                                for an example).
1.1380    raeburn  9334:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9335: 
1.648     raeburn  9336: =back
1.460     albertel 9337: 
1.648     raeburn  9338: =back
1.562     albertel 9339: 
1.306     albertel 9340: =cut
                   9341: 
                   9342: sub start_page {
1.309     albertel 9343:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9344:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9345: 
1.315     albertel 9346:     $env{'internal.start_page'}++;
1.1359    raeburn  9347:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9348: 
1.338     albertel 9349:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9350:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9351:     }
1.1316    raeburn  9352: 
                   9353:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9354:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9355:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9356:                 $args->{'no_primary_menu'} = 1;
                   9357:             }
                   9358:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9359:                 $args->{'no_inline_menu'} = 1;
                   9360:             }
                   9361:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9362:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9363:             }
                   9364:         } else {
                   9365:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9366:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9367:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9368:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9369:                     $args->{'no_primary_menu'} = 1;
                   9370:                 }
                   9371:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9372:                     $args->{'no_inline_menu'} = 1;
                   9373:                 }
                   9374:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9375:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9376:                 }
                   9377:             }
                   9378:         }
1.1316    raeburn  9379:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9380:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9381:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9382:     } elsif ($env{'request.course.id'}) {
                   9383:         my $expiretime=600;
                   9384:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9385:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9386:         }
                   9387:         my ($deeplinkmenu,$menuref);
                   9388:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9389:         if ($menucoll) {
                   9390:             if (ref($menuref) eq 'HASH') {
                   9391:                 %menu = %{$menuref};
                   9392:             }
                   9393:             if ($menu{'top'} eq 'n') {
                   9394:                 $args->{'no_primary_menu'} = 1;
                   9395:             }
                   9396:             if ($menu{'inline'} eq 'n') {
                   9397:                 unless (&Apache::lonnet::allowed('opa')) {
                   9398:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9399:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9400:                     my $crstype = &course_type();
                   9401:                     my $now = time;
                   9402:                     my $ccrole;
                   9403:                     if ($crstype eq 'Community') {
                   9404:                         $ccrole = 'co';
                   9405:                     } else {
                   9406:                         $ccrole = 'cc';
                   9407:                     }
                   9408:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9409:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9410:                         if ((($start) && ($start<0)) ||
                   9411:                             (($end) && ($end<$now))  ||
                   9412:                             (($start) && ($now<$start))) {
                   9413:                             $args->{'no_inline_menu'} = 1;
                   9414:                         }
                   9415:                     } else {
                   9416:                         $args->{'no_inline_menu'} = 1;
                   9417:                     }
                   9418:                 }
                   9419:             }
                   9420:         }
1.1316    raeburn  9421:     }
1.1359    raeburn  9422: 
1.1385    raeburn  9423:     my $showncrumbs;
1.338     albertel 9424:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9425: 	if ($args->{'frameset'}) {
                   9426: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9427: 						$args->{'add_entries'});
                   9428: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9429:         } else {
                   9430:             $result .=
                   9431:                 &bodytag($title, 
                   9432:                          $args->{'function'},       $args->{'add_entries'},
                   9433:                          $args->{'only_body'},      $args->{'domain'},
                   9434:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9435:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  9436:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   9437:                          \%menu,\$showncrumbs);
1.831     bisitz   9438:         }
1.330     albertel 9439:     }
1.338     albertel 9440: 
1.315     albertel 9441:     if ($args->{'js_ready'}) {
1.713     kaisler  9442: 		$result = &js_ready($result);
1.315     albertel 9443:     }
1.320     albertel 9444:     if ($args->{'html_encode'}) {
1.713     kaisler  9445: 		$result = &html_encode($result);
                   9446:     }
                   9447: 
1.813     bisitz   9448:     # Preparation for new and consistent functionlist at top of screen
                   9449:     # if ($args->{'functionlist'}) {
                   9450:     #            $result .= &build_functionlist();
                   9451:     #}
                   9452: 
1.964     droeschl 9453:     # Don't add anything more if only_body wanted or in const space
                   9454:     return $result if    $args->{'only_body'} 
                   9455:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9456: 
                   9457:     #Breadcrumbs
1.758     kaisler  9458:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  9459:         unless ($showncrumbs) {
1.758     kaisler  9460: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9461: 		#if any br links exists, add them to the breadcrumbs
                   9462: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9463: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9464: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9465: 			}
                   9466: 		}
1.1096    raeburn  9467:                 # if @advtools array contains items add then to the breadcrumbs
                   9468:                 if (@advtools > 0) {
                   9469:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9470:                 }
1.1272    raeburn  9471:                 my $menulink;
                   9472:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9473:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9474:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9475:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9476:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9477:                      (!$env{'request.role.adv'}))) {
                   9478:                     $menulink = 0;
                   9479:                 } else {
                   9480:                     undef($menulink);
                   9481:                 }
1.1385    raeburn  9482:                 my $linkprotout;
                   9483:                 if ($env{'request.deeplink.login'}) {
                   9484:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9485:                     if ($linkprotout) {
                   9486:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9487:                     }
                   9488:                 }
1.758     kaisler  9489: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9490: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9491: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9492:                 } else {
1.1272    raeburn  9493: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9494: 		}
1.1385    raeburn  9495:         }
1.320     albertel 9496:     }
1.315     albertel 9497:     return $result;
1.306     albertel 9498: }
                   9499: 
                   9500: sub end_page {
1.315     albertel 9501:     my ($args) = @_;
                   9502:     $env{'internal.end_page'}++;
1.330     albertel 9503:     my $result;
1.335     albertel 9504:     if ($args->{'discussion'}) {
                   9505: 	my ($target,$parser);
                   9506: 	if (ref($args->{'discussion'})) {
                   9507: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9508: 				$args->{'discussion'}{'parser'});
                   9509: 	}
                   9510: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9511:     }
1.330     albertel 9512:     if ($args->{'frameset'}) {
                   9513: 	$result .= '</frameset>';
                   9514:     } else {
1.635     raeburn  9515: 	$result .= &endbodytag($args);
1.330     albertel 9516:     }
1.1080    raeburn  9517:     unless ($args->{'notbody'}) {
                   9518:         $result .= "\n</html>";
                   9519:     }
1.330     albertel 9520: 
1.315     albertel 9521:     if ($args->{'js_ready'}) {
1.317     albertel 9522: 	$result = &js_ready($result);
1.315     albertel 9523:     }
1.335     albertel 9524: 
1.320     albertel 9525:     if ($args->{'html_encode'}) {
                   9526: 	$result = &html_encode($result);
                   9527:     }
1.335     albertel 9528: 
1.315     albertel 9529:     return $result;
                   9530: }
                   9531: 
1.1359    raeburn  9532: sub menucoll_in_effect {
                   9533:     my ($menucoll,$deeplinkmenu,%menu);
                   9534:     if ($env{'request.course.id'}) {
                   9535:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9536:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9537:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9538:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9539:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9540:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9541:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9542:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9543:                     if (ref($navmap)) {
                   9544:                         $deeplink = $navmap->get_mapparam(undef,
                   9545:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9546:                                                           '0.deeplink');
1.1370    raeburn  9547:                     } else {
                   9548:                         $check_login_symb = 1;
1.1362    raeburn  9549:                     }
                   9550:                 } else {
1.1370    raeburn  9551:                     my $symb = &Apache::lonnet::symbread();
                   9552:                     if ($symb) {
                   9553:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9554:                     } else {
                   9555:                         $check_login_symb = 1;
                   9556:                     }
1.1362    raeburn  9557:                 }
                   9558:             } else {
1.1370    raeburn  9559:                 $check_login_symb = 1;
                   9560:             }
                   9561:             if ($check_login_symb) {
1.1362    raeburn  9562:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9563:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9564:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9565:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9566:                     if (ref($navmap)) {
                   9567:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9568:                     }
                   9569:                 } else {
                   9570:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9571:                 }
                   9572:             }
1.1359    raeburn  9573:             if ($deeplink ne '') {
1.1378    raeburn  9574:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  9575:                 if ($display =~ /^\d+$/) {
                   9576:                     $deeplinkmenu = 1;
                   9577:                     $menucoll = $display;
                   9578:                 }
                   9579:             }
                   9580:         }
                   9581:         if ($menucoll) {
                   9582:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9583:         }
                   9584:     }
                   9585:     return ($menucoll,$deeplinkmenu,\%menu);
                   9586: }
                   9587: 
1.1362    raeburn  9588: sub deeplink_login_symb {
                   9589:     my ($cnum,$cdom) = @_;
                   9590:     my $login_symb;
                   9591:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9592:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9593:     }
                   9594:     return $login_symb;
                   9595: }
                   9596: 
                   9597: sub symb_from_tinyurl {
                   9598:     my ($url,$cnum,$cdom) = @_;
                   9599:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9600:         my $key = $1;
                   9601:         my ($tinyurl,$login);
                   9602:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9603:         if (defined($cached)) {
                   9604:             $tinyurl = $result;
                   9605:         } else {
                   9606:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9607:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9608:             if ($currtiny{$key} ne '') {
                   9609:                 $tinyurl = $currtiny{$key};
                   9610:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9611:             }
1.1364    raeburn  9612:         }
                   9613:         if ($tinyurl ne '') {
                   9614:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9615:             if (wantarray) {
                   9616:                 return ($cnumreq,$symb);
                   9617:             } elsif ($cnumreq eq $cnum) {
                   9618:                 return $symb;
1.1362    raeburn  9619:             }
                   9620:         }
                   9621:     }
1.1364    raeburn  9622:     if (wantarray) {
                   9623:         return ();
                   9624:     } else {
                   9625:         return;
                   9626:     }
1.1362    raeburn  9627: }
                   9628: 
1.1034    www      9629: sub wishlist_window {
                   9630:     return(<<'ENDWISHLIST');
1.1046    raeburn  9631: <script type="text/javascript">
1.1034    www      9632: // <![CDATA[
                   9633: // <!-- BEGIN LON-CAPA Internal
                   9634: function set_wishlistlink(title, path) {
                   9635:     if (!title) {
                   9636:         title = document.title;
                   9637:         title = title.replace(/^LON-CAPA /,'');
                   9638:     }
1.1175    raeburn  9639:     title = encodeURIComponent(title);
1.1203    raeburn  9640:     title = title.replace("'","\\\'");
1.1034    www      9641:     if (!path) {
                   9642:         path = location.pathname;
                   9643:     }
1.1175    raeburn  9644:     path = encodeURIComponent(path);
1.1203    raeburn  9645:     path = path.replace("'","\\\'");
1.1034    www      9646:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9647:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9648: }
                   9649: // END LON-CAPA Internal -->
                   9650: // ]]>
                   9651: </script>
                   9652: ENDWISHLIST
                   9653: }
                   9654: 
1.1030    www      9655: sub modal_window {
                   9656:     return(<<'ENDMODAL');
1.1046    raeburn  9657: <script type="text/javascript">
1.1030    www      9658: // <![CDATA[
                   9659: // <!-- BEGIN LON-CAPA Internal
                   9660: var modalWindow = {
                   9661: 	parent:"body",
                   9662: 	windowId:null,
                   9663: 	content:null,
                   9664: 	width:null,
                   9665: 	height:null,
                   9666: 	close:function()
                   9667: 	{
                   9668: 	        $(".LCmodal-window").remove();
                   9669: 	        $(".LCmodal-overlay").remove();
                   9670: 	},
                   9671: 	open:function()
                   9672: 	{
                   9673: 		var modal = "";
                   9674: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9675: 		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;\">";
                   9676: 		modal += this.content;
                   9677: 		modal += "</div>";	
                   9678: 
                   9679: 		$(this.parent).append(modal);
                   9680: 
                   9681: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9682: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9683: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9684: 	}
                   9685: };
1.1140    raeburn  9686: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9687: 	{
1.1266    raeburn  9688:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9689: 		modalWindow.windowId = "myModal";
                   9690: 		modalWindow.width = width;
                   9691: 		modalWindow.height = height;
1.1196    raeburn  9692: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9693: 		modalWindow.open();
1.1208    raeburn  9694: 	};
1.1030    www      9695: // END LON-CAPA Internal -->
                   9696: // ]]>
                   9697: </script>
                   9698: ENDMODAL
                   9699: }
                   9700: 
                   9701: sub modal_link {
1.1140    raeburn  9702:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9703:     unless ($width) { $width=480; }
                   9704:     unless ($height) { $height=400; }
1.1031    www      9705:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9706:     unless ($transparency) { $transparency='true'; }
                   9707: 
1.1074    raeburn  9708:     my $target_attr;
                   9709:     if (defined($target)) {
                   9710:         $target_attr = 'target="'.$target.'"';
                   9711:     }
                   9712:     return <<"ENDLINK";
1.1336    raeburn  9713: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9714: ENDLINK
1.1030    www      9715: }
                   9716: 
1.1032    www      9717: sub modal_adhoc_script {
1.1365    raeburn  9718:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9719:     my $mathjax;
                   9720:     if ($possmathjax) {
                   9721:         $mathjax = <<'ENDJAX';
                   9722:                if (typeof MathJax == 'object') {
                   9723:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9724:                }
                   9725: ENDJAX
                   9726:     }
1.1032    www      9727:     return (<<ENDADHOC);
1.1046    raeburn  9728: <script type="text/javascript">
1.1032    www      9729: // <![CDATA[
                   9730:         var $funcname = function()
                   9731:         {
                   9732:                 modalWindow.windowId = "myModal";
                   9733:                 modalWindow.width = $width;
                   9734:                 modalWindow.height = $height;
                   9735:                 modalWindow.content = '$content';
                   9736:                 modalWindow.open();
1.1365    raeburn  9737:                 $mathjax
1.1032    www      9738:         };  
                   9739: // ]]>
                   9740: </script>
                   9741: ENDADHOC
                   9742: }
                   9743: 
1.1041    www      9744: sub modal_adhoc_inner {
1.1365    raeburn  9745:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9746:     my $innerwidth=$width-20;
                   9747:     $content=&js_ready(
1.1140    raeburn  9748:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9749:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9750:                  $content.
1.1041    www      9751:                  &end_scrollbox().
1.1140    raeburn  9752:                  &end_page()
1.1041    www      9753:              );
1.1365    raeburn  9754:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9755: }
                   9756: 
                   9757: sub modal_adhoc_window {
1.1365    raeburn  9758:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9759:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9760:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9761: }
                   9762: 
                   9763: sub modal_adhoc_launch {
                   9764:     my ($funcname,$width,$height,$content)=@_;
                   9765:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9766: <script type="text/javascript">
                   9767: // <![CDATA[
                   9768: $funcname();
                   9769: // ]]>
                   9770: </script>
                   9771: ENDLAUNCH
                   9772: }
                   9773: 
                   9774: sub modal_adhoc_close {
                   9775:     return (<<ENDCLOSE);
                   9776: <script type="text/javascript">
                   9777: // <![CDATA[
                   9778: modalWindow.close();
                   9779: // ]]>
                   9780: </script>
                   9781: ENDCLOSE
                   9782: }
                   9783: 
1.1038    www      9784: sub togglebox_script {
                   9785:    return(<<ENDTOGGLE);
                   9786: <script type="text/javascript"> 
                   9787: // <![CDATA[
                   9788: function LCtoggleDisplay(id,hidetext,showtext) {
                   9789:    link = document.getElementById(id + "link").childNodes[0];
                   9790:    with (document.getElementById(id).style) {
                   9791:       if (display == "none" ) {
                   9792:           display = "inline";
                   9793:           link.nodeValue = hidetext;
                   9794:         } else {
                   9795:           display = "none";
                   9796:           link.nodeValue = showtext;
                   9797:        }
                   9798:    }
                   9799: }
                   9800: // ]]>
                   9801: </script>
                   9802: ENDTOGGLE
                   9803: }
                   9804: 
1.1039    www      9805: sub start_togglebox {
                   9806:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9807:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9808:     unless ($showtext) { $showtext=&mt('show'); }
                   9809:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9810:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9811:     return &start_data_table().
                   9812:            &start_data_table_header_row().
                   9813:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9814:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9815:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9816:            &end_data_table_header_row().
                   9817:            '<tr id="'.$id.'" style="display:none""><td>';
                   9818: }
                   9819: 
                   9820: sub end_togglebox {
                   9821:     return '</td></tr>'.&end_data_table();
                   9822: }
                   9823: 
1.1041    www      9824: sub LCprogressbar_script {
1.1302    raeburn  9825:    my ($id,$number_to_do)=@_;
                   9826:    if ($number_to_do) {
                   9827:        return(<<ENDPROGRESS);
1.1041    www      9828: <script type="text/javascript">
                   9829: // <![CDATA[
1.1045    www      9830: \$('#progressbar$id').progressbar({
1.1041    www      9831:   value: 0,
                   9832:   change: function(event, ui) {
                   9833:     var newVal = \$(this).progressbar('option', 'value');
                   9834:     \$('.pblabel', this).text(LCprogressTxt);
                   9835:   }
                   9836: });
                   9837: // ]]>
                   9838: </script>
                   9839: ENDPROGRESS
1.1302    raeburn  9840:    } else {
                   9841:        return(<<ENDPROGRESS);
                   9842: <script type="text/javascript">
                   9843: // <![CDATA[
                   9844: \$('#progressbar$id').progressbar({
                   9845:   value: false,
                   9846:   create: function(event, ui) {
                   9847:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9848:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9849:   }
                   9850: });
                   9851: // ]]>
                   9852: </script>
                   9853: ENDPROGRESS
                   9854:    }
1.1041    www      9855: }
                   9856: 
                   9857: sub LCprogressbarUpdate_script {
                   9858:    return(<<ENDPROGRESSUPDATE);
                   9859: <style type="text/css">
                   9860: .ui-progressbar { position:relative; }
1.1302    raeburn  9861: .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      9862: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9863: </style>
                   9864: <script type="text/javascript">
                   9865: // <![CDATA[
1.1045    www      9866: var LCprogressTxt='---';
                   9867: 
1.1302    raeburn  9868: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9869:    LCprogressTxt=progresstext;
1.1302    raeburn  9870:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9871:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9872:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9873:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9874:    } else {
                   9875:        \$('#progressbar'+id).progressbar('value',percent);
                   9876:    }
1.1041    www      9877: }
                   9878: // ]]>
                   9879: </script>
                   9880: ENDPROGRESSUPDATE
                   9881: }
                   9882: 
1.1042    www      9883: my $LClastpercent;
1.1045    www      9884: my $LCidcnt;
                   9885: my $LCcurrentid;
1.1042    www      9886: 
1.1041    www      9887: sub LCprogressbar {
1.1302    raeburn  9888:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9889:     $LClastpercent=0;
1.1045    www      9890:     $LCidcnt++;
                   9891:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9892:     my ($starting,$content);
                   9893:     if ($number_to_do) {
                   9894:         $starting=&mt('Starting');
                   9895:         $content=(<<ENDPROGBAR);
                   9896: $preamble
1.1045    www      9897:   <div id="progressbar$LCcurrentid">
1.1041    www      9898:     <span class="pblabel">$starting</span>
                   9899:   </div>
                   9900: ENDPROGBAR
1.1302    raeburn  9901:     } else {
                   9902:         $starting=&mt('Loading...');
                   9903:         $LClastpercent='false';
                   9904:         $content=(<<ENDPROGBAR);
                   9905: $preamble
                   9906:   <div id="progressbar$LCcurrentid">
                   9907:       <div class="progress-label">$starting</div>
                   9908:   </div>
                   9909: ENDPROGBAR
                   9910:     }
                   9911:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9912: }
                   9913: 
                   9914: sub LCprogressbarUpdate {
1.1302    raeburn  9915:     my ($r,$val,$text,$number_to_do)=@_;
                   9916:     if ($number_to_do) {
                   9917:         unless ($val) { 
                   9918:             if ($LClastpercent) {
                   9919:                 $val=$LClastpercent;
                   9920:             } else {
                   9921:                 $val=0;
                   9922:             }
                   9923:         }
                   9924:         if ($val<0) { $val=0; }
                   9925:         if ($val>100) { $val=0; }
                   9926:         $LClastpercent=$val;
                   9927:         unless ($text) { $text=$val.'%'; }
                   9928:     } else {
                   9929:         $val = 'false';
1.1042    www      9930:     }
1.1041    www      9931:     $text=&js_ready($text);
1.1044    www      9932:     &r_print($r,<<ENDUPDATE);
1.1041    www      9933: <script type="text/javascript">
                   9934: // <![CDATA[
1.1302    raeburn  9935: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9936: // ]]>
                   9937: </script>
                   9938: ENDUPDATE
1.1035    www      9939: }
                   9940: 
1.1042    www      9941: sub LCprogressbarClose {
                   9942:     my ($r)=@_;
                   9943:     $LClastpercent=0;
1.1044    www      9944:     &r_print($r,<<ENDCLOSE);
1.1042    www      9945: <script type="text/javascript">
                   9946: // <![CDATA[
1.1045    www      9947: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9948: // ]]>
                   9949: </script>
                   9950: ENDCLOSE
1.1044    www      9951: }
                   9952: 
                   9953: sub r_print {
                   9954:     my ($r,$to_print)=@_;
                   9955:     if ($r) {
                   9956:       $r->print($to_print);
                   9957:       $r->rflush();
                   9958:     } else {
                   9959:       print($to_print);
                   9960:     }
1.1042    www      9961: }
                   9962: 
1.320     albertel 9963: sub html_encode {
                   9964:     my ($result) = @_;
                   9965: 
1.322     albertel 9966:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9967:     
                   9968:     return $result;
                   9969: }
1.1044    www      9970: 
1.317     albertel 9971: sub js_ready {
                   9972:     my ($result) = @_;
                   9973: 
1.323     albertel 9974:     $result =~ s/[\n\r]/ /xmsg;
                   9975:     $result =~ s/\\/\\\\/xmsg;
                   9976:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9977:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9978:     
                   9979:     return $result;
                   9980: }
                   9981: 
1.315     albertel 9982: sub validate_page {
                   9983:     if (  exists($env{'internal.start_page'})
1.316     albertel 9984: 	  &&     $env{'internal.start_page'} > 1) {
                   9985: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9986: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9987: 				 $ENV{'request.filename'});
1.315     albertel 9988:     }
                   9989:     if (  exists($env{'internal.end_page'})
1.316     albertel 9990: 	  &&     $env{'internal.end_page'} > 1) {
                   9991: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9992: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9993: 				 $env{'request.filename'});
1.315     albertel 9994:     }
                   9995:     if (     exists($env{'internal.start_page'})
                   9996: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9997: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9998: 				 $env{'request.filename'});
1.315     albertel 9999:     }
                   10000:     if (   ! exists($env{'internal.start_page'})
                   10001: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10002: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10003: 				 $env{'request.filename'});
1.315     albertel 10004:     }
1.306     albertel 10005: }
1.315     albertel 10006: 
1.996     www      10007: 
                   10008: sub start_scrollbox {
1.1140    raeburn  10009:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10010:     unless ($outerwidth) { $outerwidth='520px'; }
                   10011:     unless ($width) { $width='500px'; }
                   10012:     unless ($height) { $height='200px'; }
1.1075    raeburn  10013:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10014:     if ($id ne '') {
1.1140    raeburn  10015:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10016:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10017:     }
1.1075    raeburn  10018:     if ($bgcolor ne '') {
                   10019:         $tdcol = "background-color: $bgcolor;";
                   10020:     }
1.1137    raeburn  10021:     my $nicescroll_js;
                   10022:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10023:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10024:     }
                   10025:     return <<"END";
                   10026: $nicescroll_js
                   10027: 
                   10028: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10029: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10030: END
                   10031: }
                   10032: 
                   10033: sub end_scrollbox {
                   10034:     return '</div></td></tr></table>';
                   10035: }
                   10036: 
                   10037: sub nicescroll_javascript {
                   10038:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10039:     my %options;
                   10040:     if (ref($cursor) eq 'HASH') {
                   10041:         %options = %{$cursor};
                   10042:     }
                   10043:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10044:         $options{'railalign'} = 'left';
                   10045:     }
                   10046:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10047:         my $function  = &get_users_function();
                   10048:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10049:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10050:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10051:         }
1.1140    raeburn  10052:     }
                   10053:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10054:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10055:             $options{'cursoropacity'}='1.0';
                   10056:         }
1.1140    raeburn  10057:     } else {
                   10058:         $options{'cursoropacity'}='1.0';
                   10059:     }
                   10060:     if ($options{'cursorfixedheight'} eq 'none') {
                   10061:         delete($options{'cursorfixedheight'});
                   10062:     } else {
                   10063:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10064:     }
                   10065:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10066:         delete($options{'railoffset'});
                   10067:     }
                   10068:     my @niceoptions;
                   10069:     while (my($key,$value) = each(%options)) {
                   10070:         if ($value =~ /^\{.+\}$/) {
                   10071:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10072:         } else {
1.1140    raeburn  10073:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10074:         }
1.1140    raeburn  10075:     }
                   10076:     my $nicescroll_js = '
1.1137    raeburn  10077: $(document).ready(
1.1140    raeburn  10078:       function() {
                   10079:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10080:       }
1.1137    raeburn  10081: );
                   10082: ';
1.1140    raeburn  10083:     if ($framecheck) {
                   10084:         $nicescroll_js .= '
                   10085: function expand_div(caller) {
                   10086:     if (top === self) {
                   10087:         document.getElementById("'.$id.'").style.width = "auto";
                   10088:         document.getElementById("'.$id.'").style.height = "auto";
                   10089:     } else {
                   10090:         try {
                   10091:             if (parent.frames) {
                   10092:                 if (parent.frames.length > 1) {
                   10093:                     var framesrc = parent.frames[1].location.href;
                   10094:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10095:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10096:                         document.getElementById("'.$id.'").style.width = "auto";
                   10097:                         document.getElementById("'.$id.'").style.height = "auto";
                   10098:                     }
                   10099:                 }
                   10100:             }
                   10101:         } catch (e) {
                   10102:             return;
                   10103:         }
1.1137    raeburn  10104:     }
1.1140    raeburn  10105:     return;
1.996     www      10106: }
1.1140    raeburn  10107: ';
                   10108:     }
                   10109:     if ($needjsready) {
                   10110:         $nicescroll_js = '
                   10111: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10112:     } else {
                   10113:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10114:     }
                   10115:     return $nicescroll_js;
1.996     www      10116: }
                   10117: 
1.318     albertel 10118: sub simple_error_page {
1.1150    bisitz   10119:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10120:     my %displayargs;
1.1151    raeburn  10121:     if (ref($args) eq 'HASH') {
                   10122:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10123:         if ($args->{'only_body'}) {
                   10124:             $displayargs{'only_body'} = 1;
                   10125:         }
                   10126:         if ($args->{'no_nav_bar'}) {
                   10127:             $displayargs{'no_nav_bar'} = 1;
                   10128:         }
1.1151    raeburn  10129:     } else {
                   10130:         $msg = &mt($msg);
                   10131:     }
1.1150    bisitz   10132: 
1.318     albertel 10133:     my $page =
1.1304    raeburn  10134: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10135: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10136: 	&Apache::loncommon::end_page();
                   10137:     if (ref($r)) {
                   10138: 	$r->print($page);
1.327     albertel 10139: 	return;
1.318     albertel 10140:     }
                   10141:     return $page;
                   10142: }
1.347     albertel 10143: 
                   10144: {
1.610     albertel 10145:     my @row_count;
1.961     onken    10146: 
                   10147:     sub start_data_table_count {
                   10148:         unshift(@row_count, 0);
                   10149:         return;
                   10150:     }
                   10151: 
                   10152:     sub end_data_table_count {
                   10153:         shift(@row_count);
                   10154:         return;
                   10155:     }
                   10156: 
1.347     albertel 10157:     sub start_data_table {
1.1018    raeburn  10158: 	my ($add_class,$id) = @_;
1.422     albertel 10159: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10160:         my $table_id;
                   10161:         if (defined($id)) {
                   10162:             $table_id = ' id="'.$id.'"';
                   10163:         }
1.961     onken    10164: 	&start_data_table_count();
1.1018    raeburn  10165: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10166:     }
                   10167: 
                   10168:     sub end_data_table {
1.961     onken    10169: 	&end_data_table_count();
1.389     albertel 10170: 	return '</table>'."\n";;
1.347     albertel 10171:     }
                   10172: 
                   10173:     sub start_data_table_row {
1.974     wenzelju 10174: 	my ($add_class, $id) = @_;
1.610     albertel 10175: 	$row_count[0]++;
                   10176: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10177: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10178:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10179:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10180:     }
1.471     banghart 10181:     
                   10182:     sub continue_data_table_row {
1.974     wenzelju 10183: 	my ($add_class, $id) = @_;
1.610     albertel 10184: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10185: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10186:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10187:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10188:     }
1.347     albertel 10189: 
                   10190:     sub end_data_table_row {
1.389     albertel 10191: 	return '</tr>'."\n";;
1.347     albertel 10192:     }
1.367     www      10193: 
1.421     albertel 10194:     sub start_data_table_empty_row {
1.707     bisitz   10195: #	$row_count[0]++;
1.421     albertel 10196: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10197:     }
                   10198: 
                   10199:     sub end_data_table_empty_row {
                   10200: 	return '</tr>'."\n";;
                   10201:     }
                   10202: 
1.367     www      10203:     sub start_data_table_header_row {
1.389     albertel 10204: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10205:     }
                   10206: 
                   10207:     sub end_data_table_header_row {
1.389     albertel 10208: 	return '</tr>'."\n";;
1.367     www      10209:     }
1.890     droeschl 10210: 
                   10211:     sub data_table_caption {
                   10212:         my $caption = shift;
                   10213:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10214:     }
1.347     albertel 10215: }
                   10216: 
1.548     albertel 10217: =pod
                   10218: 
                   10219: =item * &inhibit_menu_check($arg)
                   10220: 
                   10221: Checks for a inhibitmenu state and generates output to preserve it
                   10222: 
                   10223: Inputs:         $arg - can be any of
                   10224:                      - undef - in which case the return value is a string 
                   10225:                                to add  into arguments list of a uri
                   10226:                      - 'input' - in which case the return value is a HTML
                   10227:                                  <form> <input> field of type hidden to
                   10228:                                  preserve the value
                   10229:                      - a url - in which case the return value is the url with
                   10230:                                the neccesary cgi args added to preserve the
                   10231:                                inhibitmenu state
                   10232:                      - a ref to a url - no return value, but the string is
                   10233:                                         updated to include the neccessary cgi
                   10234:                                         args to preserve the inhibitmenu state
                   10235: 
                   10236: =cut
                   10237: 
                   10238: sub inhibit_menu_check {
                   10239:     my ($arg) = @_;
                   10240:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10241:     if ($arg eq 'input') {
                   10242: 	if ($env{'form.inhibitmenu'}) {
                   10243: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10244: 	} else {
                   10245: 	    return
                   10246: 	}
                   10247:     }
                   10248:     if ($env{'form.inhibitmenu'}) {
                   10249: 	if (ref($arg)) {
                   10250: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10251: 	} elsif ($arg eq '') {
                   10252: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10253: 	} else {
                   10254: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10255: 	}
                   10256:     }
                   10257:     if (!ref($arg)) {
                   10258: 	return $arg;
                   10259:     }
                   10260: }
                   10261: 
1.251     albertel 10262: ###############################################
1.182     matthew  10263: 
                   10264: =pod
                   10265: 
1.549     albertel 10266: =back
                   10267: 
                   10268: =head1 User Information Routines
                   10269: 
                   10270: =over 4
                   10271: 
1.405     albertel 10272: =item * &get_users_function()
1.182     matthew  10273: 
                   10274: Used by &bodytag to determine the current users primary role.
                   10275: Returns either 'student','coordinator','admin', or 'author'.
                   10276: 
                   10277: =cut
                   10278: 
                   10279: ###############################################
                   10280: sub get_users_function {
1.815     tempelho 10281:     my $function = 'norole';
1.818     tempelho 10282:     if ($env{'request.role'}=~/^(st)/) {
                   10283:         $function='student';
                   10284:     }
1.907     raeburn  10285:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10286:         $function='coordinator';
                   10287:     }
1.258     albertel 10288:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10289:         $function='admin';
                   10290:     }
1.826     bisitz   10291:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10292:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10293:         $function='author';
                   10294:     }
                   10295:     return $function;
1.54      www      10296: }
1.99      www      10297: 
                   10298: ###############################################
                   10299: 
1.233     raeburn  10300: =pod
                   10301: 
1.821     raeburn  10302: =item * &show_course()
                   10303: 
                   10304: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10305: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10306: 
                   10307: Inputs:
                   10308: None
                   10309: 
                   10310: Outputs:
                   10311: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10312: 
                   10313: =cut
                   10314: 
                   10315: ###############################################
                   10316: sub show_course {
                   10317:     my $course = !$env{'user.adv'};
                   10318:     if (!$env{'user.adv'}) {
                   10319:         foreach my $env (keys(%env)) {
                   10320:             next if ($env !~ m/^user\.priv\./);
                   10321:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10322:                 $course = 0;
                   10323:                 last;
                   10324:             }
                   10325:         }
                   10326:     }
                   10327:     return $course;
                   10328: }
                   10329: 
                   10330: ###############################################
                   10331: 
                   10332: =pod
                   10333: 
1.542     raeburn  10334: =item * &check_user_status()
1.274     raeburn  10335: 
                   10336: Determines current status of supplied role for a
                   10337: specific user. Roles can be active, previous or future.
                   10338: 
                   10339: Inputs: 
                   10340: user's domain, user's username, course's domain,
1.375     raeburn  10341: course's number, optional section ID.
1.274     raeburn  10342: 
                   10343: Outputs:
                   10344: role status: active, previous or future. 
                   10345: 
                   10346: =cut
                   10347: 
                   10348: sub check_user_status {
1.412     raeburn  10349:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10350:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10351:     my @uroles = keys(%userinfo);
1.274     raeburn  10352:     my $srchstr;
                   10353:     my $active_chk = 'none';
1.412     raeburn  10354:     my $now = time;
1.274     raeburn  10355:     if (@uroles > 0) {
1.908     raeburn  10356:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10357:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10358:         } else {
1.412     raeburn  10359:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10360:         }
                   10361:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10362:             my $role_end = 0;
                   10363:             my $role_start = 0;
                   10364:             $active_chk = 'active';
1.412     raeburn  10365:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10366:                 $role_end = $1;
                   10367:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10368:                     $role_start = $1;
1.274     raeburn  10369:                 }
                   10370:             }
                   10371:             if ($role_start > 0) {
1.412     raeburn  10372:                 if ($now < $role_start) {
1.274     raeburn  10373:                     $active_chk = 'future';
                   10374:                 }
                   10375:             }
                   10376:             if ($role_end > 0) {
1.412     raeburn  10377:                 if ($now > $role_end) {
1.274     raeburn  10378:                     $active_chk = 'previous';
                   10379:                 }
                   10380:             }
                   10381:         }
                   10382:     }
                   10383:     return $active_chk;
                   10384: }
                   10385: 
                   10386: ###############################################
                   10387: 
                   10388: =pod
                   10389: 
1.405     albertel 10390: =item * &get_sections()
1.233     raeburn  10391: 
                   10392: Determines all the sections for a course including
                   10393: sections with students and sections containing other roles.
1.419     raeburn  10394: Incoming parameters: 
                   10395: 
                   10396: 1. domain
                   10397: 2. course number 
                   10398: 3. reference to array containing roles for which sections should 
                   10399: be gathered (optional).
                   10400: 4. reference to array containing status types for which sections 
                   10401: should be gathered (optional).
                   10402: 
                   10403: If the third argument is undefined, sections are gathered for any role. 
                   10404: If the fourth argument is undefined, sections are gathered for any status.
                   10405: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10406:  
1.374     raeburn  10407: Returns section hash (keys are section IDs, values are
                   10408: number of users in each section), subject to the
1.419     raeburn  10409: optional roles filter, optional status filter 
1.233     raeburn  10410: 
                   10411: =cut
                   10412: 
                   10413: ###############################################
                   10414: sub get_sections {
1.419     raeburn  10415:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10416:     if (!defined($cdom) || !defined($cnum)) {
                   10417:         my $cid =  $env{'request.course.id'};
                   10418: 
                   10419: 	return if (!defined($cid));
                   10420: 
                   10421:         $cdom = $env{'course.'.$cid.'.domain'};
                   10422:         $cnum = $env{'course.'.$cid.'.num'};
                   10423:     }
                   10424: 
                   10425:     my %sectioncount;
1.419     raeburn  10426:     my $now = time;
1.240     albertel 10427: 
1.1118    raeburn  10428:     my $check_students = 1;
                   10429:     my $only_students = 0;
                   10430:     if (ref($possible_roles) eq 'ARRAY') {
                   10431:         if (grep(/^st$/,@{$possible_roles})) {
                   10432:             if (@{$possible_roles} == 1) {
                   10433:                 $only_students = 1;
                   10434:             }
                   10435:         } else {
                   10436:             $check_students = 0;
                   10437:         }
                   10438:     }
                   10439: 
                   10440:     if ($check_students) { 
1.276     albertel 10441: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10442: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10443: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10444:         my $start_index = &Apache::loncoursedata::CL_START();
                   10445:         my $end_index = &Apache::loncoursedata::CL_END();
                   10446:         my $status;
1.366     albertel 10447: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10448: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10449: 				                     $data->[$status_index],
                   10450:                                                      $data->[$start_index],
                   10451:                                                      $data->[$end_index]);
                   10452:             if ($stu_status eq 'Active') {
                   10453:                 $status = 'active';
                   10454:             } elsif ($end < $now) {
                   10455:                 $status = 'previous';
                   10456:             } elsif ($start > $now) {
                   10457:                 $status = 'future';
                   10458:             } 
                   10459: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10460:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10461:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10462: 		    $sectioncount{$section}++;
                   10463:                 }
1.240     albertel 10464: 	    }
                   10465: 	}
                   10466:     }
1.1118    raeburn  10467:     if ($only_students) {
                   10468:         return %sectioncount;
                   10469:     }
1.240     albertel 10470:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10471:     foreach my $user (sort(keys(%courseroles))) {
                   10472: 	if ($user !~ /^(\w{2})/) { next; }
                   10473: 	my ($role) = ($user =~ /^(\w{2})/);
                   10474: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10475: 	my ($section,$status);
1.240     albertel 10476: 	if ($role eq 'cr' &&
                   10477: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10478: 	    $section=$1;
                   10479: 	}
                   10480: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10481: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10482:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10483:         if ($end == -1 && $start == -1) {
                   10484:             next; #deleted role
                   10485:         }
                   10486:         if (!defined($possible_status)) { 
                   10487:             $sectioncount{$section}++;
                   10488:         } else {
                   10489:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10490:                 $status = 'active';
                   10491:             } elsif ($end < $now) {
                   10492:                 $status = 'future';
                   10493:             } elsif ($start > $now) {
                   10494:                 $status = 'previous';
                   10495:             }
                   10496:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10497:                 $sectioncount{$section}++;
                   10498:             }
                   10499:         }
1.233     raeburn  10500:     }
1.366     albertel 10501:     return %sectioncount;
1.233     raeburn  10502: }
                   10503: 
1.274     raeburn  10504: ###############################################
1.294     raeburn  10505: 
                   10506: =pod
1.405     albertel 10507: 
                   10508: =item * &get_course_users()
                   10509: 
1.275     raeburn  10510: Retrieves usernames:domains for users in the specified course
                   10511: with specific role(s), and access status. 
                   10512: 
                   10513: Incoming parameters:
1.277     albertel 10514: 1. course domain
                   10515: 2. course number
                   10516: 3. access status: users must have - either active, 
1.275     raeburn  10517: previous, future, or all.
1.277     albertel 10518: 4. reference to array of permissible roles
1.288     raeburn  10519: 5. reference to array of section restrictions (optional)
                   10520: 6. reference to results object (hash of hashes).
                   10521: 7. reference to optional userdata hash
1.609     raeburn  10522: 8. reference to optional statushash
1.630     raeburn  10523: 9. flag if privileged users (except those set to unhide in
                   10524:    course settings) should be excluded    
1.609     raeburn  10525: Keys of top level results hash are roles.
1.275     raeburn  10526: Keys of inner hashes are username:domain, with 
                   10527: values set to access type.
1.288     raeburn  10528: Optional userdata hash returns an array with arguments in the 
                   10529: same order as loncoursedata::get_classlist() for student data.
                   10530: 
1.609     raeburn  10531: Optional statushash returns
                   10532: 
1.288     raeburn  10533: Entries for end, start, section and status are blank because
                   10534: of the possibility of multiple values for non-student roles.
                   10535: 
1.275     raeburn  10536: =cut
1.405     albertel 10537: 
1.275     raeburn  10538: ###############################################
1.405     albertel 10539: 
1.275     raeburn  10540: sub get_course_users {
1.630     raeburn  10541:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10542:     my %idx = ();
1.419     raeburn  10543:     my %seclists;
1.288     raeburn  10544: 
                   10545:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10546:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10547:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10548:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10549:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10550:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10551:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10552:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10553: 
1.290     albertel 10554:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10555:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10556:         my $now = time;
1.277     albertel 10557:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10558:             my $match = 0;
1.412     raeburn  10559:             my $secmatch = 0;
1.419     raeburn  10560:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10561:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10562:             if ($section eq '') {
                   10563:                 $section = 'none';
                   10564:             }
1.291     albertel 10565:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10566:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10567:                     $secmatch = 1;
                   10568:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10569:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10570:                         $secmatch = 1;
                   10571:                     }
                   10572:                 } else {  
1.419     raeburn  10573: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10574: 		        $secmatch = 1;
                   10575:                     }
1.290     albertel 10576: 		}
1.412     raeburn  10577:                 if (!$secmatch) {
                   10578:                     next;
                   10579:                 }
1.419     raeburn  10580:             }
1.275     raeburn  10581:             if (defined($$types{'active'})) {
1.288     raeburn  10582:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10583:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10584:                     $match = 1;
1.275     raeburn  10585:                 }
                   10586:             }
                   10587:             if (defined($$types{'previous'})) {
1.609     raeburn  10588:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10589:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10590:                     $match = 1;
1.275     raeburn  10591:                 }
                   10592:             }
                   10593:             if (defined($$types{'future'})) {
1.609     raeburn  10594:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10595:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10596:                     $match = 1;
1.275     raeburn  10597:                 }
                   10598:             }
1.609     raeburn  10599:             if ($match) {
                   10600:                 push(@{$seclists{$student}},$section);
                   10601:                 if (ref($userdata) eq 'HASH') {
                   10602:                     $$userdata{$student} = $$classlist{$student};
                   10603:                 }
                   10604:                 if (ref($statushash) eq 'HASH') {
                   10605:                     $statushash->{$student}{'st'}{$section} = $status;
                   10606:                 }
1.288     raeburn  10607:             }
1.275     raeburn  10608:         }
                   10609:     }
1.412     raeburn  10610:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10611:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10612:         my $now = time;
1.609     raeburn  10613:         my %displaystatus = ( previous => 'Expired',
                   10614:                               active   => 'Active',
                   10615:                               future   => 'Future',
                   10616:                             );
1.1121    raeburn  10617:         my (%nothide,@possdoms);
1.630     raeburn  10618:         if ($hidepriv) {
                   10619:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10620:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10621:                 if ($user !~ /:/) {
                   10622:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10623:                 } else {
                   10624:                     $nothide{$user} = 1;
                   10625:                 }
                   10626:             }
1.1121    raeburn  10627:             my @possdoms = ($cdom);
                   10628:             if ($coursehash{'checkforpriv'}) {
                   10629:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10630:             }
1.630     raeburn  10631:         }
1.439     raeburn  10632:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10633:             my $match = 0;
1.412     raeburn  10634:             my $secmatch = 0;
1.439     raeburn  10635:             my $status;
1.412     raeburn  10636:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10637:             $user =~ s/:$//;
1.439     raeburn  10638:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10639:             if ($end == -1 || $start == -1) {
                   10640:                 next;
                   10641:             }
                   10642:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10643:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10644:                 my ($uname,$udom) = split(/:/,$user);
                   10645:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10646:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10647:                         $secmatch = 1;
                   10648:                     } elsif ($usec eq '') {
1.420     albertel 10649:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10650:                             $secmatch = 1;
                   10651:                         }
                   10652:                     } else {
                   10653:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10654:                             $secmatch = 1;
                   10655:                         }
                   10656:                     }
                   10657:                     if (!$secmatch) {
                   10658:                         next;
                   10659:                     }
1.288     raeburn  10660:                 }
1.419     raeburn  10661:                 if ($usec eq '') {
                   10662:                     $usec = 'none';
                   10663:                 }
1.275     raeburn  10664:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10665:                     if ($hidepriv) {
1.1121    raeburn  10666:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10667:                             (!$nothide{$uname.':'.$udom})) {
                   10668:                             next;
                   10669:                         }
                   10670:                     }
1.503     raeburn  10671:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10672:                         $status = 'previous';
                   10673:                     } elsif ($start > $now) {
                   10674:                         $status = 'future';
                   10675:                     } else {
                   10676:                         $status = 'active';
                   10677:                     }
1.277     albertel 10678:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10679:                         if ($status eq $type) {
1.420     albertel 10680:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10681:                                 push(@{$$users{$role}{$user}},$type);
                   10682:                             }
1.288     raeburn  10683:                             $match = 1;
                   10684:                         }
                   10685:                     }
1.419     raeburn  10686:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10687:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10688: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10689:                         }
1.420     albertel 10690:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10691:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10692:                         }
1.609     raeburn  10693:                         if (ref($statushash) eq 'HASH') {
                   10694:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10695:                         }
1.275     raeburn  10696:                     }
                   10697:                 }
                   10698:             }
                   10699:         }
1.290     albertel 10700:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10701:             if ((defined($cdom)) && (defined($cnum))) {
                   10702:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10703:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10704:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10705:                     next if ($owner eq '');
                   10706:                     my ($ownername,$ownerdom);
                   10707:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10708:                         $ownername = $1;
                   10709:                         $ownerdom = $2;
                   10710:                     } else {
                   10711:                         $ownername = $owner;
                   10712:                         $ownerdom = $cdom;
                   10713:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10714:                     }
                   10715:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10716:                     if (defined($userdata) && 
1.609     raeburn  10717: 			!exists($$userdata{$owner})) {
                   10718: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10719:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10720:                             push(@{$seclists{$owner}},'none');
                   10721:                         }
                   10722:                         if (ref($statushash) eq 'HASH') {
                   10723:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10724:                         }
1.290     albertel 10725: 		    }
1.279     raeburn  10726:                 }
                   10727:             }
                   10728:         }
1.419     raeburn  10729:         foreach my $user (keys(%seclists)) {
                   10730:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10731:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10732:         }
1.275     raeburn  10733:     }
                   10734:     return;
                   10735: }
                   10736: 
1.288     raeburn  10737: sub get_user_info {
                   10738:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10739:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10740: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10741:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10742:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10743:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10744:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10745:     return;
                   10746: }
1.275     raeburn  10747: 
1.472     raeburn  10748: ###############################################
                   10749: 
                   10750: =pod
                   10751: 
                   10752: =item * &get_user_quota()
                   10753: 
1.1134    raeburn  10754: Retrieves quota assigned for storage of user files.
                   10755: Default is to report quota for portfolio files.
1.472     raeburn  10756: 
                   10757: Incoming parameters:
                   10758: 1. user's username
                   10759: 2. user's domain
1.1134    raeburn  10760: 3. quota name - portfolio, author, or course
1.1136    raeburn  10761:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10762: 4. crstype - official, unofficial, textbook, placement or community, 
                   10763:    if quota name is course
1.472     raeburn  10764: 
                   10765: Returns:
1.1163    raeburn  10766: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10767: 2. (Optional) Type of setting: custom or default
                   10768:    (individually assigned or default for user's 
                   10769:    institutional status).
                   10770: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10771:    or student - types as defined in localenroll::inst_usertypes 
                   10772:    for user's domain, which determines default quota for user.
                   10773: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10774: 
                   10775: If a value has been stored in the user's environment, 
1.536     raeburn  10776: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10777: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10778: 
                   10779: =cut
                   10780: 
                   10781: ###############################################
                   10782: 
                   10783: 
                   10784: sub get_user_quota {
1.1136    raeburn  10785:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10786:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10787:     if (!defined($udom)) {
                   10788:         $udom = $env{'user.domain'};
                   10789:     }
                   10790:     if (!defined($uname)) {
                   10791:         $uname = $env{'user.name'};
                   10792:     }
                   10793:     if (($udom eq '' || $uname eq '') ||
                   10794:         ($udom eq 'public') && ($uname eq 'public')) {
                   10795:         $quota = 0;
1.536     raeburn  10796:         $quotatype = 'default';
                   10797:         $defquota = 0; 
1.472     raeburn  10798:     } else {
1.536     raeburn  10799:         my $inststatus;
1.1134    raeburn  10800:         if ($quotaname eq 'course') {
                   10801:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10802:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10803:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10804:             } else {
                   10805:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10806:                 $quota = $cenv{'internal.uploadquota'};
                   10807:             }
1.536     raeburn  10808:         } else {
1.1134    raeburn  10809:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10810:                 if ($quotaname eq 'author') {
                   10811:                     $quota = $env{'environment.authorquota'};
                   10812:                 } else {
                   10813:                     $quota = $env{'environment.portfolioquota'};
                   10814:                 }
                   10815:                 $inststatus = $env{'environment.inststatus'};
                   10816:             } else {
                   10817:                 my %userenv = 
                   10818:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10819:                                          'authorquota','inststatus'],$udom,$uname);
                   10820:                 my ($tmp) = keys(%userenv);
                   10821:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10822:                     if ($quotaname eq 'author') {
                   10823:                         $quota = $userenv{'authorquota'};
                   10824:                     } else {
                   10825:                         $quota = $userenv{'portfolioquota'};
                   10826:                     }
                   10827:                     $inststatus = $userenv{'inststatus'};
                   10828:                 } else {
                   10829:                     undef(%userenv);
                   10830:                 }
                   10831:             }
                   10832:         }
                   10833:         if ($quota eq '' || wantarray) {
                   10834:             if ($quotaname eq 'course') {
                   10835:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10836:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10837:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10838:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10839:                     $defquota = $domdefs{$crstype.'quota'};
                   10840:                 }
                   10841:                 if ($defquota eq '') {
                   10842:                     $defquota = 500;
                   10843:                 }
1.1134    raeburn  10844:             } else {
                   10845:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10846:             }
                   10847:             if ($quota eq '') {
                   10848:                 $quota = $defquota;
                   10849:                 $quotatype = 'default';
                   10850:             } else {
                   10851:                 $quotatype = 'custom';
                   10852:             }
1.472     raeburn  10853:         }
                   10854:     }
1.536     raeburn  10855:     if (wantarray) {
                   10856:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10857:     } else {
                   10858:         return $quota;
                   10859:     }
1.472     raeburn  10860: }
                   10861: 
                   10862: ###############################################
                   10863: 
                   10864: =pod
                   10865: 
                   10866: =item * &default_quota()
                   10867: 
1.536     raeburn  10868: Retrieves default quota assigned for storage of user portfolio files,
                   10869: given an (optional) user's institutional status.
1.472     raeburn  10870: 
                   10871: Incoming parameters:
1.1142    raeburn  10872: 
1.472     raeburn  10873: 1. domain
1.536     raeburn  10874: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10875:    status types (e.g., faculty, staff, student etc.)
                   10876:    which apply to the user for whom the default is being retrieved.
                   10877:    If the institutional status string in undefined, the domain
1.1134    raeburn  10878:    default quota will be returned.
                   10879: 3.  quota name - portfolio, author, or course
                   10880:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10881: 
                   10882: Returns:
1.1142    raeburn  10883: 
1.1163    raeburn  10884: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10885: 2. (Optional) institutional type which determined the value of the
                   10886:    default quota.
1.472     raeburn  10887: 
                   10888: If a value has been stored in the domain's configuration db,
                   10889: it will return that, otherwise it returns 20 (for backwards 
                   10890: compatibility with domains which have not set up a configuration
1.1163    raeburn  10891: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10892: 
1.536     raeburn  10893: If the user's status includes multiple types (e.g., staff and student),
                   10894: the largest default quota which applies to the user determines the
                   10895: default quota returned.
                   10896: 
1.472     raeburn  10897: =cut
                   10898: 
                   10899: ###############################################
                   10900: 
                   10901: 
                   10902: sub default_quota {
1.1134    raeburn  10903:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10904:     my ($defquota,$settingstatus);
                   10905:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10906:                                             ['quotas'],$udom);
1.1134    raeburn  10907:     my $key = 'defaultquota';
                   10908:     if ($quotaname eq 'author') {
                   10909:         $key = 'authorquota';
                   10910:     }
1.622     raeburn  10911:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10912:         if ($inststatus ne '') {
1.765     raeburn  10913:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10914:             foreach my $item (@statuses) {
1.1134    raeburn  10915:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10916:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10917:                         if ($defquota eq '') {
1.1134    raeburn  10918:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10919:                             $settingstatus = $item;
1.1134    raeburn  10920:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10921:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10922:                             $settingstatus = $item;
                   10923:                         }
                   10924:                     }
1.1134    raeburn  10925:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10926:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10927:                         if ($defquota eq '') {
                   10928:                             $defquota = $quotahash{'quotas'}{$item};
                   10929:                             $settingstatus = $item;
                   10930:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10931:                             $defquota = $quotahash{'quotas'}{$item};
                   10932:                             $settingstatus = $item;
                   10933:                         }
1.536     raeburn  10934:                     }
                   10935:                 }
                   10936:             }
                   10937:         }
                   10938:         if ($defquota eq '') {
1.1134    raeburn  10939:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10940:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10941:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10942:                 $defquota = $quotahash{'quotas'}{'default'};
                   10943:             }
1.536     raeburn  10944:             $settingstatus = 'default';
1.1139    raeburn  10945:             if ($defquota eq '') {
                   10946:                 if ($quotaname eq 'author') {
                   10947:                     $defquota = 500;
                   10948:                 }
                   10949:             }
1.536     raeburn  10950:         }
                   10951:     } else {
                   10952:         $settingstatus = 'default';
1.1134    raeburn  10953:         if ($quotaname eq 'author') {
                   10954:             $defquota = 500;
                   10955:         } else {
                   10956:             $defquota = 20;
                   10957:         }
1.536     raeburn  10958:     }
                   10959:     if (wantarray) {
                   10960:         return ($defquota,$settingstatus);
1.472     raeburn  10961:     } else {
1.536     raeburn  10962:         return $defquota;
1.472     raeburn  10963:     }
                   10964: }
                   10965: 
1.1135    raeburn  10966: ###############################################
                   10967: 
                   10968: =pod
                   10969: 
1.1136    raeburn  10970: =item * &excess_filesize_warning()
1.1135    raeburn  10971: 
                   10972: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10973: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10974: space to be exceeded.
1.1136    raeburn  10975: 
                   10976: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10977: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10978: 
1.1165    raeburn  10979: Inputs: 7 
1.1136    raeburn  10980: 1. username or coursenum
1.1135    raeburn  10981: 2. domain
1.1136    raeburn  10982: 3. context ('author' or 'course')
1.1135    raeburn  10983: 4. filename of file for which action is being requested
                   10984: 5. filesize (kB) of file
                   10985: 6. action being taken: copy or upload.
1.1237    raeburn  10986: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10987: 
                   10988: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10989:          otherwise return null.
                   10990: 
                   10991: =back
1.1135    raeburn  10992: 
                   10993: =cut
                   10994: 
1.1136    raeburn  10995: sub excess_filesize_warning {
1.1165    raeburn  10996:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10997:     my $current_disk_usage = 0;
1.1165    raeburn  10998:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10999:     if ($context eq 'author') {
                   11000:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11001:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11002:     } else {
                   11003:         foreach my $subdir ('docs','supplemental') {
                   11004:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11005:         }
                   11006:     }
1.1135    raeburn  11007:     $disk_quota = int($disk_quota * 1000);
                   11008:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11009:         return '<p class="LC_warning">'.
1.1135    raeburn  11010:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11011:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11012:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11013:                             $disk_quota,$current_disk_usage).
                   11014:                '</p>';
                   11015:     }
                   11016:     return;
                   11017: }
                   11018: 
                   11019: ###############################################
                   11020: 
                   11021: 
1.1136    raeburn  11022: 
                   11023: 
1.384     raeburn  11024: sub get_secgrprole_info {
                   11025:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11026:     my %sections_count = &get_sections($cdom,$cnum);
                   11027:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11028:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11029:     my @groups = sort(keys(%curr_groups));
                   11030:     my $allroles = [];
                   11031:     my $rolehash;
                   11032:     my $accesshash = {
                   11033:                      active => 'Currently has access',
                   11034:                      future => 'Will have future access',
                   11035:                      previous => 'Previously had access',
                   11036:                   };
                   11037:     if ($needroles) {
                   11038:         $rolehash = {'all' => 'all'};
1.385     albertel 11039:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11040: 	if (&Apache::lonnet::error(%user_roles)) {
                   11041: 	    undef(%user_roles);
                   11042: 	}
                   11043:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11044:             my ($role)=split(/\:/,$item,2);
                   11045:             if ($role eq 'cr') { next; }
                   11046:             if ($role =~ /^cr/) {
                   11047:                 $$rolehash{$role} = (split('/',$role))[3];
                   11048:             } else {
                   11049:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11050:             }
                   11051:         }
                   11052:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11053:             push(@{$allroles},$key);
                   11054:         }
                   11055:         push (@{$allroles},'st');
                   11056:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11057:     }
                   11058:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11059: }
                   11060: 
1.555     raeburn  11061: sub user_picker {
1.1279    raeburn  11062:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11063:     my $currdom = $dom;
1.1253    raeburn  11064:     my @alldoms = &Apache::lonnet::all_domains();
                   11065:     if (@alldoms == 1) {
                   11066:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11067:                                                ['directorysrch'],$alldoms[0]);
                   11068:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11069:         my $showdom = $domdesc;
                   11070:         if ($showdom eq '') {
                   11071:             $showdom = $dom;
                   11072:         }
                   11073:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11074:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11075:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11076:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11077:             }
                   11078:         }
                   11079:     }
1.555     raeburn  11080:     my %curr_selected = (
                   11081:                         srchin => 'dom',
1.580     raeburn  11082:                         srchby => 'lastname',
1.555     raeburn  11083:                       );
                   11084:     my $srchterm;
1.625     raeburn  11085:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11086:         if ($srch->{'srchby'} ne '') {
                   11087:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11088:         }
                   11089:         if ($srch->{'srchin'} ne '') {
                   11090:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11091:         }
                   11092:         if ($srch->{'srchtype'} ne '') {
                   11093:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11094:         }
                   11095:         if ($srch->{'srchdomain'} ne '') {
                   11096:             $currdom = $srch->{'srchdomain'};
                   11097:         }
                   11098:         $srchterm = $srch->{'srchterm'};
                   11099:     }
1.1222    damieng  11100:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11101:                     'usr'       => 'Search criteria',
1.563     raeburn  11102:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11103:                     'uname'     => 'username',
                   11104:                     'lastname'  => 'last name',
1.555     raeburn  11105:                     'lastfirst' => 'last name, first name',
1.558     albertel 11106:                     'crs'       => 'in this course',
1.576     raeburn  11107:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11108:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11109:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11110:                     'exact'     => 'is',
                   11111:                     'contains'  => 'contains',
1.569     raeburn  11112:                     'begins'    => 'begins with',
1.1222    damieng  11113:                                        );
                   11114:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11115:                     'youm'      => "You must include some text to search for.",
                   11116:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11117:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11118:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11119:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11120:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11121:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11122:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11123:                                        );
1.1222    damieng  11124:     &html_escape(\%html_lt);
                   11125:     &js_escape(\%js_lt);
1.1255    raeburn  11126:     my $domform;
1.1277    raeburn  11127:     my $allow_blank = 1;
1.1255    raeburn  11128:     if ($fixeddom) {
1.1277    raeburn  11129:         $allow_blank = 0;
                   11130:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11131:     } else {
1.1287    raeburn  11132:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11133:         my ($trusted,$untrusted);
1.1287    raeburn  11134:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11135:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11136:         } elsif ($context eq 'author') {
1.1288    raeburn  11137:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11138:         } elsif ($context eq 'domain') {
1.1288    raeburn  11139:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11140:         }
1.1288    raeburn  11141:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11142:     }
1.563     raeburn  11143:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11144: 
                   11145:     my @srchins = ('crs','dom','alc','instd');
                   11146: 
                   11147:     foreach my $option (@srchins) {
                   11148:         # FIXME 'alc' option unavailable until 
                   11149:         #       loncreateuser::print_user_query_page()
                   11150:         #       has been completed.
                   11151:         next if ($option eq 'alc');
1.880     raeburn  11152:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11153:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11154:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11155:         if ($curr_selected{'srchin'} eq $option) {
                   11156:             $srchinsel .= ' 
1.1222    damieng  11157:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11158:         } else {
                   11159:             $srchinsel .= '
1.1222    damieng  11160:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11161:         }
1.555     raeburn  11162:     }
1.563     raeburn  11163:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11164: 
                   11165:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11166:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11167:         if ($curr_selected{'srchby'} eq $option) {
                   11168:             $srchbysel .= '
1.1222    damieng  11169:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11170:         } else {
                   11171:             $srchbysel .= '
1.1222    damieng  11172:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11173:          }
                   11174:     }
                   11175:     $srchbysel .= "\n  </select>\n";
                   11176: 
                   11177:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11178:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11179:         if ($curr_selected{'srchtype'} eq $option) {
                   11180:             $srchtypesel .= '
1.1222    damieng  11181:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11182:         } else {
                   11183:             $srchtypesel .= '
1.1222    damieng  11184:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11185:         }
                   11186:     }
                   11187:     $srchtypesel .= "\n  </select>\n";
                   11188: 
1.558     albertel 11189:     my ($newuserscript,$new_user_create);
1.994     raeburn  11190:     my $context_dom = $env{'request.role.domain'};
                   11191:     if ($context eq 'requestcrs') {
                   11192:         if ($env{'form.coursedom'} ne '') { 
                   11193:             $context_dom = $env{'form.coursedom'};
                   11194:         }
                   11195:     }
1.556     raeburn  11196:     if ($forcenewuser) {
1.576     raeburn  11197:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11198:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11199:                 if ($cancreate) {
                   11200:                     $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>';
                   11201:                 } else {
1.799     bisitz   11202:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11203:                     my %usertypetext = (
                   11204:                         official   => 'institutional',
                   11205:                         unofficial => 'non-institutional',
                   11206:                     );
1.799     bisitz   11207:                     $new_user_create = '<p class="LC_warning">'
                   11208:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11209:                                       .' '
                   11210:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11211:                                           ,'<a href="'.$helplink.'">','</a>')
                   11212:                                       .'</p><br />';
1.627     raeburn  11213:                 }
1.576     raeburn  11214:             }
                   11215:         }
                   11216: 
1.556     raeburn  11217:         $newuserscript = <<"ENDSCRIPT";
                   11218: 
1.570     raeburn  11219: function setSearch(createnew,callingForm) {
1.556     raeburn  11220:     if (createnew == 1) {
1.570     raeburn  11221:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11222:             if (callingForm.srchby.options[i].value == 'uname') {
                   11223:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11224:             }
                   11225:         }
1.570     raeburn  11226:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11227:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11228: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11229:             }
                   11230:         }
1.570     raeburn  11231:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11232:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11233:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11234:             }
                   11235:         }
1.570     raeburn  11236:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11237:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11238:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11239:             }
                   11240:         }
                   11241:     }
                   11242: }
                   11243: ENDSCRIPT
1.558     albertel 11244: 
1.556     raeburn  11245:     }
                   11246: 
1.555     raeburn  11247:     my $output = <<"END_BLOCK";
1.556     raeburn  11248: <script type="text/javascript">
1.824     bisitz   11249: // <![CDATA[
1.570     raeburn  11250: function validateEntry(callingForm) {
1.558     albertel 11251: 
1.556     raeburn  11252:     var checkok = 1;
1.558     albertel 11253:     var srchin;
1.570     raeburn  11254:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11255: 	if ( callingForm.srchin[i].checked ) {
                   11256: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11257: 	}
                   11258:     }
                   11259: 
1.570     raeburn  11260:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11261:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11262:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11263:     var srchterm =  callingForm.srchterm.value;
                   11264:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11265:     var msg = "";
                   11266: 
                   11267:     if (srchterm == "") {
                   11268:         checkok = 0;
1.1222    damieng  11269:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11270:     }
                   11271: 
1.569     raeburn  11272:     if (srchtype== 'begins') {
                   11273:         if (srchterm.length < 2) {
                   11274:             checkok = 0;
1.1222    damieng  11275:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11276:         }
                   11277:     }
                   11278: 
1.556     raeburn  11279:     if (srchtype== 'contains') {
                   11280:         if (srchterm.length < 3) {
                   11281:             checkok = 0;
1.1222    damieng  11282:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11283:         }
                   11284:     }
                   11285:     if (srchin == 'instd') {
                   11286:         if (srchdomain == '') {
                   11287:             checkok = 0;
1.1222    damieng  11288:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11289:         }
                   11290:     }
                   11291:     if (srchin == 'dom') {
                   11292:         if (srchdomain == '') {
                   11293:             checkok = 0;
1.1222    damieng  11294:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11295:         }
                   11296:     }
                   11297:     if (srchby == 'lastfirst') {
                   11298:         if (srchterm.indexOf(",") == -1) {
                   11299:             checkok = 0;
1.1222    damieng  11300:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11301:         }
                   11302:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11303:             checkok = 0;
1.1222    damieng  11304:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11305:         }
                   11306:     }
                   11307:     if (checkok == 0) {
1.1222    damieng  11308:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11309:         return;
                   11310:     }
                   11311:     if (checkok == 1) {
1.570     raeburn  11312:         callingForm.submit();
1.556     raeburn  11313:     }
                   11314: }
                   11315: 
                   11316: $newuserscript
                   11317: 
1.824     bisitz   11318: // ]]>
1.556     raeburn  11319: </script>
1.558     albertel 11320: 
                   11321: $new_user_create
                   11322: 
1.555     raeburn  11323: END_BLOCK
1.558     albertel 11324: 
1.876     raeburn  11325:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11326:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11327:                $domform.
                   11328:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11329:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11330:                $srchbysel.
                   11331:                $srchtypesel. 
                   11332:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11333:                $srchinsel.
                   11334:                &Apache::lonhtmlcommon::row_closure(1). 
                   11335:                &Apache::lonhtmlcommon::end_pick_box().
                   11336:                '<br />';
1.1253    raeburn  11337:     return ($output,1);
1.555     raeburn  11338: }
                   11339: 
1.612     raeburn  11340: sub user_rule_check {
1.615     raeburn  11341:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11342:     my ($response,%inst_response);
1.612     raeburn  11343:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11344:         if (keys(%{$usershash}) > 1) {
                   11345:             my (%by_username,%by_id,%userdoms);
                   11346:             my $checkid; 
                   11347:             if (ref($checks) eq 'HASH') {
                   11348:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11349:                     $checkid = 1;
                   11350:                 }
                   11351:             }
                   11352:             foreach my $user (keys(%{$usershash})) {
                   11353:                 my ($uname,$udom) = split(/:/,$user);
                   11354:                 if ($checkid) {
                   11355:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11356:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11357:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11358:                             $userdoms{$udom} = 1;
1.1227    raeburn  11359:                             if (ref($inst_results) eq 'HASH') {
                   11360:                                 $inst_results->{$uname.':'.$udom} = {};
                   11361:                             }
1.1226    raeburn  11362:                         }
                   11363:                     }
                   11364:                 } else {
                   11365:                     $by_username{$udom}{$uname} = 1;
                   11366:                     $userdoms{$udom} = 1;
1.1227    raeburn  11367:                     if (ref($inst_results) eq 'HASH') {
                   11368:                         $inst_results->{$uname.':'.$udom} = {};
                   11369:                     }
1.1226    raeburn  11370:                 }
                   11371:             }
                   11372:             foreach my $udom (keys(%userdoms)) {
                   11373:                 if (!$got_rules->{$udom}) {
                   11374:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11375:                                                              ['usercreation'],$udom);
                   11376:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11377:                         foreach my $item ('username','id') {
                   11378:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11379:                                 $$curr_rules{$udom}{$item} =
                   11380:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11381:                             }
                   11382:                         }
                   11383:                     }
                   11384:                     $got_rules->{$udom} = 1;
                   11385:                 }
1.612     raeburn  11386:             }
1.1226    raeburn  11387:             if ($checkid) {
                   11388:                 foreach my $udom (keys(%by_id)) {
                   11389:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11390:                     if ($outcome eq 'ok') {
1.1227    raeburn  11391:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11392:                             my $uname = $by_id{$udom}{$id};
                   11393:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11394:                         }
1.1226    raeburn  11395:                         if (ref($results) eq 'HASH') {
                   11396:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11397:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11398:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11399:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11400:                                 }
1.1226    raeburn  11401:                             }
                   11402:                         }
                   11403:                     }
1.612     raeburn  11404:                 }
1.615     raeburn  11405:             } else {
1.1226    raeburn  11406:                 foreach my $udom (keys(%by_username)) {
                   11407:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11408:                     if ($outcome eq 'ok') {
1.1227    raeburn  11409:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11410:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11411:                         }
1.1226    raeburn  11412:                         if (ref($results) eq 'HASH') {
                   11413:                             foreach my $uname (keys(%{$results})) {
                   11414:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11415:                             }
                   11416:                         }
                   11417:                     }
                   11418:                 }
1.612     raeburn  11419:             }
1.1226    raeburn  11420:         } elsif (keys(%{$usershash}) == 1) {
                   11421:             my $user = (keys(%{$usershash}))[0];
                   11422:             my ($uname,$udom) = split(/:/,$user);
                   11423:             if (($udom ne '') && ($uname ne '')) {
                   11424:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11425:                     if (ref($checks) eq 'HASH') {
                   11426:                         if (defined($checks->{'username'})) {
                   11427:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11428:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11429:                         } elsif (defined($checks->{'id'})) {
                   11430:                             if ($usershash->{$user}->{'id'} ne '') {
                   11431:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11432:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11433:                                                                   $usershash->{$user}->{'id'});
                   11434:                             } else {
                   11435:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11436:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11437:                             }
1.585     raeburn  11438:                         }
1.1226    raeburn  11439:                     } else {
                   11440:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11441:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11442:                        return;
                   11443:                     }
                   11444:                     if (!$got_rules->{$udom}) {
                   11445:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11446:                                                                  ['usercreation'],$udom);
                   11447:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11448:                             foreach my $item ('username','id') {
                   11449:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11450:                                    $$curr_rules{$udom}{$item} = 
                   11451:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11452:                                 }
                   11453:                             }
                   11454:                         }
                   11455:                         $got_rules->{$udom} = 1;
1.585     raeburn  11456:                     }
                   11457:                 }
1.1226    raeburn  11458:             } else {
                   11459:                 return;
                   11460:             }
                   11461:         } else {
                   11462:             return;
                   11463:         }
                   11464:         foreach my $user (keys(%{$usershash})) {
                   11465:             my ($uname,$udom) = split(/:/,$user);
                   11466:             next if (($udom eq '') || ($uname eq ''));
                   11467:             my $id;
1.1227    raeburn  11468:             if (ref($inst_results) eq 'HASH') {
                   11469:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11470:                     $id = $inst_results->{$user}->{'id'};
                   11471:                 }
                   11472:             }
                   11473:             if ($id eq '') { 
                   11474:                 if (ref($usershash->{$user})) {
                   11475:                     $id = $usershash->{$user}->{'id'};
                   11476:                 }
1.585     raeburn  11477:             }
1.612     raeburn  11478:             foreach my $item (keys(%{$checks})) {
                   11479:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11480:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11481:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11482:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11483:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11484:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11485:                                 if ($rule_check{$rule}) {
                   11486:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11487:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11488:                                         if (ref($inst_results) eq 'HASH') {
                   11489:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11490:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11491:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11492:                                                 } elsif ($item eq 'id') {
                   11493:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11494:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11495:                                                     }
1.615     raeburn  11496:                                                 }
1.612     raeburn  11497:                                             }
                   11498:                                         }
1.615     raeburn  11499:                                     }
                   11500:                                     last;
1.585     raeburn  11501:                                 }
                   11502:                             }
                   11503:                         }
                   11504:                     }
                   11505:                 }
                   11506:             }
                   11507:         }
                   11508:     }
1.612     raeburn  11509:     return;
                   11510: }
                   11511: 
                   11512: sub user_rule_formats {
                   11513:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11514:     my %text = ( 
                   11515:                  'username' => 'Usernames',
                   11516:                  'id'       => 'IDs',
                   11517:                );
                   11518:     my $output;
                   11519:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11520:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11521:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11522:             $output = '<br />'.
                   11523:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11524:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11525:                       ' <ul>';
1.612     raeburn  11526:             foreach my $rule (@{$ruleorder}) {
                   11527:                 if (ref($curr_rules) eq 'ARRAY') {
                   11528:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11529:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11530:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11531:                                         $rules->{$rule}{'desc'}.'</li>';
                   11532:                         }
                   11533:                     }
                   11534:                 }
                   11535:             }
                   11536:             $output .= '</ul>';
                   11537:         }
                   11538:     }
                   11539:     return $output;
                   11540: }
                   11541: 
                   11542: sub instrule_disallow_msg {
1.615     raeburn  11543:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11544:     my $response;
                   11545:     my %text = (
                   11546:                   item   => 'username',
                   11547:                   items  => 'usernames',
                   11548:                   match  => 'matches',
                   11549:                   do     => 'does',
                   11550:                   action => 'a username',
                   11551:                   one    => 'one',
                   11552:                );
                   11553:     if ($count > 1) {
                   11554:         $text{'item'} = 'usernames';
                   11555:         $text{'match'} ='match';
                   11556:         $text{'do'} = 'do';
                   11557:         $text{'action'} = 'usernames',
                   11558:         $text{'one'} = 'ones';
                   11559:     }
                   11560:     if ($checkitem eq 'id') {
                   11561:         $text{'items'} = 'IDs';
                   11562:         $text{'item'} = 'ID';
                   11563:         $text{'action'} = 'an ID';
1.615     raeburn  11564:         if ($count > 1) {
                   11565:             $text{'item'} = 'IDs';
                   11566:             $text{'action'} = 'IDs';
                   11567:         }
1.612     raeburn  11568:     }
1.674     bisitz   11569:     $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  11570:     if ($mode eq 'upload') {
                   11571:         if ($checkitem eq 'username') {
                   11572:             $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'}.");
                   11573:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11574:             $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  11575:         }
1.669     raeburn  11576:     } elsif ($mode eq 'selfcreate') {
                   11577:         if ($checkitem eq 'id') {
                   11578:             $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.");
                   11579:         }
1.615     raeburn  11580:     } else {
                   11581:         if ($checkitem eq 'username') {
                   11582:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11583:         } elsif ($checkitem eq 'id') {
                   11584:             $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.");
                   11585:         }
1.612     raeburn  11586:     }
                   11587:     return $response;
1.585     raeburn  11588: }
                   11589: 
1.624     raeburn  11590: sub personal_data_fieldtitles {
                   11591:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11592:                         id => 'Student/Employee ID',
                   11593:                         permanentemail => 'E-mail address',
                   11594:                         lastname => 'Last Name',
                   11595:                         firstname => 'First Name',
                   11596:                         middlename => 'Middle Name',
                   11597:                         generation => 'Generation',
                   11598:                         gen => 'Generation',
1.765     raeburn  11599:                         inststatus => 'Affiliation',
1.624     raeburn  11600:                    );
                   11601:     return %fieldtitles;
                   11602: }
                   11603: 
1.642     raeburn  11604: sub sorted_inst_types {
                   11605:     my ($dom) = @_;
1.1185    raeburn  11606:     my ($usertypes,$order);
                   11607:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11608:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11609:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11610:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11611:     } else {
                   11612:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11613:     }
1.642     raeburn  11614:     my $othertitle = &mt('All users');
                   11615:     if ($env{'request.course.id'}) {
1.668     raeburn  11616:         $othertitle  = &mt('Any users');
1.642     raeburn  11617:     }
                   11618:     my @types;
                   11619:     if (ref($order) eq 'ARRAY') {
                   11620:         @types = @{$order};
                   11621:     }
                   11622:     if (@types == 0) {
                   11623:         if (ref($usertypes) eq 'HASH') {
                   11624:             @types = sort(keys(%{$usertypes}));
                   11625:         }
                   11626:     }
                   11627:     if (keys(%{$usertypes}) > 0) {
                   11628:         $othertitle = &mt('Other users');
                   11629:     }
                   11630:     return ($othertitle,$usertypes,\@types);
                   11631: }
                   11632: 
1.645     raeburn  11633: sub get_institutional_codes {
1.1361    raeburn  11634:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11635: # Get complete list of course sections to update
                   11636:     my @currsections = ();
                   11637:     my @currxlists = ();
1.1361    raeburn  11638:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11639:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11640:     my $crskey = $crs.':'.$coursecode;
                   11641:     @{$unclutteredsec{$crskey}} = ();
                   11642:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11643: 
                   11644:     if ($$settings{'internal.sectionnums'} ne '') {
                   11645:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11646:     }
                   11647: 
                   11648:     if ($$settings{'internal.crosslistings'} ne '') {
                   11649:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11650:     }
                   11651: 
                   11652:     if (@currxlists > 0) {
1.1361    raeburn  11653:         foreach my $xl (@currxlists) {
                   11654:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11655:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11656:                     push(@{$allcourses},$1);
1.645     raeburn  11657:                     $$LC_code{$1} = $2;
                   11658:                 }
                   11659:             }
                   11660:         }
                   11661:     }
1.1361    raeburn  11662: 
1.645     raeburn  11663:     if (@currsections > 0) {
1.1361    raeburn  11664:         foreach my $sec (@currsections) {
                   11665:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11666:                 my $instsec = $1;
1.645     raeburn  11667:                 my $lc_sec = $2;
1.1361    raeburn  11668:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11669:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11670:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11671:                 }
                   11672:             }
                   11673:         }
                   11674:     }
                   11675: 
                   11676:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11677:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11678:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11679:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11680:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11681:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11682:                     push(@{$allcourses},$sec);
1.1361    raeburn  11683:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11684:                 }
                   11685:             }
                   11686:         }
                   11687:     }
                   11688:     return;
                   11689: }
                   11690: 
1.971     raeburn  11691: sub get_standard_codeitems {
                   11692:     return ('Year','Semester','Department','Number','Section');
                   11693: }
                   11694: 
1.112     bowersj2 11695: =pod
                   11696: 
1.780     raeburn  11697: =head1 Slot Helpers
                   11698: 
                   11699: =over 4
                   11700: 
                   11701: =item * sorted_slots()
                   11702: 
1.1040    raeburn  11703: Sorts an array of slot names in order of an optional sort key,
                   11704: default sort is by slot start time (earliest first). 
1.780     raeburn  11705: 
                   11706: Inputs:
                   11707: 
                   11708: =over 4
                   11709: 
                   11710: slotsarr  - Reference to array of unsorted slot names.
                   11711: 
                   11712: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11713: 
1.1040    raeburn  11714: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11715: 
1.549     albertel 11716: =back
                   11717: 
1.780     raeburn  11718: Returns:
                   11719: 
                   11720: =over 4
                   11721: 
1.1040    raeburn  11722: sorted   - An array of slot names sorted by a specified sort key 
                   11723:            (default sort key is start time of the slot).
1.780     raeburn  11724: 
                   11725: =back
                   11726: 
                   11727: =cut
                   11728: 
                   11729: 
                   11730: sub sorted_slots {
1.1040    raeburn  11731:     my ($slotsarr,$slots,$sortkey) = @_;
                   11732:     if ($sortkey eq '') {
                   11733:         $sortkey = 'starttime';
                   11734:     }
1.780     raeburn  11735:     my @sorted;
                   11736:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11737:         @sorted =
                   11738:             sort {
                   11739:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11740:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11741:                      }
                   11742:                      if (ref($slots->{$a})) { return -1;}
                   11743:                      if (ref($slots->{$b})) { return 1;}
                   11744:                      return 0;
                   11745:                  } @{$slotsarr};
                   11746:     }
                   11747:     return @sorted;
                   11748: }
                   11749: 
1.1040    raeburn  11750: =pod
                   11751: 
                   11752: =item * get_future_slots()
                   11753: 
                   11754: Inputs:
                   11755: 
                   11756: =over 4
                   11757: 
                   11758: cnum - course number
                   11759: 
                   11760: cdom - course domain
                   11761: 
                   11762: now - current UNIX time
                   11763: 
                   11764: symb - optional symb
                   11765: 
                   11766: =back
                   11767: 
                   11768: Returns:
                   11769: 
                   11770: =over 4
                   11771: 
                   11772: sorted_reservable - ref to array of student_schedulable slots currently 
                   11773:                     reservable, ordered by end date of reservation period.
                   11774: 
                   11775: reservable_now - ref to hash of student_schedulable slots currently
                   11776:                  reservable.
                   11777: 
                   11778:     Keys in inner hash are:
                   11779:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11780:     (b) endreserve: end date of reservation period.
                   11781:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11782:         selected.
1.1040    raeburn  11783: 
                   11784: sorted_future - ref to array of student_schedulable slots reservable in
                   11785:                 the future, ordered by start date of reservation period.
                   11786: 
                   11787: future_reservable - ref to hash of student_schedulable slots reservable
                   11788:                     in the future.
                   11789: 
                   11790:     Keys in inner hash are:
                   11791:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11792:     (b) startreserve: start date of reservation period.
                   11793:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11794:         selected.
1.1040    raeburn  11795: 
                   11796: =back
                   11797: 
                   11798: =cut
                   11799: 
                   11800: sub get_future_slots {
                   11801:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11802:     my $map;
                   11803:     if ($symb) {
                   11804:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11805:     }
1.1040    raeburn  11806:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11807:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11808:     foreach my $slot (keys(%slots)) {
                   11809:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11810:         if ($symb) {
1.1229    raeburn  11811:             if ($slots{$slot}->{'symb'} ne '') {
                   11812:                 my $canuse;
                   11813:                 my %oksymbs;
                   11814:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11815:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11816:                 if ($oksymbs{$symb}) {
                   11817:                     $canuse = 1;
                   11818:                 } else {
                   11819:                     foreach my $item (@slotsymbs) {
                   11820:                         if ($item =~ /\.(page|sequence)$/) {
                   11821:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11822:                             if (($map ne '') && ($map eq $sloturl)) {
                   11823:                                 $canuse = 1;
                   11824:                                 last;
                   11825:                             }
                   11826:                         }
                   11827:                     }
                   11828:                 }
                   11829:                 next unless ($canuse);
                   11830:             }
1.1040    raeburn  11831:         }
                   11832:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11833:             ($slots{$slot}->{'endtime'} > $now)) {
                   11834:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11835:                 my $userallowed = 0;
                   11836:                 if ($slots{$slot}->{'allowedsections'}) {
                   11837:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11838:                     if (!defined($env{'request.role.sec'})
                   11839:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11840:                         $userallowed=1;
                   11841:                     } else {
                   11842:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11843:                             $userallowed=1;
                   11844:                         }
                   11845:                     }
                   11846:                     unless ($userallowed) {
                   11847:                         if (defined($env{'request.course.groups'})) {
                   11848:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11849:                             foreach my $group (@groups) {
                   11850:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11851:                                     $userallowed=1;
                   11852:                                     last;
                   11853:                                 }
                   11854:                             }
                   11855:                         }
                   11856:                     }
                   11857:                 }
                   11858:                 if ($slots{$slot}->{'allowedusers'}) {
                   11859:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11860:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11861:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11862:                         $userallowed = 1;
                   11863:                     }
                   11864:                 }
                   11865:                 next unless($userallowed);
                   11866:             }
                   11867:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11868:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11869:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11870:             my $uniqueperiod;
                   11871:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11872:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11873:             }
1.1040    raeburn  11874:             if (($startreserve < $now) &&
                   11875:                 (!$endreserve || $endreserve > $now)) {
                   11876:                 my $lastres = $endreserve;
                   11877:                 if (!$lastres) {
                   11878:                     $lastres = $slots{$slot}->{'starttime'};
                   11879:                 }
                   11880:                 $reservable_now{$slot} = {
                   11881:                                            symb       => $symb,
1.1250    raeburn  11882:                                            endreserve => $lastres,
                   11883:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11884:                                          };
                   11885:             } elsif (($startreserve > $now) &&
                   11886:                      (!$endreserve || $endreserve > $startreserve)) {
                   11887:                 $future_reservable{$slot} = {
                   11888:                                               symb         => $symb,
1.1250    raeburn  11889:                                               startreserve => $startreserve,
                   11890:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11891:                                             };
                   11892:             }
                   11893:         }
                   11894:     }
                   11895:     my @unsorted_reservable = keys(%reservable_now);
                   11896:     if (@unsorted_reservable > 0) {
                   11897:         @sorted_reservable = 
                   11898:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11899:     }
                   11900:     my @unsorted_future = keys(%future_reservable);
                   11901:     if (@unsorted_future > 0) {
                   11902:         @sorted_future =
                   11903:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11904:     }
                   11905:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11906: }
1.780     raeburn  11907: 
                   11908: =pod
                   11909: 
1.1057    foxr     11910: =back
                   11911: 
1.549     albertel 11912: =head1 HTTP Helpers
                   11913: 
                   11914: =over 4
                   11915: 
1.648     raeburn  11916: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11917: 
1.258     albertel 11918: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11919: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11920: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11921: 
                   11922: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11923: $possible_names is an ref to an array of form element names.  As an example:
                   11924: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11925: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11926: 
                   11927: =cut
1.1       albertel 11928: 
1.6       albertel 11929: sub get_unprocessed_cgi {
1.25      albertel 11930:   my ($query,$possible_names)= @_;
1.26      matthew  11931:   # $Apache::lonxml::debug=1;
1.356     albertel 11932:   foreach my $pair (split(/&/,$query)) {
                   11933:     my ($name, $value) = split(/=/,$pair);
1.369     www      11934:     $name = &unescape($name);
1.25      albertel 11935:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11936:       $value =~ tr/+/ /;
                   11937:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11938:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11939:     }
1.16      harris41 11940:   }
1.6       albertel 11941: }
                   11942: 
1.112     bowersj2 11943: =pod
                   11944: 
1.648     raeburn  11945: =item * &cacheheader() 
1.112     bowersj2 11946: 
                   11947: returns cache-controlling header code
                   11948: 
                   11949: =cut
                   11950: 
1.7       albertel 11951: sub cacheheader {
1.258     albertel 11952:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11953:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11954:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11955:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11956:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11957:     return $output;
1.7       albertel 11958: }
                   11959: 
1.112     bowersj2 11960: =pod
                   11961: 
1.648     raeburn  11962: =item * &no_cache($r) 
1.112     bowersj2 11963: 
                   11964: specifies header code to not have cache
                   11965: 
                   11966: =cut
                   11967: 
1.9       albertel 11968: sub no_cache {
1.216     albertel 11969:     my ($r) = @_;
                   11970:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11971: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11972:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11973:     $r->no_cache(1);
                   11974:     $r->header_out("Expires" => $date);
                   11975:     $r->header_out("Pragma" => "no-cache");
1.123     www      11976: }
                   11977: 
                   11978: sub content_type {
1.181     albertel 11979:     my ($r,$type,$charset) = @_;
1.299     foxr     11980:     if ($r) {
                   11981: 	#  Note that printout.pl calls this with undef for $r.
                   11982: 	&no_cache($r);
                   11983:     }
1.258     albertel 11984:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11985:     unless ($charset) {
                   11986: 	$charset=&Apache::lonlocal::current_encoding;
                   11987:     }
                   11988:     if ($charset) { $type.='; charset='.$charset; }
                   11989:     if ($r) {
                   11990: 	$r->content_type($type);
                   11991:     } else {
                   11992: 	print("Content-type: $type\n\n");
                   11993:     }
1.9       albertel 11994: }
1.25      albertel 11995: 
1.112     bowersj2 11996: =pod
                   11997: 
1.648     raeburn  11998: =item * &add_to_env($name,$value) 
1.112     bowersj2 11999: 
1.258     albertel 12000: adds $name to the %env hash with value
1.112     bowersj2 12001: $value, if $name already exists, the entry is converted to an array
                   12002: reference and $value is added to the array.
                   12003: 
                   12004: =cut
                   12005: 
1.25      albertel 12006: sub add_to_env {
                   12007:   my ($name,$value)=@_;
1.258     albertel 12008:   if (defined($env{$name})) {
                   12009:     if (ref($env{$name})) {
1.25      albertel 12010:       #already have multiple values
1.258     albertel 12011:       push(@{ $env{$name} },$value);
1.25      albertel 12012:     } else {
                   12013:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12014:       my $first=$env{$name};
                   12015:       undef($env{$name});
                   12016:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12017:     }
                   12018:   } else {
1.258     albertel 12019:     $env{$name}=$value;
1.25      albertel 12020:   }
1.31      albertel 12021: }
1.149     albertel 12022: 
                   12023: =pod
                   12024: 
1.648     raeburn  12025: =item * &get_env_multiple($name) 
1.149     albertel 12026: 
1.258     albertel 12027: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12028: values may be defined and end up as an array ref.
                   12029: 
                   12030: returns an array of values
                   12031: 
                   12032: =cut
                   12033: 
                   12034: sub get_env_multiple {
                   12035:     my ($name) = @_;
                   12036:     my @values;
1.258     albertel 12037:     if (defined($env{$name})) {
1.149     albertel 12038:         # exists is it an array
1.258     albertel 12039:         if (ref($env{$name})) {
                   12040:             @values=@{ $env{$name} };
1.149     albertel 12041:         } else {
1.258     albertel 12042:             $values[0]=$env{$name};
1.149     albertel 12043:         }
                   12044:     }
                   12045:     return(@values);
                   12046: }
                   12047: 
1.1249    damieng  12048: # Looks at given dependencies, and returns something depending on the context.
                   12049: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12050: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12051: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12052: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12053: # $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.
                   12054: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12055: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12056: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12057: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12058: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12059: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12060: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12061: # @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)
                   12062: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12063: sub ask_for_embedded_content {
1.1249    damieng  12064:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12065:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12066:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12067:         %currsubfile,%unused,$rem);
1.1071    raeburn  12068:     my $counter = 0;
                   12069:     my $numnew = 0;
1.987     raeburn  12070:     my $numremref = 0;
                   12071:     my $numinvalid = 0;
                   12072:     my $numpathchg = 0;
                   12073:     my $numexisting = 0;
1.1071    raeburn  12074:     my $numunused = 0;
                   12075:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12076:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12077:     my $heading = &mt('Upload embedded files');
                   12078:     my $buttontext = &mt('Upload');
                   12079: 
1.1249    damieng  12080:     # fills these variables based on the context:
                   12081:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12082:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12083:     if ($env{'request.course.id'}) {
1.1123    raeburn  12084:         if ($actionurl eq '/adm/dependencies') {
                   12085:             $navmap = Apache::lonnavmaps::navmap->new();
                   12086:         }
                   12087:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12088:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12089:     }
1.1123    raeburn  12090:     if (($actionurl eq '/adm/portfolio') || 
                   12091:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12092:         my $current_path='/';
                   12093:         if ($env{'form.currentpath'}) {
                   12094:             $current_path = $env{'form.currentpath'};
                   12095:         }
                   12096:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12097:             $udom = $cdom;
                   12098:             $uname = $cnum;
1.984     raeburn  12099:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12100:         } else {
                   12101:             $udom = $env{'user.domain'};
                   12102:             $uname = $env{'user.name'};
                   12103:             $url = '/userfiles/portfolio';
                   12104:         }
1.987     raeburn  12105:         $toplevel = $url.'/';
1.984     raeburn  12106:         $url .= $current_path;
                   12107:         $getpropath = 1;
1.987     raeburn  12108:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12109:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12110:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12111:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12112:         $toplevel = $url;
1.984     raeburn  12113:         if ($rest ne '') {
1.987     raeburn  12114:             $url .= $rest;
                   12115:         }
                   12116:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12117:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12118:             $url = $args->{'docs_url'};
                   12119:             $toplevel = $url;
1.1084    raeburn  12120:             if ($args->{'context'} eq 'paste') {
                   12121:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12122:                 ($path) = 
                   12123:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12124:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12125:                 $fileloc =~ s{^/}{};
                   12126:             }
1.1071    raeburn  12127:         }
1.1084    raeburn  12128:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12129:         if ($env{'request.course.id'} ne '') {
                   12130:             if (ref($args) eq 'HASH') {
                   12131:                 $url = $args->{'docs_url'};
                   12132:                 $title = $args->{'docs_title'};
1.1126    raeburn  12133:                 $toplevel = $url; 
                   12134:                 unless ($toplevel =~ m{^/}) {
                   12135:                     $toplevel = "/$url";
                   12136:                 }
1.1085    raeburn  12137:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12138:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12139:                     $path = $1;
                   12140:                 } else {
                   12141:                     ($path) =
                   12142:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12143:                 }
1.1195    raeburn  12144:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12145:                     $fileloc = $toplevel;
                   12146:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12147:                     my ($udom,$uname,$fname) =
                   12148:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12149:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12150:                 } else {
                   12151:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12152:                 }
1.1071    raeburn  12153:                 $fileloc =~ s{^/}{};
                   12154:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12155:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12156:             }
1.987     raeburn  12157:         }
1.1123    raeburn  12158:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12159:         $udom = $cdom;
                   12160:         $uname = $cnum;
                   12161:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12162:         $toplevel = $url;
                   12163:         $path = $url;
                   12164:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12165:         $fileloc =~ s{^/}{};
1.987     raeburn  12166:     }
1.1249    damieng  12167:     
                   12168:     # parses the dependency paths to get some info
                   12169:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12170:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12171:     # (will be completed later)
                   12172:     # $mapping:
                   12173:     #   for external URLs: external URL -> external URL
                   12174:     #   for relative paths: clean path -> original path
                   12175:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12176:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12177:     foreach my $file (keys(%{$allfiles})) {
                   12178:         my $embed_file;
                   12179:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12180:             $embed_file = $1;
                   12181:         } else {
                   12182:             $embed_file = $file;
                   12183:         }
1.1158    raeburn  12184:         my ($absolutepath,$cleaned_file);
                   12185:         if ($embed_file =~ m{^\w+://}) {
                   12186:             $cleaned_file = $embed_file;
1.1147    raeburn  12187:             $newfiles{$cleaned_file} = 1;
                   12188:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12189:         } else {
1.1158    raeburn  12190:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12191:             if ($embed_file =~ m{^/}) {
                   12192:                 $absolutepath = $embed_file;
                   12193:             }
1.1147    raeburn  12194:             if ($cleaned_file =~ m{/}) {
                   12195:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12196:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12197:                 my $item = $fname;
                   12198:                 if ($path ne '') {
                   12199:                     $item = $path.'/'.$fname;
                   12200:                     $subdependencies{$path}{$fname} = 1;
                   12201:                 } else {
                   12202:                     $dependencies{$item} = 1;
                   12203:                 }
                   12204:                 if ($absolutepath) {
                   12205:                     $mapping{$item} = $absolutepath;
                   12206:                 } else {
                   12207:                     $mapping{$item} = $embed_file;
                   12208:                 }
                   12209:             } else {
                   12210:                 $dependencies{$embed_file} = 1;
                   12211:                 if ($absolutepath) {
1.1147    raeburn  12212:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12213:                 } else {
1.1147    raeburn  12214:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12215:                 }
                   12216:             }
1.984     raeburn  12217:         }
                   12218:     }
1.1249    damieng  12219:     
                   12220:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12221:     # and lists
                   12222:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12223:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12224:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12225:     #                                    the path had to be cleaned up
                   12226:     # $existing: hash clean path -> 1 if the file exists
                   12227:     # $numexisting: number of keys in $existing
                   12228:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12229:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12230:     #                                      dependency subdirectories that are
                   12231:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12232:     my $dirptr = 16384;
1.984     raeburn  12233:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12234:         $currsubfile{$path} = {};
1.1123    raeburn  12235:         if (($actionurl eq '/adm/portfolio') || 
                   12236:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12237:             my ($sublistref,$listerror) =
                   12238:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12239:             if (ref($sublistref) eq 'ARRAY') {
                   12240:                 foreach my $line (@{$sublistref}) {
                   12241:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12242:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12243:                 }
1.984     raeburn  12244:             }
1.987     raeburn  12245:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12246:             if (opendir(my $dir,$url.'/'.$path)) {
                   12247:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12248:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12249:             }
1.1084    raeburn  12250:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12251:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12252:                   ($args->{'context'} eq 'paste')) ||
                   12253:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12254:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12255:                 my $dir;
                   12256:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12257:                     $dir = $fileloc;
                   12258:                 } else {
                   12259:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12260:                 }
1.1071    raeburn  12261:                 if ($dir ne '') {
                   12262:                     my ($sublistref,$listerror) =
                   12263:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12264:                     if (ref($sublistref) eq 'ARRAY') {
                   12265:                         foreach my $line (@{$sublistref}) {
                   12266:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12267:                                 undef,$mtime)=split(/\&/,$line,12);
                   12268:                             unless (($testdir&$dirptr) ||
                   12269:                                     ($file_name =~ /^\.\.?$/)) {
                   12270:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12271:                             }
                   12272:                         }
                   12273:                     }
                   12274:                 }
1.984     raeburn  12275:             }
                   12276:         }
                   12277:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12278:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12279:                 my $item = $path.'/'.$file;
                   12280:                 unless ($mapping{$item} eq $item) {
                   12281:                     $pathchanges{$item} = 1;
                   12282:                 }
                   12283:                 $existing{$item} = 1;
                   12284:                 $numexisting ++;
                   12285:             } else {
                   12286:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12287:             }
                   12288:         }
1.1071    raeburn  12289:         if ($actionurl eq '/adm/dependencies') {
                   12290:             foreach my $path (keys(%currsubfile)) {
                   12291:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12292:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12293:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12294:                              next if (($rem ne '') &&
                   12295:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12296:                                        (ref($navmap) &&
                   12297:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12298:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12299:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12300:                              $unused{$path.'/'.$file} = 1; 
                   12301:                          }
                   12302:                     }
                   12303:                 }
                   12304:             }
                   12305:         }
1.984     raeburn  12306:     }
1.1249    damieng  12307:     
                   12308:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12309:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12310:     my %currfile;
1.1123    raeburn  12311:     if (($actionurl eq '/adm/portfolio') ||
                   12312:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12313:         my ($dirlistref,$listerror) =
                   12314:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12315:         if (ref($dirlistref) eq 'ARRAY') {
                   12316:             foreach my $line (@{$dirlistref}) {
                   12317:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12318:                 $currfile{$file_name} = 1;
                   12319:             }
1.984     raeburn  12320:         }
1.987     raeburn  12321:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12322:         if (opendir(my $dir,$url)) {
1.987     raeburn  12323:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12324:             map {$currfile{$_} = 1;} @dir_list;
                   12325:         }
1.1084    raeburn  12326:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12327:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12328:               ($args->{'context'} eq 'paste')) ||
                   12329:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12330:         if ($env{'request.course.id'} ne '') {
                   12331:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12332:             if ($dir ne '') {
                   12333:                 my ($dirlistref,$listerror) =
                   12334:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12335:                 if (ref($dirlistref) eq 'ARRAY') {
                   12336:                     foreach my $line (@{$dirlistref}) {
                   12337:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12338:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12339:                         unless (($testdir&$dirptr) ||
                   12340:                                 ($file_name =~ /^\.\.?$/)) {
                   12341:                             $currfile{$file_name} = [$size,$mtime];
                   12342:                         }
                   12343:                     }
                   12344:                 }
                   12345:             }
                   12346:         }
1.984     raeburn  12347:     }
1.1249    damieng  12348:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12349:     # are not in subdirectories, using $currfile
1.984     raeburn  12350:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12351:         if (exists($currfile{$file})) {
1.987     raeburn  12352:             unless ($mapping{$file} eq $file) {
                   12353:                 $pathchanges{$file} = 1;
                   12354:             }
                   12355:             $existing{$file} = 1;
                   12356:             $numexisting ++;
                   12357:         } else {
1.984     raeburn  12358:             $newfiles{$file} = 1;
                   12359:         }
                   12360:     }
1.1071    raeburn  12361:     foreach my $file (keys(%currfile)) {
                   12362:         unless (($file eq $filename) ||
                   12363:                 ($file eq $filename.'.bak') ||
                   12364:                 ($dependencies{$file})) {
1.1085    raeburn  12365:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12366:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12367:                     next if (($rem ne '') &&
                   12368:                              (($env{"httpref.$rem".$file} ne '') ||
                   12369:                               (ref($navmap) &&
                   12370:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12371:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12372:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12373:                 }
1.1085    raeburn  12374:             }
1.1071    raeburn  12375:             $unused{$file} = 1;
                   12376:         }
                   12377:     }
1.1249    damieng  12378:     
                   12379:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12380:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12381:         ($args->{'context'} eq 'paste')) {
                   12382:         $counter = scalar(keys(%existing));
                   12383:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12384:         return ($output,$counter,$numpathchg,\%existing);
                   12385:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12386:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12387:         $counter = scalar(keys(%existing));
                   12388:         $numpathchg = scalar(keys(%pathchanges));
                   12389:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12390:     }
1.1249    damieng  12391:     
                   12392:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12393:     
                   12394:     # $upload_output: missing dependencies (with upload form)
                   12395:     # $modify_output: uploaded dependencies (in use)
                   12396:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12397:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12398:         if ($actionurl eq '/adm/dependencies') {
                   12399:             next if ($embed_file =~ m{^\w+://});
                   12400:         }
1.660     raeburn  12401:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12402:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12403:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12404:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12405:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12406:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12407:         }
1.1123    raeburn  12408:         $upload_output .= '</td>';
1.1071    raeburn  12409:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12410:             $upload_output.='<td align="right">'.
                   12411:                             '<span class="LC_info LC_fontsize_medium">'.
                   12412:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12413:             $numremref++;
1.660     raeburn  12414:         } elsif ($args->{'error_on_invalid_names'}
                   12415:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12416:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12417:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12418:             $numinvalid++;
1.660     raeburn  12419:         } else {
1.1123    raeburn  12420:             $upload_output .= '<td>'.
                   12421:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12422:                                                      $embed_file,\%mapping,
1.1071    raeburn  12423:                                                      $allfiles,$codebase,'upload');
                   12424:             $counter ++;
                   12425:             $numnew ++;
1.987     raeburn  12426:         }
                   12427:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12428:     }
                   12429:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12430:         if ($actionurl eq '/adm/dependencies') {
                   12431:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12432:             $modify_output .= &start_data_table_row().
                   12433:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12434:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12435:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12436:                               '<td>'.$size.'</td>'.
                   12437:                               '<td>'.$mtime.'</td>'.
                   12438:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12439:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12440:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12441:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12442:                               &embedded_file_element('upload_embedded',$counter,
                   12443:                                                      $embed_file,\%mapping,
                   12444:                                                      $allfiles,$codebase,'modify').
                   12445:                               '</div></td>'.
                   12446:                               &end_data_table_row()."\n";
                   12447:             $counter ++;
                   12448:         } else {
                   12449:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12450:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12451:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12452:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12453:                               &Apache::loncommon::end_data_table_row()."\n";
                   12454:         }
                   12455:     }
                   12456:     my $delidx = $counter;
                   12457:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12458:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12459:         $delete_output .= &start_data_table_row().
                   12460:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12461:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12462:                           '<td>'.$size.'</td>'.
                   12463:                           '<td>'.$mtime.'</td>'.
                   12464:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12465:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12466:                           &embedded_file_element('upload_embedded',$delidx,
                   12467:                                                  $oldfile,\%mapping,$allfiles,
                   12468:                                                  $codebase,'delete').'</td>'.
                   12469:                           &end_data_table_row()."\n"; 
                   12470:         $numunused ++;
                   12471:         $delidx ++;
1.987     raeburn  12472:     }
                   12473:     if ($upload_output) {
                   12474:         $upload_output = &start_data_table().
                   12475:                          $upload_output.
                   12476:                          &end_data_table()."\n";
                   12477:     }
1.1071    raeburn  12478:     if ($modify_output) {
                   12479:         $modify_output = &start_data_table().
                   12480:                          &start_data_table_header_row().
                   12481:                          '<th>'.&mt('File').'</th>'.
                   12482:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12483:                          '<th>'.&mt('Modified').'</th>'.
                   12484:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12485:                          &end_data_table_header_row().
                   12486:                          $modify_output.
                   12487:                          &end_data_table()."\n";
                   12488:     }
                   12489:     if ($delete_output) {
                   12490:         $delete_output = &start_data_table().
                   12491:                          &start_data_table_header_row().
                   12492:                          '<th>'.&mt('File').'</th>'.
                   12493:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12494:                          '<th>'.&mt('Modified').'</th>'.
                   12495:                          '<th>'.&mt('Delete?').'</th>'.
                   12496:                          &end_data_table_header_row().
                   12497:                          $delete_output.
                   12498:                          &end_data_table()."\n";
                   12499:     }
1.987     raeburn  12500:     my $applies = 0;
                   12501:     if ($numremref) {
                   12502:         $applies ++;
                   12503:     }
                   12504:     if ($numinvalid) {
                   12505:         $applies ++;
                   12506:     }
                   12507:     if ($numexisting) {
                   12508:         $applies ++;
                   12509:     }
1.1071    raeburn  12510:     if ($counter || $numunused) {
1.987     raeburn  12511:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12512:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12513:                   $state.'<h3>'.$heading.'</h3>'; 
                   12514:         if ($actionurl eq '/adm/dependencies') {
                   12515:             if ($numnew) {
                   12516:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12517:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12518:                            $upload_output.'<br />'."\n";
                   12519:             }
                   12520:             if ($numexisting) {
                   12521:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12522:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12523:                            $modify_output.'<br />'."\n";
                   12524:                            $buttontext = &mt('Save changes');
                   12525:             }
                   12526:             if ($numunused) {
                   12527:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12528:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12529:                            $delete_output.'<br />'."\n";
                   12530:                            $buttontext = &mt('Save changes');
                   12531:             }
                   12532:         } else {
                   12533:             $output .= $upload_output.'<br />'."\n";
                   12534:         }
                   12535:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12536:                    $counter.'" />'."\n";
                   12537:         if ($actionurl eq '/adm/dependencies') { 
                   12538:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12539:                        $numnew.'" />'."\n";
                   12540:         } elsif ($actionurl eq '') {
1.987     raeburn  12541:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12542:         }
                   12543:     } elsif ($applies) {
                   12544:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12545:         if ($applies > 1) {
                   12546:             $output .=  
1.1123    raeburn  12547:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12548:             if ($numremref) {
                   12549:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12550:             }
                   12551:             if ($numinvalid) {
                   12552:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12553:             }
                   12554:             if ($numexisting) {
                   12555:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12556:             }
                   12557:             $output .= '</ul><br />';
                   12558:         } elsif ($numremref) {
                   12559:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12560:         } elsif ($numinvalid) {
                   12561:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12562:         } elsif ($numexisting) {
                   12563:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12564:         }
                   12565:         $output .= $upload_output.'<br />';
                   12566:     }
                   12567:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12568:     $chgcount = $counter;
1.987     raeburn  12569:     if (keys(%pathchanges) > 0) {
                   12570:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12571:             if ($counter) {
1.987     raeburn  12572:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12573:                                                   $embed_file,\%mapping,
1.1071    raeburn  12574:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12575:             } else {
                   12576:                 $pathchange_output .= 
                   12577:                     &start_data_table_row().
                   12578:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12579:                     $chgcount.'" checked="checked" /></td>'.
                   12580:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12581:                     '<td>'.$embed_file.
                   12582:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12583:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12584:                     '</td>'.&end_data_table_row();
1.660     raeburn  12585:             }
1.987     raeburn  12586:             $numpathchg ++;
                   12587:             $chgcount ++;
1.660     raeburn  12588:         }
                   12589:     }
1.1127    raeburn  12590:     if (($counter) || ($numunused)) {
1.987     raeburn  12591:         if ($numpathchg) {
                   12592:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12593:                        $numpathchg.'" />'."\n";
                   12594:         }
                   12595:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12596:             ($actionurl eq '/adm/imsimport')) {
                   12597:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12598:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12599:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12600:         } elsif ($actionurl eq '/adm/dependencies') {
                   12601:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12602:         }
1.1123    raeburn  12603:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12604:     } elsif ($numpathchg) {
                   12605:         my %pathchange = ();
                   12606:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12607:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12608:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12609:         }
1.987     raeburn  12610:     }
1.1071    raeburn  12611:     return ($output,$counter,$numpathchg);
1.987     raeburn  12612: }
                   12613: 
1.1147    raeburn  12614: =pod
                   12615: 
                   12616: =item * clean_path($name)
                   12617: 
                   12618: Performs clean-up of directories, subdirectories and filename in an
                   12619: embedded object, referenced in an HTML file which is being uploaded
                   12620: to a course or portfolio, where 
                   12621: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12622: checked.
                   12623: 
                   12624: Clean-up is similar to replacements in lonnet::clean_filename()
                   12625: except each / between sub-directory and next level is preserved.
                   12626: 
                   12627: =cut
                   12628: 
                   12629: sub clean_path {
                   12630:     my ($embed_file) = @_;
                   12631:     $embed_file =~s{^/+}{};
                   12632:     my @contents;
                   12633:     if ($embed_file =~ m{/}) {
                   12634:         @contents = split(/\//,$embed_file);
                   12635:     } else {
                   12636:         @contents = ($embed_file);
                   12637:     }
                   12638:     my $lastidx = scalar(@contents)-1;
                   12639:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12640:         $contents[$i]=~s{\\}{/}g;
                   12641:         $contents[$i]=~s/\s+/\_/g;
                   12642:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12643:         if ($i == $lastidx) {
                   12644:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12645:         }
                   12646:     }
                   12647:     if ($lastidx > 0) {
                   12648:         return join('/',@contents);
                   12649:     } else {
                   12650:         return $contents[0];
                   12651:     }
                   12652: }
                   12653: 
1.987     raeburn  12654: sub embedded_file_element {
1.1071    raeburn  12655:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12656:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12657:                    (ref($codebase) eq 'HASH'));
                   12658:     my $output;
1.1071    raeburn  12659:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12660:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12661:     }
                   12662:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12663:                &escape($embed_file).'" />';
                   12664:     unless (($context eq 'upload_embedded') && 
                   12665:             ($mapping->{$embed_file} eq $embed_file)) {
                   12666:         $output .='
                   12667:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12668:     }
                   12669:     my $attrib;
                   12670:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12671:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12672:     }
                   12673:     $output .=
                   12674:         "\n\t\t".
                   12675:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12676:         $attrib.'" />';
                   12677:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12678:         $output .=
                   12679:             "\n\t\t".
                   12680:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12681:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12682:     }
1.987     raeburn  12683:     return $output;
1.660     raeburn  12684: }
                   12685: 
1.1071    raeburn  12686: sub get_dependency_details {
                   12687:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12688:     my ($size,$mtime,$showsize,$showmtime);
                   12689:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12690:         if ($embed_file =~ m{/}) {
                   12691:             my ($path,$fname) = split(/\//,$embed_file);
                   12692:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12693:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12694:             }
                   12695:         } else {
                   12696:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12697:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12698:             }
                   12699:         }
                   12700:         $showsize = $size/1024.0;
                   12701:         $showsize = sprintf("%.1f",$showsize);
                   12702:         if ($mtime > 0) {
                   12703:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12704:         }
                   12705:     }
                   12706:     return ($showsize,$showmtime);
                   12707: }
                   12708: 
                   12709: sub ask_embedded_js {
                   12710:     return <<"END";
                   12711: <script type="text/javascript"">
                   12712: // <![CDATA[
                   12713: function toggleBrowse(counter) {
                   12714:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12715:     var fileid = document.getElementById('embedded_item_'+counter);
                   12716:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12717:     if (chkboxid.checked == true) {
                   12718:         uploaddivid.style.display='block';
                   12719:     } else {
                   12720:         uploaddivid.style.display='none';
                   12721:         fileid.value = '';
                   12722:     }
                   12723: }
                   12724: // ]]>
                   12725: </script>
                   12726: 
                   12727: END
                   12728: }
                   12729: 
1.661     raeburn  12730: sub upload_embedded {
                   12731:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12732:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12733:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12734:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12735:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12736:         my $orig_uploaded_filename =
                   12737:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12738:         foreach my $type ('orig','ref','attrib','codebase') {
                   12739:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12740:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12741:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12742:             }
                   12743:         }
1.661     raeburn  12744:         my ($path,$fname) =
                   12745:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12746:         # no path, whole string is fname
                   12747:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12748:         $fname = &Apache::lonnet::clean_filename($fname);
                   12749:         # See if there is anything left
                   12750:         next if ($fname eq '');
                   12751: 
                   12752:         # Check if file already exists as a file or directory.
                   12753:         my ($state,$msg);
                   12754:         if ($context eq 'portfolio') {
                   12755:             my $port_path = $dirpath;
                   12756:             if ($group ne '') {
                   12757:                 $port_path = "groups/$group/$port_path";
                   12758:             }
1.987     raeburn  12759:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12760:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12761:                                               $dir_root,$port_path,$disk_quota,
                   12762:                                               $current_disk_usage,$uname,$udom);
                   12763:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12764:                 || $state eq 'file_locked') {
1.661     raeburn  12765:                 $output .= $msg;
                   12766:                 next;
                   12767:             }
                   12768:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12769:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12770:             if ($state eq 'exists') {
                   12771:                 $output .= $msg;
                   12772:                 next;
                   12773:             }
                   12774:         }
                   12775:         # Check if extension is valid
                   12776:         if (($fname =~ /\.(\w+)$/) &&
                   12777:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12778:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12779:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12780:             next;
                   12781:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12782:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12783:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12784:             next;
                   12785:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12786:             $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  12787:             next;
                   12788:         }
                   12789:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12790:         my $subdir = $path;
                   12791:         $subdir =~ s{/+$}{};
1.661     raeburn  12792:         if ($context eq 'portfolio') {
1.984     raeburn  12793:             my $result;
                   12794:             if ($state eq 'existingfile') {
                   12795:                 $result=
                   12796:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12797:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12798:             } else {
1.984     raeburn  12799:                 $result=
                   12800:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12801:                                                     $dirpath.
1.1123    raeburn  12802:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12803:                 if ($result !~ m|^/uploaded/|) {
                   12804:                     $output .= '<span class="LC_error">'
                   12805:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12806:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12807:                                .'</span><br />';
                   12808:                     next;
                   12809:                 } else {
1.987     raeburn  12810:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12811:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12812:                 }
1.661     raeburn  12813:             }
1.1123    raeburn  12814:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12815:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12816:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12817:             my $result =
1.1126    raeburn  12818:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12819:             if ($result !~ m|^/uploaded/|) {
                   12820:                 $output .= '<span class="LC_error">'
                   12821:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12822:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12823:                            .'</span><br />';
                   12824:                     next;
                   12825:             } else {
                   12826:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12827:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12828:                 if ($context eq 'syllabus') {
                   12829:                     &Apache::lonnet::make_public_indefinitely($result);
                   12830:                 }
1.987     raeburn  12831:             }
1.661     raeburn  12832:         } else {
                   12833: # Save the file
                   12834:             my $target = $env{'form.embedded_item_'.$i};
                   12835:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12836:             my $dest = $fullpath.$fname;
                   12837:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12838:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12839:             my $count;
                   12840:             my $filepath = $dir_root;
1.1027    raeburn  12841:             foreach my $subdir (@parts) {
                   12842:                 $filepath .= "/$subdir";
                   12843:                 if (!-e $filepath) {
1.661     raeburn  12844:                     mkdir($filepath,0770);
                   12845:                 }
                   12846:             }
                   12847:             my $fh;
                   12848:             if (!open($fh,'>'.$dest)) {
                   12849:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12850:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12851:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12852:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12853:                            '</span><br />';
                   12854:             } else {
                   12855:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12856:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12857:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12858:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12859:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12860:                               '</span><br />';
                   12861:                 } else {
1.987     raeburn  12862:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12863:                                $url.'</span>').'<br />';
                   12864:                     unless ($context eq 'testbank') {
                   12865:                         $footer .= &mt('View embedded file: [_1]',
                   12866:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12867:                     }
                   12868:                 }
                   12869:                 close($fh);
                   12870:             }
                   12871:         }
                   12872:         if ($env{'form.embedded_ref_'.$i}) {
                   12873:             $pathchange{$i} = 1;
                   12874:         }
                   12875:     }
                   12876:     if ($output) {
                   12877:         $output = '<p>'.$output.'</p>';
                   12878:     }
                   12879:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12880:     $returnflag = 'ok';
1.1071    raeburn  12881:     my $numpathchgs = scalar(keys(%pathchange));
                   12882:     if ($numpathchgs > 0) {
1.987     raeburn  12883:         if ($context eq 'portfolio') {
                   12884:             $output .= '<p>'.&mt('or').'</p>';
                   12885:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12886:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12887:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12888:             $returnflag = 'modify_orightml';
                   12889:         }
                   12890:     }
1.1071    raeburn  12891:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12892: }
                   12893: 
                   12894: sub modify_html_form {
                   12895:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12896:     my $end = 0;
                   12897:     my $modifyform;
                   12898:     if ($context eq 'upload_embedded') {
                   12899:         return unless (ref($pathchange) eq 'HASH');
                   12900:         if ($env{'form.number_embedded_items'}) {
                   12901:             $end += $env{'form.number_embedded_items'};
                   12902:         }
                   12903:         if ($env{'form.number_pathchange_items'}) {
                   12904:             $end += $env{'form.number_pathchange_items'};
                   12905:         }
                   12906:         if ($end) {
                   12907:             for (my $i=0; $i<$end; $i++) {
                   12908:                 if ($i < $env{'form.number_embedded_items'}) {
                   12909:                     next unless($pathchange->{$i});
                   12910:                 }
                   12911:                 $modifyform .=
                   12912:                     &start_data_table_row().
                   12913:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12914:                     'checked="checked" /></td>'.
                   12915:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12916:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12917:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12918:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12919:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12920:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12921:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12922:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12923:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12924:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12925:                     &end_data_table_row();
1.1071    raeburn  12926:             }
1.987     raeburn  12927:         }
                   12928:     } else {
                   12929:         $modifyform = $pathchgtable;
                   12930:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12931:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12932:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12933:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12934:         }
                   12935:     }
                   12936:     if ($modifyform) {
1.1071    raeburn  12937:         if ($actionurl eq '/adm/dependencies') {
                   12938:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12939:         }
1.987     raeburn  12940:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12941:                '<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".
                   12942:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12943:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12944:                '</ol></p>'."\n".'<p>'.
                   12945:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12946:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12947:                &start_data_table()."\n".
                   12948:                &start_data_table_header_row().
                   12949:                '<th>'.&mt('Change?').'</th>'.
                   12950:                '<th>'.&mt('Current reference').'</th>'.
                   12951:                '<th>'.&mt('Required reference').'</th>'.
                   12952:                &end_data_table_header_row()."\n".
                   12953:                $modifyform.
                   12954:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12955:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12956:                '</form>'."\n";
                   12957:     }
                   12958:     return;
                   12959: }
                   12960: 
                   12961: sub modify_html_refs {
1.1123    raeburn  12962:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12963:     my $container;
                   12964:     if ($context eq 'portfolio') {
                   12965:         $container = $env{'form.container'};
                   12966:     } elsif ($context eq 'coursedoc') {
                   12967:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12968:     } elsif ($context eq 'manage_dependencies') {
                   12969:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12970:         $container = "/$container";
1.1123    raeburn  12971:     } elsif ($context eq 'syllabus') {
                   12972:         $container = $url;
1.987     raeburn  12973:     } else {
1.1027    raeburn  12974:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12975:     }
                   12976:     my (%allfiles,%codebase,$output,$content);
                   12977:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12978:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12979:         if (wantarray) {
                   12980:             return ('',0,0); 
                   12981:         } else {
                   12982:             return;
                   12983:         }
                   12984:     }
                   12985:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12986:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12987:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12988:             if (wantarray) {
                   12989:                 return ('',0,0);
                   12990:             } else {
                   12991:                 return;
                   12992:             }
                   12993:         } 
1.987     raeburn  12994:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12995:         if ($content eq '-1') {
                   12996:             if (wantarray) {
                   12997:                 return ('',0,0);
                   12998:             } else {
                   12999:                 return;
                   13000:             }
                   13001:         }
1.987     raeburn  13002:     } else {
1.1071    raeburn  13003:         unless ($container =~ /^\Q$dir_root\E/) {
                   13004:             if (wantarray) {
                   13005:                 return ('',0,0);
                   13006:             } else {
                   13007:                 return;
                   13008:             }
                   13009:         } 
1.1317    raeburn  13010:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13011:             $content = join('', <$fh>);
                   13012:             close($fh);
                   13013:         } else {
1.1071    raeburn  13014:             if (wantarray) {
                   13015:                 return ('',0,0);
                   13016:             } else {
                   13017:                 return;
                   13018:             }
1.987     raeburn  13019:         }
                   13020:     }
                   13021:     my ($count,$codebasecount) = (0,0);
                   13022:     my $mm = new File::MMagic;
                   13023:     my $mime_type = $mm->checktype_contents($content);
                   13024:     if ($mime_type eq 'text/html') {
                   13025:         my $parse_result = 
                   13026:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13027:                                                     \%codebase,\$content);
                   13028:         if ($parse_result eq 'ok') {
                   13029:             foreach my $i (@changes) {
                   13030:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13031:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13032:                 if ($allfiles{$ref}) {
                   13033:                     my $newname =  $orig;
                   13034:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13035:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13036:                     if ($attrib_regexp =~ /:/) {
                   13037:                         $attrib_regexp =~ s/\:/|/g;
                   13038:                     }
                   13039:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13040:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13041:                         $count += $numchg;
1.1123    raeburn  13042:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13043:                         delete($allfiles{$ref});
1.987     raeburn  13044:                     }
                   13045:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13046:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13047:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13048:                         $codebasecount ++;
                   13049:                     }
                   13050:                 }
                   13051:             }
1.1123    raeburn  13052:             my $skiprewrites;
1.987     raeburn  13053:             if ($count || $codebasecount) {
                   13054:                 my $saveresult;
1.1071    raeburn  13055:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13056:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13057:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13058:                     if ($url eq $container) {
                   13059:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13060:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13061:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13062:                                             $fname.'</span>').'</p>';
1.987     raeburn  13063:                     } else {
                   13064:                          $output = '<p class="LC_error">'.
                   13065:                                    &mt('Error: update failed for: [_1].',
                   13066:                                    '<span class="LC_filename">'.
                   13067:                                    $container.'</span>').'</p>';
                   13068:                     }
1.1123    raeburn  13069:                     if ($context eq 'syllabus') {
                   13070:                         unless ($saveresult eq 'ok') {
                   13071:                             $skiprewrites = 1;
                   13072:                         }
                   13073:                     }
1.987     raeburn  13074:                 } else {
1.1317    raeburn  13075:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13076:                         print $fh $content;
                   13077:                         close($fh);
                   13078:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13079:                                   $count,'<span class="LC_filename">'.
                   13080:                                   $container.'</span>').'</p>';
1.661     raeburn  13081:                     } else {
1.987     raeburn  13082:                          $output = '<p class="LC_error">'.
                   13083:                                    &mt('Error: could not update [_1].',
                   13084:                                    '<span class="LC_filename">'.
                   13085:                                    $container.'</span>').'</p>';
1.661     raeburn  13086:                     }
                   13087:                 }
                   13088:             }
1.1123    raeburn  13089:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13090:                 my ($actionurl,$state);
                   13091:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13092:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13093:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13094:                                               \%codebase,
                   13095:                                               {'context' => 'rewrites',
                   13096:                                                'ignore_remote_references' => 1,});
                   13097:                 if (ref($mapping) eq 'HASH') {
                   13098:                     my $rewrites = 0;
                   13099:                     foreach my $key (keys(%{$mapping})) {
                   13100:                         next if ($key =~ m{^https?://});
                   13101:                         my $ref = $mapping->{$key};
                   13102:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13103:                         my $attrib;
                   13104:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13105:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13106:                         }
                   13107:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13108:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13109:                             $rewrites += $numchg;
                   13110:                         }
                   13111:                     }
                   13112:                     if ($rewrites) {
                   13113:                         my $saveresult; 
                   13114:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13115:                         if ($url eq $container) {
                   13116:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13117:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13118:                                             $count,'<span class="LC_filename">'.
                   13119:                                             $fname.'</span>').'</p>';
                   13120:                         } else {
                   13121:                             $output .= '<p class="LC_error">'.
                   13122:                                        &mt('Error: could not update links in [_1].',
                   13123:                                        '<span class="LC_filename">'.
                   13124:                                        $container.'</span>').'</p>';
                   13125: 
                   13126:                         }
                   13127:                     }
                   13128:                 }
                   13129:             }
1.987     raeburn  13130:         } else {
                   13131:             &logthis('Failed to parse '.$container.
                   13132:                      ' to modify references: '.$parse_result);
1.661     raeburn  13133:         }
                   13134:     }
1.1071    raeburn  13135:     if (wantarray) {
                   13136:         return ($output,$count,$codebasecount);
                   13137:     } else {
                   13138:         return $output;
                   13139:     }
1.661     raeburn  13140: }
                   13141: 
                   13142: sub check_for_existing {
                   13143:     my ($path,$fname,$element) = @_;
                   13144:     my ($state,$msg);
                   13145:     if (-d $path.'/'.$fname) {
                   13146:         $state = 'exists';
                   13147:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13148:     } elsif (-e $path.'/'.$fname) {
                   13149:         $state = 'exists';
                   13150:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13151:     }
                   13152:     if ($state eq 'exists') {
                   13153:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13154:     }
                   13155:     return ($state,$msg);
                   13156: }
                   13157: 
                   13158: sub check_for_upload {
                   13159:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13160:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13161:     my $filesize = length($env{'form.'.$element});
                   13162:     if (!$filesize) {
                   13163:         my $msg = '<span class="LC_error">'.
                   13164:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13165:                       '<span class="LC_filename">'.$fname.'</span>',
                   13166:                       $filesize).'<br />'.
1.1007    raeburn  13167:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13168:                   '</span>';
                   13169:         return ('zero_bytes',$msg);
                   13170:     }
                   13171:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13172:     my $getpropath = 1;
1.1021    raeburn  13173:     my ($dirlistref,$listerror) =
                   13174:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13175:     my $found_file = 0;
                   13176:     my $locked_file = 0;
1.991     raeburn  13177:     my @lockers;
                   13178:     my $navmap;
                   13179:     if ($env{'request.course.id'}) {
                   13180:         $navmap = Apache::lonnavmaps::navmap->new();
                   13181:     }
1.1021    raeburn  13182:     if (ref($dirlistref) eq 'ARRAY') {
                   13183:         foreach my $line (@{$dirlistref}) {
                   13184:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13185:             if ($file_name eq $fname){
                   13186:                 $file_name = $path.$file_name;
                   13187:                 if ($group ne '') {
                   13188:                     $file_name = $group.$file_name;
                   13189:                 }
                   13190:                 $found_file = 1;
                   13191:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13192:                     foreach my $lock (@lockers) {
                   13193:                         if (ref($lock) eq 'ARRAY') {
                   13194:                             my ($symb,$crsid) = @{$lock};
                   13195:                             if ($crsid eq $env{'request.course.id'}) {
                   13196:                                 if (ref($navmap)) {
                   13197:                                     my $res = $navmap->getBySymb($symb);
                   13198:                                     foreach my $part (@{$res->parts()}) { 
                   13199:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13200:                                         unless (($slot_status == $res->RESERVED) ||
                   13201:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13202:                                             $locked_file = 1;
                   13203:                                         }
1.991     raeburn  13204:                                     }
1.1021    raeburn  13205:                                 } else {
                   13206:                                     $locked_file = 1;
1.991     raeburn  13207:                                 }
                   13208:                             } else {
                   13209:                                 $locked_file = 1;
                   13210:                             }
                   13211:                         }
1.1021    raeburn  13212:                    }
                   13213:                 } else {
                   13214:                     my @info = split(/\&/,$rest);
                   13215:                     my $currsize = $info[6]/1000;
                   13216:                     if ($currsize < $filesize) {
                   13217:                         my $extra = $filesize - $currsize;
                   13218:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13219:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13220:                                       &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   13221:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13222:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13223:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13224:                             return ('will_exceed_quota',$msg);
                   13225:                         }
1.984     raeburn  13226:                     }
                   13227:                 }
1.661     raeburn  13228:             }
                   13229:         }
                   13230:     }
                   13231:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13232:         my $msg = '<p class="LC_warning">'.
                   13233:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13234:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13235:         return ('will_exceed_quota',$msg);
                   13236:     } elsif ($found_file) {
                   13237:         if ($locked_file) {
1.1179    bisitz   13238:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13239:             $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   13240:             $msg .= '</p>';
1.661     raeburn  13241:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13242:             return ('file_locked',$msg);
                   13243:         } else {
1.1179    bisitz   13244:             my $msg = '<p class="LC_error">';
1.984     raeburn  13245:             $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   13246:             $msg .= '</p>';
1.984     raeburn  13247:             return ('existingfile',$msg);
1.661     raeburn  13248:         }
                   13249:     }
                   13250: }
                   13251: 
1.987     raeburn  13252: sub check_for_traversal {
                   13253:     my ($path,$url,$toplevel) = @_;
                   13254:     my @parts=split(/\//,$path);
                   13255:     my $cleanpath;
                   13256:     my $fullpath = $url;
                   13257:     for (my $i=0;$i<@parts;$i++) {
                   13258:         next if ($parts[$i] eq '.');
                   13259:         if ($parts[$i] eq '..') {
                   13260:             $fullpath =~ s{([^/]+/)$}{};
                   13261:         } else {
                   13262:             $fullpath .= $parts[$i].'/';
                   13263:         }
                   13264:     }
                   13265:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13266:         $cleanpath = $1;
                   13267:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13268:         my $curr_toprel = $1;
                   13269:         my @parts = split(/\//,$curr_toprel);
                   13270:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13271:         my @urlparts = split(/\//,$url_toprel);
                   13272:         my $doubledots;
                   13273:         my $startdiff = -1;
                   13274:         for (my $i=0; $i<@urlparts; $i++) {
                   13275:             if ($startdiff == -1) {
                   13276:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13277:                     $startdiff = $i;
                   13278:                     $doubledots .= '../';
                   13279:                 }
                   13280:             } else {
                   13281:                 $doubledots .= '../';
                   13282:             }
                   13283:         }
                   13284:         if ($startdiff > -1) {
                   13285:             $cleanpath = $doubledots;
                   13286:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13287:                 $cleanpath .= $parts[$i].'/';
                   13288:             }
                   13289:         }
                   13290:     }
                   13291:     $cleanpath =~ s{(/)$}{};
                   13292:     return $cleanpath;
                   13293: }
1.31      albertel 13294: 
1.1053    raeburn  13295: sub is_archive_file {
                   13296:     my ($mimetype) = @_;
                   13297:     if (($mimetype eq 'application/octet-stream') ||
                   13298:         ($mimetype eq 'application/x-stuffit') ||
                   13299:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13300:         return 1;
                   13301:     }
                   13302:     return;
                   13303: }
                   13304: 
                   13305: sub decompress_form {
1.1065    raeburn  13306:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13307:     my %lt = &Apache::lonlocal::texthash (
                   13308:         this => 'This file is an archive file.',
1.1067    raeburn  13309:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13310:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13311:         youm => 'You may wish to extract its contents.',
                   13312:         extr => 'Extract contents',
1.1067    raeburn  13313:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13314:         proa => 'Process automatically?',
1.1053    raeburn  13315:         yes  => 'Yes',
                   13316:         no   => 'No',
1.1067    raeburn  13317:         fold => 'Title for folder containing movie',
                   13318:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13319:     );
1.1065    raeburn  13320:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13321:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13322:     my $info = &list_archive_contents($fileloc,\@paths);
                   13323:     if (@paths) {
                   13324:         foreach my $path (@paths) {
                   13325:             $path =~ s{^/}{};
1.1067    raeburn  13326:             if ($path =~ m{^([^/]+)/$}) {
                   13327:                 $topdir = $1;
                   13328:             }
1.1065    raeburn  13329:             if ($path =~ m{^([^/]+)/}) {
                   13330:                 $toplevel{$1} = $path;
                   13331:             } else {
                   13332:                 $toplevel{$path} = $path;
                   13333:             }
                   13334:         }
                   13335:     }
1.1067    raeburn  13336:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13337:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13338:                         "$topdir/media/",
                   13339:                         "$topdir/media/$topdir.mp4",
                   13340:                         "$topdir/media/FirstFrame.png",
                   13341:                         "$topdir/media/player.swf",
                   13342:                         "$topdir/media/swfobject.js",
                   13343:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13344:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13345:                          "$topdir/$topdir.mp4",
                   13346:                          "$topdir/$topdir\_config.xml",
                   13347:                          "$topdir/$topdir\_controller.swf",
                   13348:                          "$topdir/$topdir\_embed.css",
                   13349:                          "$topdir/$topdir\_First_Frame.png",
                   13350:                          "$topdir/$topdir\_player.html",
                   13351:                          "$topdir/$topdir\_Thumbnails.png",
                   13352:                          "$topdir/playerProductInstall.swf",
                   13353:                          "$topdir/scripts/",
                   13354:                          "$topdir/scripts/config_xml.js",
                   13355:                          "$topdir/scripts/handlebars.js",
                   13356:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13357:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13358:                          "$topdir/scripts/modernizr.js",
                   13359:                          "$topdir/scripts/player-min.js",
                   13360:                          "$topdir/scripts/swfobject.js",
                   13361:                          "$topdir/skins/",
                   13362:                          "$topdir/skins/configuration_express.xml",
                   13363:                          "$topdir/skins/express_show/",
                   13364:                          "$topdir/skins/express_show/player-min.css",
                   13365:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13366:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13367:                          "$topdir/$topdir.mp4",
                   13368:                          "$topdir/$topdir\_config.xml",
                   13369:                          "$topdir/$topdir\_controller.swf",
                   13370:                          "$topdir/$topdir\_embed.css",
                   13371:                          "$topdir/$topdir\_First_Frame.png",
                   13372:                          "$topdir/$topdir\_player.html",
                   13373:                          "$topdir/$topdir\_Thumbnails.png",
                   13374:                          "$topdir/playerProductInstall.swf",
                   13375:                          "$topdir/scripts/",
                   13376:                          "$topdir/scripts/config_xml.js",
                   13377:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13378:                          "$topdir/skins/",
                   13379:                          "$topdir/skins/configuration_express.xml",
                   13380:                          "$topdir/skins/express_show/",
                   13381:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13382:                          "$topdir/skins/express_show/spritesheet.png",
                   13383:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13384:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13385:         if (@diffs == 0) {
1.1164    raeburn  13386:             $is_camtasia = 6;
                   13387:         } else {
1.1197    raeburn  13388:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13389:             if (@diffs == 0) {
                   13390:                 $is_camtasia = 8;
1.1197    raeburn  13391:             } else {
                   13392:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13393:                 if (@diffs == 0) {
                   13394:                     $is_camtasia = 8;
                   13395:                 }
1.1164    raeburn  13396:             }
1.1067    raeburn  13397:         }
                   13398:     }
                   13399:     my $output;
                   13400:     if ($is_camtasia) {
                   13401:         $output = <<"ENDCAM";
                   13402: <script type="text/javascript" language="Javascript">
                   13403: // <![CDATA[
                   13404: 
                   13405: function camtasiaToggle() {
                   13406:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13407:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13408:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13409:                 document.getElementById('camtasia_titles').style.display='block';
                   13410:             } else {
                   13411:                 document.getElementById('camtasia_titles').style.display='none';
                   13412:             }
                   13413:         }
                   13414:     }
                   13415:     return;
                   13416: }
                   13417: 
                   13418: // ]]>
                   13419: </script>
                   13420: <p>$lt{'camt'}</p>
                   13421: ENDCAM
1.1065    raeburn  13422:     } else {
1.1067    raeburn  13423:         $output = '<p>'.$lt{'this'};
                   13424:         if ($info eq '') {
                   13425:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13426:         } else {
                   13427:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13428:                        '<div><pre>'.$info.'</pre></div>';
                   13429:         }
1.1065    raeburn  13430:     }
1.1067    raeburn  13431:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13432:     my $duplicates;
                   13433:     my $num = 0;
                   13434:     if (ref($dirlist) eq 'ARRAY') {
                   13435:         foreach my $item (@{$dirlist}) {
                   13436:             if (ref($item) eq 'ARRAY') {
                   13437:                 if (exists($toplevel{$item->[0]})) {
                   13438:                     $duplicates .= 
                   13439:                         &start_data_table_row().
                   13440:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13441:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13442:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13443:                         'value="1" />'.&mt('Yes').'</label>'.
                   13444:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13445:                         '<td>'.$item->[0].'</td>';
                   13446:                     if ($item->[2]) {
                   13447:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13448:                     } else {
                   13449:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13450:                     }
                   13451:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13452:                                    '<td>'.
                   13453:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13454:                                    '</td>'.
                   13455:                                    &end_data_table_row();
                   13456:                     $num ++;
                   13457:                 }
                   13458:             }
                   13459:         }
                   13460:     }
                   13461:     my $itemcount;
                   13462:     if (@paths > 0) {
                   13463:         $itemcount = scalar(@paths);
                   13464:     } else {
                   13465:         $itemcount = 1;
                   13466:     }
1.1067    raeburn  13467:     if ($is_camtasia) {
                   13468:         $output .= $lt{'auto'}.'<br />'.
                   13469:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13470:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13471:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13472:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13473:                    $lt{'no'}.'</label></span><br />'.
                   13474:                    '<div id="camtasia_titles" style="display:block">'.
                   13475:                    &Apache::lonhtmlcommon::start_pick_box().
                   13476:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13477:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13478:                    &Apache::lonhtmlcommon::row_closure().
                   13479:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13480:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13481:                    &Apache::lonhtmlcommon::row_closure(1).
                   13482:                    &Apache::lonhtmlcommon::end_pick_box().
                   13483:                    '</div>';
                   13484:     }
1.1065    raeburn  13485:     $output .= 
                   13486:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13487:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13488:         "\n";
1.1065    raeburn  13489:     if ($duplicates ne '') {
                   13490:         $output .= '<p><span class="LC_warning">'.
                   13491:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13492:                    &start_data_table().
                   13493:                    &start_data_table_header_row().
                   13494:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13495:                    '<th>'.&mt('Name').'</th>'.
                   13496:                    '<th>'.&mt('Type').'</th>'.
                   13497:                    '<th>'.&mt('Size').'</th>'.
                   13498:                    '<th>'.&mt('Last modified').'</th>'.
                   13499:                    &end_data_table_header_row().
                   13500:                    $duplicates.
                   13501:                    &end_data_table().
                   13502:                    '</p>';
                   13503:     }
1.1067    raeburn  13504:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13505:     if (ref($hiddenelements) eq 'HASH') {
                   13506:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13507:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13508:         }
                   13509:     }
                   13510:     $output .= <<"END";
1.1067    raeburn  13511: <br />
1.1053    raeburn  13512: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13513: </form>
                   13514: $noextract
                   13515: END
                   13516:     return $output;
                   13517: }
                   13518: 
1.1065    raeburn  13519: sub decompression_utility {
                   13520:     my ($program) = @_;
                   13521:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13522:     my $location;
                   13523:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13524:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13525:                          '/usr/sbin/') {
                   13526:             if (-x $dir.$program) {
                   13527:                 $location = $dir.$program;
                   13528:                 last;
                   13529:             }
                   13530:         }
                   13531:     }
                   13532:     return $location;
                   13533: }
                   13534: 
                   13535: sub list_archive_contents {
                   13536:     my ($file,$pathsref) = @_;
                   13537:     my (@cmd,$output);
                   13538:     my $needsregexp;
                   13539:     if ($file =~ /\.zip$/) {
                   13540:         @cmd = (&decompression_utility('unzip'),"-l");
                   13541:         $needsregexp = 1;
                   13542:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13543:              ($file =~ /\.tgz$/)) {
                   13544:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13545:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13546:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13547:     } elsif ($file =~ m|\.tar$|) {
                   13548:         @cmd = (&decompression_utility('tar'),"-tf");
                   13549:     }
                   13550:     if (@cmd) {
                   13551:         undef($!);
                   13552:         undef($@);
                   13553:         if (open(my $fh,"-|", @cmd, $file)) {
                   13554:             while (my $line = <$fh>) {
                   13555:                 $output .= $line;
                   13556:                 chomp($line);
                   13557:                 my $item;
                   13558:                 if ($needsregexp) {
                   13559:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13560:                 } else {
                   13561:                     $item = $line;
                   13562:                 }
                   13563:                 if ($item ne '') {
                   13564:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13565:                         push(@{$pathsref},$item);
                   13566:                     } 
                   13567:                 }
                   13568:             }
                   13569:             close($fh);
                   13570:         }
                   13571:     }
                   13572:     return $output;
                   13573: }
                   13574: 
1.1053    raeburn  13575: sub decompress_uploaded_file {
                   13576:     my ($file,$dir) = @_;
                   13577:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13578:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13579:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13580:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13581:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13582:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13583:     my $decompressed = $env{'cgi.decompressed'};
                   13584:     &Apache::lonnet::delenv('cgi.file');
                   13585:     &Apache::lonnet::delenv('cgi.dir');
                   13586:     &Apache::lonnet::delenv('cgi.decompressed');
                   13587:     return ($decompressed,$result);
                   13588: }
                   13589: 
1.1055    raeburn  13590: sub process_decompression {
                   13591:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13592:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13593:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13594:                &mt('Unexpected file path.').'</p>'."\n";
                   13595:     }
                   13596:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13597:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13598:                &mt('Unexpected course context.').'</p>'."\n";
                   13599:     }
1.1293    raeburn  13600:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13601:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13602:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13603:     }
1.1055    raeburn  13604:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13605:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13606:         $error = &mt('Filename not a supported archive file type.').
                   13607:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13608:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13609:     } else {
                   13610:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13611:         if ($docuhome eq 'no_host') {
                   13612:             $error = &mt('Could not determine home server for course.');
                   13613:         } else {
                   13614:             my @ids=&Apache::lonnet::current_machine_ids();
                   13615:             my $currdir = "$dir_root/$destination";
                   13616:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13617:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13618:                        "$dir_root/$destination";
                   13619:             } else {
                   13620:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13621:                        "$dir_root/$docudom/$docuname/$destination";
                   13622:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13623:                     $error = &mt('Archive file not found.');
                   13624:                 }
                   13625:             }
1.1065    raeburn  13626:             my (@to_overwrite,@to_skip);
                   13627:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13628:                 my $total = $env{'form.archive_overwrite_total'};
                   13629:                 for (my $i=0; $i<$total; $i++) {
                   13630:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13631:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13632:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13633:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13634:                     }
                   13635:                 }
                   13636:             }
                   13637:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13638:             my $numoverwrite = scalar(@to_overwrite);
                   13639:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13640:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13641:             } elsif ($dir eq '') {
1.1055    raeburn  13642:                 $error = &mt('Directory containing archive file unavailable.');
                   13643:             } elsif (!$error) {
1.1065    raeburn  13644:                 my ($decompressed,$display);
1.1292    raeburn  13645:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13646:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13647:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13648:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13649:                         ($decompressed,$display) = 
                   13650:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13651:                         foreach my $item (@to_skip) {
                   13652:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13653:                                 if (-f "$dir/$tempdir/$item") { 
                   13654:                                     unlink("$dir/$tempdir/$item");
                   13655:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13656:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13657:                                 }
                   13658:                             }
                   13659:                         }
                   13660:                         foreach my $item (@to_overwrite) {
                   13661:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13662:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13663:                                     if (-f "$dir/$item") {
                   13664:                                         unlink("$dir/$item");
                   13665:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13666:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13667:                                     }
                   13668:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13669:                                 }
1.1065    raeburn  13670:                             }
                   13671:                         }
1.1292    raeburn  13672:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13673:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13674:                         }
1.1065    raeburn  13675:                     }
                   13676:                 } else {
                   13677:                     ($decompressed,$display) = 
                   13678:                         &decompress_uploaded_file($file,$dir);
                   13679:                 }
1.1055    raeburn  13680:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13681:                     $output = '<p class="LC_info">'.
                   13682:                               &mt('Files extracted successfully from archive.').
                   13683:                               '</p>'."\n";
1.1055    raeburn  13684:                     my ($warning,$result,@contents);
                   13685:                     my ($newdirlistref,$newlisterror) =
                   13686:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13687:                                                  $docuname,1);
                   13688:                     my (%is_dir,%changes,@newitems);
                   13689:                     my $dirptr = 16384;
1.1065    raeburn  13690:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13691:                         foreach my $dir_line (@{$newdirlistref}) {
                   13692:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13693:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13694:                                 push(@newitems,$item);
                   13695:                                 if ($dirptr&$testdir) {
                   13696:                                     $is_dir{$item} = 1;
                   13697:                                 }
                   13698:                                 $changes{$item} = 1;
                   13699:                             }
                   13700:                         }
                   13701:                     }
                   13702:                     if (keys(%changes) > 0) {
                   13703:                         foreach my $item (sort(@newitems)) {
                   13704:                             if ($changes{$item}) {
                   13705:                                 push(@contents,$item);
                   13706:                             }
                   13707:                         }
                   13708:                     }
                   13709:                     if (@contents > 0) {
1.1067    raeburn  13710:                         my $wantform;
                   13711:                         unless ($env{'form.autoextract_camtasia'}) {
                   13712:                             $wantform = 1;
                   13713:                         }
1.1056    raeburn  13714:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13715:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13716:                                                                 $currdir,\%is_dir,
                   13717:                                                                 \%children,\%parent,
1.1056    raeburn  13718:                                                                 \@contents,\%dirorder,
                   13719:                                                                 \%titles,$wantform);
1.1055    raeburn  13720:                         if ($datatable ne '') {
                   13721:                             $output .= &archive_options_form('decompressed',$datatable,
                   13722:                                                              $count,$hiddenelem);
1.1065    raeburn  13723:                             my $startcount = 6;
1.1055    raeburn  13724:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13725:                                                            \%titles,\%children);
1.1055    raeburn  13726:                         }
1.1067    raeburn  13727:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13728:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13729:                             my %displayed;
                   13730:                             my $total = 1;
                   13731:                             $env{'form.archive_directory'} = [];
                   13732:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13733:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13734:                                 $path =~ s{/$}{};
                   13735:                                 my $item;
                   13736:                                 if ($path ne '') {
                   13737:                                     $item = "$path/$titles{$i}";
                   13738:                                 } else {
                   13739:                                     $item = $titles{$i};
                   13740:                                 }
                   13741:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13742:                                 if ($item eq $contents[0]) {
                   13743:                                     push(@{$env{'form.archive_directory'}},$i);
                   13744:                                     $env{'form.archive_'.$i} = 'display';
                   13745:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13746:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13747:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13748:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13749:                                     $env{'form.archive_'.$i} = 'display';
                   13750:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13751:                                     $displayed{'web'} = $i;
                   13752:                                 } else {
1.1164    raeburn  13753:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13754:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13755:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13756:                                         push(@{$env{'form.archive_directory'}},$i);
                   13757:                                     }
                   13758:                                     $env{'form.archive_'.$i} = 'dependency';
                   13759:                                 }
                   13760:                                 $total ++;
                   13761:                             }
                   13762:                             for (my $i=1; $i<$total; $i++) {
                   13763:                                 next if ($i == $displayed{'web'});
                   13764:                                 next if ($i == $displayed{'folder'});
                   13765:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13766:                             }
                   13767:                             $env{'form.phase'} = 'decompress_cleanup';
                   13768:                             $env{'form.archivedelete'} = 1;
                   13769:                             $env{'form.archive_count'} = $total-1;
                   13770:                             $output .=
                   13771:                                 &process_extracted_files('coursedocs',$docudom,
                   13772:                                                          $docuname,$destination,
                   13773:                                                          $dir_root,$hiddenelem);
                   13774:                         }
1.1055    raeburn  13775:                     } else {
                   13776:                         $warning = &mt('No new items extracted from archive file.');
                   13777:                     }
                   13778:                 } else {
                   13779:                     $output = $display;
                   13780:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13781:                 }
                   13782:             }
                   13783:         }
                   13784:     }
                   13785:     if ($error) {
                   13786:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13787:                    $error.'</p>'."\n";
                   13788:     }
                   13789:     if ($warning) {
                   13790:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13791:     }
                   13792:     return $output;
                   13793: }
                   13794: 
                   13795: sub get_extracted {
1.1056    raeburn  13796:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13797:         $titles,$wantform) = @_;
1.1055    raeburn  13798:     my $count = 0;
                   13799:     my $depth = 0;
                   13800:     my $datatable;
1.1056    raeburn  13801:     my @hierarchy;
1.1055    raeburn  13802:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13803:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13804:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13805:     foreach my $item (@{$contents}) {
                   13806:         $count ++;
1.1056    raeburn  13807:         @{$dirorder->{$count}} = @hierarchy;
                   13808:         $titles->{$count} = $item;
1.1055    raeburn  13809:         &archive_hierarchy($depth,$count,$parent,$children);
                   13810:         if ($wantform) {
                   13811:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13812:                                        $currdir,$depth,$count);
                   13813:         }
                   13814:         if ($is_dir->{$item}) {
                   13815:             $depth ++;
1.1056    raeburn  13816:             push(@hierarchy,$count);
                   13817:             $parent->{$depth} = $count;
1.1055    raeburn  13818:             $datatable .=
                   13819:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13820:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13821:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13822:             $depth --;
1.1056    raeburn  13823:             pop(@hierarchy);
1.1055    raeburn  13824:         }
                   13825:     }
                   13826:     return ($count,$datatable);
                   13827: }
                   13828: 
                   13829: sub recurse_extracted_archive {
1.1056    raeburn  13830:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13831:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13832:     my $result='';
1.1056    raeburn  13833:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13834:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13835:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13836:         return $result;
                   13837:     }
                   13838:     my $dirptr = 16384;
                   13839:     my ($newdirlistref,$newlisterror) =
                   13840:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13841:     if (ref($newdirlistref) eq 'ARRAY') {
                   13842:         foreach my $dir_line (@{$newdirlistref}) {
                   13843:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13844:             unless ($item =~ /^\.+$/) {
                   13845:                 $$count ++;
1.1056    raeburn  13846:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13847:                 $titles->{$$count} = $item;
1.1055    raeburn  13848:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13849: 
1.1055    raeburn  13850:                 my $is_dir;
                   13851:                 if ($dirptr&$testdir) {
                   13852:                     $is_dir = 1;
                   13853:                 }
                   13854:                 if ($wantform) {
                   13855:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13856:                 }
                   13857:                 if ($is_dir) {
                   13858:                     $$depth ++;
1.1056    raeburn  13859:                     push(@{$hierarchy},$$count);
                   13860:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13861:                     $result .=
                   13862:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13863:                                                    $docuname,$depth,$count,
1.1056    raeburn  13864:                                                    $hierarchy,$dirorder,$children,
                   13865:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13866:                     $$depth --;
1.1056    raeburn  13867:                     pop(@{$hierarchy});
1.1055    raeburn  13868:                 }
                   13869:             }
                   13870:         }
                   13871:     }
                   13872:     return $result;
                   13873: }
                   13874: 
                   13875: sub archive_hierarchy {
                   13876:     my ($depth,$count,$parent,$children) =@_;
                   13877:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13878:         if (exists($parent->{$depth})) {
                   13879:              $children->{$parent->{$depth}} .= $count.':';
                   13880:         }
                   13881:     }
                   13882:     return;
                   13883: }
                   13884: 
                   13885: sub archive_row {
                   13886:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13887:     my ($name) = ($item =~ m{([^/]+)$});
                   13888:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13889:                                        'display'    => 'Add as file',
1.1055    raeburn  13890:                                        'dependency' => 'Include as dependency',
                   13891:                                        'discard'    => 'Discard',
                   13892:                                       );
                   13893:     if ($is_dir) {
1.1059    raeburn  13894:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13895:     }
1.1056    raeburn  13896:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13897:     my $offset = 0;
1.1055    raeburn  13898:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13899:         $offset ++;
1.1065    raeburn  13900:         if ($action ne 'display') {
                   13901:             $offset ++;
                   13902:         }  
1.1055    raeburn  13903:         $output .= '<td><span class="LC_nobreak">'.
                   13904:                    '<label><input type="radio" name="archive_'.$count.
                   13905:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13906:         my $text = $choices{$action};
                   13907:         if ($is_dir) {
                   13908:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13909:             if ($action eq 'display') {
1.1059    raeburn  13910:                 $text = &mt('Add as folder');
1.1055    raeburn  13911:             }
1.1056    raeburn  13912:         } else {
                   13913:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13914: 
                   13915:         }
                   13916:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13917:         if ($action eq 'dependency') {
                   13918:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13919:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13920:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13921:                        '<option value=""></option>'."\n".
                   13922:                        '</select>'."\n".
                   13923:                        '</div>';
1.1059    raeburn  13924:         } elsif ($action eq 'display') {
                   13925:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13926:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13927:                        '</div>';
1.1055    raeburn  13928:         }
1.1056    raeburn  13929:         $output .= '</td>';
1.1055    raeburn  13930:     }
                   13931:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13932:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13933:     for (my $i=0; $i<$depth; $i++) {
                   13934:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13935:     }
                   13936:     if ($is_dir) {
                   13937:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13938:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13939:     } else {
                   13940:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13941:     }
                   13942:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13943:                &end_data_table_row();
                   13944:     return $output;
                   13945: }
                   13946: 
                   13947: sub archive_options_form {
1.1065    raeburn  13948:     my ($form,$display,$count,$hiddenelem) = @_;
                   13949:     my %lt = &Apache::lonlocal::texthash(
                   13950:                perm => 'Permanently remove archive file?',
                   13951:                hows => 'How should each extracted item be incorporated in the course?',
                   13952:                cont => 'Content actions for all',
                   13953:                addf => 'Add as folder/file',
                   13954:                incd => 'Include as dependency for a displayed file',
                   13955:                disc => 'Discard',
                   13956:                no   => 'No',
                   13957:                yes  => 'Yes',
                   13958:                save => 'Save',
                   13959:     );
                   13960:     my $output = <<"END";
                   13961: <form name="$form" method="post" action="">
                   13962: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13963: <label>
                   13964:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13965: </label>
                   13966: &nbsp;
                   13967: <label>
                   13968:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13969: </span>
                   13970: </p>
                   13971: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13972: <br />$lt{'hows'}
                   13973: <div class="LC_columnSection">
                   13974:   <fieldset>
                   13975:     <legend>$lt{'cont'}</legend>
                   13976:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13977:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13978:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13979:   </fieldset>
                   13980: </div>
                   13981: END
                   13982:     return $output.
1.1055    raeburn  13983:            &start_data_table()."\n".
1.1065    raeburn  13984:            $display."\n".
1.1055    raeburn  13985:            &end_data_table()."\n".
                   13986:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13987:            $hiddenelem.
1.1065    raeburn  13988:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13989:            '</form>';
                   13990: }
                   13991: 
                   13992: sub archive_javascript {
1.1056    raeburn  13993:     my ($startcount,$numitems,$titles,$children) = @_;
                   13994:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13995:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13996:     my $scripttag = <<START;
                   13997: <script type="text/javascript">
                   13998: // <![CDATA[
                   13999: 
                   14000: function checkAll(form,prefix) {
                   14001:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14002:     for (var i=0; i < form.elements.length; i++) {
                   14003:         var id = form.elements[i].id;
                   14004:         if ((id != '') && (id != undefined)) {
                   14005:             if (idstr.test(id)) {
                   14006:                 if (form.elements[i].type == 'radio') {
                   14007:                     form.elements[i].checked = true;
1.1056    raeburn  14008:                     var nostart = i-$startcount;
1.1059    raeburn  14009:                     var offset = nostart%7;
                   14010:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14011:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14012:                 }
                   14013:             }
                   14014:         }
                   14015:     }
                   14016: }
                   14017: 
                   14018: function propagateCheck(form,count) {
                   14019:     if (count > 0) {
1.1059    raeburn  14020:         var startelement = $startcount + ((count-1) * 7);
                   14021:         for (var j=1; j<6; j++) {
                   14022:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14023:                 var item = startelement + j; 
                   14024:                 if (form.elements[item].type == 'radio') {
                   14025:                     if (form.elements[item].checked) {
                   14026:                         containerCheck(form,count,j);
                   14027:                         break;
                   14028:                     }
1.1055    raeburn  14029:                 }
                   14030:             }
                   14031:         }
                   14032:     }
                   14033: }
                   14034: 
                   14035: numitems = $numitems
1.1056    raeburn  14036: var titles = new Array(numitems);
                   14037: var parents = new Array(numitems);
1.1055    raeburn  14038: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14039:     parents[i] = new Array;
1.1055    raeburn  14040: }
1.1059    raeburn  14041: var maintitle = '$maintitle';
1.1055    raeburn  14042: 
                   14043: START
                   14044: 
1.1056    raeburn  14045:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14046:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14047:         for (my $i=0; $i<@contents; $i ++) {
                   14048:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14049:         }
                   14050:     }
                   14051: 
1.1056    raeburn  14052:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14053:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14054:     }
                   14055: 
1.1055    raeburn  14056:     $scripttag .= <<END;
                   14057: 
                   14058: function containerCheck(form,count,offset) {
                   14059:     if (count > 0) {
1.1056    raeburn  14060:         dependencyCheck(form,count,offset);
1.1059    raeburn  14061:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14062:         form.elements[item].checked = true;
                   14063:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14064:             if (parents[count].length > 0) {
                   14065:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14066:                     containerCheck(form,parents[count][j],offset);
                   14067:                 }
                   14068:             }
                   14069:         }
                   14070:     }
                   14071: }
                   14072: 
                   14073: function dependencyCheck(form,count,offset) {
                   14074:     if (count > 0) {
1.1059    raeburn  14075:         var chosen = (offset+$startcount)+7*(count-1);
                   14076:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14077:         var currtype = form.elements[depitem].type;
                   14078:         if (form.elements[chosen].value == 'dependency') {
                   14079:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14080:             form.elements[depitem].options.length = 0;
                   14081:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14082:             for (var i=1; i<=numitems; i++) {
                   14083:                 if (i == count) {
                   14084:                     continue;
                   14085:                 }
1.1059    raeburn  14086:                 var startelement = $startcount + (i-1) * 7;
                   14087:                 for (var j=1; j<6; j++) {
                   14088:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14089:                         var item = startelement + j;
                   14090:                         if (form.elements[item].type == 'radio') {
                   14091:                             if (form.elements[item].checked) {
                   14092:                                 if (form.elements[item].value == 'display') {
                   14093:                                     var n = form.elements[depitem].options.length;
                   14094:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14095:                                 }
                   14096:                             }
                   14097:                         }
                   14098:                     }
                   14099:                 }
                   14100:             }
                   14101:         } else {
                   14102:             document.getElementById('arc_depon_'+count).style.display='none';
                   14103:             form.elements[depitem].options.length = 0;
                   14104:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14105:         }
1.1059    raeburn  14106:         titleCheck(form,count,offset);
1.1056    raeburn  14107:     }
                   14108: }
                   14109: 
                   14110: function propagateSelect(form,count,offset) {
                   14111:     if (count > 0) {
1.1065    raeburn  14112:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14113:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14114:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14115:             if (parents[count].length > 0) {
                   14116:                 for (var j=0; j<parents[count].length; j++) {
                   14117:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14118:                 }
                   14119:             }
                   14120:         }
                   14121:     }
                   14122: }
1.1056    raeburn  14123: 
                   14124: function containerSelect(form,count,offset,picked) {
                   14125:     if (count > 0) {
1.1065    raeburn  14126:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14127:         if (form.elements[item].type == 'radio') {
                   14128:             if (form.elements[item].value == 'dependency') {
                   14129:                 if (form.elements[item+1].type == 'select-one') {
                   14130:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14131:                         if (form.elements[item+1].options[i].value == picked) {
                   14132:                             form.elements[item+1].selectedIndex = i;
                   14133:                             break;
                   14134:                         }
                   14135:                     }
                   14136:                 }
                   14137:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14138:                     if (parents[count].length > 0) {
                   14139:                         for (var j=0; j<parents[count].length; j++) {
                   14140:                             containerSelect(form,parents[count][j],offset,picked);
                   14141:                         }
                   14142:                     }
                   14143:                 }
                   14144:             }
                   14145:         }
                   14146:     }
                   14147: }
                   14148: 
1.1059    raeburn  14149: function titleCheck(form,count,offset) {
                   14150:     if (count > 0) {
                   14151:         var chosen = (offset+$startcount)+7*(count-1);
                   14152:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14153:         var currtype = form.elements[depitem].type;
                   14154:         if (form.elements[chosen].value == 'display') {
                   14155:             document.getElementById('arc_title_'+count).style.display='block';
                   14156:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14157:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14158:             }
                   14159:         } else {
                   14160:             document.getElementById('arc_title_'+count).style.display='none';
                   14161:             if (currtype == 'text') { 
                   14162:                 document.getElementById('archive_title_'+count).value='';
                   14163:             }
                   14164:         }
                   14165:     }
                   14166:     return;
                   14167: }
                   14168: 
1.1055    raeburn  14169: // ]]>
                   14170: </script>
                   14171: END
                   14172:     return $scripttag;
                   14173: }
                   14174: 
                   14175: sub process_extracted_files {
1.1067    raeburn  14176:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14177:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14178:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14179:     my @ids=&Apache::lonnet::current_machine_ids();
                   14180:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14181:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14182:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14183:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14184:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14185:         $pathtocheck = "$dir_root/$destination";
                   14186:         $dir = $dir_root;
                   14187:         $ishome = 1;
                   14188:     } else {
                   14189:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14190:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14191:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14192:     }
                   14193:     my $currdir = "$dir_root/$destination";
                   14194:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14195:     if ($env{'form.folderpath'}) {
                   14196:         my @items = split('&',$env{'form.folderpath'});
                   14197:         $folders{'0'} = $items[-2];
1.1099    raeburn  14198:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14199:             $containers{'0'}='page';
                   14200:         } else {  
                   14201:             $containers{'0'}='sequence';
                   14202:         }
1.1055    raeburn  14203:     }
                   14204:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14205:     if ($numitems) {
                   14206:         for (my $i=1; $i<=$numitems; $i++) {
                   14207:             my $path = $env{'form.archive_content_'.$i};
                   14208:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14209:                 my $item = $1;
                   14210:                 $toplevelitems{$item} = $i;
                   14211:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14212:                     $is_dir{$item} = 1;
                   14213:                 }
                   14214:             }
                   14215:         }
                   14216:     }
1.1067    raeburn  14217:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14218:     if (keys(%toplevelitems) > 0) {
                   14219:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14220:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14221:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14222:     }
1.1066    raeburn  14223:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14224:     if ($numitems) {
                   14225:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14226:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14227:             my $path = $env{'form.archive_content_'.$i};
                   14228:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14229:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14230:                     if ($prefix ne '' && $path ne '') {
                   14231:                         if (-e $prefix.$path) {
1.1066    raeburn  14232:                             if ((@archdirs > 0) && 
                   14233:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14234:                                 $todeletedir{$prefix.$path} = 1;
                   14235:                             } else {
                   14236:                                 $todelete{$prefix.$path} = 1;
                   14237:                             }
1.1055    raeburn  14238:                         }
                   14239:                     }
                   14240:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14241:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14242:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14243:                     $docstitle = $env{'form.archive_title_'.$i};
                   14244:                     if ($docstitle eq '') {
                   14245:                         $docstitle = $title;
                   14246:                     }
1.1055    raeburn  14247:                     $outer = 0;
1.1056    raeburn  14248:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14249:                         if (@{$dirorder{$i}} > 0) {
                   14250:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14251:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14252:                                     $outer = $item;
                   14253:                                     last;
                   14254:                                 }
                   14255:                             }
                   14256:                         }
                   14257:                     }
                   14258:                     my ($errtext,$fatal) = 
                   14259:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14260:                                                '/'.$folders{$outer}.'.'.
                   14261:                                                $containers{$outer});
                   14262:                     next if ($fatal);
                   14263:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14264:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14265:                             $mapinner{$i} = time;
1.1055    raeburn  14266:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14267:                             $containers{$i} = 'sequence';
                   14268:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14269:                                       $folders{$i}.'.'.$containers{$i};
                   14270:                             my $newidx = &LONCAPA::map::getresidx();
                   14271:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14272:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14273:                             push(@LONCAPA::map::order,$newidx);
                   14274:                             my ($outtext,$errtext) =
                   14275:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14276:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14277:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14278:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14279:                             unless ($errtext) {
1.1294    raeburn  14280:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14281:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14282:                                             '</li>'."\n";
1.1067    raeburn  14283:                             }
1.1055    raeburn  14284:                         }
                   14285:                     } else {
                   14286:                         if ($context eq 'coursedocs') {
                   14287:                             my $newidx=&LONCAPA::map::getresidx();
                   14288:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14289:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14290:                                       $title;
1.1392    raeburn  14291:                             if (($outer !~ /\D/) &&
                   14292:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14293:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14294:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14295:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14296:                                 }
                   14297:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14298:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14299:                                 }
                   14300:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14301:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14302:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14303:                                         unless ($ishome) {
                   14304:                                             my $fetch = "$newdest{$i}/$title";
                   14305:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14306:                                             $prompttofetch{$fetch} = 1;
                   14307:                                         }
1.1292    raeburn  14308:                                     }
1.1067    raeburn  14309:                                 }
1.1294    raeburn  14310:                                 $LONCAPA::map::resources[$newidx]=
                   14311:                                     $docstitle.':'.$url.':false:normal:res';
                   14312:                                 push(@LONCAPA::map::order, $newidx);
                   14313:                                 my ($outtext,$errtext)=
                   14314:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14315:                                                             $docuname.'/'.$folders{$outer}.
                   14316:                                                             '.'.$containers{$outer},1,1);
                   14317:                                 unless ($errtext) {
                   14318:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14319:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14320:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14321:                                                    '</li>'."\n";
                   14322:                                     }
1.1067    raeburn  14323:                                 }
1.1294    raeburn  14324:                             } else {
                   14325:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14326:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14327:                             }
1.1055    raeburn  14328:                         }
                   14329:                     }
1.1086    raeburn  14330:                 }
                   14331:             } else {
1.1294    raeburn  14332:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14333:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14334:             }
                   14335:         }
                   14336:         for (my $i=1; $i<=$numitems; $i++) {
                   14337:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14338:             my $path = $env{'form.archive_content_'.$i};
                   14339:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14340:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14341:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14342:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14343:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14344:                         my ($itemidx,$fullpath,$relpath);
                   14345:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14346:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14347:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14348:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14349:                                     $itemidx = $j;
1.1056    raeburn  14350:                                 }
                   14351:                             }
1.1086    raeburn  14352:                         }
                   14353:                         if ($itemidx eq '') {
                   14354:                             $itemidx =  0;
                   14355:                         } 
                   14356:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14357:                             if ($mapinner{$referrer{$i}}) {
                   14358:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14359:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14360:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14361:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14362:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14363:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14364:                                             if (!-e $fullpath) {
                   14365:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14366:                                             }
                   14367:                                         }
1.1086    raeburn  14368:                                     } else {
                   14369:                                         last;
1.1056    raeburn  14370:                                     }
1.1086    raeburn  14371:                                 }
                   14372:                             }
                   14373:                         } elsif ($newdest{$referrer{$i}}) {
                   14374:                             $fullpath = $newdest{$referrer{$i}};
                   14375:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14376:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14377:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14378:                                     last;
                   14379:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14380:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14381:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14382:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14383:                                         if (!-e $fullpath) {
                   14384:                                             mkdir($fullpath,0755);
1.1056    raeburn  14385:                                         }
                   14386:                                     }
1.1086    raeburn  14387:                                 } else {
                   14388:                                     last;
1.1056    raeburn  14389:                                 }
1.1055    raeburn  14390:                             }
                   14391:                         }
1.1086    raeburn  14392:                         if ($fullpath ne '') {
                   14393:                             if (-e "$prefix$path") {
1.1292    raeburn  14394:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14395:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14396:                                 }
1.1086    raeburn  14397:                             }
                   14398:                             if (-e "$fullpath/$title") {
                   14399:                                 my $showpath;
                   14400:                                 if ($relpath ne '') {
                   14401:                                     $showpath = "$relpath/$title";
                   14402:                                 } else {
                   14403:                                     $showpath = "/$title";
                   14404:                                 } 
1.1294    raeburn  14405:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14406:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14407:                                            '</li>'."\n";
1.1292    raeburn  14408:                                 unless ($ishome) {
                   14409:                                     my $fetch = "$fullpath/$title";
                   14410:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14411:                                     $prompttofetch{$fetch} = 1;
                   14412:                                 }
1.1086    raeburn  14413:                             }
                   14414:                         }
1.1055    raeburn  14415:                     }
1.1086    raeburn  14416:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14417:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14418:                                     &HTML::Entities::encode($path,'<>&"'),
                   14419:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14420:                                 '<br />';
1.1055    raeburn  14421:                 }
                   14422:             } else {
1.1294    raeburn  14423:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14424:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14425:             }
                   14426:         }
                   14427:         if (keys(%todelete)) {
                   14428:             foreach my $key (keys(%todelete)) {
                   14429:                 unlink($key);
1.1066    raeburn  14430:             }
                   14431:         }
                   14432:         if (keys(%todeletedir)) {
                   14433:             foreach my $key (keys(%todeletedir)) {
                   14434:                 rmdir($key);
                   14435:             }
                   14436:         }
                   14437:         foreach my $dir (sort(keys(%is_dir))) {
                   14438:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14439:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14440:             }
                   14441:         }
1.1067    raeburn  14442:         if ($result ne '') {
                   14443:             $output .= '<ul>'."\n".
                   14444:                        $result."\n".
                   14445:                        '</ul>';
                   14446:         }
                   14447:         unless ($ishome) {
                   14448:             my $replicationfail;
                   14449:             foreach my $item (keys(%prompttofetch)) {
                   14450:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14451:                 unless ($fetchresult eq 'ok') {
                   14452:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14453:                 }
                   14454:             }
                   14455:             if ($replicationfail) {
                   14456:                 $output .= '<p class="LC_error">'.
                   14457:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14458:                            $replicationfail.
                   14459:                            '</ul></p>';
                   14460:             }
                   14461:         }
1.1055    raeburn  14462:     } else {
                   14463:         $warning = &mt('No items found in archive.');
                   14464:     }
                   14465:     if ($error) {
                   14466:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14467:                    $error.'</p>'."\n";
                   14468:     }
                   14469:     if ($warning) {
                   14470:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14471:     }
                   14472:     return $output;
                   14473: }
                   14474: 
1.1066    raeburn  14475: sub cleanup_empty_dirs {
                   14476:     my ($path) = @_;
                   14477:     if (($path ne '') && (-d $path)) {
                   14478:         if (opendir(my $dirh,$path)) {
                   14479:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14480:             my $numitems = 0;
                   14481:             foreach my $item (@dircontents) {
                   14482:                 if (-d "$path/$item") {
1.1111    raeburn  14483:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14484:                     if (-e "$path/$item") {
                   14485:                         $numitems ++;
                   14486:                     }
                   14487:                 } else {
                   14488:                     $numitems ++;
                   14489:                 }
                   14490:             }
                   14491:             if ($numitems == 0) {
                   14492:                 rmdir($path);
                   14493:             }
                   14494:             closedir($dirh);
                   14495:         }
                   14496:     }
                   14497:     return;
                   14498: }
                   14499: 
1.41      ng       14500: =pod
1.45      matthew  14501: 
1.1162    raeburn  14502: =item * &get_folder_hierarchy()
1.1068    raeburn  14503: 
                   14504: Provides hierarchy of names of folders/sub-folders containing the current
                   14505: item,
                   14506: 
                   14507: Inputs: 3
                   14508:      - $navmap - navmaps object
                   14509: 
                   14510:      - $map - url for map (either the trigger itself, or map containing
                   14511:                            the resource, which is the trigger).
                   14512: 
                   14513:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14514: 
                   14515: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14516: 
                   14517: =cut
                   14518: 
                   14519: sub get_folder_hierarchy {
                   14520:     my ($navmap,$map,$showitem) = @_;
                   14521:     my @pathitems;
                   14522:     if (ref($navmap)) {
                   14523:         my $mapres = $navmap->getResourceByUrl($map);
                   14524:         if (ref($mapres)) {
                   14525:             my $pcslist = $mapres->map_hierarchy();
                   14526:             if ($pcslist ne '') {
                   14527:                 my @pcs = split(/,/,$pcslist);
                   14528:                 foreach my $pc (@pcs) {
                   14529:                     if ($pc == 1) {
1.1129    raeburn  14530:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14531:                     } else {
                   14532:                         my $res = $navmap->getByMapPc($pc);
                   14533:                         if (ref($res)) {
                   14534:                             my $title = $res->compTitle();
                   14535:                             $title =~ s/\W+/_/g;
                   14536:                             if ($title ne '') {
                   14537:                                 push(@pathitems,$title);
                   14538:                             }
                   14539:                         }
                   14540:                     }
                   14541:                 }
                   14542:             }
1.1071    raeburn  14543:             if ($showitem) {
                   14544:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14545:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14546:                 } else {
                   14547:                     my $maptitle = $mapres->compTitle();
                   14548:                     $maptitle =~ s/\W+/_/g;
                   14549:                     if ($maptitle ne '') {
                   14550:                         push(@pathitems,$maptitle);
                   14551:                     }
1.1068    raeburn  14552:                 }
                   14553:             }
                   14554:         }
                   14555:     }
                   14556:     return @pathitems;
                   14557: }
                   14558: 
                   14559: =pod
                   14560: 
1.1015    raeburn  14561: =item * &get_turnedin_filepath()
                   14562: 
                   14563: Determines path in a user's portfolio file for storage of files uploaded
                   14564: to a specific essayresponse or dropbox item.
                   14565: 
                   14566: Inputs: 3 required + 1 optional.
                   14567: $symb is symb for resource, $uname and $udom are for current user (required).
                   14568: $caller is optional (can be "submission", if routine is called when storing
                   14569: an upoaded file when "Submit Answer" button was pressed).
                   14570: 
                   14571: Returns array containing $path and $multiresp. 
                   14572: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14573: than one file upload item.  Callers of routine should append partid as a 
                   14574: subdirectory to $path in cases where $multiresp is 1.
                   14575: 
                   14576: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14577: 
                   14578: =cut
                   14579: 
                   14580: sub get_turnedin_filepath {
                   14581:     my ($symb,$uname,$udom,$caller) = @_;
                   14582:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14583:     my $turnindir;
                   14584:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14585:     $turnindir = $userhash{'turnindir'};
                   14586:     my ($path,$multiresp);
                   14587:     if ($turnindir eq '') {
                   14588:         if ($caller eq 'submission') {
                   14589:             $turnindir = &mt('turned in');
                   14590:             $turnindir =~ s/\W+/_/g;
                   14591:             my %newhash = (
                   14592:                             'turnindir' => $turnindir,
                   14593:                           );
                   14594:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14595:         }
                   14596:     }
                   14597:     if ($turnindir ne '') {
                   14598:         $path = '/'.$turnindir.'/';
                   14599:         my ($multipart,$turnin,@pathitems);
                   14600:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14601:         if (defined($navmap)) {
                   14602:             my $mapres = $navmap->getResourceByUrl($map);
                   14603:             if (ref($mapres)) {
                   14604:                 my $pcslist = $mapres->map_hierarchy();
                   14605:                 if ($pcslist ne '') {
                   14606:                     foreach my $pc (split(/,/,$pcslist)) {
                   14607:                         my $res = $navmap->getByMapPc($pc);
                   14608:                         if (ref($res)) {
                   14609:                             my $title = $res->compTitle();
                   14610:                             $title =~ s/\W+/_/g;
                   14611:                             if ($title ne '') {
1.1149    raeburn  14612:                                 if (($pc > 1) && (length($title) > 12)) {
                   14613:                                     $title = substr($title,0,12);
                   14614:                                 }
1.1015    raeburn  14615:                                 push(@pathitems,$title);
                   14616:                             }
                   14617:                         }
                   14618:                     }
                   14619:                 }
                   14620:                 my $maptitle = $mapres->compTitle();
                   14621:                 $maptitle =~ s/\W+/_/g;
                   14622:                 if ($maptitle ne '') {
1.1149    raeburn  14623:                     if (length($maptitle) > 12) {
                   14624:                         $maptitle = substr($maptitle,0,12);
                   14625:                     }
1.1015    raeburn  14626:                     push(@pathitems,$maptitle);
                   14627:                 }
                   14628:                 unless ($env{'request.state'} eq 'construct') {
                   14629:                     my $res = $navmap->getBySymb($symb);
                   14630:                     if (ref($res)) {
                   14631:                         my $partlist = $res->parts();
                   14632:                         my $totaluploads = 0;
                   14633:                         if (ref($partlist) eq 'ARRAY') {
                   14634:                             foreach my $part (@{$partlist}) {
                   14635:                                 my @types = $res->responseType($part);
                   14636:                                 my @ids = $res->responseIds($part);
                   14637:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14638:                                     if ($types[$i] eq 'essay') {
                   14639:                                         my $partid = $part.'_'.$ids[$i];
                   14640:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14641:                                             $totaluploads ++;
                   14642:                                         }
                   14643:                                     }
                   14644:                                 }
                   14645:                             }
                   14646:                             if ($totaluploads > 1) {
                   14647:                                 $multiresp = 1;
                   14648:                             }
                   14649:                         }
                   14650:                     }
                   14651:                 }
                   14652:             } else {
                   14653:                 return;
                   14654:             }
                   14655:         } else {
                   14656:             return;
                   14657:         }
                   14658:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14659:         $restitle =~ s/\W+/_/g;
                   14660:         if ($restitle eq '') {
                   14661:             $restitle = ($resurl =~ m{/[^/]+$});
                   14662:             if ($restitle eq '') {
                   14663:                 $restitle = time;
                   14664:             }
                   14665:         }
1.1149    raeburn  14666:         if (length($restitle) > 12) {
                   14667:             $restitle = substr($restitle,0,12);
                   14668:         }
1.1015    raeburn  14669:         push(@pathitems,$restitle);
                   14670:         $path .= join('/',@pathitems);
                   14671:     }
                   14672:     return ($path,$multiresp);
                   14673: }
                   14674: 
                   14675: =pod
                   14676: 
1.464     albertel 14677: =back
1.41      ng       14678: 
1.112     bowersj2 14679: =head1 CSV Upload/Handling functions
1.38      albertel 14680: 
1.41      ng       14681: =over 4
                   14682: 
1.648     raeburn  14683: =item * &upfile_store($r)
1.41      ng       14684: 
                   14685: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14686: needs $env{'form.upfile'}
1.41      ng       14687: returns $datatoken to be put into hidden field
                   14688: 
                   14689: =cut
1.31      albertel 14690: 
                   14691: sub upfile_store {
                   14692:     my $r=shift;
1.258     albertel 14693:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14694:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14695:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14696:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14697: 
1.1299    raeburn  14698:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14699:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14700:                                      time.'_'.$$);
                   14701:     return if ($datatoken eq '');
                   14702: 
1.31      albertel 14703:     {
1.158     raeburn  14704:         my $datafile = $r->dir_config('lonDaemons').
                   14705:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14706:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14707:             print $fh $env{'form.upfile'};
1.158     raeburn  14708:             close($fh);
                   14709:         }
1.31      albertel 14710:     }
                   14711:     return $datatoken;
                   14712: }
                   14713: 
1.56      matthew  14714: =pod
                   14715: 
1.1290    raeburn  14716: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14717: 
                   14718: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14719: $datatoken is the name to assign to the temporary file.
1.258     albertel 14720: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14721: 
                   14722: =cut
1.31      albertel 14723: 
                   14724: sub load_tmp_file {
1.1290    raeburn  14725:     my ($r,$datatoken) = @_;
                   14726:     return if ($datatoken eq '');
1.31      albertel 14727:     my @studentdata=();
                   14728:     {
1.158     raeburn  14729:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14730:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14731:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14732:             @studentdata=<$fh>;
                   14733:             close($fh);
                   14734:         }
1.31      albertel 14735:     }
1.258     albertel 14736:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14737: }
                   14738: 
1.1290    raeburn  14739: sub valid_datatoken {
                   14740:     my ($datatoken) = @_;
1.1325    raeburn  14741:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14742:         return $datatoken;
                   14743:     }
                   14744:     return;
                   14745: }
                   14746: 
1.56      matthew  14747: =pod
                   14748: 
1.648     raeburn  14749: =item * &upfile_record_sep()
1.41      ng       14750: 
                   14751: Separate uploaded file into records
                   14752: returns array of records,
1.258     albertel 14753: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14754: 
                   14755: =cut
1.31      albertel 14756: 
                   14757: sub upfile_record_sep {
1.258     albertel 14758:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14759:     } else {
1.248     albertel 14760: 	my @records;
1.258     albertel 14761: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14762: 	    if ($line=~/^\s*$/) { next; }
                   14763: 	    push(@records,$line);
                   14764: 	}
                   14765: 	return @records;
1.31      albertel 14766:     }
                   14767: }
                   14768: 
1.56      matthew  14769: =pod
                   14770: 
1.648     raeburn  14771: =item * &record_sep($record)
1.41      ng       14772: 
1.258     albertel 14773: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14774: 
                   14775: =cut
                   14776: 
1.263     www      14777: sub takeleft {
                   14778:     my $index=shift;
                   14779:     return substr('0000'.$index,-4,4);
                   14780: }
                   14781: 
1.31      albertel 14782: sub record_sep {
                   14783:     my $record=shift;
                   14784:     my %components=();
1.258     albertel 14785:     if ($env{'form.upfiletype'} eq 'xml') {
                   14786:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14787:         my $i=0;
1.356     albertel 14788:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14789:             $field=~s/^(\"|\')//;
                   14790:             $field=~s/(\"|\')$//;
1.263     www      14791:             $components{&takeleft($i)}=$field;
1.31      albertel 14792:             $i++;
                   14793:         }
1.258     albertel 14794:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14795:         my $i=0;
1.356     albertel 14796:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14797:             $field=~s/^(\"|\')//;
                   14798:             $field=~s/(\"|\')$//;
1.263     www      14799:             $components{&takeleft($i)}=$field;
1.31      albertel 14800:             $i++;
                   14801:         }
                   14802:     } else {
1.561     www      14803:         my $separator=',';
1.480     banghart 14804:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14805:             $separator=';';
1.480     banghart 14806:         }
1.31      albertel 14807:         my $i=0;
1.561     www      14808: # the character we are looking for to indicate the end of a quote or a record 
                   14809:         my $looking_for=$separator;
                   14810: # do not add the characters to the fields
                   14811:         my $ignore=0;
                   14812: # we just encountered a separator (or the beginning of the record)
                   14813:         my $just_found_separator=1;
                   14814: # store the field we are working on here
                   14815:         my $field='';
                   14816: # work our way through all characters in record
                   14817:         foreach my $character ($record=~/(.)/g) {
                   14818:             if ($character eq $looking_for) {
                   14819:                if ($character ne $separator) {
                   14820: # Found the end of a quote, again looking for separator
                   14821:                   $looking_for=$separator;
                   14822:                   $ignore=1;
                   14823:                } else {
                   14824: # Found a separator, store away what we got
                   14825:                   $components{&takeleft($i)}=$field;
                   14826: 	          $i++;
                   14827:                   $just_found_separator=1;
                   14828:                   $ignore=0;
                   14829:                   $field='';
                   14830:                }
                   14831:                next;
                   14832:             }
                   14833: # single or double quotation marks after a separator indicate beginning of a quote
                   14834: # we are now looking for the end of the quote and need to ignore separators
                   14835:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14836:                $looking_for=$character;
                   14837:                next;
                   14838:             }
                   14839: # ignore would be true after we reached the end of a quote
                   14840:             if ($ignore) { next; }
                   14841:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14842:             $field.=$character;
                   14843:             $just_found_separator=0; 
1.31      albertel 14844:         }
1.561     www      14845: # catch the very last entry, since we never encountered the separator
                   14846:         $components{&takeleft($i)}=$field;
1.31      albertel 14847:     }
                   14848:     return %components;
                   14849: }
                   14850: 
1.144     matthew  14851: ######################################################
                   14852: ######################################################
                   14853: 
1.56      matthew  14854: =pod
                   14855: 
1.648     raeburn  14856: =item * &upfile_select_html()
1.41      ng       14857: 
1.144     matthew  14858: Return HTML code to select a file from the users machine and specify 
                   14859: the file type.
1.41      ng       14860: 
                   14861: =cut
                   14862: 
1.144     matthew  14863: ######################################################
                   14864: ######################################################
1.31      albertel 14865: sub upfile_select_html {
1.144     matthew  14866:     my %Types = (
                   14867:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14868:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14869:                  space => &mt('Space separated'),
                   14870:                  tab   => &mt('Tabulator separated'),
                   14871: #                 xml   => &mt('HTML/XML'),
                   14872:                  );
                   14873:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14874:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14875:     foreach my $type (sort(keys(%Types))) {
                   14876:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14877:     }
                   14878:     $Str .= "</select>\n";
                   14879:     return $Str;
1.31      albertel 14880: }
                   14881: 
1.301     albertel 14882: sub get_samples {
                   14883:     my ($records,$toget) = @_;
                   14884:     my @samples=({});
                   14885:     my $got=0;
                   14886:     foreach my $rec (@$records) {
                   14887: 	my %temp = &record_sep($rec);
                   14888: 	if (! grep(/\S/, values(%temp))) { next; }
                   14889: 	if (%temp) {
                   14890: 	    $samples[$got]=\%temp;
                   14891: 	    $got++;
                   14892: 	    if ($got == $toget) { last; }
                   14893: 	}
                   14894:     }
                   14895:     return \@samples;
                   14896: }
                   14897: 
1.144     matthew  14898: ######################################################
                   14899: ######################################################
                   14900: 
1.56      matthew  14901: =pod
                   14902: 
1.648     raeburn  14903: =item * &csv_print_samples($r,$records)
1.41      ng       14904: 
                   14905: Prints a table of sample values from each column uploaded $r is an
                   14906: Apache Request ref, $records is an arrayref from
                   14907: &Apache::loncommon::upfile_record_sep
                   14908: 
                   14909: =cut
                   14910: 
1.144     matthew  14911: ######################################################
                   14912: ######################################################
1.31      albertel 14913: sub csv_print_samples {
                   14914:     my ($r,$records) = @_;
1.662     bisitz   14915:     my $samples = &get_samples($records,5);
1.301     albertel 14916: 
1.594     raeburn  14917:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14918:               &start_data_table_header_row());
1.356     albertel 14919:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14920:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14921:     $r->print(&end_data_table_header_row());
1.301     albertel 14922:     foreach my $hash (@$samples) {
1.594     raeburn  14923: 	$r->print(&start_data_table_row());
1.356     albertel 14924: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14925: 	    $r->print('<td>');
1.356     albertel 14926: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14927: 	    $r->print('</td>');
                   14928: 	}
1.594     raeburn  14929: 	$r->print(&end_data_table_row());
1.31      albertel 14930:     }
1.594     raeburn  14931:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14932: }
                   14933: 
1.144     matthew  14934: ######################################################
                   14935: ######################################################
                   14936: 
1.56      matthew  14937: =pod
                   14938: 
1.648     raeburn  14939: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14940: 
                   14941: Prints a table to create associations between values and table columns.
1.144     matthew  14942: 
1.41      ng       14943: $r is an Apache Request ref,
                   14944: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14945: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14946: 
                   14947: =cut
                   14948: 
1.144     matthew  14949: ######################################################
                   14950: ######################################################
1.31      albertel 14951: sub csv_print_select_table {
                   14952:     my ($r,$records,$d) = @_;
1.301     albertel 14953:     my $i=0;
                   14954:     my $samples = &get_samples($records,1);
1.144     matthew  14955:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14956: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14957:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14958:               '<th>'.&mt('Column').'</th>'.
                   14959:               &end_data_table_header_row()."\n");
1.356     albertel 14960:     foreach my $array_ref (@$d) {
                   14961: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14962: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14963: 
1.875     bisitz   14964: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14965: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14966: 	$r->print('<option value="none"></option>');
1.356     albertel 14967: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14968: 	    $r->print('<option value="'.$sample.'"'.
                   14969:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14970:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14971: 	}
1.594     raeburn  14972: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14973: 	$i++;
                   14974:     }
1.594     raeburn  14975:     $r->print(&end_data_table());
1.31      albertel 14976:     $i--;
                   14977:     return $i;
                   14978: }
1.56      matthew  14979: 
1.144     matthew  14980: ######################################################
                   14981: ######################################################
                   14982: 
1.56      matthew  14983: =pod
1.31      albertel 14984: 
1.648     raeburn  14985: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14986: 
                   14987: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14988: 
                   14989: $r is an Apache Request ref,
                   14990: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14991: $d is an array of 2 element arrays (internal name, displayed name)
                   14992: 
                   14993: =cut
                   14994: 
1.144     matthew  14995: ######################################################
                   14996: ######################################################
1.31      albertel 14997: sub csv_samples_select_table {
                   14998:     my ($r,$records,$d) = @_;
                   14999:     my $i=0;
1.144     matthew  15000:     #
1.662     bisitz   15001:     my $max_samples = 5;
                   15002:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15003:     $r->print(&start_data_table().
                   15004:               &start_data_table_header_row().'<th>'.
                   15005:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15006:               &end_data_table_header_row());
1.301     albertel 15007: 
                   15008:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15009: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15010: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15011: 	foreach my $option (@$d) {
                   15012: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15013: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15014:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15015:                       $display.'</option>');
1.31      albertel 15016: 	}
                   15017: 	$r->print('</select></td><td>');
1.662     bisitz   15018: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15019: 	    if (defined($samples->[$line]{$key})) { 
                   15020: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15021: 	    }
                   15022: 	}
1.594     raeburn  15023: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15024: 	$i++;
                   15025:     }
1.594     raeburn  15026:     $r->print(&end_data_table());
1.31      albertel 15027:     $i--;
                   15028:     return($i);
1.115     matthew  15029: }
                   15030: 
1.144     matthew  15031: ######################################################
                   15032: ######################################################
                   15033: 
1.115     matthew  15034: =pod
                   15035: 
1.648     raeburn  15036: =item * &clean_excel_name($name)
1.115     matthew  15037: 
                   15038: Returns a replacement for $name which does not contain any illegal characters.
                   15039: 
                   15040: =cut
                   15041: 
1.144     matthew  15042: ######################################################
                   15043: ######################################################
1.115     matthew  15044: sub clean_excel_name {
                   15045:     my ($name) = @_;
                   15046:     $name =~ s/[:\*\?\/\\]//g;
                   15047:     if (length($name) > 31) {
                   15048:         $name = substr($name,0,31);
                   15049:     }
                   15050:     return $name;
1.25      albertel 15051: }
1.84      albertel 15052: 
1.85      albertel 15053: =pod
                   15054: 
1.648     raeburn  15055: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15056: 
                   15057: Returns either 1 or undef
                   15058: 
                   15059: 1 if the part is to be hidden, undef if it is to be shown
                   15060: 
                   15061: Arguments are:
                   15062: 
                   15063: $id the id of the part to be checked
                   15064: $symb, optional the symb of the resource to check
                   15065: $udom, optional the domain of the user to check for
                   15066: $uname, optional the username of the user to check for
                   15067: 
                   15068: =cut
1.84      albertel 15069: 
                   15070: sub check_if_partid_hidden {
                   15071:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15072:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15073: 					 $symb,$udom,$uname);
1.141     albertel 15074:     my $truth=1;
                   15075:     #if the string starts with !, then the list is the list to show not hide
                   15076:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15077:     my @hiddenlist=split(/,/,$hiddenparts);
                   15078:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15079: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15080:     }
1.141     albertel 15081:     return !$truth;
1.84      albertel 15082: }
1.127     matthew  15083: 
1.138     matthew  15084: 
                   15085: ############################################################
                   15086: ############################################################
                   15087: 
                   15088: =pod
                   15089: 
1.157     matthew  15090: =back 
                   15091: 
1.138     matthew  15092: =head1 cgi-bin script and graphing routines
                   15093: 
1.157     matthew  15094: =over 4
                   15095: 
1.648     raeburn  15096: =item * &get_cgi_id()
1.138     matthew  15097: 
                   15098: Inputs: none
                   15099: 
                   15100: Returns an id which can be used to pass environment variables
                   15101: to various cgi-bin scripts.  These environment variables will
                   15102: be removed from the users environment after a given time by
                   15103: the routine &Apache::lonnet::transfer_profile_to_env.
                   15104: 
                   15105: =cut
                   15106: 
                   15107: ############################################################
                   15108: ############################################################
1.152     albertel 15109: my $uniq=0;
1.136     matthew  15110: sub get_cgi_id {
1.154     albertel 15111:     $uniq=($uniq+1)%100000;
1.280     albertel 15112:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15113: }
                   15114: 
1.127     matthew  15115: ############################################################
                   15116: ############################################################
                   15117: 
                   15118: =pod
                   15119: 
1.648     raeburn  15120: =item * &DrawBarGraph()
1.127     matthew  15121: 
1.138     matthew  15122: Facilitates the plotting of data in a (stacked) bar graph.
                   15123: Puts plot definition data into the users environment in order for 
                   15124: graph.png to plot it.  Returns an <img> tag for the plot.
                   15125: The bars on the plot are labeled '1','2',...,'n'.
                   15126: 
                   15127: Inputs:
                   15128: 
                   15129: =over 4
                   15130: 
                   15131: =item $Title: string, the title of the plot
                   15132: 
                   15133: =item $xlabel: string, text describing the X-axis of the plot
                   15134: 
                   15135: =item $ylabel: string, text describing the Y-axis of the plot
                   15136: 
                   15137: =item $Max: scalar, the maximum Y value to use in the plot
                   15138: If $Max is < any data point, the graph will not be rendered.
                   15139: 
1.140     matthew  15140: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15141: they are plotted.  If undefined, default values will be used.
                   15142: 
1.178     matthew  15143: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15144: 
1.138     matthew  15145: =item @Values: An array of array references.  Each array reference holds data
                   15146: to be plotted in a stacked bar chart.
                   15147: 
1.239     matthew  15148: =item If the final element of @Values is a hash reference the key/value
                   15149: pairs will be added to the graph definition.
                   15150: 
1.138     matthew  15151: =back
                   15152: 
                   15153: Returns:
                   15154: 
                   15155: An <img> tag which references graph.png and the appropriate identifying
                   15156: information for the plot.
                   15157: 
1.127     matthew  15158: =cut
                   15159: 
                   15160: ############################################################
                   15161: ############################################################
1.134     matthew  15162: sub DrawBarGraph {
1.178     matthew  15163:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15164:     #
                   15165:     if (! defined($colors)) {
                   15166:         $colors = ['#33ff00', 
                   15167:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15168:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15169:                   ]; 
                   15170:     }
1.228     matthew  15171:     my $extra_settings = {};
                   15172:     if (ref($Values[-1]) eq 'HASH') {
                   15173:         $extra_settings = pop(@Values);
                   15174:     }
1.127     matthew  15175:     #
1.136     matthew  15176:     my $identifier = &get_cgi_id();
                   15177:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15178:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15179:         return '';
                   15180:     }
1.225     matthew  15181:     #
                   15182:     my @Labels;
                   15183:     if (defined($labels)) {
                   15184:         @Labels = @$labels;
                   15185:     } else {
                   15186:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15187:             push(@Labels,$i+1);
1.225     matthew  15188:         }
                   15189:     }
                   15190:     #
1.129     matthew  15191:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15192:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15193:     my %ValuesHash;
                   15194:     my $NumSets=1;
                   15195:     foreach my $array (@Values) {
                   15196:         next if (! ref($array));
1.136     matthew  15197:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15198:             join(',',@$array);
1.129     matthew  15199:     }
1.127     matthew  15200:     #
1.136     matthew  15201:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15202:     if ($NumBars < 3) {
                   15203:         $width = 120+$NumBars*32;
1.220     matthew  15204:         $xskip = 1;
1.225     matthew  15205:         $bar_width = 30;
                   15206:     } elsif ($NumBars < 5) {
                   15207:         $width = 120+$NumBars*20;
                   15208:         $xskip = 1;
                   15209:         $bar_width = 20;
1.220     matthew  15210:     } elsif ($NumBars < 10) {
1.136     matthew  15211:         $width = 120+$NumBars*15;
                   15212:         $xskip = 1;
                   15213:         $bar_width = 15;
                   15214:     } elsif ($NumBars <= 25) {
                   15215:         $width = 120+$NumBars*11;
                   15216:         $xskip = 5;
                   15217:         $bar_width = 8;
                   15218:     } elsif ($NumBars <= 50) {
                   15219:         $width = 120+$NumBars*8;
                   15220:         $xskip = 5;
                   15221:         $bar_width = 4;
                   15222:     } else {
                   15223:         $width = 120+$NumBars*8;
                   15224:         $xskip = 5;
                   15225:         $bar_width = 4;
                   15226:     }
                   15227:     #
1.137     matthew  15228:     $Max = 1 if ($Max < 1);
                   15229:     if ( int($Max) < $Max ) {
                   15230:         $Max++;
                   15231:         $Max = int($Max);
                   15232:     }
1.127     matthew  15233:     $Title  = '' if (! defined($Title));
                   15234:     $xlabel = '' if (! defined($xlabel));
                   15235:     $ylabel = '' if (! defined($ylabel));
1.369     www      15236:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15237:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15238:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15239:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15240:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15241:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15242:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15243:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15244:     $ValuesHash{$id.'.height'}   = $height;
                   15245:     $ValuesHash{$id.'.width'}    = $width;
                   15246:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15247:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15248:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15249:     #
1.228     matthew  15250:     # Deal with other parameters
                   15251:     while (my ($key,$value) = each(%$extra_settings)) {
                   15252:         $ValuesHash{$id.'.'.$key} = $value;
                   15253:     }
                   15254:     #
1.646     raeburn  15255:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15256:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15257: }
                   15258: 
                   15259: ############################################################
                   15260: ############################################################
                   15261: 
                   15262: =pod
                   15263: 
1.648     raeburn  15264: =item * &DrawXYGraph()
1.137     matthew  15265: 
1.138     matthew  15266: Facilitates the plotting of data in an XY graph.
                   15267: Puts plot definition data into the users environment in order for 
                   15268: graph.png to plot it.  Returns an <img> tag for the plot.
                   15269: 
                   15270: Inputs:
                   15271: 
                   15272: =over 4
                   15273: 
                   15274: =item $Title: string, the title of the plot
                   15275: 
                   15276: =item $xlabel: string, text describing the X-axis of the plot
                   15277: 
                   15278: =item $ylabel: string, text describing the Y-axis of the plot
                   15279: 
                   15280: =item $Max: scalar, the maximum Y value to use in the plot
                   15281: If $Max is < any data point, the graph will not be rendered.
                   15282: 
                   15283: =item $colors: Array ref containing the hex color codes for the data to be 
                   15284: plotted in.  If undefined, default values will be used.
                   15285: 
                   15286: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15287: 
                   15288: =item $Ydata: Array ref containing Array refs.  
1.185     www      15289: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15290: 
                   15291: =item %Values: hash indicating or overriding any default values which are 
                   15292: passed to graph.png.  
                   15293: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15294: 
                   15295: =back
                   15296: 
                   15297: Returns:
                   15298: 
                   15299: An <img> tag which references graph.png and the appropriate identifying
                   15300: information for the plot.
                   15301: 
1.137     matthew  15302: =cut
                   15303: 
                   15304: ############################################################
                   15305: ############################################################
                   15306: sub DrawXYGraph {
                   15307:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15308:     #
                   15309:     # Create the identifier for the graph
                   15310:     my $identifier = &get_cgi_id();
                   15311:     my $id = 'cgi.'.$identifier;
                   15312:     #
                   15313:     $Title  = '' if (! defined($Title));
                   15314:     $xlabel = '' if (! defined($xlabel));
                   15315:     $ylabel = '' if (! defined($ylabel));
                   15316:     my %ValuesHash = 
                   15317:         (
1.369     www      15318:          $id.'.title'  => &escape($Title),
                   15319:          $id.'.xlabel' => &escape($xlabel),
                   15320:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15321:          $id.'.y_max_value'=> $Max,
                   15322:          $id.'.labels'     => join(',',@$Xlabels),
                   15323:          $id.'.PlotType'   => 'XY',
                   15324:          );
                   15325:     #
                   15326:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15327:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15328:     }
                   15329:     #
                   15330:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15331:         return '';
                   15332:     }
                   15333:     my $NumSets=1;
1.138     matthew  15334:     foreach my $array (@{$Ydata}){
1.137     matthew  15335:         next if (! ref($array));
                   15336:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15337:     }
1.138     matthew  15338:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15339:     #
                   15340:     # Deal with other parameters
                   15341:     while (my ($key,$value) = each(%Values)) {
                   15342:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15343:     }
                   15344:     #
1.646     raeburn  15345:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15346:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15347: }
                   15348: 
                   15349: ############################################################
                   15350: ############################################################
                   15351: 
                   15352: =pod
                   15353: 
1.648     raeburn  15354: =item * &DrawXYYGraph()
1.138     matthew  15355: 
                   15356: Facilitates the plotting of data in an XY graph with two Y axes.
                   15357: Puts plot definition data into the users environment in order for 
                   15358: graph.png to plot it.  Returns an <img> tag for the plot.
                   15359: 
                   15360: Inputs:
                   15361: 
                   15362: =over 4
                   15363: 
                   15364: =item $Title: string, the title of the plot
                   15365: 
                   15366: =item $xlabel: string, text describing the X-axis of the plot
                   15367: 
                   15368: =item $ylabel: string, text describing the Y-axis of the plot
                   15369: 
                   15370: =item $colors: Array ref containing the hex color codes for the data to be 
                   15371: plotted in.  If undefined, default values will be used.
                   15372: 
                   15373: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15374: 
                   15375: =item $Ydata1: The first data set
                   15376: 
                   15377: =item $Min1: The minimum value of the left Y-axis
                   15378: 
                   15379: =item $Max1: The maximum value of the left Y-axis
                   15380: 
                   15381: =item $Ydata2: The second data set
                   15382: 
                   15383: =item $Min2: The minimum value of the right Y-axis
                   15384: 
                   15385: =item $Max2: The maximum value of the left Y-axis
                   15386: 
                   15387: =item %Values: hash indicating or overriding any default values which are 
                   15388: passed to graph.png.  
                   15389: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15390: 
                   15391: =back
                   15392: 
                   15393: Returns:
                   15394: 
                   15395: An <img> tag which references graph.png and the appropriate identifying
                   15396: information for the plot.
1.136     matthew  15397: 
                   15398: =cut
                   15399: 
                   15400: ############################################################
                   15401: ############################################################
1.137     matthew  15402: sub DrawXYYGraph {
                   15403:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15404:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15405:     #
                   15406:     # Create the identifier for the graph
                   15407:     my $identifier = &get_cgi_id();
                   15408:     my $id = 'cgi.'.$identifier;
                   15409:     #
                   15410:     $Title  = '' if (! defined($Title));
                   15411:     $xlabel = '' if (! defined($xlabel));
                   15412:     $ylabel = '' if (! defined($ylabel));
                   15413:     my %ValuesHash = 
                   15414:         (
1.369     www      15415:          $id.'.title'  => &escape($Title),
                   15416:          $id.'.xlabel' => &escape($xlabel),
                   15417:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15418:          $id.'.labels' => join(',',@$Xlabels),
                   15419:          $id.'.PlotType' => 'XY',
                   15420:          $id.'.NumSets' => 2,
1.137     matthew  15421:          $id.'.two_axes' => 1,
                   15422:          $id.'.y1_max_value' => $Max1,
                   15423:          $id.'.y1_min_value' => $Min1,
                   15424:          $id.'.y2_max_value' => $Max2,
                   15425:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15426:          );
                   15427:     #
1.137     matthew  15428:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15429:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15430:     }
                   15431:     #
                   15432:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15433:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15434:         return '';
                   15435:     }
                   15436:     my $NumSets=1;
1.137     matthew  15437:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15438:         next if (! ref($array));
                   15439:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15440:     }
                   15441:     #
                   15442:     # Deal with other parameters
                   15443:     while (my ($key,$value) = each(%Values)) {
                   15444:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15445:     }
                   15446:     #
1.646     raeburn  15447:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15448:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15449: }
                   15450: 
                   15451: ############################################################
                   15452: ############################################################
                   15453: 
                   15454: =pod
                   15455: 
1.157     matthew  15456: =back 
                   15457: 
1.139     matthew  15458: =head1 Statistics helper routines?  
                   15459: 
                   15460: Bad place for them but what the hell.
                   15461: 
1.157     matthew  15462: =over 4
                   15463: 
1.648     raeburn  15464: =item * &chartlink()
1.139     matthew  15465: 
                   15466: Returns a link to the chart for a specific student.  
                   15467: 
                   15468: Inputs:
                   15469: 
                   15470: =over 4
                   15471: 
                   15472: =item $linktext: The text of the link
                   15473: 
                   15474: =item $sname: The students username
                   15475: 
                   15476: =item $sdomain: The students domain
                   15477: 
                   15478: =back
                   15479: 
1.157     matthew  15480: =back
                   15481: 
1.139     matthew  15482: =cut
                   15483: 
                   15484: ############################################################
                   15485: ############################################################
                   15486: sub chartlink {
                   15487:     my ($linktext, $sname, $sdomain) = @_;
                   15488:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15489:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15490:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15491:        '">'.$linktext.'</a>';
1.153     matthew  15492: }
                   15493: 
                   15494: #######################################################
                   15495: #######################################################
                   15496: 
                   15497: =pod
                   15498: 
                   15499: =head1 Course Environment Routines
1.157     matthew  15500: 
                   15501: =over 4
1.153     matthew  15502: 
1.648     raeburn  15503: =item * &restore_course_settings()
1.153     matthew  15504: 
1.648     raeburn  15505: =item * &store_course_settings()
1.153     matthew  15506: 
                   15507: Restores/Store indicated form parameters from the course environment.
                   15508: Will not overwrite existing values of the form parameters.
                   15509: 
                   15510: Inputs: 
                   15511: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15512: 
                   15513: a hash ref describing the data to be stored.  For example:
                   15514:    
                   15515: %Save_Parameters = ('Status' => 'scalar',
                   15516:     'chartoutputmode' => 'scalar',
                   15517:     'chartoutputdata' => 'scalar',
                   15518:     'Section' => 'array',
1.373     raeburn  15519:     'Group' => 'array',
1.153     matthew  15520:     'StudentData' => 'array',
                   15521:     'Maps' => 'array');
                   15522: 
                   15523: Returns: both routines return nothing
                   15524: 
1.631     raeburn  15525: =back
                   15526: 
1.153     matthew  15527: =cut
                   15528: 
                   15529: #######################################################
                   15530: #######################################################
                   15531: sub store_course_settings {
1.496     albertel 15532:     return &store_settings($env{'request.course.id'},@_);
                   15533: }
                   15534: 
                   15535: sub store_settings {
1.153     matthew  15536:     # save to the environment
                   15537:     # appenv the same items, just to be safe
1.300     albertel 15538:     my $udom  = $env{'user.domain'};
                   15539:     my $uname = $env{'user.name'};
1.496     albertel 15540:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15541:     my %SaveHash;
                   15542:     my %AppHash;
                   15543:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15544:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15545:         my $envname = 'environment.'.$basename;
1.258     albertel 15546:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15547:             # Save this value away
                   15548:             if ($type eq 'scalar' &&
1.258     albertel 15549:                 (! exists($env{$envname}) || 
                   15550:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15551:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15552:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15553:             } elsif ($type eq 'array') {
                   15554:                 my $stored_form;
1.258     albertel 15555:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15556:                     $stored_form = join(',',
                   15557:                                         map {
1.369     www      15558:                                             &escape($_);
1.258     albertel 15559:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15560:                 } else {
                   15561:                     $stored_form = 
1.369     www      15562:                         &escape($env{'form.'.$setting});
1.153     matthew  15563:                 }
                   15564:                 # Determine if the array contents are the same.
1.258     albertel 15565:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15566:                     $SaveHash{$basename} = $stored_form;
                   15567:                     $AppHash{$envname}   = $stored_form;
                   15568:                 }
                   15569:             }
                   15570:         }
                   15571:     }
                   15572:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15573:                                           $udom,$uname);
1.153     matthew  15574:     if ($put_result !~ /^(ok|delayed)/) {
                   15575:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15576:                                  'got error:'.$put_result);
                   15577:     }
                   15578:     # Make sure these settings stick around in this session, too
1.646     raeburn  15579:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15580:     return;
                   15581: }
                   15582: 
                   15583: sub restore_course_settings {
1.499     albertel 15584:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15585: }
                   15586: 
                   15587: sub restore_settings {
                   15588:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15589:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15590:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15591:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15592:             '.'.$setting;
1.258     albertel 15593:         if (exists($env{$envname})) {
1.153     matthew  15594:             if ($type eq 'scalar') {
1.258     albertel 15595:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15596:             } elsif ($type eq 'array') {
1.258     albertel 15597:                 $env{'form.'.$setting} = [ 
1.153     matthew  15598:                                            map { 
1.369     www      15599:                                                &unescape($_); 
1.258     albertel 15600:                                            } split(',',$env{$envname})
1.153     matthew  15601:                                            ];
                   15602:             }
                   15603:         }
                   15604:     }
1.127     matthew  15605: }
                   15606: 
1.618     raeburn  15607: #######################################################
                   15608: #######################################################
                   15609: 
                   15610: =pod
                   15611: 
                   15612: =head1 Domain E-mail Routines  
                   15613: 
                   15614: =over 4
                   15615: 
1.648     raeburn  15616: =item * &build_recipient_list()
1.618     raeburn  15617: 
1.1144    raeburn  15618: Build recipient lists for following types of e-mail:
1.766     raeburn  15619: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15620: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15621: module change checking, student/employee ID conflict checks, as
                   15622: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15623: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15624: 
                   15625: Inputs:
1.619     raeburn  15626: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15627: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15628: requestsmail, updatesmail, or idconflictsmail).
                   15629: 
1.619     raeburn  15630: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15631: 
1.619     raeburn  15632: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15633: i.e., predates configuration by DC via domainprefs.pm
                   15634: 
                   15635: $requname username of requester (if mailing type is helpdeskmail)
                   15636: 
                   15637: $requdom domain of requester (if mailing type is helpdeskmail)
                   15638: 
                   15639: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15640: 
1.618     raeburn  15641: 
1.655     raeburn  15642: Returns: comma separated list of addresses to which to send e-mail.
                   15643: 
                   15644: =back
1.618     raeburn  15645: 
                   15646: =cut
                   15647: 
                   15648: ############################################################
                   15649: ############################################################
                   15650: sub build_recipient_list {
1.1297    raeburn  15651:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15652:     my @recipients;
1.1270    raeburn  15653:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15654:     my %domconfig =
1.1270    raeburn  15655:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15656:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15657:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15658:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15659:                 my @contacts = ('adminemail','supportemail');
                   15660:                 foreach my $item (@contacts) {
                   15661:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15662:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15663:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15664:                             push(@recipients,$addr);
                   15665:                         }
1.619     raeburn  15666:                     }
1.1270    raeburn  15667:                 }
                   15668:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15669:                 if ($mailing eq 'helpdeskmail') {
                   15670:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15671:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15672:                         my @ok_bccs;
                   15673:                         foreach my $bcc (@bccs) {
                   15674:                             $bcc =~ s/^\s+//g;
                   15675:                             $bcc =~ s/\s+$//g;
                   15676:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15677:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15678:                                     push(@ok_bccs,$bcc);
                   15679:                                 }
                   15680:                             }
                   15681:                         }
                   15682:                         if (@ok_bccs > 0) {
                   15683:                             $allbcc = join(', ',@ok_bccs);
                   15684:                         }
                   15685:                     }
                   15686:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15687:                 }
                   15688:             }
1.766     raeburn  15689:         } elsif ($origmail ne '') {
1.1270    raeburn  15690:             $lastresort = $origmail;
1.618     raeburn  15691:         }
1.1297    raeburn  15692:         if ($mailing eq 'helpdeskmail') {
                   15693:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15694:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15695:                 my ($inststatus,$inststatus_checked);
                   15696:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15697:                     ($env{'user.domain'} ne 'public')) {
                   15698:                     $inststatus_checked = 1;
                   15699:                     $inststatus = $env{'environment.inststatus'};
                   15700:                 }
                   15701:                 unless ($inststatus_checked) {
                   15702:                     if (($requname ne '') && ($requdom ne '')) {
                   15703:                         if (($requname =~ /^$match_username$/) &&
                   15704:                             ($requdom =~ /^$match_domain$/) &&
                   15705:                             (&Apache::lonnet::domain($requdom))) {
                   15706:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15707:                                                                       $requdom);
                   15708:                             unless ($requhome eq 'no_host') {
                   15709:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15710:                                 $inststatus = $userenv{'inststatus'};
                   15711:                                 $inststatus_checked = 1;
                   15712:                             }
                   15713:                         }
                   15714:                     }
                   15715:                 }
                   15716:                 unless ($inststatus_checked) {
                   15717:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15718:                         my %srch = (srchby     => 'email',
                   15719:                                     srchdomain => $defdom,
                   15720:                                     srchterm   => $reqemail,
                   15721:                                     srchtype   => 'exact');
                   15722:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15723:                         foreach my $uname (keys(%srch_results)) {
                   15724:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15725:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15726:                                 $inststatus_checked = 1;
                   15727:                                 last;
                   15728:                             }
                   15729:                         }
                   15730:                         unless ($inststatus_checked) {
                   15731:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15732:                             if ($dirsrchres eq 'ok') {
                   15733:                                 foreach my $uname (keys(%srch_results)) {
                   15734:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15735:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15736:                                         $inststatus_checked = 1;
                   15737:                                         last;
                   15738:                                     }
                   15739:                                 }
                   15740:                             }
                   15741:                         }
                   15742:                     }
                   15743:                 }
                   15744:                 if ($inststatus ne '') {
                   15745:                     foreach my $status (split(/\:/,$inststatus)) {
                   15746:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15747:                             my @contacts = ('adminemail','supportemail');
                   15748:                             foreach my $item (@contacts) {
                   15749:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15750:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15751:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15752:                                         push(@recipients,$addr);
                   15753:                                     }
                   15754:                                 }
                   15755:                             }
                   15756:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15757:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15758:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15759:                                 my @ok_bccs;
                   15760:                                 foreach my $bcc (@bccs) {
                   15761:                                     $bcc =~ s/^\s+//g;
                   15762:                                     $bcc =~ s/\s+$//g;
                   15763:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15764:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15765:                                             push(@ok_bccs,$bcc);
                   15766:                                         }
                   15767:                                     }
                   15768:                                 }
                   15769:                                 if (@ok_bccs > 0) {
                   15770:                                     $allbcc = join(', ',@ok_bccs);
                   15771:                                 }
                   15772:                             }
                   15773:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15774:                             last;
                   15775:                         }
                   15776:                     }
                   15777:                 }
                   15778:             }
                   15779:         }
1.619     raeburn  15780:     } elsif ($origmail ne '') {
1.1270    raeburn  15781:         $lastresort = $origmail;
                   15782:     }
1.1297    raeburn  15783:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15784:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15785:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15786:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15787:             my %what = (
                   15788:                           perlvar => 1,
                   15789:                        );
                   15790:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15791:             if ($primary) {
                   15792:                 my $gotaddr;
                   15793:                 my ($result,$returnhash) =
                   15794:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15795:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15796:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15797:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15798:                         $gotaddr = 1;
                   15799:                     }
                   15800:                 }
                   15801:                 unless ($gotaddr) {
                   15802:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15803:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15804:                     unless ($uintdom eq $intdom) {
                   15805:                         my %domconfig =
                   15806:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15807:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15808:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15809:                                 my @contacts = ('adminemail','supportemail');
                   15810:                                 foreach my $item (@contacts) {
                   15811:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15812:                                         my $addr = $domconfig{'contacts'}{$item};
                   15813:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15814:                                             push(@recipients,$addr);
                   15815:                                         }
                   15816:                                     }
                   15817:                                 }
                   15818:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15819:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15820:                                 }
                   15821:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15822:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15823:                                     my @ok_bccs;
                   15824:                                     foreach my $bcc (@bccs) {
                   15825:                                         $bcc =~ s/^\s+//g;
                   15826:                                         $bcc =~ s/\s+$//g;
                   15827:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15828:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15829:                                                 push(@ok_bccs,$bcc);
                   15830:                                             }
                   15831:                                         }
                   15832:                                     }
                   15833:                                     if (@ok_bccs > 0) {
                   15834:                                         $allbcc = join(', ',@ok_bccs);
                   15835:                                     }
                   15836:                                 }
                   15837:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15838:                             }
                   15839:                         }
                   15840:                     }
                   15841:                 }
                   15842:             }
                   15843:         }
1.618     raeburn  15844:     }
1.688     raeburn  15845:     if (defined($defmail)) {
                   15846:         if ($defmail ne '') {
                   15847:             push(@recipients,$defmail);
                   15848:         }
1.618     raeburn  15849:     }
                   15850:     if ($otheremails) {
1.619     raeburn  15851:         my @others;
                   15852:         if ($otheremails =~ /,/) {
                   15853:             @others = split(/,/,$otheremails);
1.618     raeburn  15854:         } else {
1.619     raeburn  15855:             push(@others,$otheremails);
                   15856:         }
                   15857:         foreach my $addr (@others) {
                   15858:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15859:                 push(@recipients,$addr);
                   15860:             }
1.618     raeburn  15861:         }
                   15862:     }
1.1298    raeburn  15863:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15864:         if ((!@recipients) && ($lastresort ne '')) {
                   15865:             push(@recipients,$lastresort);
                   15866:         }
                   15867:     } elsif ($lastresort ne '') {
                   15868:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15869:             push(@recipients,$lastresort);
                   15870:         }
                   15871:     }
1.1271    raeburn  15872:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15873:     if (wantarray) {
                   15874:         return ($recipientlist,$allbcc,$addtext);
                   15875:     } else {
                   15876:         return $recipientlist;
                   15877:     }
1.618     raeburn  15878: }
                   15879: 
1.127     matthew  15880: ############################################################
                   15881: ############################################################
1.154     albertel 15882: 
1.655     raeburn  15883: =pod
                   15884: 
1.1224    musolffc 15885: =over 4
                   15886: 
1.1223    musolffc 15887: =item * &mime_email()
                   15888: 
                   15889: Sends an email with a possible attachment
                   15890: 
                   15891: Inputs:
                   15892: 
                   15893: =over 4
                   15894: 
                   15895: from -              Sender's email address
                   15896: 
1.1343    raeburn  15897: replyto -           Reply-To email address
                   15898: 
1.1223    musolffc 15899: to -                Email address of recipient
                   15900: 
                   15901: subject -           Subject of email
                   15902: 
                   15903: body -              Body of email
                   15904: 
                   15905: cc_string -         Carbon copy email address
                   15906: 
                   15907: bcc -               Blind carbon copy email address
                   15908: 
                   15909: attachment_path -   Path of file to be attached
                   15910: 
                   15911: file_name -         Name of file to be attached
                   15912: 
                   15913: attachment_text -   The body of an attachment of type "TEXT"
                   15914: 
                   15915: =back
                   15916: 
                   15917: =back
                   15918: 
                   15919: =cut
                   15920: 
                   15921: ############################################################
                   15922: ############################################################
                   15923: 
                   15924: sub mime_email {
1.1343    raeburn  15925:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15926:         $file_name,$attachment_text) = @_;
                   15927:  
1.1223    musolffc 15928:     my $msg = MIME::Lite->new(
                   15929:              From    => $from,
                   15930:              To      => $to,
                   15931:              Subject => $subject,
                   15932:              Type    =>'TEXT',
                   15933:              Data    => $body,
                   15934:              );
1.1343    raeburn  15935:     if ($replyto ne '') {
                   15936:         $msg->add("Reply-To" => $replyto);
                   15937:     }
1.1223    musolffc 15938:     if ($cc_string ne '') {
                   15939:         $msg->add("Cc" => $cc_string);
                   15940:     }
                   15941:     if ($bcc ne '') {
                   15942:         $msg->add("Bcc" => $bcc);
                   15943:     }
                   15944:     $msg->attr("content-type"         => "text/plain");
                   15945:     $msg->attr("content-type.charset" => "UTF-8");
                   15946:     # Attach file if given
                   15947:     if ($attachment_path) {
                   15948:         unless ($file_name) {
                   15949:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15950:         }
                   15951:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15952:         $msg->attach(Type     => $type,
                   15953:                      Path     => $attachment_path,
                   15954:                      Filename => $file_name
                   15955:                      );
                   15956:     # Otherwise attach text if given
                   15957:     } elsif ($attachment_text) {
                   15958:         $msg->attach(Type => 'TEXT',
                   15959:                      Data => $attachment_text);
                   15960:     }
                   15961:     # Send it
                   15962:     $msg->send('sendmail');
                   15963: }
                   15964: 
                   15965: ############################################################
                   15966: ############################################################
                   15967: 
                   15968: =pod
                   15969: 
1.655     raeburn  15970: =head1 Course Catalog Routines
                   15971: 
                   15972: =over 4
                   15973: 
                   15974: =item * &gather_categories()
                   15975: 
                   15976: Converts category definitions - keys of categories hash stored in  
                   15977: coursecategories in configuration.db on the primary library server in a 
                   15978: domain - to an array.  Also generates javascript and idx hash used to 
                   15979: generate Domain Coordinator interface for editing Course Categories.
                   15980: 
                   15981: Inputs:
1.663     raeburn  15982: 
1.655     raeburn  15983: categories (reference to hash of category definitions).
1.663     raeburn  15984: 
1.655     raeburn  15985: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15986:       categories and subcategories).
1.663     raeburn  15987: 
1.655     raeburn  15988: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15989:       editing Course Categories).
1.663     raeburn  15990: 
1.655     raeburn  15991: jsarray (reference to array of categories used to create Javascript arrays for
                   15992:          Domain Coordinator interface for editing Course Categories).
                   15993: 
                   15994: Returns: nothing
                   15995: 
                   15996: Side effects: populates cats, idx and jsarray. 
                   15997: 
                   15998: =cut
                   15999: 
                   16000: sub gather_categories {
                   16001:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16002:     my %counters;
                   16003:     my $num = 0;
                   16004:     foreach my $item (keys(%{$categories})) {
                   16005:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16006:         if ($container eq '' && $depth == 0) {
                   16007:             $cats->[$depth][$categories->{$item}] = $cat;
                   16008:         } else {
                   16009:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16010:         }
                   16011:         my ($escitem,$tail) = split(/:/,$item,2);
                   16012:         if ($counters{$tail} eq '') {
                   16013:             $counters{$tail} = $num;
                   16014:             $num ++;
                   16015:         }
                   16016:         if (ref($idx) eq 'HASH') {
                   16017:             $idx->{$item} = $counters{$tail};
                   16018:         }
                   16019:         if (ref($jsarray) eq 'ARRAY') {
                   16020:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16021:         }
                   16022:     }
                   16023:     return;
                   16024: }
                   16025: 
                   16026: =pod
                   16027: 
                   16028: =item * &extract_categories()
                   16029: 
                   16030: Used to generate breadcrumb trails for course categories.
                   16031: 
                   16032: Inputs:
1.663     raeburn  16033: 
1.655     raeburn  16034: categories (reference to hash of category definitions).
1.663     raeburn  16035: 
1.655     raeburn  16036: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16037:       categories and subcategories).
1.663     raeburn  16038: 
1.655     raeburn  16039: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16040: 
1.655     raeburn  16041: allitems (reference to hash - key is category key 
                   16042:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16043: 
1.655     raeburn  16044: idx (reference to hash of counters used in Domain Coordinator interface for
                   16045:       editing Course Categories).
1.663     raeburn  16046: 
1.655     raeburn  16047: jsarray (reference to array of categories used to create Javascript arrays for
                   16048:          Domain Coordinator interface for editing Course Categories).
                   16049: 
1.665     raeburn  16050: subcats (reference to hash of arrays containing all subcategories within each 
                   16051:          category, -recursive)
                   16052: 
1.1321    raeburn  16053: maxd (reference to hash used to hold max depth for all top-level categories).
                   16054: 
1.655     raeburn  16055: Returns: nothing
                   16056: 
                   16057: Side effects: populates trails and allitems hash references.
                   16058: 
                   16059: =cut
                   16060: 
                   16061: sub extract_categories {
1.1321    raeburn  16062:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16063:     if (ref($categories) eq 'HASH') {
                   16064:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16065:         if (ref($cats->[0]) eq 'ARRAY') {
                   16066:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16067:                 my $name = $cats->[0][$i];
                   16068:                 my $item = &escape($name).'::0';
                   16069:                 my $trailstr;
                   16070:                 if ($name eq 'instcode') {
                   16071:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16072:                 } elsif ($name eq 'communities') {
                   16073:                     $trailstr = &mt('Communities');
1.1239    raeburn  16074:                 } elsif ($name eq 'placement') {
                   16075:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16076:                 } else {
                   16077:                     $trailstr = $name;
                   16078:                 }
                   16079:                 if ($allitems->{$item} eq '') {
                   16080:                     push(@{$trails},$trailstr);
                   16081:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16082:                 }
                   16083:                 my @parents = ($name);
                   16084:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16085:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16086:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16087:                         if (ref($subcats) eq 'HASH') {
                   16088:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16089:                         }
1.1321    raeburn  16090:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16091:                     }
                   16092:                 } else {
                   16093:                     if (ref($subcats) eq 'HASH') {
                   16094:                         $subcats->{$item} = [];
1.655     raeburn  16095:                     }
1.1321    raeburn  16096:                     if (ref($maxd) eq 'HASH') {
                   16097:                         $maxd->{$name} = 1;
                   16098:                     }
1.655     raeburn  16099:                 }
                   16100:             }
                   16101:         }
                   16102:     }
                   16103:     return;
                   16104: }
                   16105: 
                   16106: =pod
                   16107: 
1.1162    raeburn  16108: =item * &recurse_categories()
1.655     raeburn  16109: 
                   16110: Recursively used to generate breadcrumb trails for course categories.
                   16111: 
                   16112: Inputs:
1.663     raeburn  16113: 
1.655     raeburn  16114: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16115:       categories and subcategories).
1.663     raeburn  16116: 
1.655     raeburn  16117: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16118: 
                   16119: category (current course category, for which breadcrumb trail is being generated).
                   16120: 
                   16121: trails (reference to array of breadcrumb trails for each category).
                   16122: 
1.655     raeburn  16123: allitems (reference to hash - key is category key
                   16124:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16125: 
1.655     raeburn  16126: parents (array containing containers directories for current category, 
                   16127:          back to top level). 
                   16128: 
                   16129: Returns: nothing
                   16130: 
                   16131: Side effects: populates trails and allitems hash references
                   16132: 
                   16133: =cut
                   16134: 
                   16135: sub recurse_categories {
1.1321    raeburn  16136:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16137:     my $shallower = $depth - 1;
                   16138:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16139:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16140:             my $name = $cats->[$depth]{$category}[$k];
                   16141:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16142:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16143:             if ($allitems->{$item} eq '') {
                   16144:                 push(@{$trails},$trailstr);
                   16145:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16146:             }
                   16147:             my $deeper = $depth+1;
                   16148:             push(@{$parents},$category);
1.665     raeburn  16149:             if (ref($subcats) eq 'HASH') {
                   16150:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16151:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16152:                     my $higher;
                   16153:                     if ($j > 0) {
                   16154:                         $higher = &escape($parents->[$j]).':'.
                   16155:                                   &escape($parents->[$j-1]).':'.$j;
                   16156:                     } else {
                   16157:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16158:                     }
                   16159:                     push(@{$subcats->{$higher}},$subcat);
                   16160:                 }
                   16161:             }
                   16162:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16163:                                 $subcats,$maxd);
1.655     raeburn  16164:             pop(@{$parents});
                   16165:         }
                   16166:     } else {
                   16167:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16168:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16169:         if ($allitems->{$item} eq '') {
                   16170:             push(@{$trails},$trailstr);
                   16171:             $allitems->{$item} = scalar(@{$trails})-1;
                   16172:         }
1.1321    raeburn  16173:         if (ref($maxd) eq 'HASH') {
                   16174:             if ($depth > $maxd->{$parents->[0]}) {
                   16175:                 $maxd->{$parents->[0]} = $depth;
                   16176:             }
                   16177:         }
1.655     raeburn  16178:     }
                   16179:     return;
                   16180: }
                   16181: 
1.663     raeburn  16182: =pod
                   16183: 
1.1162    raeburn  16184: =item * &assign_categories_table()
1.663     raeburn  16185: 
                   16186: Create a datatable for display of hierarchical categories in a domain,
                   16187: with checkboxes to allow a course to be categorized. 
                   16188: 
                   16189: Inputs:
                   16190: 
                   16191: cathash - reference to hash of categories defined for the domain (from
                   16192:           configuration.db)
                   16193: 
                   16194: currcat - scalar with an & separated list of categories assigned to a course. 
                   16195: 
1.919     raeburn  16196: type    - scalar contains course type (Course or Community).
                   16197: 
1.1260    raeburn  16198: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16199:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16200: 
1.663     raeburn  16201: Returns: $output (markup to be displayed) 
                   16202: 
                   16203: =cut
                   16204: 
                   16205: sub assign_categories_table {
1.1259    raeburn  16206:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16207:     my $output;
                   16208:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16209:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16210:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16211:         $maxdepth = scalar(@cats);
                   16212:         if (@cats > 0) {
                   16213:             my $itemcount = 0;
                   16214:             if (ref($cats[0]) eq 'ARRAY') {
                   16215:                 my @currcategories;
                   16216:                 if ($currcat ne '') {
                   16217:                     @currcategories = split('&',$currcat);
                   16218:                 }
1.919     raeburn  16219:                 my $table;
1.663     raeburn  16220:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16221:                     my $parent = $cats[0][$i];
1.919     raeburn  16222:                     next if ($parent eq 'instcode');
                   16223:                     if ($type eq 'Community') {
                   16224:                         next unless ($parent eq 'communities');
1.1239    raeburn  16225:                     } elsif ($type eq 'Placement') {
                   16226:                         next unless ($parent eq 'placement');
1.919     raeburn  16227:                     } else {
1.1239    raeburn  16228:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16229:                     }
1.663     raeburn  16230:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16231:                     my $item = &escape($parent).'::0';
                   16232:                     my $checked = '';
                   16233:                     if (@currcategories > 0) {
                   16234:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16235:                             $checked = ' checked="checked"';
1.663     raeburn  16236:                         }
                   16237:                     }
1.919     raeburn  16238:                     my $parent_title = $parent;
                   16239:                     if ($parent eq 'communities') {
                   16240:                         $parent_title = &mt('Communities');
1.1239    raeburn  16241:                     } elsif ($parent eq 'placement') {
                   16242:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16243:                     }
                   16244:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16245:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16246:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16247:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16248:                     my $depth = 1;
                   16249:                     push(@path,$parent);
1.1259    raeburn  16250:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16251:                     pop(@path);
1.919     raeburn  16252:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16253:                     $itemcount ++;
                   16254:                 }
1.919     raeburn  16255:                 if ($itemcount) {
                   16256:                     $output = &Apache::loncommon::start_data_table().
                   16257:                               $table.
                   16258:                               &Apache::loncommon::end_data_table();
                   16259:                 }
1.663     raeburn  16260:             }
                   16261:         }
                   16262:     }
                   16263:     return $output;
                   16264: }
                   16265: 
                   16266: =pod
                   16267: 
1.1162    raeburn  16268: =item * &assign_category_rows()
1.663     raeburn  16269: 
                   16270: Create a datatable row for display of nested categories in a domain,
                   16271: with checkboxes to allow a course to be categorized,called recursively.
                   16272: 
                   16273: Inputs:
                   16274: 
                   16275: itemcount - track row number for alternating colors
                   16276: 
                   16277: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16278:       categories and subcategories.
                   16279: 
                   16280: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16281: 
                   16282: parent - parent of current category item
                   16283: 
                   16284: path - Array containing all categories back up through the hierarchy from the
                   16285:        current category to the top level.
                   16286: 
                   16287: currcategories - reference to array of current categories assigned to the course
                   16288: 
1.1260    raeburn  16289: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16290:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16291: 
1.663     raeburn  16292: Returns: $output (markup to be displayed).
                   16293: 
                   16294: =cut
                   16295: 
                   16296: sub assign_category_rows {
1.1259    raeburn  16297:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16298:     my ($text,$name,$item,$chgstr);
                   16299:     if (ref($cats) eq 'ARRAY') {
                   16300:         my $maxdepth = scalar(@{$cats});
                   16301:         if (ref($cats->[$depth]) eq 'HASH') {
                   16302:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16303:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16304:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16305:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16306:                 for (my $j=0; $j<$numchildren; $j++) {
                   16307:                     $name = $cats->[$depth]{$parent}[$j];
                   16308:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16309:                     my $deeper = $depth+1;
                   16310:                     my $checked = '';
                   16311:                     if (ref($currcategories) eq 'ARRAY') {
                   16312:                         if (@{$currcategories} > 0) {
                   16313:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16314:                                 $checked = ' checked="checked"';
1.663     raeburn  16315:                             }
                   16316:                         }
                   16317:                     }
1.664     raeburn  16318:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16319:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16320:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16321:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16322:                              '</td><td>';
1.663     raeburn  16323:                     if (ref($path) eq 'ARRAY') {
                   16324:                         push(@{$path},$name);
1.1259    raeburn  16325:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16326:                         pop(@{$path});
                   16327:                     }
                   16328:                     $text .= '</td></tr>';
                   16329:                 }
                   16330:                 $text .= '</table></td>';
                   16331:             }
                   16332:         }
                   16333:     }
                   16334:     return $text;
                   16335: }
                   16336: 
1.1181    raeburn  16337: =pod
                   16338: 
                   16339: =back
                   16340: 
                   16341: =cut
                   16342: 
1.655     raeburn  16343: ############################################################
                   16344: ############################################################
                   16345: 
                   16346: 
1.443     albertel 16347: sub commit_customrole {
1.664     raeburn  16348:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16349:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16350:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16351:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16352:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16353:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16354:                  '</b><br />';
                   16355:     return $output;
                   16356: }
                   16357: 
                   16358: sub commit_standardrole {
1.1116    raeburn  16359:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16360:     my ($output,$logmsg,$linefeed);
                   16361:     if ($context eq 'auto') {
                   16362:         $linefeed = "\n";
                   16363:     } else {
                   16364:         $linefeed = "<br />\n";
                   16365:     }  
1.443     albertel 16366:     if ($three eq 'st') {
1.541     raeburn  16367:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  16368:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16369:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16370:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16371:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16372:         } else {
1.541     raeburn  16373:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16374:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16375:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16376:             if ($context eq 'auto') {
                   16377:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16378:             } else {
                   16379:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16380:                &mt('Add to classlist').': <b>ok</b>';
                   16381:             }
                   16382:             $output .= $linefeed;
1.443     albertel 16383:         }
                   16384:     } else {
                   16385:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16386:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16387:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16388:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16389:         if ($context eq 'auto') {
                   16390:             $output .= $result.$linefeed;
                   16391:         } else {
                   16392:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16393:         }
1.443     albertel 16394:     }
                   16395:     return $output;
                   16396: }
                   16397: 
                   16398: sub commit_studentrole {
1.1116    raeburn  16399:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16400:         $credits) = @_;
1.626     raeburn  16401:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16402:     if ($context eq 'auto') {
                   16403:         $linefeed = "\n";
                   16404:     } else {
                   16405:         $linefeed = '<br />'."\n";
                   16406:     }
1.443     albertel 16407:     if (defined($one) && defined($two)) {
                   16408:         my $cid=$one.'_'.$two;
                   16409:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16410:         my $secchange = 0;
                   16411:         my $expire_role_result;
                   16412:         my $modify_section_result;
1.628     raeburn  16413:         if ($oldsec ne '-1') { 
                   16414:             if ($oldsec ne $sec) {
1.443     albertel 16415:                 $secchange = 1;
1.628     raeburn  16416:                 my $now = time;
1.443     albertel 16417:                 my $uurl='/'.$cid;
                   16418:                 $uurl=~s/\_/\//g;
                   16419:                 if ($oldsec) {
                   16420:                     $uurl.='/'.$oldsec;
                   16421:                 }
1.626     raeburn  16422:                 $oldsecurl = $uurl;
1.628     raeburn  16423:                 $expire_role_result = 
1.652     raeburn  16424:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  16425:                 if ($env{'request.course.sec'} ne '') { 
                   16426:                     if ($expire_role_result eq 'refused') {
                   16427:                         my @roles = ('st');
                   16428:                         my @statuses = ('previous');
                   16429:                         my @roledoms = ($one);
                   16430:                         my $withsec = 1;
                   16431:                         my %roleshash = 
                   16432:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16433:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16434:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16435:                             my ($oldstart,$oldend) = 
                   16436:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16437:                             if ($oldend > 0 && $oldend <= $now) {
                   16438:                                 $expire_role_result = 'ok';
                   16439:                             }
                   16440:                         }
                   16441:                     }
                   16442:                 }
1.443     albertel 16443:                 $result = $expire_role_result;
                   16444:             }
                   16445:         }
                   16446:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16447:             $modify_section_result = 
                   16448:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16449:                                                            undef,undef,undef,$sec,
                   16450:                                                            $end,$start,'','',$cid,
                   16451:                                                            '',$context,$credits);
1.443     albertel 16452:             if ($modify_section_result =~ /^ok/) {
                   16453:                 if ($secchange == 1) {
1.628     raeburn  16454:                     if ($sec eq '') {
                   16455:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16456:                     } else {
                   16457:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16458:                     }
1.443     albertel 16459:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16460:                     if ($sec eq '') {
                   16461:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16462:                     } else {
                   16463:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16464:                     }
1.443     albertel 16465:                 } else {
1.628     raeburn  16466:                     if ($sec eq '') {
                   16467:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16468:                     } else {
                   16469:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16470:                     }
1.443     albertel 16471:                 }
                   16472:             } else {
1.1115    raeburn  16473:                 if ($secchange) { 
1.628     raeburn  16474:                     $$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;
                   16475:                 } else {
                   16476:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16477:                 }
1.443     albertel 16478:             }
                   16479:             $result = $modify_section_result;
                   16480:         } elsif ($secchange == 1) {
1.628     raeburn  16481:             if ($oldsec eq '') {
1.1103    raeburn  16482:                 $$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  16483:             } else {
                   16484:                 $$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;
                   16485:             }
1.626     raeburn  16486:             if ($expire_role_result eq 'refused') {
                   16487:                 my $newsecurl = '/'.$cid;
                   16488:                 $newsecurl =~ s/\_/\//g;
                   16489:                 if ($sec ne '') {
                   16490:                     $newsecurl.='/'.$sec;
                   16491:                 }
                   16492:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16493:                     if ($sec eq '') {
                   16494:                         $$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;
                   16495:                     } else {
                   16496:                         $$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;
                   16497:                     }
                   16498:                 }
                   16499:             }
1.443     albertel 16500:         }
                   16501:     } else {
1.626     raeburn  16502:         $$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 16503:         $result = "error: incomplete course id\n";
                   16504:     }
                   16505:     return $result;
                   16506: }
                   16507: 
1.1108    raeburn  16508: sub show_role_extent {
                   16509:     my ($scope,$context,$role) = @_;
                   16510:     $scope =~ s{^/}{};
                   16511:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16512:     push(@courseroles,'co');
                   16513:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16514:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16515:         $scope =~ s{/}{_};
                   16516:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16517:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16518:         my ($audom,$auname) = split(/\//,$scope);
                   16519:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16520:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16521:     } else {
                   16522:         $scope =~ s{/$}{};
                   16523:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16524:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16525:     }
                   16526: }
                   16527: 
1.443     albertel 16528: ############################################################
                   16529: ############################################################
                   16530: 
1.566     albertel 16531: sub check_clone {
1.578     raeburn  16532:     my ($args,$linefeed) = @_;
1.566     albertel 16533:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16534:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16535:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16536:     my $clonetitle;
                   16537:     my @clonemsg;
1.566     albertel 16538:     my $can_clone = 0;
1.944     raeburn  16539:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16540:     if ($lctype ne 'community') {
                   16541:         $lctype = 'course';
                   16542:     }
1.566     albertel 16543:     if ($clonehome eq 'no_host') {
1.944     raeburn  16544:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16545:             push(@clonemsg,({
                   16546:                               mt => 'No new community created.',
                   16547:                               args => [],
                   16548:                             },
                   16549:                             {
                   16550:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16551:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16552:                             }));
1.908     raeburn  16553:         } else {
1.1344    raeburn  16554:             push(@clonemsg,({
                   16555:                               mt => 'No new course created.',
                   16556:                               args => [],
                   16557:                             },
                   16558:                             {
                   16559:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16560:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16561:                             }));
                   16562:         }
1.566     albertel 16563:     } else {
                   16564: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16565:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16566:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16567:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16568:                 push(@clonemsg,({
                   16569:                                   mt => 'No new community created.',
                   16570:                                   args => [],
                   16571:                                 },
                   16572:                                 {
                   16573:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16574:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16575:                                 }));
                   16576:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16577:             }
                   16578:         }
1.1262    raeburn  16579: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16580:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16581: 	    $can_clone = 1;
                   16582: 	} else {
1.1221    raeburn  16583: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16584: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16585:             if ($clonehash{'cloners'} eq '') {
                   16586:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16587:                 if ($domdefs{'canclone'}) {
                   16588:                     unless ($domdefs{'canclone'} eq 'none') {
                   16589:                         if ($domdefs{'canclone'} eq 'domain') {
                   16590:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16591:                                 $can_clone = 1;
                   16592:                             }
                   16593:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16594:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16595:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16596:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16597:                                 $can_clone = 1;
                   16598:                             }
                   16599:                         }
                   16600:                     }
                   16601:                 }
1.578     raeburn  16602:             } else {
1.1221    raeburn  16603: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16604:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16605:                     $can_clone = 1;
1.1221    raeburn  16606:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16607:                     $can_clone = 1;
1.1225    raeburn  16608:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16609:                     $can_clone = 1;
1.1221    raeburn  16610:                 }
                   16611:                 unless ($can_clone) {
1.1225    raeburn  16612:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16613:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16614:                         my (%gotdomdefaults,%gotcodedefaults);
                   16615:                         foreach my $cloner (@cloners) {
                   16616:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16617:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16618:                                 my (%codedefaults,@code_order);
                   16619:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16620:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16621:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16622:                                     }
                   16623:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16624:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16625:                                     }
                   16626:                                 } else {
                   16627:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16628:                                                                             \%codedefaults,
                   16629:                                                                             \@code_order);
                   16630:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16631:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16632:                                 }
                   16633:                                 if (@code_order > 0) {
                   16634:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16635:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16636:                                                                                 $args->{'crscode'})) {
                   16637:                                         $can_clone = 1;
                   16638:                                         last;
                   16639:                                     }
                   16640:                                 }
                   16641:                             }
                   16642:                         }
                   16643:                     }
1.1225    raeburn  16644:                 }
                   16645:             }
                   16646:             unless ($can_clone) {
                   16647:                 my $ccrole = 'cc';
                   16648:                 if ($args->{'crstype'} eq 'Community') {
                   16649:                     $ccrole = 'co';
                   16650:                 }
                   16651: 	        my %roleshash =
                   16652: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16653: 					          $args->{'ccdomain'},
                   16654:                                                   'userroles',['active'],[$ccrole],
                   16655: 					          [$args->{'clonedomain'}]);
                   16656: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16657:                     $can_clone = 1;
                   16658:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16659:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16660:                     $can_clone = 1;
1.1221    raeburn  16661:                 }
                   16662:             }
                   16663:             unless ($can_clone) {
                   16664:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16665:                     push(@clonemsg,({
                   16666:                                       mt => 'No new community created.',
                   16667:                                       args => [],
                   16668:                                     },
                   16669:                                     {
                   16670:                                       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]).',
                   16671:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16672:                                     }));
1.942     raeburn  16673:                 } else {
1.1344    raeburn  16674:                     push(@clonemsg,({
                   16675:                                       mt => 'No new course created.',
                   16676:                                       args => [],
                   16677:                                     },
                   16678:                                     {
                   16679:                                       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]).',
                   16680:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16681:                                     }));
1.1221    raeburn  16682:                 }
1.566     albertel 16683: 	    }
1.578     raeburn  16684:         }
1.566     albertel 16685:     }
1.1344    raeburn  16686:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16687: }
                   16688: 
1.444     albertel 16689: sub construct_course {
1.1262    raeburn  16690:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16691:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16692:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16693:     my $linefeed =  '<br />'."\n";
                   16694:     if ($context eq 'auto') {
                   16695:         $linefeed = "\n";
                   16696:     }
1.566     albertel 16697: 
                   16698: #
                   16699: # Are we cloning?
                   16700: #
1.1344    raeburn  16701:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16702:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16703: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16704:         if (!$can_clone) {
1.1344    raeburn  16705: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16706: 	}
                   16707:     }
                   16708: 
1.444     albertel 16709: #
                   16710: # Open course
                   16711: #
1.1239    raeburn  16712:     my $showncrstype;
                   16713:     if ($args->{'crstype'} eq 'Placement') {
                   16714:         $showncrstype = 'placement test'; 
                   16715:     } else {  
                   16716:         $showncrstype = lc($args->{'crstype'});
                   16717:     }
1.444     albertel 16718:     my %cenv=();
                   16719:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16720:                                              $args->{'cdescr'},
                   16721:                                              $args->{'curl'},
                   16722:                                              $args->{'course_home'},
                   16723:                                              $args->{'nonstandard'},
                   16724:                                              $args->{'crscode'},
                   16725:                                              $args->{'ccuname'}.':'.
                   16726:                                              $args->{'ccdomain'},
1.882     raeburn  16727:                                              $args->{'crstype'},
1.1344    raeburn  16728:                                              $cnum,$context,$category,
                   16729:                                              $callercontext);
1.444     albertel 16730: 
                   16731:     # Note: The testing routines depend on this being output; see 
                   16732:     # Utils::Course. This needs to at least be output as a comment
                   16733:     # if anyone ever decides to not show this, and Utils::Course::new
                   16734:     # will need to be suitably modified.
1.1344    raeburn  16735:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16736:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16737:     } else {
                   16738:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16739:     }
1.943     raeburn  16740:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16741:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16742:     }
                   16743: 
1.444     albertel 16744: #
                   16745: # Check if created correctly
                   16746: #
1.479     albertel 16747:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16748:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16749:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16750:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16751:             $outcome .= &mt_user($user_lh,
                   16752:                             'Course creation failed, unrecognized course home server.');
                   16753:         } else {
                   16754:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16755:         }
                   16756:         $outcome .= $linefeed;
                   16757:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16758:     }
1.541     raeburn  16759:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16760: 
1.444     albertel 16761: #
1.566     albertel 16762: # Do the cloning
                   16763: #   
1.1344    raeburn  16764:     my @clonemsg;
1.566     albertel 16765:     if ($can_clone && $cloneid) {
1.1344    raeburn  16766:         push(@clonemsg,
                   16767:                       {
                   16768:                           mt => 'Created [_1] by cloning from [_2]',
                   16769:                           args => [$showncrstype,$clonetitle],
                   16770:                       });
1.566     albertel 16771: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16772: # Copy all files
1.1344    raeburn  16773:         my @info =
                   16774: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16775: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16776:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16777:                                                      $args->{'tinyurls'});
                   16778:         if (@info) {
                   16779:             push(@clonemsg,@info);
                   16780:         }
1.444     albertel 16781: # Restore URL
1.566     albertel 16782: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16783: # Restore title
1.566     albertel 16784: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16785: # Restore creation date, creator and creation context.
                   16786:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16787:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16788:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16789: # Mark as cloned
1.566     albertel 16790: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16791: # Need to clone grading mode
                   16792:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16793:         $cenv{'grading'}=$newenv{'grading'};
                   16794: # Do not clone these environment entries
                   16795:         &Apache::lonnet::del('environment',
                   16796:                   ['default_enrollment_start_date',
                   16797:                    'default_enrollment_end_date',
                   16798:                    'question.email',
                   16799:                    'policy.email',
                   16800:                    'comment.email',
                   16801:                    'pch.users.denied',
1.725     raeburn  16802:                    'plc.users.denied',
                   16803:                    'hidefromcat',
1.1121    raeburn  16804:                    'checkforpriv',
1.1355    raeburn  16805:                    'categories'],
1.638     www      16806:                    $$crsudom,$$crsunum);
1.1170    raeburn  16807:         if ($args->{'textbook'}) {
                   16808:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16809:         }
1.444     albertel 16810:     }
1.566     albertel 16811: 
1.444     albertel 16812: #
                   16813: # Set environment (will override cloned, if existing)
                   16814: #
                   16815:     my @sections = ();
                   16816:     my @xlists = ();
                   16817:     if ($args->{'crstype'}) {
                   16818:         $cenv{'type'}=$args->{'crstype'};
                   16819:     }
1.1371    raeburn  16820:     if ($args->{'lti'}) {
                   16821:         $cenv{'internal.lti'}=$args->{'lti'};
                   16822:     }
1.444     albertel 16823:     if ($args->{'crsid'}) {
                   16824:         $cenv{'courseid'}=$args->{'crsid'};
                   16825:     }
                   16826:     if ($args->{'crscode'}) {
                   16827:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16828:     }
                   16829:     if ($args->{'crsquota'} ne '') {
                   16830:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16831:     } else {
                   16832:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16833:     }
                   16834:     if ($args->{'ccuname'}) {
                   16835:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16836:                                         ':'.$args->{'ccdomain'};
                   16837:     } else {
                   16838:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16839:     }
1.1116    raeburn  16840:     if ($args->{'defaultcredits'}) {
                   16841:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16842:     }
1.444     albertel 16843:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16844:     if ($args->{'crssections'}) {
                   16845:         $cenv{'internal.sectionnums'} = '';
                   16846:         if ($args->{'crssections'} =~ m/,/) {
                   16847:             @sections = split/,/,$args->{'crssections'};
                   16848:         } else {
                   16849:             $sections[0] = $args->{'crssections'};
                   16850:         }
                   16851:         if (@sections > 0) {
                   16852:             foreach my $item (@sections) {
                   16853:                 my ($sec,$gp) = split/:/,$item;
                   16854:                 my $class = $args->{'crscode'}.$sec;
                   16855:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16856:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16857:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16858:                     push(@badclasses,$class);
1.444     albertel 16859:                 }
                   16860:             }
                   16861:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16862:         }
                   16863:     }
                   16864: # do not hide course coordinator from staff listing, 
                   16865: # even if privileged
                   16866:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16867: # add course coordinator's domain to domains to check for privileged users
                   16868: # if different to course domain
                   16869:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16870:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16871:     }
1.444     albertel 16872: # add crosslistings
                   16873:     if ($args->{'crsxlist'}) {
                   16874:         $cenv{'internal.crosslistings'}='';
                   16875:         if ($args->{'crsxlist'} =~ m/,/) {
                   16876:             @xlists = split/,/,$args->{'crsxlist'};
                   16877:         } else {
                   16878:             $xlists[0] = $args->{'crsxlist'};
                   16879:         }
                   16880:         if (@xlists > 0) {
                   16881:             foreach my $item (@xlists) {
                   16882:                 my ($xl,$gp) = split/:/,$item;
                   16883:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16884:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16885:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16886:                     push(@badclasses,$xl);
1.444     albertel 16887:                 }
                   16888:             }
                   16889:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16890:         }
                   16891:     }
                   16892:     if ($args->{'autoadds'}) {
                   16893:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16894:     }
                   16895:     if ($args->{'autodrops'}) {
                   16896:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16897:     }
                   16898: # check for notification of enrollment changes
                   16899:     my @notified = ();
                   16900:     if ($args->{'notify_owner'}) {
                   16901:         if ($args->{'ccuname'} ne '') {
                   16902:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16903:         }
                   16904:     }
                   16905:     if ($args->{'notify_dc'}) {
                   16906:         if ($uname ne '') { 
1.630     raeburn  16907:             push(@notified,$uname.':'.$udom);
1.444     albertel 16908:         }
                   16909:     }
                   16910:     if (@notified > 0) {
                   16911:         my $notifylist;
                   16912:         if (@notified > 1) {
                   16913:             $notifylist = join(',',@notified);
                   16914:         } else {
                   16915:             $notifylist = $notified[0];
                   16916:         }
                   16917:         $cenv{'internal.notifylist'} = $notifylist;
                   16918:     }
                   16919:     if (@badclasses > 0) {
                   16920:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16921:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16922:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16923:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16924:         );
1.1264    raeburn  16925:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16926:                            &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  16927:         if ($context eq 'auto') {
                   16928:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16929:         } else {
1.566     albertel 16930:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16931:         }
                   16932:         foreach my $item (@badclasses) {
1.541     raeburn  16933:             if ($context eq 'auto') {
1.1261    raeburn  16934:                 $outcome .= " - $item\n";
1.541     raeburn  16935:             } else {
1.1261    raeburn  16936:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16937:             }
1.1261    raeburn  16938:         }
                   16939:         if ($context eq 'auto') {
                   16940:             $outcome .= $linefeed;
                   16941:         } else {
                   16942:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16943:         } 
1.444     albertel 16944:     }
                   16945:     if ($args->{'no_end_date'}) {
                   16946:         $args->{'endaccess'} = 0;
                   16947:     }
                   16948:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16949:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16950:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16951:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16952:     if ($args->{'showphotos'}) {
                   16953:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16954:     }
                   16955:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16956:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16957:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16958:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16959:             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'); 
                   16960:             if ($context eq 'auto') {
                   16961:                 $outcome .= $krb_msg;
                   16962:             } else {
1.566     albertel 16963:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16964:             }
                   16965:             $outcome .= $linefeed;
1.444     albertel 16966:         }
                   16967:     }
                   16968:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16969:        if ($args->{'setpolicy'}) {
                   16970:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16971:        }
                   16972:        if ($args->{'setcontent'}) {
                   16973:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16974:        }
1.1251    raeburn  16975:        if ($args->{'setcomment'}) {
                   16976:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16977:        }
1.444     albertel 16978:     }
                   16979:     if ($args->{'reshome'}) {
                   16980: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16981: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16982:     }
                   16983: #
                   16984: # course has keyed access
                   16985: #
                   16986:     if ($args->{'setkeys'}) {
                   16987:        $cenv{'keyaccess'}='yes';
                   16988:     }
                   16989: # if specified, key authority is not course, but user
                   16990: # only active if keyaccess is yes
                   16991:     if ($args->{'keyauth'}) {
1.487     albertel 16992: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16993: 	$user = &LONCAPA::clean_username($user);
                   16994: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16995: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16996: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16997: 	}
                   16998:     }
                   16999: 
1.1166    raeburn  17000: #
1.1167    raeburn  17001: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17002: #
                   17003:     if ($args->{'uniquecode'}) {
                   17004:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17005:         if ($code) {
                   17006:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17007:             my %crsinfo =
                   17008:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17009:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17010:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17011:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17012:             } 
1.1166    raeburn  17013:             if (ref($coderef)) {
                   17014:                 $$coderef = $code;
                   17015:             }
                   17016:         }
                   17017:     }
                   17018: 
1.444     albertel 17019:     if ($args->{'disresdis'}) {
                   17020:         $cenv{'pch.roles.denied'}='st';
                   17021:     }
                   17022:     if ($args->{'disablechat'}) {
                   17023:         $cenv{'plc.roles.denied'}='st';
                   17024:     }
                   17025: 
                   17026:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17027:     # course
                   17028:     $cenv{'course.helper.not.run'} = 1;
                   17029:     #
                   17030:     # Use new Randomseed
                   17031:     #
                   17032:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17033:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17034:     #
                   17035:     # The encryption code and receipt prefix for this course
                   17036:     #
                   17037:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17038:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17039:     #
                   17040:     # By default, use standard grading
                   17041:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17042: 
1.541     raeburn  17043:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17044:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17045: #
                   17046: # Open all assignments
                   17047: #
                   17048:     if ($args->{'openall'}) {
1.1341    raeburn  17049:        my $opendate = time;
                   17050:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17051:            $opendate = $args->{'openallfrom'};
                   17052:        }
1.444     albertel 17053:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17054:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17055:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17056:        $outcome .= &mt('All assignments open starting [_1]',
                   17057:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17058:                    &Apache::lonnet::cput
                   17059:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17060:    }
                   17061: #
                   17062: # Set first page
                   17063: #
                   17064:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17065: 	    || ($cloneid)) {
                   17066: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17067: 
                   17068: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17069:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17070: 
1.444     albertel 17071:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17072:         my $title; my $url;
                   17073:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17074: 	    $title=&mt('Syllabus');
1.444     albertel 17075:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17076:         } else {
1.963     raeburn  17077:             $title=&mt('Table of Contents');
1.444     albertel 17078:             $url='/adm/navmaps';
                   17079:         }
1.445     albertel 17080: 
                   17081:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17082: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17083: 
                   17084: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17085:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17086:     }
1.566     albertel 17087: 
1.1237    raeburn  17088: # 
                   17089: # Set params for Placement Tests
                   17090: #
1.1239    raeburn  17091:     if ($args->{'crstype'} eq 'Placement') {
                   17092:        my %storecontent; 
                   17093:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17094:        my %defaults = (
                   17095:                         buttonshide   => { value => 'yes',
                   17096:                                            type => 'string_yesno',},
                   17097:                         type          => { value => 'randomizetry',
                   17098:                                            type  => 'string_questiontype',},
                   17099:                         maxtries      => { value => 1,
                   17100:                                            type => 'int_pos',},
                   17101:                         problemstatus => { value => 'no',
                   17102:                                            type  => 'string_problemstatus',},
                   17103:                       );
                   17104:        foreach my $key (keys(%defaults)) {
                   17105:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17106:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17107:        }
1.1237    raeburn  17108:        &Apache::lonnet::cput
                   17109:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17110:     }
                   17111: 
1.1344    raeburn  17112:     return (1,$outcome,\@clonemsg);
1.444     albertel 17113: }
                   17114: 
1.1166    raeburn  17115: sub make_unique_code {
                   17116:     my ($cdom,$cnum) = @_;
                   17117:     # get lock on uniquecodes db
                   17118:     my $lockhash = {
                   17119:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17120:                                                   ':'.$env{'user.domain'},
                   17121:                    };
                   17122:     my $tries = 0;
                   17123:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17124:     my ($code,$error);
                   17125:   
                   17126:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17127:         $tries ++;
                   17128:         sleep 1;
                   17129:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17130:     }
                   17131:     if ($gotlock eq 'ok') {
                   17132:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17133:         my $gotcode;
                   17134:         my $attempts = 0;
                   17135:         while ((!$gotcode) && ($attempts < 100)) {
                   17136:             $code = &generate_code();
                   17137:             if (!exists($currcodes{$code})) {
                   17138:                 $gotcode = 1;
                   17139:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17140:                     $error = 'nostore';
                   17141:                 }
                   17142:             }
                   17143:             $attempts ++;
                   17144:         }
                   17145:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17146:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17147:     } else {
                   17148:         $error = 'nolock';
                   17149:     }
                   17150:     return ($code,$error);
                   17151: }
                   17152: 
                   17153: sub generate_code {
                   17154:     my $code;
                   17155:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17156:     for (my $i=0; $i<6; $i++) {
                   17157:         my $lettnum = int (rand 2);
                   17158:         my $item = '';
                   17159:         if ($lettnum) {
                   17160:             $item = $letts[int( rand(18) )];
                   17161:         } else {
                   17162:             $item = 1+int( rand(8) );
                   17163:         }
                   17164:         $code .= $item;
                   17165:     }
                   17166:     return $code;
                   17167: }
                   17168: 
1.444     albertel 17169: ############################################################
                   17170: ############################################################
                   17171: 
1.1237    raeburn  17172: # Community, Course and Placement Test
1.378     raeburn  17173: sub course_type {
                   17174:     my ($cid) = @_;
                   17175:     if (!defined($cid)) {
                   17176:         $cid = $env{'request.course.id'};
                   17177:     }
1.404     albertel 17178:     if (defined($env{'course.'.$cid.'.type'})) {
                   17179:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17180:     } else {
                   17181:         return 'Course';
1.377     raeburn  17182:     }
                   17183: }
1.156     albertel 17184: 
1.406     raeburn  17185: sub group_term {
                   17186:     my $crstype = &course_type();
                   17187:     my %names = (
                   17188:                   'Course' => 'group',
1.865     raeburn  17189:                   'Community' => 'group',
1.1237    raeburn  17190:                   'Placement' => 'group',
1.406     raeburn  17191:                 );
                   17192:     return $names{$crstype};
                   17193: }
                   17194: 
1.902     raeburn  17195: sub course_types {
1.1310    raeburn  17196:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17197:     my %typename = (
                   17198:                          official   => 'Official course',
                   17199:                          unofficial => 'Unofficial course',
                   17200:                          community  => 'Community',
1.1165    raeburn  17201:                          textbook   => 'Textbook course',
1.1237    raeburn  17202:                          placement  => 'Placement test',
1.1310    raeburn  17203:                          lti        => 'LTI provider',
1.902     raeburn  17204:                    );
                   17205:     return (\@types,\%typename);
                   17206: }
                   17207: 
1.156     albertel 17208: sub icon {
                   17209:     my ($file)=@_;
1.505     albertel 17210:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17211:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17212:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17213:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17214: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17215: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17216: 	            $curfext.".gif") {
                   17217: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17218: 		$curfext.".gif";
                   17219: 	}
                   17220:     }
1.249     albertel 17221:     return &lonhttpdurl($iconname);
1.154     albertel 17222: } 
1.84      albertel 17223: 
1.575     albertel 17224: sub lonhttpdurl {
1.692     www      17225: #
                   17226: # Had been used for "small fry" static images on separate port 8080.
                   17227: # Modify here if lightweight http functionality desired again.
                   17228: # Currently eliminated due to increasing firewall issues.
                   17229: #
1.575     albertel 17230:     my ($url)=@_;
1.692     www      17231:     return $url;
1.215     albertel 17232: }
                   17233: 
1.213     albertel 17234: sub connection_aborted {
                   17235:     my ($r)=@_;
                   17236:     $r->print(" ");$r->rflush();
                   17237:     my $c = $r->connection;
                   17238:     return $c->aborted();
                   17239: }
                   17240: 
1.221     foxr     17241: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17242: #    strings as 'strings'.
                   17243: sub escape_single {
1.221     foxr     17244:     my ($input) = @_;
1.223     albertel 17245:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17246:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17247:     return $input;
                   17248: }
1.223     albertel 17249: 
1.222     foxr     17250: #  Same as escape_single, but escape's "'s  This 
                   17251: #  can be used for  "strings"
                   17252: sub escape_double {
                   17253:     my ($input) = @_;
                   17254:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17255:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17256:     return $input;
                   17257: }
1.223     albertel 17258:  
1.222     foxr     17259: #   Escapes the last element of a full URL.
                   17260: sub escape_url {
                   17261:     my ($url)   = @_;
1.238     raeburn  17262:     my @urlslices = split(/\//, $url,-1);
1.369     www      17263:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17264:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17265: }
1.462     albertel 17266: 
1.820     raeburn  17267: sub compare_arrays {
                   17268:     my ($arrayref1,$arrayref2) = @_;
                   17269:     my (@difference,%count);
                   17270:     @difference = ();
                   17271:     %count = ();
                   17272:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17273:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17274:         foreach my $element (keys(%count)) {
                   17275:             if ($count{$element} == 1) {
                   17276:                 push(@difference,$element);
                   17277:             }
                   17278:         }
                   17279:     }
                   17280:     return @difference;
                   17281: }
                   17282: 
1.1322    raeburn  17283: sub lon_status_items {
                   17284:     my %defaults = (
                   17285:                      E         => 100,
                   17286:                      W         => 4,
                   17287:                      N         => 1,
1.1324    raeburn  17288:                      U         => 5,
1.1322    raeburn  17289:                      threshold => 200,
                   17290:                      sysmail   => 2500,
                   17291:                    );
                   17292:     my %names = (
                   17293:                    E => 'Errors',
                   17294:                    W => 'Warnings',
                   17295:                    N => 'Notices',
1.1324    raeburn  17296:                    U => 'Unsent',
1.1322    raeburn  17297:                 );
                   17298:     return (\%defaults,\%names);
                   17299: }
                   17300: 
1.817     bisitz   17301: # -------------------------------------------------------- Initialize user login
1.462     albertel 17302: sub init_user_environment {
1.463     albertel 17303:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17304:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17305: 
                   17306:     my $public=($username eq 'public' && $domain eq 'public');
                   17307: 
1.1062    raeburn  17308:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 17309:     my $now=time;
                   17310: 
                   17311:     if ($public) {
                   17312: 	my $max_public=100;
                   17313: 	my $oldest;
                   17314: 	my $oldest_time=0;
                   17315: 	for(my $next=1;$next<=$max_public;$next++) {
                   17316: 	    if (-e $lonids."/publicuser_$next.id") {
                   17317: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17318: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17319: 		    $oldest_time=$mtime;
                   17320: 		    $oldest=$next;
                   17321: 		}
                   17322: 	    } else {
                   17323: 		$cookie="publicuser_$next";
                   17324: 		last;
                   17325: 	    }
                   17326: 	}
                   17327: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17328:     } else {
1.1275    raeburn  17329: 	# See if old ID present, if so, remove if this isn't a robot,
                   17330: 	# killing any existing non-robot sessions
1.463     albertel 17331: 	if (!$args->{'robot'}) {
                   17332: 	    opendir(DIR,$lonids);
                   17333: 	    while ($filename=readdir(DIR)) {
                   17334: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17335:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17336:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17337:                         my $linkedfile;
1.1320    raeburn  17338:                         if (exists($oldenv{'user.linkedenv'})) {
                   17339:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17340:                         }
1.1320    raeburn  17341:                         untie(%oldenv);
                   17342:                         if (unlink("$lonids/$filename")) {
                   17343:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17344:                                 if (-l "$lonids/$linkedfile.id") {
                   17345:                                     unlink("$lonids/$linkedfile.id");
                   17346:                                 }
1.1295    raeburn  17347:                             }
                   17348:                         }
                   17349:                     } else {
                   17350:                         unlink($lonids.'/'.$filename);
                   17351:                     }
1.463     albertel 17352: 		}
1.462     albertel 17353: 	    }
1.463     albertel 17354: 	    closedir(DIR);
1.1204    raeburn  17355: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17356:             my $namespace = 'nohist_courseeditor';
                   17357:             my $lockingkey = 'paste'."\0".'locked_num';
                   17358:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17359:                                                 $domain,$username);
                   17360:             if (exists($lockhash{$lockingkey})) {
                   17361:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17362:                 unless ($delresult eq 'ok') {
                   17363:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17364:                 }
                   17365:             }
1.462     albertel 17366: 	}
                   17367: # Give them a new cookie
1.463     albertel 17368: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17369: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17370: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17371:     
                   17372: # Initialize roles
                   17373: 
1.1062    raeburn  17374: 	($userroles,$firstaccenv,$timerintenv) = 
                   17375:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17376:     }
                   17377: # ------------------------------------ Check browser type and MathML capability
                   17378: 
1.1194    raeburn  17379:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17380:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17381: 
                   17382: # ------------------------------------------------------------- Get environment
                   17383: 
                   17384:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17385:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17386:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17387: 	undef(%userenv);
                   17388:     }
                   17389:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17390: 	$form->{'interface'}=$userenv{'interface'};
                   17391:     }
                   17392:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17393: 
                   17394: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17395:     foreach my $option ('interface','localpath','localres') {
                   17396:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17397:     }
                   17398: # --------------------------------------------------------- Write first profile
                   17399: 
                   17400:     {
1.1350    raeburn  17401:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17402: 	my %initial_env = 
                   17403: 	    ("user.name"          => $username,
                   17404: 	     "user.domain"        => $domain,
                   17405: 	     "user.home"          => $authhost,
                   17406: 	     "browser.type"       => $clientbrowser,
                   17407: 	     "browser.version"    => $clientversion,
                   17408: 	     "browser.mathml"     => $clientmathml,
                   17409: 	     "browser.unicode"    => $clientunicode,
                   17410: 	     "browser.os"         => $clientos,
1.1137    raeburn  17411:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17412:              "browser.info"       => $clientinfo,
1.1194    raeburn  17413:              "browser.osversion"  => $clientosversion,
1.462     albertel 17414: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17415: 	     "request.course.fn"  => '',
                   17416: 	     "request.course.uri" => '',
                   17417: 	     "request.course.sec" => '',
                   17418: 	     "request.role"       => 'cm',
                   17419: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17420: 	     "request.host"       => $ip,);
1.462     albertel 17421: 
                   17422:         if ($form->{'localpath'}) {
                   17423: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17424: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17425:         }
                   17426: 	
                   17427: 	if ($form->{'interface'}) {
                   17428: 	    $form->{'interface'}=~s/\W//gs;
                   17429: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17430: 	    $env{'browser.interface'}=$form->{'interface'};
                   17431: 	}
                   17432: 
1.1157    raeburn  17433:         if ($form->{'iptoken'}) {
                   17434:             my $lonhost = $r->dir_config('lonHostID');
                   17435:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17436:             $env{'user.noloadbalance'} = $lonhost;
                   17437:         }
                   17438: 
1.1268    raeburn  17439:         if ($form->{'noloadbalance'}) {
                   17440:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17441:             my $hosthere = $form->{'noloadbalance'};
                   17442:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17443:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17444:                 $env{'user.noloadbalance'} = $hosthere;
                   17445:             }
                   17446:         }
                   17447: 
1.1016    raeburn  17448:         unless ($domain eq 'public') {
1.1273    raeburn  17449:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17450:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17451: 
1.1387    raeburn  17452:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
1.1273    raeburn  17453:                 $userenv{'availabletools.'.$tool} = 
                   17454:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17455:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17456:             }
1.980     raeburn  17457: 
1.1311    raeburn  17458:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17459:                 $userenv{'canrequest.'.$crstype} =
                   17460:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17461:                                                       'reload','requestcourses',
                   17462:                                                       \%userenv,\%domdef,\%is_adv);
                   17463:             }
1.724     raeburn  17464: 
1.1273    raeburn  17465:             $userenv{'canrequest.author'} =
                   17466:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17467:                                                   'reload','requestauthor',
1.980     raeburn  17468:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17469:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17470:                                                  $domain,$username);
                   17471:             my $reqstatus = $reqauthor{'author_status'};
                   17472:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17473:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17474:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17475:                                                       $reqauthor{'author'}{'timestamp'};
                   17476:                 }
1.1092    raeburn  17477:             }
1.1287    raeburn  17478:             my ($types,$typename) = &course_types();
                   17479:             if (ref($types) eq 'ARRAY') {
                   17480:                 my @options = ('approval','validate','autolimit');
                   17481:                 my $optregex = join('|',@options);
                   17482:                 my (%willtrust,%trustchecked);
                   17483:                 foreach my $type (@{$types}) {
                   17484:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17485:                     if ($dom_str ne '') {
                   17486:                         my $updatedstr = '';
                   17487:                         my @possdomains = split(',',$dom_str);
                   17488:                         foreach my $entry (@possdomains) {
                   17489:                             my ($extdom,$extopt) = split(':',$entry);
                   17490:                             unless ($trustchecked{$extdom}) {
                   17491:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17492:                                 $trustchecked{$extdom} = 1;
                   17493:                             }
                   17494:                             if ($willtrust{$extdom}) {
                   17495:                                 $updatedstr .= $entry.',';
                   17496:                             }
                   17497:                         }
                   17498:                         $updatedstr =~ s/,$//;
                   17499:                         if ($updatedstr) {
                   17500:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17501:                         } else {
                   17502:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17503:                         }
                   17504:                     }
                   17505:                 }
                   17506:             }
1.1092    raeburn  17507:         }
1.462     albertel 17508: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17509: 
1.462     albertel 17510: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17511: 		 &GDBM_WRCREAT(),0640)) {
                   17512: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17513: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17514: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17515:             if (ref($firstaccenv) eq 'HASH') {
                   17516:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17517:             }
                   17518:             if (ref($timerintenv) eq 'HASH') {
                   17519:                 &_add_to_env(\%disk_env,$timerintenv);
                   17520:             }
1.463     albertel 17521: 	    if (ref($args->{'extra_env'})) {
                   17522: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17523: 	    }
1.462     albertel 17524: 	    untie(%disk_env);
                   17525: 	} else {
1.705     tempelho 17526: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17527: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17528: 	    return 'error: '.$!;
                   17529: 	}
                   17530:     }
                   17531:     $env{'request.role'}='cm';
                   17532:     $env{'request.role.adv'}=$env{'user.adv'};
                   17533:     $env{'browser.type'}=$clientbrowser;
                   17534: 
                   17535:     return $cookie;
                   17536: 
                   17537: }
                   17538: 
                   17539: sub _add_to_env {
                   17540:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17541:     if (ref($env_data) eq 'HASH') {
                   17542:         while (my ($key,$value) = each(%$env_data)) {
                   17543: 	    $idf->{$prefix.$key} = $value;
                   17544: 	    $env{$prefix.$key}   = $value;
                   17545:         }
1.462     albertel 17546:     }
                   17547: }
                   17548: 
1.685     tempelho 17549: # --- Get the symbolic name of a problem and the url
                   17550: sub get_symb {
                   17551:     my ($request,$silent) = @_;
1.726     raeburn  17552:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17553:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17554:     if ($symb eq '') {
                   17555:         if (!$silent) {
1.1071    raeburn  17556:             if (ref($request)) { 
                   17557:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17558:             }
1.685     tempelho 17559:             return ();
                   17560:         }
                   17561:     }
                   17562:     &Apache::lonenc::check_decrypt(\$symb);
                   17563:     return ($symb);
                   17564: }
                   17565: 
                   17566: # --------------------------------------------------------------Get annotation
                   17567: 
                   17568: sub get_annotation {
                   17569:     my ($symb,$enc) = @_;
                   17570: 
                   17571:     my $key = $symb;
                   17572:     if (!$enc) {
                   17573:         $key =
                   17574:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17575:     }
                   17576:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17577:     return $annotation{$key};
                   17578: }
                   17579: 
                   17580: sub clean_symb {
1.731     raeburn  17581:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17582: 
                   17583:     &Apache::lonenc::check_decrypt(\$symb);
                   17584:     my $enc = $env{'request.enc'};
1.731     raeburn  17585:     if ($delete_enc) {
1.730     raeburn  17586:         delete($env{'request.enc'});
                   17587:     }
1.685     tempelho 17588: 
                   17589:     return ($symb,$enc);
                   17590: }
1.462     albertel 17591: 
1.1181    raeburn  17592: ############################################################
                   17593: ############################################################
                   17594: 
                   17595: =pod
                   17596: 
                   17597: =head1 Routines for building display used to search for courses
                   17598: 
                   17599: 
                   17600: =over 4
                   17601: 
                   17602: =item * &build_filters()
                   17603: 
                   17604: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17605: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17606: and quotacheck.pl
                   17607: 
1.1181    raeburn  17608: 
                   17609: Inputs:
                   17610: 
                   17611: filterlist - anonymous array of fields to include as potential filters 
                   17612: 
                   17613: crstype - course type
                   17614: 
                   17615: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17616:               to pop-open a course selector (will contain "extra element"). 
                   17617: 
                   17618: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17619: 
                   17620: filter - anonymous hash of criteria and their values
                   17621: 
                   17622: action - form action
                   17623: 
                   17624: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17625: 
1.1182    raeburn  17626: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17627: 
                   17628: cloneruname - username of owner of new course who wants to clone
                   17629: 
                   17630: clonerudom - domain of owner of new course who wants to clone
                   17631: 
                   17632: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17633: 
                   17634: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17635: 
                   17636: codedom - domain
                   17637: 
                   17638: formname - value of form element named "form". 
                   17639: 
                   17640: fixeddom - domain, if fixed.
                   17641: 
                   17642: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17643: 
                   17644: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17645: 
                   17646: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17647: 
                   17648: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17649: 
                   17650: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17651: 
                   17652: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17653: 
                   17654: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17655: 
1.1182    raeburn  17656: 
1.1181    raeburn  17657: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17658: 
1.1182    raeburn  17659: 
1.1181    raeburn  17660: Side Effects: None
                   17661: 
                   17662: =cut
                   17663: 
                   17664: # ---------------------------------------------- search for courses based on last activity etc.
                   17665: 
                   17666: sub build_filters {
                   17667:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17668:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17669:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17670:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17671:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17672:     my ($list,$jscript);
1.1181    raeburn  17673:     my $onchange = 'javascript:updateFilters(this)';
                   17674:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17675:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17676:         $typeselectform,$instcodetitle);
                   17677:     if ($formname eq '') {
                   17678:         $formname = $caller;
                   17679:     }
                   17680:     foreach my $item (@{$filterlist}) {
                   17681:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17682:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17683:             if ($item eq 'domainfilter') {
                   17684:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17685:             } elsif ($item eq 'coursefilter') {
                   17686:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17687:             } elsif ($item eq 'ownerfilter') {
                   17688:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17689:             } elsif ($item eq 'ownerdomfilter') {
                   17690:                 $filter->{'ownerdomfilter'} =
                   17691:                     &LONCAPA::clean_domain($filter->{$item});
                   17692:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17693:                                                        'ownerdomfilter',1);
                   17694:             } elsif ($item eq 'personfilter') {
                   17695:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17696:             } elsif ($item eq 'persondomfilter') {
                   17697:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17698:                                                         'persondomfilter',1);
                   17699:             } else {
                   17700:                 $filter->{$item} =~ s/\W//g;
                   17701:             }
                   17702:             if (!$filter->{$item}) {
                   17703:                 $filter->{$item} = '';
                   17704:             }
                   17705:         }
                   17706:         if ($item eq 'domainfilter') {
                   17707:             my $allow_blank = 1;
                   17708:             if ($formname eq 'portform') {
                   17709:                 $allow_blank=0;
                   17710:             } elsif ($formname eq 'studentform') {
                   17711:                 $allow_blank=0;
                   17712:             }
                   17713:             if ($fixeddom) {
                   17714:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17715:                                     ' value="'.$codedom.'" />'.
                   17716:                                     &Apache::lonnet::domain($codedom,'description');
                   17717:             } else {
                   17718:                 $domainselectform = &select_dom_form($filter->{$item},
                   17719:                                                      'domainfilter',
                   17720:                                                       $allow_blank,'',$onchange);
                   17721:             }
                   17722:         } else {
                   17723:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17724:         }
                   17725:     }
                   17726: 
                   17727:     # last course activity filter and selection
                   17728:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17729: 
                   17730:     # course created filter and selection
                   17731:     if (exists($filter->{'createdfilter'})) {
                   17732:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17733:     }
                   17734: 
1.1239    raeburn  17735:     my $prefix = $crstype;
                   17736:     if ($crstype eq 'Placement') {
                   17737:         $prefix = 'Placement Test'
                   17738:     }
1.1181    raeburn  17739:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17740:                 'cac' => "$prefix Activity",
                   17741:                 'ccr' => "$prefix Created",
                   17742:                 'cde' => "$prefix Title",
                   17743:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17744:                 'ins' => 'Institutional Code',
                   17745:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17746:                 'cow' => "$prefix Owner/Co-owner",
                   17747:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17748:                 'cog' => 'Type',
                   17749:              );
                   17750: 
                   17751:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17752:         my $typeval = 'Course';
                   17753:         if ($crstype eq 'Community') {
                   17754:             $typeval = 'Community';
1.1239    raeburn  17755:         } elsif ($crstype eq 'Placement') {
                   17756:             $typeval = 'Placement';
1.1181    raeburn  17757:         }
                   17758:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17759:     } else {
                   17760:         $typeselectform =  '<select name="type" size="1"';
                   17761:         if ($onchange) {
                   17762:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17763:         }
                   17764:         $typeselectform .= '>'."\n";
1.1237    raeburn  17765:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17766:             my $shown;
                   17767:             if ($posstype eq 'Placement') {
                   17768:                 $shown = &mt('Placement Test');
                   17769:             } else {
                   17770:                 $shown = &mt($posstype);
                   17771:             }
1.1181    raeburn  17772:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17773:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17774:         }
                   17775:         $typeselectform.="</select>";
                   17776:     }
                   17777: 
                   17778:     my ($cloneableonlyform,$cloneabletitle);
                   17779:     if (exists($filter->{'cloneableonly'})) {
                   17780:         my $cloneableon = '';
                   17781:         my $cloneableoff = ' checked="checked"';
                   17782:         if ($filter->{'cloneableonly'}) {
                   17783:             $cloneableon = $cloneableoff;
                   17784:             $cloneableoff = '';
                   17785:         }
                   17786:         $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>';
                   17787:         if ($formname eq 'ccrs') {
1.1187    bisitz   17788:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17789:         } else {
                   17790:             $cloneabletitle = &mt('Cloneable by you');
                   17791:         }
                   17792:     }
                   17793:     my $officialjs;
                   17794:     if ($crstype eq 'Course') {
                   17795:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17796: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17797: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17798:             if ($codedom) { 
1.1181    raeburn  17799:                 $officialjs = 1;
                   17800:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17801:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17802:                                                                   $officialjs,$codetitlesref);
                   17803:                 if ($jscript) {
1.1182    raeburn  17804:                     $jscript = '<script type="text/javascript">'."\n".
                   17805:                                '// <![CDATA['."\n".
                   17806:                                $jscript."\n".
                   17807:                                '// ]]>'."\n".
                   17808:                                '</script>'."\n";
1.1181    raeburn  17809:                 }
                   17810:             }
                   17811:             if ($instcodeform eq '') {
                   17812:                 $instcodeform =
                   17813:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17814:                     $list->{'instcodefilter'}.'" />';
                   17815:                 $instcodetitle = $lt{'ins'};
                   17816:             } else {
                   17817:                 $instcodetitle = $lt{'inc'};
                   17818:             }
                   17819:             if ($fixeddom) {
                   17820:                 $instcodetitle .= '<br />('.$codedom.')';
                   17821:             }
                   17822:         }
                   17823:     }
                   17824:     my $output = qq|
                   17825: <form method="post" name="filterpicker" action="$action">
                   17826: <input type="hidden" name="form" value="$formname" />
                   17827: |;
                   17828:     if ($formname eq 'modifycourse') {
                   17829:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17830:                    '<input type="hidden" name="prevphase" value="'.
                   17831:                    $prevphase.'" />'."\n";
1.1198    musolffc 17832:     } elsif ($formname eq 'quotacheck') {
                   17833:         $output .= qq|
                   17834: <input type="hidden" name="sortby" value="" />
                   17835: <input type="hidden" name="sortorder" value="" />
                   17836: |;
                   17837:     } else {
1.1181    raeburn  17838:         my $name_input;
                   17839:         if ($cnameelement ne '') {
                   17840:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17841:                           $cnameelement.'" />';
                   17842:         }
                   17843:         $output .= qq|
1.1182    raeburn  17844: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17845: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17846: $name_input
                   17847: $roleelement
                   17848: $multelement
                   17849: $typeelement
                   17850: |;
                   17851:         if ($formname eq 'portform') {
                   17852:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17853:         }
                   17854:     }
                   17855:     if ($fixeddom) {
                   17856:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17857:     }
                   17858:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17859:     if ($sincefilterform) {
                   17860:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17861:                   .$sincefilterform
                   17862:                   .&Apache::lonhtmlcommon::row_closure();
                   17863:     }
                   17864:     if ($createdfilterform) {
                   17865:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17866:                   .$createdfilterform
                   17867:                   .&Apache::lonhtmlcommon::row_closure();
                   17868:     }
                   17869:     if ($domainselectform) {
                   17870:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17871:                   .$domainselectform
                   17872:                   .&Apache::lonhtmlcommon::row_closure();
                   17873:     }
                   17874:     if ($typeselectform) {
                   17875:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17876:             $output .= $typeselectform;
                   17877:         } else {
                   17878:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17879:                       .$typeselectform
                   17880:                       .&Apache::lonhtmlcommon::row_closure();
                   17881:         }
                   17882:     }
                   17883:     if ($instcodeform) {
                   17884:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17885:                   .$instcodeform
                   17886:                   .&Apache::lonhtmlcommon::row_closure();
                   17887:     }
                   17888:     if (exists($filter->{'ownerfilter'})) {
                   17889:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17890:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17891:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17892:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17893:                    $ownerdomselectform.'</td></tr></table>'.
                   17894:                    &Apache::lonhtmlcommon::row_closure();
                   17895:     }
                   17896:     if (exists($filter->{'personfilter'})) {
                   17897:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17898:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17899:                    '<input type="text" name="personfilter" size="20" value="'.
                   17900:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17901:                    $persondomselectform.'</td></tr></table>'.
                   17902:                    &Apache::lonhtmlcommon::row_closure();
                   17903:     }
                   17904:     if (exists($filter->{'coursefilter'})) {
                   17905:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17906:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17907:                   .$list->{'coursefilter'}.'" />'
                   17908:                   .&Apache::lonhtmlcommon::row_closure();
                   17909:     }
                   17910:     if ($cloneableonlyform) {
                   17911:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17912:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17913:     }
                   17914:     if (exists($filter->{'descriptfilter'})) {
                   17915:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17916:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17917:                   .$list->{'descriptfilter'}.'" />'
                   17918:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17919:     }
                   17920:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17921:                '<input type="hidden" name="updater" value="" />'."\n".
                   17922:                '<input type="submit" name="gosearch" value="'.
                   17923:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17924:     return $jscript.$clonewarning.$output;
                   17925: }
                   17926: 
                   17927: =pod 
                   17928: 
                   17929: =item * &timebased_select_form()
                   17930: 
1.1182    raeburn  17931: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17932: filter e.g., Course Activity, Course Created, when searching for courses
                   17933: or communities
                   17934: 
                   17935: Inputs:
                   17936: 
                   17937: item - name of form element (sincefilter or createdfilter)
                   17938: 
                   17939: filter - anonymous hash of criteria and their values
                   17940: 
                   17941: Returns: HTML for a select box contained a blank, then six time selections,
                   17942:          with value set in incoming form variables currently selected. 
                   17943: 
                   17944: Side Effects: None
                   17945: 
                   17946: =cut
                   17947: 
                   17948: sub timebased_select_form {
                   17949:     my ($item,$filter) = @_;
                   17950:     if (ref($filter) eq 'HASH') {
                   17951:         $filter->{$item} =~ s/[^\d-]//g;
                   17952:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17953:         return &select_form(
                   17954:                             $filter->{$item},
                   17955:                             $item,
                   17956:                             {      '-1' => '',
                   17957:                                 '86400' => &mt('today'),
                   17958:                                '604800' => &mt('last week'),
                   17959:                               '2592000' => &mt('last month'),
                   17960:                               '7776000' => &mt('last three months'),
                   17961:                              '15552000' => &mt('last six months'),
                   17962:                              '31104000' => &mt('last year'),
                   17963:                     'select_form_order' =>
                   17964:                            ['-1','86400','604800','2592000','7776000',
                   17965:                             '15552000','31104000']});
                   17966:     }
                   17967: }
                   17968: 
                   17969: =pod
                   17970: 
                   17971: =item * &js_changer()
                   17972: 
                   17973: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17974: when course type or domain is changed, and also to hide 'Searching ...' on
                   17975: page load completion for page showing search result.
1.1181    raeburn  17976: 
                   17977: Inputs: None
                   17978: 
1.1183    raeburn  17979: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17980: 
                   17981: Side Effects: None
                   17982: 
                   17983: =cut
                   17984: 
                   17985: sub js_changer {
                   17986:     return <<ENDJS;
                   17987: <script type="text/javascript">
                   17988: // <![CDATA[
                   17989: function updateFilters(caller) {
                   17990:     if (typeof(caller) != "undefined") {
                   17991:         document.filterpicker.updater.value = caller.name;
                   17992:     }
                   17993:     document.filterpicker.submit();
                   17994: }
1.1183    raeburn  17995: 
                   17996: function hideSearching() {
                   17997:     if (document.getElementById('searching')) {
                   17998:         document.getElementById('searching').style.display = 'none';
                   17999:     }
                   18000:     return;
                   18001: }
                   18002: 
1.1181    raeburn  18003: // ]]>
                   18004: </script>
                   18005: 
                   18006: ENDJS
                   18007: }
                   18008: 
                   18009: =pod
                   18010: 
1.1182    raeburn  18011: =item * &search_courses()
                   18012: 
                   18013: Process selected filters form course search form and pass to lonnet::courseiddump
                   18014: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18015: 
                   18016: Inputs:
                   18017: 
                   18018: dom - domain being searched 
                   18019: 
                   18020: type - course type ('Course' or 'Community' or '.' if any).
                   18021: 
                   18022: filter - anonymous hash of criteria and their values
                   18023: 
                   18024: numtitles - for institutional codes - number of categories
                   18025: 
                   18026: cloneruname - optional username of new course owner
                   18027: 
                   18028: clonerudom - optional domain of new course owner
                   18029: 
1.1221    raeburn  18030: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18031:             (used when DC is using course creation form)
                   18032: 
                   18033: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18034: 
1.1221    raeburn  18035: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18036:            (and so can clone automatically)
                   18037: 
                   18038: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18039: 
                   18040: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18041:               courses to clone 
1.1182    raeburn  18042: 
                   18043: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18044: 
                   18045: 
                   18046: Side Effects: None
                   18047: 
                   18048: =cut
                   18049: 
                   18050: 
                   18051: sub search_courses {
1.1221    raeburn  18052:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18053:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18054:     my (%courses,%showcourses,$cloner);
                   18055:     if (($filter->{'ownerfilter'} ne '') ||
                   18056:         ($filter->{'ownerdomfilter'} ne '')) {
                   18057:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18058:                                        $filter->{'ownerdomfilter'};
                   18059:     }
                   18060:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18061:         if (!$filter->{$item}) {
                   18062:             $filter->{$item}='.';
                   18063:         }
                   18064:     }
                   18065:     my $now = time;
                   18066:     my $timefilter =
                   18067:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18068:     my ($createdbefore,$createdafter);
                   18069:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18070:         $createdbefore = $now;
                   18071:         $createdafter = $now-$filter->{'createdfilter'};
                   18072:     }
                   18073:     my ($instcodefilter,$regexpok);
                   18074:     if ($numtitles) {
                   18075:         if ($env{'form.official'} eq 'on') {
                   18076:             $instcodefilter =
                   18077:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18078:             $regexpok = 1;
                   18079:         } elsif ($env{'form.official'} eq 'off') {
                   18080:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18081:             unless ($instcodefilter eq '') {
                   18082:                 $regexpok = -1;
                   18083:             }
                   18084:         }
                   18085:     } else {
                   18086:         $instcodefilter = $filter->{'instcodefilter'};
                   18087:     }
                   18088:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18089:     if ($type eq '') { $type = '.'; }
                   18090: 
                   18091:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18092:         $cloner = $cloneruname.':'.$clonerudom;
                   18093:     }
                   18094:     %courses = &Apache::lonnet::courseiddump($dom,
                   18095:                                              $filter->{'descriptfilter'},
                   18096:                                              $timefilter,
                   18097:                                              $instcodefilter,
                   18098:                                              $filter->{'combownerfilter'},
                   18099:                                              $filter->{'coursefilter'},
                   18100:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18101:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18102:                                              $filter->{'cloneableonly'},
                   18103:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18104:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18105:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18106:         my $ccrole;
                   18107:         if ($type eq 'Community') {
                   18108:             $ccrole = 'co';
                   18109:         } else {
                   18110:             $ccrole = 'cc';
                   18111:         }
                   18112:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18113:                                                      $filter->{'persondomfilter'},
                   18114:                                                      'userroles',undef,
                   18115:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18116:                                                      $dom);
                   18117:         foreach my $role (keys(%rolehash)) {
                   18118:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18119:             my $cid = $cdom.'_'.$cnum;
                   18120:             if (exists($courses{$cid})) {
                   18121:                 if (ref($courses{$cid}) eq 'HASH') {
                   18122:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18123:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18124:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18125:                         }
                   18126:                     } else {
                   18127:                         $courses{$cid}{roles} = [$courserole];
                   18128:                     }
                   18129:                     $showcourses{$cid} = $courses{$cid};
                   18130:                 }
                   18131:             }
                   18132:         }
                   18133:         %courses = %showcourses;
                   18134:     }
                   18135:     return %courses;
                   18136: }
                   18137: 
                   18138: =pod
                   18139: 
1.1181    raeburn  18140: =back
                   18141: 
1.1207    raeburn  18142: =head1 Routines for version requirements for current course.
                   18143: 
                   18144: =over 4
                   18145: 
                   18146: =item * &check_release_required()
                   18147: 
                   18148: Compares required LON-CAPA version with version on server, and
                   18149: if required version is newer looks for a server with the required version.
                   18150: 
                   18151: Looks first at servers in user's owen domain; if none suitable, looks at
                   18152: servers in course's domain are permitted to host sessions for user's domain.
                   18153: 
                   18154: Inputs:
                   18155: 
                   18156: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18157: 
                   18158: $courseid - Course ID of current course
                   18159: 
                   18160: $rolecode - User's current role in course (for switchserver query string).
                   18161: 
                   18162: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18163: 
                   18164: 
                   18165: Returns:
                   18166: 
                   18167: $switchserver - query string tp append to /adm/switchserver call (if 
                   18168:                 current server's LON-CAPA version is too old. 
                   18169: 
                   18170: $warning - Message is displayed if no suitable server could be found.
                   18171: 
                   18172: =cut
                   18173: 
                   18174: sub check_release_required {
                   18175:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18176:     my ($switchserver,$warning);
                   18177:     if ($required ne '') {
                   18178:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18179:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18180:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18181:             my $otherserver;
                   18182:             if (($major eq '' && $minor eq '') ||
                   18183:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18184:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18185:                 my $switchlcrev =
                   18186:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18187:                                                            $userdomserver);
                   18188:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18189:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18190:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18191:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18192:                     if ($cdom ne $env{'user.domain'}) {
                   18193:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18194:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18195:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18196:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18197:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18198:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18199:                         my $canhost =
                   18200:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18201:                                                               $coursedomserver,
                   18202:                                                               $remoterev,
                   18203:                                                               $udomdefaults{'remotesessions'},
                   18204:                                                               $defdomdefaults{'hostedsessions'});
                   18205: 
                   18206:                         if ($canhost) {
                   18207:                             $otherserver = $coursedomserver;
                   18208:                         } else {
                   18209:                             $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.");
                   18210:                         }
                   18211:                     } else {
                   18212:                         $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).");
                   18213:                     }
                   18214:                 } else {
                   18215:                     $otherserver = $userdomserver;
                   18216:                 }
                   18217:             }
                   18218:             if ($otherserver ne '') {
                   18219:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18220:             }
                   18221:         }
                   18222:     }
                   18223:     return ($switchserver,$warning);
                   18224: }
                   18225: 
                   18226: =pod
                   18227: 
                   18228: =item * &check_release_result()
                   18229: 
                   18230: Inputs:
                   18231: 
                   18232: $switchwarning - Warning message if no suitable server found to host session.
                   18233: 
                   18234: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18235:                 and current role.
                   18236: 
                   18237: Returns: HTML to display with information about requirement to switch server.
                   18238:          Either displaying warning with link to Roles/Courses screen or
                   18239:          display link to switchserver.
                   18240: 
1.1181    raeburn  18241: =cut
                   18242: 
1.1207    raeburn  18243: sub check_release_result {
                   18244:     my ($switchwarning,$switchserver) = @_;
                   18245:     my $output = &start_page('Selected course unavailable on this server').
                   18246:                  '<p class="LC_warning">';
                   18247:     if ($switchwarning) {
                   18248:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18249:         if (&show_course()) {
                   18250:             $output .= &mt('Display courses');
                   18251:         } else {
                   18252:             $output .= &mt('Display roles');
                   18253:         }
                   18254:         $output .= '</a>';
                   18255:     } elsif ($switchserver) {
                   18256:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18257:                    '<br />'.
                   18258:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18259:                    &mt('Switch Server').
                   18260:                    '</a>';
                   18261:     }
                   18262:     $output .= '</p>'.&end_page();
                   18263:     return $output;
                   18264: }
                   18265: 
                   18266: =pod
                   18267: 
                   18268: =item * &needs_coursereinit()
                   18269: 
                   18270: Determine if course contents stored for user's session needs to be
                   18271: refreshed, because content has changed since "Big Hash" last tied.
                   18272: 
                   18273: Check for change is made if time last checked is more than 10 minutes ago
                   18274: (by default).
                   18275: 
                   18276: Inputs:
                   18277: 
                   18278: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18279: 
                   18280: $interval (optional) - Time which may elapse (in s) between last check for content
                   18281:                        change in current course. (default: 600 s).  
                   18282: 
                   18283: Returns: an array; first element is:
                   18284: 
                   18285: =over 4
                   18286: 
                   18287: 'switch' - if content updates mean user's session
                   18288:            needs to be switched to a server running a newer LON-CAPA version
                   18289:  
                   18290: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18291:            on current server hosting user's session                
                   18292: 
                   18293: ''       - if no action required.
                   18294: 
                   18295: =back
                   18296: 
                   18297: If first item element is 'switch':
                   18298: 
                   18299: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18300: 
                   18301: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18302:                               and current role. 
                   18303: 
                   18304: otherwise: no other elements returned.
                   18305: 
                   18306: =back
                   18307: 
                   18308: =cut
                   18309: 
                   18310: sub needs_coursereinit {
                   18311:     my ($loncaparev,$interval) = @_;
                   18312:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18313:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18314:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18315:     my $now = time;
                   18316:     if ($interval eq '') {
                   18317:         $interval = 600;
                   18318:     }
                   18319:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18320:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18321:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18322:         if ($blocked) {
                   18323:             return ();
                   18324:         }
1.1391    raeburn  18325:         my $update;
                   18326:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18327:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   18328:         if ($lastmainchange > $env{'request.course.tied'}) {
                   18329:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18330:             if ($needswitch) {
                   18331:                 return ('switch',$switchwarning,$switchserver);
                   18332:             }
                   18333:             $update = 'main';
                   18334:         }
                   18335:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   18336:             if ($update) {
                   18337:                 $update = 'both';
                   18338:             } else {
                   18339:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18340:                 if ($needswitch) {
                   18341:                     return ('switch',$switchwarning,$switchserver);
                   18342:                 } else {
                   18343:                     $update = 'supp';
1.1207    raeburn  18344:                 }
                   18345:             }
1.1391    raeburn  18346:             return ($update);
                   18347:         }
                   18348:     }
                   18349:     return ();
                   18350: }
                   18351: 
                   18352: sub switch_for_update {
                   18353:     my ($loncaparev,$cdom,$cnum) = @_;
                   18354:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18355:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18356:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18357:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18358:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18359:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   18360:             my ($switchserver,$switchwarning) =
                   18361:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18362:                                         $curr_reqd_hash{'internal.releaserequired'});
                   18363:             if ($switchwarning ne '' || $switchserver ne '') {
                   18364:                 return ('switch',$switchwarning,$switchserver);
                   18365:             }
1.1207    raeburn  18366:         }
                   18367:     }
                   18368:     return ();
                   18369: }
1.1181    raeburn  18370: 
1.1083    raeburn  18371: sub update_content_constraints {
1.1395  ! raeburn  18372:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  18373:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18374:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18375:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18376:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18377:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18378:         if ($item eq 'resourcetag') {
                   18379:             if ($name eq 'responsetype') {
                   18380:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18381:             }
1.1307    raeburn  18382:         } elsif ($item eq 'course') {
                   18383:             if ($name eq 'courserestype') {
                   18384:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18385:             }
1.1083    raeburn  18386:         }
                   18387:     }
                   18388:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18389:     if (defined($navmap)) {
1.1307    raeburn  18390:         my (%allresponses,%allcrsrestypes);
                   18391:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18392:             if ($res->is_tool()) {
                   18393:                 if ($allcrsrestypes{'exttool'}) {
                   18394:                     $allcrsrestypes{'exttool'} ++;
                   18395:                 } else {
                   18396:                     $allcrsrestypes{'exttool'} = 1;
                   18397:                 }
                   18398:                 next;
                   18399:             }
1.1083    raeburn  18400:             my %responses = $res->responseTypes();
                   18401:             foreach my $key (keys(%responses)) {
                   18402:                 next unless(exists($checkresponsetypes{$key}));
                   18403:                 $allresponses{$key} += $responses{$key};
                   18404:             }
                   18405:         }
                   18406:         foreach my $key (keys(%allresponses)) {
                   18407:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18408:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18409:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18410:             }
                   18411:         }
1.1307    raeburn  18412:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18413:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18414:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18415:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18416:             }
                   18417:         }
1.1083    raeburn  18418:         undef($navmap);
                   18419:     }
1.1391    raeburn  18420:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  18421:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18422:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18423:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18424:         }
                   18425:     }
1.1083    raeburn  18426:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18427:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18428:     }
                   18429:     return;
                   18430: }
                   18431: 
1.1110    raeburn  18432: sub allmaps_incourse {
                   18433:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18434:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18435:         $cid = $env{'request.course.id'};
                   18436:         $cdom = $env{'course.'.$cid.'.domain'};
                   18437:         $cnum = $env{'course.'.$cid.'.num'};
                   18438:         $chome = $env{'course.'.$cid.'.home'};
                   18439:     }
                   18440:     my %allmaps = ();
                   18441:     my $lastchange =
                   18442:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18443:     if ($lastchange > $env{'request.course.tied'}) {
                   18444:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18445:         unless ($ferr) {
1.1395  ! raeburn  18446:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  18447:         }
                   18448:     }
                   18449:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18450:     if (defined($navmap)) {
                   18451:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18452:             $allmaps{$res->src()} = 1;
                   18453:         }
                   18454:     }
                   18455:     return \%allmaps;
                   18456: }
                   18457: 
1.1083    raeburn  18458: sub parse_supplemental_title {
                   18459:     my ($title) = @_;
                   18460: 
                   18461:     my ($foldertitle,$renametitle);
                   18462:     if ($title =~ /&amp;&amp;&amp;/) {
                   18463:         $title = &HTML::Entites::decode($title);
                   18464:     }
                   18465:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18466:         $renametitle=$4;
                   18467:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18468:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18469:         my $name =  &plainname($uname,$udom);
                   18470:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18471:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   18472:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   18473:             $name.': <br />'.$foldertitle;
                   18474:     }
                   18475:     if (wantarray) {
                   18476:         return ($title,$foldertitle,$renametitle);
                   18477:     }
                   18478:     return $title;
                   18479: }
                   18480: 
1.1395  ! raeburn  18481: sub get_supplemental {
        !          18482:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
        !          18483:     my $hashid=$cnum.':'.$cdom;
        !          18484:     my ($supplemental,$cached,$set_httprefs);
        !          18485:     unless ($ignorecache) {
        !          18486:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
        !          18487:     }
        !          18488:     unless (defined($cached)) {
        !          18489:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
        !          18490:         unless ($chome eq 'no_host') {
        !          18491:             my @order = @LONCAPA::map::order;
        !          18492:             my @resources = @LONCAPA::map::resources;
        !          18493:             my @resparms = @LONCAPA::map::resparms;
        !          18494:             my @zombies = @LONCAPA::map::zombies;
        !          18495:             my ($errors,%ids,%hidden);
        !          18496:             $errors =
        !          18497:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
        !          18498:                                       $errors,$possdel,\%ids,\%hidden);
        !          18499:             @LONCAPA::map::order = @order;
        !          18500:             @LONCAPA::map::resources = @resources;
        !          18501:             @LONCAPA::map::resparms = @resparms;
        !          18502:             @LONCAPA::map::zombies = @zombies;
        !          18503:             $set_httprefs = 1;
        !          18504:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
        !          18505:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
        !          18506:             }
        !          18507:             $supplemental = {
        !          18508:                                ids => \%ids,
        !          18509:                                hidden => \%hidden,
        !          18510:                             };
        !          18511:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
        !          18512:         }
        !          18513:     }
        !          18514:     return ($supplemental,$set_httprefs);
        !          18515: }
        !          18516: 
1.1143    raeburn  18517: sub recurse_supplemental {
1.1391    raeburn  18518:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   18519:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   18520:         my $mapnum;
                   18521:         if ($suppmap eq 'supplemental.sequence') {
                   18522:             $mapnum = 0;
                   18523:         } else {
                   18524:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   18525:         }
1.1143    raeburn  18526:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18527:         if ($fatal) {
                   18528:             $errors ++;
                   18529:         } else {
1.1389    raeburn  18530:             my @order = @LONCAPA::map::order;
                   18531:             if (@order > 0) {
                   18532:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  18533:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  18534:                 foreach my $idx (@order) {
                   18535:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  18536:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  18537:                         my $id = $mapnum.':'.$idx;
                   18538:                         push(@{$suppids->{$src}},$id);
                   18539:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   18540:                             $hiddensupp->{$id} = 1;
                   18541:                         }
1.1146    raeburn  18542:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  18543:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   18544:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  18545:                         } else {
1.1391    raeburn  18546:                             my $allowed;
                   18547:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   18548:                                 $allowed = 1;
                   18549:                             } elsif ($possdel) {
                   18550:                                 foreach my $item (@{$suppids->{$src}}) {
                   18551:                                     next if ($item eq $id);
                   18552:                                     unless ($hiddensupp->{$item}) {
                   18553:                                        $allowed = 1;
                   18554:                                        last;
                   18555:                                     }
                   18556:                                 }
                   18557:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   18558:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   18559:                                 }
                   18560:                             }
                   18561:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   18562:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  18563:                             }
1.1143    raeburn  18564:                         }
                   18565:                     }
                   18566:                 }
                   18567:             }
                   18568:         }
                   18569:     }
1.1391    raeburn  18570:     return $errors;
                   18571: }
                   18572: 
                   18573: sub set_supp_httprefs {
                   18574:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   18575:     if (ref($supplemental) eq 'HASH') {
                   18576:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   18577:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   18578:                 next if ($src =~ /\.sequence$/);
                   18579:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   18580:                     my $allowed;
                   18581:                     if ($env{'request.role.adv'}) {
                   18582:                         $allowed = 1;
                   18583:                     } else {
                   18584:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   18585:                             unless ($supplemental->{'hidden'}->{$id}) {
                   18586:                                 $allowed = 1;
                   18587:                                 last;
                   18588:                             }
                   18589:                         }
                   18590:                     }
                   18591:                     if (exists($env{'httpref.'.$src})) {
                   18592:                         if ($possdel) {
                   18593:                             unless ($allowed) {
                   18594:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   18595:                             }
                   18596:                         }
                   18597:                     } elsif ($allowed) {
                   18598:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   18599:                     }
                   18600:                 }
                   18601:             }
                   18602:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   18603:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   18604:             }
                   18605:         }
                   18606:     }
                   18607: }
                   18608: 
                   18609: sub get_supp_parameter {
                   18610:     my ($resparm,$name)=@_;
                   18611:     return if ($resparm eq '');
                   18612:     my $value=undef;
                   18613:     my $ptype=undef;
                   18614:     foreach (split('&&&',$resparm)) {
                   18615:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   18616:         if ($thisname eq $name) {
                   18617:             $value=$thisvalue;
                   18618:             $ptype=$thistype;
                   18619:         }
                   18620:     }
                   18621:     return $value;
1.1143    raeburn  18622: }
                   18623: 
1.1101    raeburn  18624: sub symb_to_docspath {
1.1267    raeburn  18625:     my ($symb,$navmapref) = @_;
                   18626:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18627:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18628:     if ($resurl=~/\.(sequence|page)$/) {
                   18629:         $mapurl=$resurl;
                   18630:     } elsif ($resurl eq 'adm/navmaps') {
                   18631:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18632:     }
                   18633:     my $mapresobj;
1.1267    raeburn  18634:     unless (ref($$navmapref)) {
                   18635:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18636:     }
                   18637:     if (ref($$navmapref)) {
                   18638:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18639:     }
                   18640:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18641:     my $type=$2;
                   18642:     my $path;
                   18643:     if (ref($mapresobj)) {
                   18644:         my $pcslist = $mapresobj->map_hierarchy();
                   18645:         if ($pcslist ne '') {
                   18646:             foreach my $pc (split(/,/,$pcslist)) {
                   18647:                 next if ($pc <= 1);
1.1267    raeburn  18648:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18649:                 if (ref($res)) {
                   18650:                     my $thisurl = $res->src();
                   18651:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18652:                     my $thistitle = $res->title();
                   18653:                     $path .= '&'.
                   18654:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18655:                              &escape($thistitle).
1.1101    raeburn  18656:                              ':'.$res->randompick().
                   18657:                              ':'.$res->randomout().
                   18658:                              ':'.$res->encrypted().
                   18659:                              ':'.$res->randomorder().
                   18660:                              ':'.$res->is_page();
                   18661:                 }
                   18662:             }
                   18663:         }
                   18664:         $path =~ s/^\&//;
                   18665:         my $maptitle = $mapresobj->title();
                   18666:         if ($mapurl eq 'default') {
1.1129    raeburn  18667:             $maptitle = 'Main Content';
1.1101    raeburn  18668:         }
                   18669:         $path .= (($path ne '')? '&' : '').
                   18670:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18671:                  &escape($maptitle).
1.1101    raeburn  18672:                  ':'.$mapresobj->randompick().
                   18673:                  ':'.$mapresobj->randomout().
                   18674:                  ':'.$mapresobj->encrypted().
                   18675:                  ':'.$mapresobj->randomorder().
                   18676:                  ':'.$mapresobj->is_page();
                   18677:     } else {
                   18678:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18679:         my $ispage = (($type eq 'page')? 1 : '');
                   18680:         if ($mapurl eq 'default') {
1.1129    raeburn  18681:             $maptitle = 'Main Content';
1.1101    raeburn  18682:         }
                   18683:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18684:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18685:     }
                   18686:     unless ($mapurl eq 'default') {
                   18687:         $path = 'default&'.
1.1146    raeburn  18688:                 &escape('Main Content').
1.1101    raeburn  18689:                 ':::::&'.$path;
                   18690:     }
                   18691:     return $path;
                   18692: }
                   18693: 
1.1393    raeburn  18694: sub validate_folderpath {
                   18695:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   18696:     if ($env{'form.folderpath'} ne '') {
                   18697:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  18698:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  18699:         for (my $i=0; $i<@items; $i++) {
                   18700:             my $odd = $i%2;
                   18701:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   18702:                 $badpath = 1;
1.1394    raeburn  18703:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  18704:                 my $idx = $i-1;
1.1394    raeburn  18705:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   18706:                     my $esc_name = $1;
                   18707:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   18708:                         $supppath .= '&'.$esc_name;
                   18709:                         $changed = 1;
                   18710:                     } else {
                   18711:                         $supppath .= '&'.$items[$i];
                   18712:                     }
                   18713:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   18714:                     $changed = 1;
1.1393    raeburn  18715:                     my $is_hidden;
                   18716:                     unless ($got_supp) {
1.1395  ! raeburn  18717:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  18718:                         if (ref($supplemental) eq 'HASH') {
                   18719:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   18720:                                 %supphidden = %{$supplemental->{'hidden'}};
                   18721:                             }
                   18722:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   18723:                                 %suppids = %{$supplemental->{'ids'}};
                   18724:                             }
                   18725:                         }
                   18726:                         $got_supp = 1;
                   18727:                     }
                   18728:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   18729:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   18730:                         if ($supphidden{$mapid}) {
                   18731:                             $is_hidden = 1;
                   18732:                         }
                   18733:                     }
1.1394    raeburn  18734:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   18735:                 } else {
                   18736:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  18737:                 }
                   18738:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   18739:                 $badpath = 1;
1.1394    raeburn  18740:             } elsif ($supplementalflag) {
1.1393    raeburn  18741:                 $supppath .= '&'.$items[$i];
                   18742:             }
                   18743:             last if ($badpath);
                   18744:         }
                   18745:         if ($badpath) {
                   18746:             delete($env{'form.folderpath'});
1.1394    raeburn  18747:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  18748:             $supppath =~ s/^\&//;
                   18749:             $env{'form.folderpath'} = $supppath;
                   18750:         }
                   18751:     }
                   18752:     return;
                   18753: }
                   18754: 
1.1094    raeburn  18755: sub captcha_display {
1.1327    raeburn  18756:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18757:     my ($output,$error);
1.1234    raeburn  18758:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18759:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18760:     if ($captcha eq 'original') {
1.1094    raeburn  18761:         $output = &create_captcha();
                   18762:         unless ($output) {
1.1172    raeburn  18763:             $error = 'captcha';
1.1094    raeburn  18764:         }
                   18765:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18766:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18767:         unless ($output) {
1.1172    raeburn  18768:             $error = 'recaptcha';
1.1094    raeburn  18769:         }
                   18770:     }
1.1234    raeburn  18771:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18772: }
                   18773: 
                   18774: sub captcha_response {
1.1327    raeburn  18775:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18776:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18777:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18778:     if ($captcha eq 'original') {
1.1094    raeburn  18779:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18780:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18781:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18782:     } else {
                   18783:         $captcha_chk = 1;
                   18784:     }
                   18785:     return ($captcha_chk,$captcha_error);
                   18786: }
                   18787: 
                   18788: sub get_captcha_config {
1.1327    raeburn  18789:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  18790:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  18791:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18792:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18793:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  18794:     if ($context eq 'usercreation') {
                   18795:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18796:         if (ref($domconfig{$context}) eq 'HASH') {
                   18797:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18798:             if (ref($hashtocheck) eq 'HASH') {
                   18799:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18800:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18801:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18802:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18803:                     }
                   18804:                     if ($privkey && $pubkey) {
                   18805:                         $captcha = 'recaptcha';
1.1234    raeburn  18806:                         $version = $hashtocheck->{'recaptchaversion'};
                   18807:                         if ($version ne '2') {
                   18808:                             $version = 1;
                   18809:                         }
1.1095    raeburn  18810:                     } else {
                   18811:                         $captcha = 'original';
                   18812:                     }
                   18813:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18814:                     $captcha = 'original';
                   18815:                 }
1.1094    raeburn  18816:             }
1.1095    raeburn  18817:         } else {
                   18818:             $captcha = 'captcha';
                   18819:         }
                   18820:     } elsif ($context eq 'login') {
                   18821:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18822:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18823:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18824:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  18825:             if ($privkey && $pubkey) {
                   18826:                 $captcha = 'recaptcha';
1.1234    raeburn  18827:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18828:                 if ($version ne '2') {
                   18829:                     $version = 1; 
                   18830:                 }
1.1095    raeburn  18831:             } else {
                   18832:                 $captcha = 'original';
1.1094    raeburn  18833:             }
1.1095    raeburn  18834:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18835:             $captcha = 'original';
1.1094    raeburn  18836:         }
1.1327    raeburn  18837:     } elsif ($context eq 'passwords') {
                   18838:         if ($dom_in_effect) {
                   18839:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18840:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18841:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18842:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18843:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18844:                 }
                   18845:                 if ($privkey && $pubkey) {
                   18846:                     $captcha = 'recaptcha';
                   18847:                     $version = $passwdconf{'recaptchaversion'};
                   18848:                     if ($version ne '2') {
                   18849:                         $version = 1;
                   18850:                     }
                   18851:                 } else {
                   18852:                     $captcha = 'original';
                   18853:                 }
                   18854:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18855:                 $captcha = 'original';
                   18856:             }
                   18857:         }
                   18858:     } 
1.1234    raeburn  18859:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18860: }
                   18861: 
                   18862: sub create_captcha {
                   18863:     my %captcha_params = &captcha_settings();
                   18864:     my ($output,$maxtries,$tries) = ('',10,0);
                   18865:     while ($tries < $maxtries) {
                   18866:         $tries ++;
                   18867:         my $captcha = Authen::Captcha->new (
                   18868:                                            output_folder => $captcha_params{'output_dir'},
                   18869:                                            data_folder   => $captcha_params{'db_dir'},
                   18870:                                           );
                   18871:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18872: 
                   18873:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18874:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  18875:                       '<span class="LC_nobreak">'.
1.1094    raeburn  18876:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  18877:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1367    raeburn  18878:                       '</span><br />'.
1.1176    raeburn  18879:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18880:             last;
                   18881:         }
                   18882:     }
1.1323    raeburn  18883:     if ($output eq '') {
                   18884:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18885:     }
1.1094    raeburn  18886:     return $output;
                   18887: }
                   18888: 
                   18889: sub captcha_settings {
                   18890:     my %captcha_params = (
                   18891:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18892:                            www_output_dir => "/captchaspool",
                   18893:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18894:                            numchars       => '5',
                   18895:                          );
                   18896:     return %captcha_params;
                   18897: }
                   18898: 
                   18899: sub check_captcha {
                   18900:     my ($captcha_chk,$captcha_error);
                   18901:     my $code = $env{'form.code'};
                   18902:     my $md5sum = $env{'form.crypt'};
                   18903:     my %captcha_params = &captcha_settings();
                   18904:     my $captcha = Authen::Captcha->new(
                   18905:                       output_folder => $captcha_params{'output_dir'},
                   18906:                       data_folder   => $captcha_params{'db_dir'},
                   18907:                   );
1.1109    raeburn  18908:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18909:     my %captcha_hash = (
                   18910:                         0       => 'Code not checked (file error)',
                   18911:                        -1      => 'Failed: code expired',
                   18912:                        -2      => 'Failed: invalid code (not in database)',
                   18913:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18914:     );
                   18915:     if ($captcha_chk != 1) {
                   18916:         $captcha_error = $captcha_hash{$captcha_chk}
                   18917:     }
                   18918:     return ($captcha_chk,$captcha_error);
                   18919: }
                   18920: 
                   18921: sub create_recaptcha {
1.1234    raeburn  18922:     my ($pubkey,$version) = @_;
                   18923:     if ($version >= 2) {
1.1367    raeburn  18924:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18925:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  18926:     } else {
                   18927:         my $use_ssl;
                   18928:         if ($ENV{'SERVER_PORT'} == 443) {
                   18929:             $use_ssl = 1;
                   18930:         }
                   18931:         my $captcha = Captcha::reCAPTCHA->new;
                   18932:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18933:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18934:                &mt('If the text is hard to read, [_1] will replace them.',
                   18935:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18936:                '<br /><br />';
                   18937:     }
1.1094    raeburn  18938: }
                   18939: 
                   18940: sub check_recaptcha {
1.1234    raeburn  18941:     my ($privkey,$version) = @_;
1.1094    raeburn  18942:     my $captcha_chk;
1.1350    raeburn  18943:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  18944:     if ($version >= 2) {
                   18945:         my %info = (
                   18946:                      secret   => $privkey, 
                   18947:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  18948:                      remoteip => $ip,
1.1234    raeburn  18949:                    );
1.1280    raeburn  18950:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18951:         $request->content(join('&',map {
                   18952:                          my $name = escape($_);
                   18953:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18954:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18955:                          : &escape($info{$_}) );
                   18956:         } keys(%info)));
                   18957:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18958:         if ($response->is_success)  {
                   18959:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18960:             if (ref($data) eq 'HASH') {
                   18961:                 if ($data->{'success'}) {
                   18962:                     $captcha_chk = 1;
                   18963:                 }
                   18964:             }
                   18965:         }
                   18966:     } else {
                   18967:         my $captcha = Captcha::reCAPTCHA->new;
                   18968:         my $captcha_result =
                   18969:             $captcha->check_answer(
                   18970:                                     $privkey,
1.1350    raeburn  18971:                                     $ip,
1.1234    raeburn  18972:                                     $env{'form.recaptcha_challenge_field'},
                   18973:                                     $env{'form.recaptcha_response_field'},
                   18974:                                   );
                   18975:         if ($captcha_result->{is_valid}) {
                   18976:             $captcha_chk = 1;
                   18977:         }
1.1094    raeburn  18978:     }
                   18979:     return $captcha_chk;
                   18980: }
                   18981: 
1.1174    raeburn  18982: sub emailusername_info {
1.1244    raeburn  18983:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18984:     my %titles = &Apache::lonlocal::texthash (
                   18985:                      lastname      => 'Last Name',
                   18986:                      firstname     => 'First Name',
                   18987:                      institution   => 'School/college/university',
                   18988:                      location      => "School's city, state/province, country",
                   18989:                      web           => "School's web address",
                   18990:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18991:                      id            => 'Student/Employee ID',
1.1174    raeburn  18992:                  );
                   18993:     return (\@fields,\%titles);
                   18994: }
                   18995: 
1.1161    raeburn  18996: sub cleanup_html {
                   18997:     my ($incoming) = @_;
                   18998:     my $outgoing;
                   18999:     if ($incoming ne '') {
                   19000:         $outgoing = $incoming;
                   19001:         $outgoing =~ s/;/&#059;/g;
                   19002:         $outgoing =~ s/\#/&#035;/g;
                   19003:         $outgoing =~ s/\&/&#038;/g;
                   19004:         $outgoing =~ s/</&#060;/g;
                   19005:         $outgoing =~ s/>/&#062;/g;
                   19006:         $outgoing =~ s/\(/&#040/g;
                   19007:         $outgoing =~ s/\)/&#041;/g;
                   19008:         $outgoing =~ s/"/&#034;/g;
                   19009:         $outgoing =~ s/'/&#039;/g;
                   19010:         $outgoing =~ s/\$/&#036;/g;
                   19011:         $outgoing =~ s{/}{&#047;}g;
                   19012:         $outgoing =~ s/=/&#061;/g;
                   19013:         $outgoing =~ s/\\/&#092;/g
                   19014:     }
                   19015:     return $outgoing;
                   19016: }
                   19017: 
1.1190    musolffc 19018: # Checks for critical messages and returns a redirect url if one exists.
                   19019: # $interval indicates how often to check for messages.
1.1282    raeburn  19020: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19021: sub critical_redirect {
1.1282    raeburn  19022:     my ($interval,$context) = @_;
1.1356    raeburn  19023:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19024:         return ();
                   19025:     }
1.1190    musolffc 19026:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19027:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19028:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19029:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19030:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19031:             if ($blocked) {
                   19032:                 my $checkrole = "cm./$cdom/$cnum";
                   19033:                 if ($env{'request.course.sec'} ne '') {
                   19034:                     $checkrole .= "/$env{'request.course.sec'}";
                   19035:                 }
                   19036:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19037:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19038:                     return;
                   19039:                 }
                   19040:             }
                   19041:         }
1.1190    musolffc 19042:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19043:                                         $env{'user.name'});
                   19044:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19045:         my $redirecturl;
1.1190    musolffc 19046:         if ($what[0]) {
1.1356    raeburn  19047: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19048: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19049: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19050:                 return (1, $url);
1.1190    musolffc 19051:             }
1.1191    raeburn  19052:         }
                   19053:     } 
                   19054:     return ();
1.1190    musolffc 19055: }
                   19056: 
1.1174    raeburn  19057: # Use:
                   19058: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19059: #
                   19060: ##################################################
                   19061: #          password associated functions         #
                   19062: ##################################################
                   19063: sub des_keys {
                   19064:     # Make a new key for DES encryption.
                   19065:     # Each key has two parts which are returned separately.
                   19066:     # Please note:  Each key must be passed through the &hex function
                   19067:     # before it is output to the web browser.  The hex versions cannot
                   19068:     # be used to decrypt.
                   19069:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19070:                 '8','9','a','b','c','d','e','f');
                   19071:     my $lkey='';
                   19072:     for (0..7) {
                   19073:         $lkey.=$hexstr[rand(15)];
                   19074:     }
                   19075:     my $ukey='';
                   19076:     for (0..7) {
                   19077:         $ukey.=$hexstr[rand(15)];
                   19078:     }
                   19079:     return ($lkey,$ukey);
                   19080: }
                   19081: 
                   19082: sub des_decrypt {
                   19083:     my ($key,$cyphertext) = @_;
                   19084:     my $keybin=pack("H16",$key);
                   19085:     my $cypher;
                   19086:     if ($Crypt::DES::VERSION>=2.03) {
                   19087:         $cypher=new Crypt::DES $keybin;
                   19088:     } else {
                   19089:         $cypher=new DES $keybin;
                   19090:     }
1.1233    raeburn  19091:     my $plaintext='';
                   19092:     my $cypherlength = length($cyphertext);
                   19093:     my $numchunks = int($cypherlength/32);
                   19094:     for (my $j=0; $j<$numchunks; $j++) {
                   19095:         my $start = $j*32;
                   19096:         my $cypherblock = substr($cyphertext,$start,32);
                   19097:         my $chunk =
                   19098:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19099:         $chunk .=
                   19100:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19101:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19102:         $plaintext .= $chunk;
                   19103:     }
1.1174    raeburn  19104:     return $plaintext;
                   19105: }
                   19106: 
1.1344    raeburn  19107: sub get_requested_shorturls {
1.1309    raeburn  19108:     my ($cdom,$cnum,$navmap) = @_;
                   19109:     return unless (ref($navmap));
1.1344    raeburn  19110:     my ($numnew,$errors);
1.1309    raeburn  19111:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19112:     if (@toshorten) {
                   19113:         my (%maps,%resources,%titles);
                   19114:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19115:                                                                'shorturls',$cdom,$cnum);
                   19116:         if (keys(%resources)) {
1.1344    raeburn  19117:             my %tocreate;
1.1309    raeburn  19118:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19119:                 my $symb = $resources{$item};
                   19120:                 if ($symb) {
                   19121:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19122:                 }
                   19123:             }
1.1344    raeburn  19124:             if (keys(%tocreate)) {
                   19125:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19126:                                                       \%tocreate);
                   19127:             }
1.1309    raeburn  19128:         }
1.1344    raeburn  19129:     }
                   19130:     return ($numnew,$errors);
                   19131: }
                   19132: 
                   19133: sub make_short_symbs {
                   19134:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19135:     my ($numnew,@errors);
                   19136:     if (ref($tocreateref) eq 'HASH') {
                   19137:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19138:         if (keys(%tocreate)) {
                   19139:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19140:             my $su = Short::URL->new(no_vowels => 1);
                   19141:             my $init = '';
                   19142:             my (%newunique,%addcourse,%courseonly,%failed);
                   19143:             # get lock on tiny db
                   19144:             my $now = time;
1.1344    raeburn  19145:             if ($lockuser eq '') {
                   19146:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19147:             }
1.1309    raeburn  19148:             my $lockhash = {
1.1344    raeburn  19149:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19150:                             };
                   19151:             my $tries = 0;
                   19152:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19153:             my ($code,$error);
                   19154:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19155:                 $tries ++;
                   19156:                 sleep 1;
1.1319    raeburn  19157:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19158:             }
                   19159:             if ($gotlock eq 'ok') {
                   19160:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19161:                                        \%addcourse,\%courseonly,\%failed);
                   19162:                 if (keys(%failed)) {
                   19163:                     my $numfailed = scalar(keys(%failed));
                   19164:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19165:                 }
                   19166:                 if (keys(%newunique)) {
                   19167:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19168:                     if ($putres eq 'ok') {
                   19169:                         $numnew = scalar(keys(%newunique));
                   19170:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19171:                         unless ($newputres eq 'ok') {
                   19172:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19173:                         }
                   19174:                     } else {
                   19175:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19176:                     }
                   19177:                 }
                   19178:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19179:                 unless ($dellockres eq 'ok') {
                   19180:                     push(@errors,&mt('error: could not release lockfile'));
                   19181:                 }
                   19182:             } else {
                   19183:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19184:             }
                   19185:             if (keys(%courseonly)) {
                   19186:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19187:                 if ($result ne 'ok') {
                   19188:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19189:                 }
                   19190:             }
                   19191:         }
                   19192:     }
                   19193:     return ($numnew,\@errors);
                   19194: }
                   19195: 
                   19196: sub shorten_symbs {
                   19197:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19198:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19199:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19200:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19201:     my (%possibles,%collisions);
                   19202:     foreach my $key (keys(%{$tocreate})) {
                   19203:         my $num = String::CRC32::crc32($key);
                   19204:         my $tiny = $su->encode($num,$init);
                   19205:         if ($tiny) {
                   19206:             $possibles{$tiny} = $key;
                   19207:         }
                   19208:     }
                   19209:     if (!$init) {
                   19210:         $init = 1;
                   19211:     } else {
                   19212:         $init ++;
                   19213:     }
                   19214:     if (keys(%possibles)) {
                   19215:         my @posstiny = keys(%possibles);
                   19216:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19217:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19218:         if (keys(%currtiny)) {
                   19219:             foreach my $key (keys(%currtiny)) {
                   19220:                 next if ($currtiny{$key} eq '');
                   19221:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19222:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19223:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19224:                         $courseonly->{$tsymb} = $key;
                   19225:                     }
                   19226:                 } else {
                   19227:                     $collisions{$possibles{$key}} = 1;
                   19228:                 }
                   19229:                 delete($possibles{$key});
                   19230:             }
                   19231:         }
                   19232:         foreach my $key (keys(%possibles)) {
                   19233:             $newunique->{$key} = $possibles{$key};
                   19234:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19235:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19236:                 $addcourse->{$tsymb} = $key;
                   19237:             }
                   19238:         }
                   19239:     }
                   19240:     if (keys(%collisions)) {
                   19241:         if ($init <5) {
                   19242:             if (!$init) {
                   19243:                 $init = 1;
                   19244:             } else {
                   19245:                 $init ++;
                   19246:             }
                   19247:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19248:                                    $newunique,$addcourse,$courseonly,$failed);
                   19249:         } else {
                   19250:             foreach my $key (keys(%collisions)) {
                   19251:                 $failed->{$key} = 1;
                   19252:             }
                   19253:         }
                   19254:     }
                   19255:     return $init;
                   19256: }
                   19257: 
1.1328    raeburn  19258: sub is_nonframeable {
1.1329    raeburn  19259:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19260:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19261:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19262: 
                   19263:     $remprotocol = lc($remprotocol);
                   19264:     $remhost = lc($remhost);
                   19265:     my $remport = 80;
                   19266:     if ($remprotocol eq 'https') {
                   19267:         $remport = 443;
                   19268:     }
1.1330    raeburn  19269:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19270:     if ($cached) {
                   19271:         unless ($nocache) {
                   19272:             if ($result) {
                   19273:                 return 1;
                   19274:             } else {
                   19275:                 return 0;
                   19276:             }
                   19277:         }
                   19278:     }
1.1328    raeburn  19279:     my $uselink;
                   19280:     my $request = new HTTP::Request('HEAD',$url);
                   19281:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19282:     if ($response->is_success()) {
                   19283:         my $secpolicy = lc($response->header('content-security-policy'));
                   19284:         my $xframeop = lc($response->header('x-frame-options'));
                   19285:         $secpolicy =~ s/^\s+|\s+$//g;
                   19286:         $xframeop =~ s/^\s+|\s+$//g;
                   19287:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19288:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19289:             my ($origin,$protocol,$port);
                   19290:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19291:                 $port = $ENV{'SERVER_PORT'};
                   19292:             } else {
                   19293:                 $port = 80;
                   19294:             }
                   19295:             if ($absolute eq '') {
                   19296:                 $protocol = 'http:';
                   19297:                 if ($port == 443) {
                   19298:                     $protocol = 'https:';
                   19299:                 }
                   19300:                 $origin = $protocol.'//'.lc($hostname);
                   19301:             } else {
                   19302:                 $origin = lc($absolute);
                   19303:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19304:             }
                   19305:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19306:                 my $framepolicy = $1;
                   19307:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19308:                 my @policies = split(/\s+/,$framepolicy);
                   19309:                 if (@policies) {
                   19310:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19311:                         $uselink = 1;
                   19312:                     } else {
                   19313:                         $uselink = 1;
                   19314:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19315:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19316:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19317:                             undef($uselink);
                   19318:                         }
                   19319:                         if ($uselink) {
                   19320:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19321:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19322:                                     undef($uselink);
                   19323:                                 }
                   19324:                             }
                   19325:                         }
                   19326:                         if ($uselink) {
                   19327:                             my @possok;
                   19328:                             if ($ip ne '') {
                   19329:                                 push(@possok,$ip);
                   19330:                             }
                   19331:                             my $hoststr = '';
                   19332:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19333:                                 if ($hoststr eq '') {
                   19334:                                     $hoststr = $part;
                   19335:                                 } else {
                   19336:                                     $hoststr = "$part.$hoststr";
                   19337:                                 }
                   19338:                                 if ($hoststr eq $hostname) {
                   19339:                                     push(@possok,$hostname);
                   19340:                                 } else {
                   19341:                                     push(@possok,"*.$hoststr");
                   19342:                                 }
                   19343:                             }
                   19344:                             if (@possok) {
                   19345:                                 foreach my $poss (@possok) {
                   19346:                                     last if (!$uselink);
                   19347:                                     foreach my $policy (@policies) {
                   19348:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19349:                                             undef($uselink);
                   19350:                                             last;
                   19351:                                         }
                   19352:                                     }
                   19353:                                 }
                   19354:                             }
                   19355:                         }
                   19356:                     }
                   19357:                 }
                   19358:             } elsif ($xframeop ne '') {
                   19359:                 $uselink = 1;
                   19360:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19361:                 if (@policies) {
                   19362:                     unless (grep(/^deny$/,@policies)) {
                   19363:                         if ($origin ne '') {
                   19364:                             if (grep(/^sameorigin$/,@policies)) {
                   19365:                                 if ($remotehost eq $origin) {
                   19366:                                     undef($uselink);
                   19367:                                 }
                   19368:                             }
                   19369:                             if ($uselink) {
                   19370:                                 foreach my $policy (@policies) {
                   19371:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19372:                                         my $allowfrom = $1;
                   19373:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19374:                                             undef($uselink);
                   19375:                                             last;
                   19376:                                         }
                   19377:                                     }
                   19378:                                 }
                   19379:                             }
                   19380:                         }
                   19381:                     }
                   19382:                 }
                   19383:             }
                   19384:         }
                   19385:     }
1.1329    raeburn  19386:     if ($nocache) {
                   19387:         if ($cached) {
                   19388:             my $devalidate;
                   19389:             if ($uselink && !$result) {
                   19390:                 $devalidate = 1;
                   19391:             } elsif (!$uselink && $result) {
                   19392:                 $devalidate = 1;
                   19393:             }
                   19394:             if ($devalidate) {
                   19395:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19396:             }
                   19397:         }
                   19398:     } else {
                   19399:         if ($uselink) {
                   19400:             $result = 1;
                   19401:         } else {
                   19402:             $result = 0;
                   19403:         }
                   19404:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19405:     }
1.1328    raeburn  19406:     return $uselink;
                   19407: }
                   19408: 
1.1359    raeburn  19409: sub page_menu {
                   19410:     my ($menucolls,$menunum) = @_;
                   19411:     my %menu;
                   19412:     foreach my $item (split(/;/,$menucolls)) {
                   19413:         my ($num,$value) = split(/\%/,$item);
                   19414:         if ($num eq $menunum) {
                   19415:             my @entries = split(/\&/,$value);
                   19416:             foreach my $entry (@entries) {
                   19417:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19418:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  19419:                     $menu{$name} = $fields;
                   19420:                 } else {
                   19421:                     my @shown;
                   19422:                     if ($fields =~ /,/) {
                   19423:                         @shown = split(/,/,$fields);
                   19424:                     } else {
                   19425:                         @shown = ($fields);
                   19426:                     }
                   19427:                     if (@shown) {
                   19428:                         foreach my $field (@shown) {
                   19429:                             next if ($field eq '');
                   19430:                             $menu{$field} = 1;
                   19431:                         }
                   19432:                     }
                   19433:                 }
                   19434:             }
                   19435:         }
                   19436:     }
                   19437:     return %menu;
                   19438: }
                   19439: 
1.112     bowersj2 19440: 1;
                   19441: __END__;
1.41      ng       19442: 

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