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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1332  ! raeburn     4: # $Id: loncommon.pm,v 1.1331 2019/05/05 23:19:47 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1280    raeburn    74: use LONCAPA::LWPReq;
1.1328    raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1241    raeburn    77: use DateTime::Locale;
1.1220    raeburn    78: use Encode();
1.1091    foxr       79: use Text::Aspell;
1.1094    raeburn    80: use Authen::Captcha;
                     81: use Captcha::reCAPTCHA;
1.1234    raeburn    82: use JSON::DWIW;
                     83: use LWP::UserAgent;
1.1174    raeburn    84: use Crypt::DES;
                     85: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   86: use MIME::Lite;
                     87: use MIME::Types;
1.1292    raeburn    88: use File::Copy();
1.1300    raeburn    89: use File::Path();
1.1309    raeburn    90: use String::CRC32();
                     91: use Short::URL();
1.117     www        92: 
1.517     raeburn    93: # ---------------------------------------------- Designs
                     94: use vars qw(%defaultdesign);
                     95: 
1.22      www        96: my $readit;
                     97: 
1.517     raeburn    98: 
1.157     matthew    99: ##
                    100: ## Global Variables
                    101: ##
1.46      matthew   102: 
1.643     foxr      103: 
                    104: # ----------------------------------------------- SSI with retries:
                    105: #
                    106: 
                    107: =pod
                    108: 
1.648     raeburn   109: =head1 Server Side include with retries:
1.643     foxr      110: 
                    111: =over 4
                    112: 
1.648     raeburn   113: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      114: 
                    115: Performs an ssi with some number of retries.  Retries continue either
                    116: until the result is ok or until the retry count supplied by the
                    117: caller is exhausted.  
                    118: 
                    119: Inputs:
1.648     raeburn   120: 
                    121: =over 4
                    122: 
1.643     foxr      123: resource   - Identifies the resource to insert.
1.648     raeburn   124: 
1.643     foxr      125: retries    - Count of the number of retries allowed.
1.648     raeburn   126: 
1.643     foxr      127: form       - Hash that identifies the rendering options.
                    128: 
1.648     raeburn   129: =back
                    130: 
                    131: Returns:
                    132: 
                    133: =over 4
                    134: 
1.643     foxr      135: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   136: 
1.643     foxr      137: response   - The response from the last attempt (which may or may not have been successful.
                    138: 
1.648     raeburn   139: =back
                    140: 
                    141: =back
                    142: 
1.643     foxr      143: =cut
                    144: 
                    145: sub ssi_with_retries {
                    146:     my ($resource, $retries, %form) = @_;
                    147: 
                    148: 
                    149:     my $ok = 0;			# True if we got a good response.
                    150:     my $content;
                    151:     my $response;
                    152: 
                    153:     # Try to get the ssi done. within the retries count:
                    154: 
                    155:     do {
                    156: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    157: 	$ok      = $response->is_success;
1.650     www       158:         if (!$ok) {
                    159:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    160:         }
1.643     foxr      161: 	$retries--;
                    162:     } while (!$ok && ($retries > 0));
                    163: 
                    164:     if (!$ok) {
                    165: 	$content = '';		# On error return an empty content.
                    166:     }
                    167:     return ($content, $response);
                    168: 
                    169: }
                    170: 
                    171: 
                    172: 
1.20      www       173: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  174: my %language;
1.124     www       175: my %supported_language;
1.1088    foxr      176: my %supported_codes;
1.1048    foxr      177: my %latex_language;		# For choosing hyphenation in <transl..>
                    178: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  179: my %cprtag;
1.192     taceyjo1  180: my %scprtag;
1.351     www       181: my %fe; my %fd; my %fm;
1.41      ng        182: my %category_extensions;
1.12      harris41  183: 
1.46      matthew   184: # ---------------------------------------------- Thesaurus variables
1.144     matthew   185: #
                    186: # %Keywords:
                    187: #      A hash used by &keyword to determine if a word is considered a keyword.
                    188: # $thesaurus_db_file 
                    189: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   190: 
                    191: my %Keywords;
                    192: my $thesaurus_db_file;
                    193: 
1.144     matthew   194: #
                    195: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    196: # thesaurus.tab, and filecategories.tab.
                    197: #
1.18      www       198: BEGIN {
1.46      matthew   199:     # Variable initialization
                    200:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    201:     #
1.22      www       202:     unless ($readit) {
1.12      harris41  203: # ------------------------------------------------------------------- languages
                    204:     {
1.158     raeburn   205:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    206:                                    '/language.tab';
1.1317    raeburn   207:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  208:             while (my $line = <$fh>) {
                    209:                 next if ($line=~/^\#/);
                    210:                 chomp($line);
1.1088    foxr      211:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   212:                 $language{$key}=$val.' - '.$enc;
                    213:                 if ($sup) {
                    214:                     $supported_language{$key}=$sup;
1.1088    foxr      215: 		    $supported_codes{$key}   = $code;
1.158     raeburn   216:                 }
1.1048    foxr      217: 		if ($latex) {
                    218: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      219: 		    $latex_language{$code} = $latex;
1.1048    foxr      220: 		}
1.158     raeburn   221:             }
                    222:             close($fh);
                    223:         }
1.12      harris41  224:     }
                    225: # ------------------------------------------------------------------ copyrights
                    226:     {
1.158     raeburn   227:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    228:                                   '/copyright.tab';
1.1317    raeburn   229:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  230:             while (my $line = <$fh>) {
                    231:                 next if ($line=~/^\#/);
                    232:                 chomp($line);
                    233:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   234:                 $cprtag{$key}=$val;
                    235:             }
                    236:             close($fh);
                    237:         }
1.12      harris41  238:     }
1.351     www       239: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  240:     {
                    241:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    242:                                   '/source_copyright.tab';
1.1317    raeburn   243:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  244:             while (my $line = <$fh>) {
                    245:                 next if ($line =~ /^\#/);
                    246:                 chomp($line);
                    247:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  248:                 $scprtag{$key}=$val;
                    249:             }
                    250:             close($fh);
                    251:         }
                    252:     }
1.63      www       253: 
1.517     raeburn   254: # -------------------------------------------------------------- default domain designs
1.63      www       255:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   256:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   257:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   258:         while (my $line = <$fh>) {
                    259:             next if ($line =~ /^\#/);
                    260:             chomp($line);
                    261:             my ($key,$val)=(split(/\=/,$line));
                    262:             if ($val) { $defaultdesign{$key}=$val; }
                    263:         }
                    264:         close($fh);
1.63      www       265:     }
                    266: 
1.15      harris41  267: # ------------------------------------------------------------- file categories
                    268:     {
1.158     raeburn   269:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    270:                                   '/filecategories.tab';
1.1317    raeburn   271:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  272: 	    while (my $line = <$fh>) {
                    273: 		next if ($line =~ /^\#/);
                    274: 		chomp($line);
                    275:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   276:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   277:             }
                    278:             close($fh);
                    279:         }
                    280: 
1.15      harris41  281:     }
1.12      harris41  282: # ------------------------------------------------------------------ file types
                    283:     {
1.158     raeburn   284:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    285:                '/filetypes.tab';
1.1317    raeburn   286:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  287:             while (my $line = <$fh>) {
                    288: 		next if ($line =~ /^\#/);
                    289: 		chomp($line);
                    290:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   291:                 if ($descr ne '') {
                    292:                     $fe{$ending}=lc($emb);
                    293:                     $fd{$ending}=$descr;
1.351     www       294:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   295:                 }
                    296:             }
                    297:             close($fh);
                    298:         }
1.12      harris41  299:     }
1.22      www       300:     &Apache::lonnet::logthis(
1.705     tempelho  301:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       302:     $readit=1;
1.46      matthew   303:     }  # end of unless($readit) 
1.32      matthew   304:     
                    305: }
1.112     bowersj2  306: 
1.42      matthew   307: ###############################################################
                    308: ##           HTML and Javascript Helper Functions            ##
                    309: ###############################################################
                    310: 
                    311: =pod 
                    312: 
1.112     bowersj2  313: =head1 HTML and Javascript Functions
1.42      matthew   314: 
1.112     bowersj2  315: =over 4
                    316: 
1.648     raeburn   317: =item * &browser_and_searcher_javascript()
1.112     bowersj2  318: 
                    319: X<browsing, javascript>X<searching, javascript>Returns a string
                    320: containing javascript with two functions, C<openbrowser> and
                    321: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    322: tags.
1.42      matthew   323: 
1.648     raeburn   324: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   325: 
                    326: inputs: formname, elementname, only, omit
                    327: 
                    328: formname and elementname indicate the name of the html form and name of
                    329: the element that the results of the browsing selection are to be placed in. 
                    330: 
                    331: Specifying 'only' will restrict the browser to displaying only files
1.185     www       332: with the given extension.  Can be a comma separated list.
1.42      matthew   333: 
                    334: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       335: with the given extension.  Can be a comma separated list.
1.42      matthew   336: 
1.648     raeburn   337: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   338: 
                    339: Inputs: formname, elementname
                    340: 
                    341: formname and elementname specify the name of the html form and the name
                    342: of the element the selection from the search results will be placed in.
1.542     raeburn   343: 
1.42      matthew   344: =cut
                    345: 
                    346: sub browser_and_searcher_javascript {
1.199     albertel  347:     my ($mode)=@_;
                    348:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  349:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   350:     return <<END;
1.219     albertel  351: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   352:     var editbrowser = null;
1.135     albertel  353:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       354:         var url = '$resurl/?';
1.42      matthew   355:         if (editbrowser == null) {
                    356:             url += 'launch=1&';
                    357:         }
                    358:         url += 'catalogmode=interactive&';
1.199     albertel  359:         url += 'mode=$mode&';
1.611     albertel  360:         url += 'inhibitmenu=yes&';
1.42      matthew   361:         url += 'form=' + formname + '&';
                    362:         if (only != null) {
                    363:             url += 'only=' + only + '&';
1.217     albertel  364:         } else {
                    365:             url += 'only=&';
                    366: 	}
1.42      matthew   367:         if (omit != null) {
                    368:             url += 'omit=' + omit + '&';
1.217     albertel  369:         } else {
                    370:             url += 'omit=&';
                    371: 	}
1.135     albertel  372:         if (titleelement != null) {
                    373:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  374:         } else {
                    375: 	    url += 'titleelement=&';
                    376: 	}
1.42      matthew   377:         url += 'element=' + elementname + '';
                    378:         var title = 'Browser';
1.435     albertel  379:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   380:         options += ',width=700,height=600';
                    381:         editbrowser = open(url,title,options,'1');
                    382:         editbrowser.focus();
                    383:     }
                    384:     var editsearcher;
1.135     albertel  385:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   386:         var url = '/adm/searchcat?';
                    387:         if (editsearcher == null) {
                    388:             url += 'launch=1&';
                    389:         }
                    390:         url += 'catalogmode=interactive&';
1.199     albertel  391:         url += 'mode=$mode&';
1.42      matthew   392:         url += 'form=' + formname + '&';
1.135     albertel  393:         if (titleelement != null) {
                    394:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  395:         } else {
                    396: 	    url += 'titleelement=&';
                    397: 	}
1.42      matthew   398:         url += 'element=' + elementname + '';
                    399:         var title = 'Search';
1.435     albertel  400:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   401:         options += ',width=700,height=600';
                    402:         editsearcher = open(url,title,options,'1');
                    403:         editsearcher.focus();
                    404:     }
1.219     albertel  405: // END LON-CAPA Internal -->
1.42      matthew   406: END
1.170     www       407: }
                    408: 
                    409: sub lastresurl {
1.258     albertel  410:     if ($env{'environment.lastresurl'}) {
                    411: 	return $env{'environment.lastresurl'}
1.170     www       412:     } else {
                    413: 	return '/res';
                    414:     }
                    415: }
                    416: 
                    417: sub storeresurl {
                    418:     my $resurl=&Apache::lonnet::clutter(shift);
                    419:     unless ($resurl=~/^\/res/) { return 0; }
                    420:     $resurl=~s/\/$//;
                    421:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   422:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       423:     return 1;
1.42      matthew   424: }
                    425: 
1.74      www       426: sub studentbrowser_javascript {
1.111     www       427:    unless (
1.258     albertel  428:             (($env{'request.course.id'}) && 
1.302     albertel  429:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    430: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    431: 					  '/'.$env{'request.course.sec'})
                    432: 	      ))
1.258     albertel  433:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       434:           ) { return ''; }  
1.74      www       435:    return (<<'ENDSTDBRW');
1.776     bisitz    436: <script type="text/javascript" language="Javascript">
1.824     bisitz    437: // <![CDATA[
1.74      www       438:     var stdeditbrowser;
1.999     www       439:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       440:         var url = '/adm/pickstudent?';
                    441:         var filter;
1.558     albertel  442: 	if (!ignorefilter) {
                    443: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    444: 	}
1.74      www       445:         if (filter != null) {
                    446:            if (filter != '') {
                    447:                url += 'filter='+filter+'&';
                    448: 	   }
                    449:         }
                    450:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       451:                                     '&udomelement='+udom+
                    452:                                     '&clicker='+clicker;
1.111     www       453: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   454:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       455:         var title = 'Student_Browser';
1.74      www       456:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    457:         options += ',width=700,height=600';
                    458:         stdeditbrowser = open(url,title,options,'1');
                    459:         stdeditbrowser.focus();
                    460:     }
1.824     bisitz    461: // ]]>
1.74      www       462: </script>
                    463: ENDSTDBRW
                    464: }
1.42      matthew   465: 
1.1003    www       466: sub resourcebrowser_javascript {
                    467:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       468:    return (<<'ENDRESBRW');
1.1003    www       469: <script type="text/javascript" language="Javascript">
                    470: // <![CDATA[
                    471:     var reseditbrowser;
1.1004    www       472:     function openresbrowser(formname,reslink) {
1.1005    www       473:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       474:         var title = 'Resource_Browser';
                    475:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       476:         options += ',width=700,height=500';
1.1004    www       477:         reseditbrowser = open(url,title,options,'1');
                    478:         reseditbrowser.focus();
1.1003    www       479:     }
                    480: // ]]>
                    481: </script>
1.1004    www       482: ENDRESBRW
1.1003    www       483: }
                    484: 
1.74      www       485: sub selectstudent_link {
1.999     www       486:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    487:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    489:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  490:    if ($env{'request.course.id'}) {  
1.302     albertel  491:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    492: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    493: 					'/'.$env{'request.course.sec'})) {
1.111     www       494: 	   return '';
                    495:        }
1.999     www       496:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   497:        if ($courseadvonly)  {
                    498:            $callargs .= ",'',1,1";
                    499:        }
                    500:        return '<span class="LC_nobreak">'.
                    501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    502:               &mt('Select User').'</a></span>';
1.74      www       503:    }
1.258     albertel  504:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       505:        $callargs .= ",'',1"; 
1.793     raeburn   506:        return '<span class="LC_nobreak">'.
                    507:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    508:               &mt('Select User').'</a></span>';
1.111     www       509:    }
                    510:    return '';
1.91      www       511: }
                    512: 
1.1004    www       513: sub selectresource_link {
                    514:    my ($form,$reslink,$arg)=@_;
                    515:    
                    516:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    517:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    518:    unless ($env{'request.course.id'}) { return $arg; }
                    519:    return '<span class="LC_nobreak">'.
                    520:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    521:               $arg.'</a></span>';
                    522: }
                    523: 
                    524: 
                    525: 
1.653     raeburn   526: sub authorbrowser_javascript {
                    527:     return <<"ENDAUTHORBRW";
1.776     bisitz    528: <script type="text/javascript" language="JavaScript">
1.824     bisitz    529: // <![CDATA[
1.653     raeburn   530: var stdeditbrowser;
                    531: 
                    532: function openauthorbrowser(formname,udom) {
                    533:     var url = '/adm/pickauthor?';
                    534:     url += 'form='+formname+'&roledom='+udom;
                    535:     var title = 'Author_Browser';
                    536:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    537:     options += ',width=700,height=600';
                    538:     stdeditbrowser = open(url,title,options,'1');
                    539:     stdeditbrowser.focus();
                    540: }
                    541: 
1.824     bisitz    542: // ]]>
1.653     raeburn   543: </script>
                    544: ENDAUTHORBRW
                    545: }
                    546: 
1.91      www       547: sub coursebrowser_javascript {
1.1116    raeburn   548:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   549:         $credits_element,$instcode) = @_;
1.932     raeburn   550:     my $wintitle = 'Course_Browser';
1.931     raeburn   551:     if ($crstype eq 'Community') {
1.932     raeburn   552:         $wintitle = 'Community_Browser';
1.909     raeburn   553:     }
1.876     raeburn   554:     my $id_functions = &javascript_index_functions();
                    555:     my $output = '
1.776     bisitz    556: <script type="text/javascript" language="JavaScript">
1.824     bisitz    557: // <![CDATA[
1.468     raeburn   558:     var stdeditbrowser;'."\n";
1.876     raeburn   559: 
                    560:     $output .= <<"ENDSTDBRW";
1.909     raeburn   561:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       562:         var url = '/adm/pickcourse?';
1.895     raeburn   563:         var formid = getFormIdByName(formname);
1.876     raeburn   564:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  565:         if (domainfilter != null) {
                    566:            if (domainfilter != '') {
                    567:                url += 'domainfilter='+domainfilter+'&';
                    568: 	   }
                    569:         }
1.91      www       570:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  571: 	                            '&cdomelement='+udom+
                    572:                                     '&cnameelement='+desc;
1.468     raeburn   573:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   574:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   575:                 url += '&roleelement='+extra_element;
                    576:                 if (domainfilter == null || domainfilter == '') {
                    577:                     url += '&domainfilter='+extra_element;
                    578:                 }
1.234     raeburn   579:             }
1.468     raeburn   580:             else {
                    581:                 if (formname == 'portform') {
                    582:                     url += '&setroles='+extra_element;
1.800     raeburn   583:                 } else {
                    584:                     if (formname == 'rules') {
                    585:                         url += '&fixeddom='+extra_element; 
                    586:                     }
1.468     raeburn   587:                 }
                    588:             }     
1.230     raeburn   589:         }
1.909     raeburn   590:         if (type != null && type != '') {
                    591:             url += '&type='+type;
                    592:         }
                    593:         if (type_elem != null && type_elem != '') {
                    594:             url += '&typeelement='+type_elem;
                    595:         }
1.872     raeburn   596:         if (formname == 'ccrs') {
                    597:             var ownername = document.forms[formid].ccuname.value;
                    598:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   599:             url += '&cloner='+ownername+':'+ownerdom;
                    600:             if (type == 'Course') {
                    601:                 url += '&crscode='+document.forms[formid].crscode.value;
                    602:             }
1.1221    raeburn   603:         }
                    604:         if (formname == 'requestcrs') {
                    605:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   606:         }
1.293     raeburn   607:         if (multflag !=null && multflag != '') {
                    608:             url += '&multiple='+multflag;
                    609:         }
1.909     raeburn   610:         var title = '$wintitle';
1.91      www       611:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    612:         options += ',width=700,height=600';
                    613:         stdeditbrowser = open(url,title,options,'1');
                    614:         stdeditbrowser.focus();
                    615:     }
1.876     raeburn   616: $id_functions
                    617: ENDSTDBRW
1.1116    raeburn   618:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    619:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    620:                                       $credits_element);
1.876     raeburn   621:     }
                    622:     $output .= '
                    623: // ]]>
                    624: </script>';
                    625:     return $output;
                    626: }
                    627: 
                    628: sub javascript_index_functions {
                    629:     return <<"ENDJS";
                    630: 
                    631: function getFormIdByName(formname) {
                    632:     for (var i=0;i<document.forms.length;i++) {
                    633:         if (document.forms[i].name == formname) {
                    634:             return i;
                    635:         }
                    636:     }
                    637:     return -1;
                    638: }
                    639: 
                    640: function getIndexByName(formid,item) {
                    641:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    642:         if (document.forms[formid].elements[i].name == item) {
                    643:             return i;
                    644:         }
                    645:     }
                    646:     return -1;
                    647: }
1.468     raeburn   648: 
1.876     raeburn   649: function getDomainFromSelectbox(formname,udom) {
                    650:     var userdom;
                    651:     var formid = getFormIdByName(formname);
                    652:     if (formid > -1) {
                    653:         var domid = getIndexByName(formid,udom);
                    654:         if (domid > -1) {
                    655:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    656:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    657:             }
                    658:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    659:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   660:             }
                    661:         }
                    662:     }
1.876     raeburn   663:     return userdom;
                    664: }
                    665: 
                    666: ENDJS
1.468     raeburn   667: 
1.876     raeburn   668: }
                    669: 
1.1017    raeburn   670: sub javascript_array_indexof {
1.1018    raeburn   671:     return <<ENDJS;
1.1017    raeburn   672: <script type="text/javascript" language="JavaScript">
                    673: // <![CDATA[
                    674: 
                    675: if (!Array.prototype.indexOf) {
                    676:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    677:         "use strict";
                    678:         if (this === void 0 || this === null) {
                    679:             throw new TypeError();
                    680:         }
                    681:         var t = Object(this);
                    682:         var len = t.length >>> 0;
                    683:         if (len === 0) {
                    684:             return -1;
                    685:         }
                    686:         var n = 0;
                    687:         if (arguments.length > 0) {
                    688:             n = Number(arguments[1]);
1.1088    foxr      689:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   690:                 n = 0;
                    691:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    692:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    693:             }
                    694:         }
                    695:         if (n >= len) {
                    696:             return -1;
                    697:         }
                    698:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    699:         for (; k < len; k++) {
                    700:             if (k in t && t[k] === searchElement) {
                    701:                 return k;
                    702:             }
                    703:         }
                    704:         return -1;
                    705:     }
                    706: }
                    707: 
                    708: // ]]>
                    709: </script>
                    710: 
                    711: ENDJS
                    712: 
                    713: }
                    714: 
1.876     raeburn   715: sub userbrowser_javascript {
                    716:     my $id_functions = &javascript_index_functions();
                    717:     return <<"ENDUSERBRW";
                    718: 
1.888     raeburn   719: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   720:     var url = '/adm/pickuser?';
                    721:     var userdom = getDomainFromSelectbox(formname,udom);
                    722:     if (userdom != null) {
                    723:        if (userdom != '') {
                    724:            url += 'srchdom='+userdom+'&';
                    725:        }
                    726:     }
                    727:     url += 'form=' + formname + '&unameelement='+uname+
                    728:                                 '&udomelement='+udom+
                    729:                                 '&ulastelement='+ulast+
                    730:                                 '&ufirstelement='+ufirst+
                    731:                                 '&uemailelement='+uemail+
1.881     raeburn   732:                                 '&hideudomelement='+hideudom+
                    733:                                 '&coursedom='+crsdom;
1.888     raeburn   734:     if ((caller != null) && (caller != undefined)) {
                    735:         url += '&caller='+caller;
                    736:     }
1.876     raeburn   737:     var title = 'User_Browser';
                    738:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    739:     options += ',width=700,height=600';
                    740:     var stdeditbrowser = open(url,title,options,'1');
                    741:     stdeditbrowser.focus();
                    742: }
                    743: 
1.888     raeburn   744: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   745:     var formid = getFormIdByName(formname);
                    746:     if (formid > -1) {
1.888     raeburn   747:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   748:         var domid = getIndexByName(formid,udom);
                    749:         var hidedomid = getIndexByName(formid,origdom);
                    750:         if (hidedomid > -1) {
                    751:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   752:             var unameval = document.forms[formid].elements[unameid].value;
                    753:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    754:                 if (domid > -1) {
                    755:                     var slct = document.forms[formid].elements[domid];
                    756:                     if (slct.type == 'select-one') {
                    757:                         var i;
                    758:                         for (i=0;i<slct.length;i++) {
                    759:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    760:                         }
                    761:                     }
                    762:                     if (slct.type == 'hidden') {
                    763:                         slct.value = fixeddom;
1.876     raeburn   764:                     }
                    765:                 }
1.468     raeburn   766:             }
                    767:         }
                    768:     }
1.876     raeburn   769:     return;
                    770: }
                    771: 
                    772: $id_functions
                    773: ENDUSERBRW
1.468     raeburn   774: }
                    775: 
                    776: sub setsec_javascript {
1.1116    raeburn   777:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   778:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    779:         $communityrolestr);
                    780:     if ($role_element ne '') {
                    781:         my @allroles = ('st','ta','ep','in','ad');
                    782:         foreach my $crstype ('Course','Community') {
                    783:             if ($crstype eq 'Community') {
                    784:                 foreach my $role (@allroles) {
                    785:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    786:                 }
                    787:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    788:             } else {
                    789:                 foreach my $role (@allroles) {
                    790:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    791:                 }
                    792:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    793:             }
                    794:         }
                    795:         $rolestr = '"'.join('","',@allroles).'"';
                    796:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    797:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    798:     }
1.468     raeburn   799:     my $setsections = qq|
                    800: function setSect(sectionlist) {
1.629     raeburn   801:     var sectionsArray = new Array();
                    802:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    803:         sectionsArray = sectionlist.split(",");
                    804:     }
1.468     raeburn   805:     var numSections = sectionsArray.length;
                    806:     document.$formname.$sec_element.length = 0;
                    807:     if (numSections == 0) {
                    808:         document.$formname.$sec_element.multiple=false;
                    809:         document.$formname.$sec_element.size=1;
                    810:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    811:     } else {
                    812:         if (numSections == 1) {
                    813:             document.$formname.$sec_element.multiple=false;
                    814:             document.$formname.$sec_element.size=1;
                    815:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    816:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    817:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    818:         } else {
                    819:             for (var i=0; i<numSections; i++) {
                    820:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    821:             }
                    822:             document.$formname.$sec_element.multiple=true
                    823:             if (numSections < 3) {
                    824:                 document.$formname.$sec_element.size=numSections;
                    825:             } else {
                    826:                 document.$formname.$sec_element.size=3;
                    827:             }
                    828:             document.$formname.$sec_element.options[0].selected = false
                    829:         }
                    830:     }
1.91      www       831: }
1.905     raeburn   832: 
                    833: function setRole(crstype) {
1.468     raeburn   834: |;
1.905     raeburn   835:     if ($role_element eq '') {
                    836:         $setsections .= '    return;
                    837: }
                    838: ';
                    839:     } else {
                    840:         $setsections .= qq|
                    841:     var elementLength = document.$formname.$role_element.length;
                    842:     var allroles = Array($rolestr);
                    843:     var courserolenames = Array($courserolestr);
                    844:     var communityrolenames = Array($communityrolestr);
                    845:     if (elementLength != undefined) {
                    846:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    847:             if (crstype == 'Course') {
                    848:                 return;
                    849:             } else {
                    850:                 allroles[5] = 'co';
                    851:                 for (var i=0; i<6; i++) {
                    852:                     document.$formname.$role_element.options[i].value = allroles[i];
                    853:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    854:                 }
                    855:             }
                    856:         } else {
                    857:             if (crstype == 'Community') {
                    858:                 return;
                    859:             } else {
                    860:                 allroles[5] = 'cc';
                    861:                 for (var i=0; i<6; i++) {
                    862:                     document.$formname.$role_element.options[i].value = allroles[i];
                    863:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    864:                 }
                    865:             }
                    866:         }
                    867:     }
                    868:     return;
                    869: }
                    870: |;
                    871:     }
1.1116    raeburn   872:     if ($credits_element) {
                    873:         $setsections .= qq|
                    874: function setCredits(defaultcredits) {
                    875:     document.$formname.$credits_element.value = defaultcredits;
                    876:     return;
                    877: }
                    878: |;
                    879:     }
1.468     raeburn   880:     return $setsections;
                    881: }
                    882: 
1.91      www       883: sub selectcourse_link {
1.909     raeburn   884:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    885:        $typeelement) = @_;
                    886:    my $type = $selecttype;
1.871     raeburn   887:    my $linktext = &mt('Select Course');
                    888:    if ($selecttype eq 'Community') {
1.909     raeburn   889:        $linktext = &mt('Select Community');
1.1239    raeburn   890:    } elsif ($selecttype eq 'Placement') {
                    891:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   892:    } elsif ($selecttype eq 'Course/Community') {
                    893:        $linktext = &mt('Select Course/Community');
1.909     raeburn   894:        $type = '';
1.1019    raeburn   895:    } elsif ($selecttype eq 'Select') {
                    896:        $linktext = &mt('Select');
                    897:        $type = '';
1.871     raeburn   898:    }
1.787     bisitz    899:    return '<span class="LC_nobreak">'
                    900:          ."<a href='"
                    901:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    902:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   903:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   904:          ."'>".$linktext.'</a>'
1.787     bisitz    905:          .'</span>';
1.74      www       906: }
1.42      matthew   907: 
1.653     raeburn   908: sub selectauthor_link {
                    909:    my ($form,$udom)=@_;
                    910:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    911:           &mt('Select Author').'</a>';
                    912: }
                    913: 
1.876     raeburn   914: sub selectuser_link {
1.881     raeburn   915:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   916:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   917:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   918:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   919:            ');">'.$linktext.'</a>';
1.876     raeburn   920: }
                    921: 
1.273     raeburn   922: sub check_uncheck_jscript {
                    923:     my $jscript = <<"ENDSCRT";
                    924: function checkAll(field) {
                    925:     if (field.length > 0) {
                    926:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   927:             if (!field[i].disabled) { 
                    928:                 field[i].checked = true;
                    929:             }
1.273     raeburn   930:         }
                    931:     } else {
1.1093    raeburn   932:         if (!field.disabled) { 
                    933:             field.checked = true;
                    934:         }
1.273     raeburn   935:     }
                    936: }
                    937:  
                    938: function uncheckAll(field) {
                    939:     if (field.length > 0) {
                    940:         for (i = 0; i < field.length; i++) {
                    941:             field[i].checked = false ;
1.543     albertel  942:         }
                    943:     } else {
1.273     raeburn   944:         field.checked = false ;
                    945:     }
                    946: }
                    947: ENDSCRT
                    948:     return $jscript;
                    949: }
                    950: 
1.656     www       951: sub select_timezone {
1.1256    raeburn   952:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    953:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   954:    if ($includeempty) {
                    955:        $output .= '<option value=""';
                    956:        if (($selected eq '') || ($selected eq 'local')) {
                    957:            $output .= ' selected="selected" ';
                    958:        }
                    959:        $output .= '> </option>';
                    960:    }
1.657     raeburn   961:    my @timezones = DateTime::TimeZone->all_names;
                    962:    foreach my $tzone (@timezones) {
                    963:        $output.= '<option value="'.$tzone.'"';
                    964:        if ($tzone eq $selected) {
                    965:            $output.=' selected="selected"';
                    966:        }
                    967:        $output.=">$tzone</option>\n";
1.656     www       968:    }
                    969:    $output.="</select>";
                    970:    return $output;
                    971: }
1.273     raeburn   972: 
1.687     raeburn   973: sub select_datelocale {
1.1256    raeburn   974:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    975:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   976:     if ($includeempty) {
                    977:         $output .= '<option value=""';
                    978:         if ($selected eq '') {
                    979:             $output .= ' selected="selected" ';
                    980:         }
                    981:         $output .= '> </option>';
                    982:     }
1.1241    raeburn   983:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   984:     my (@possibles,%locale_names);
1.1241    raeburn   985:     my @locales = DateTime::Locale->ids();
                    986:     foreach my $id (@locales) {
                    987:         if ($id ne '') {
                    988:             my ($en_terr,$native_terr);
                    989:             my $loc = DateTime::Locale->load($id);
                    990:             if (ref($loc)) {
                    991:                 $en_terr = $loc->name();
                    992:                 $native_terr = $loc->native_name();
1.687     raeburn   993:                 if (grep(/^en$/,@languages) || !@languages) {
                    994:                     if ($en_terr ne '') {
                    995:                         $locale_names{$id} = '('.$en_terr.')';
                    996:                     } elsif ($native_terr ne '') {
                    997:                         $locale_names{$id} = $native_terr;
                    998:                     }
                    999:                 } else {
                   1000:                     if ($native_terr ne '') {
                   1001:                         $locale_names{$id} = $native_terr.' ';
                   1002:                     } elsif ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     }
                   1005:                 }
1.1220    raeburn  1006:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1007:                 push(@possibles,$id);
                   1008:             } 
1.687     raeburn  1009:         }
                   1010:     }
                   1011:     foreach my $item (sort(@possibles)) {
                   1012:         $output.= '<option value="'.$item.'"';
                   1013:         if ($item eq $selected) {
                   1014:             $output.=' selected="selected"';
                   1015:         }
                   1016:         $output.=">$item";
                   1017:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1018:             $output.='  '.$locale_names{$item};
1.687     raeburn  1019:         }
                   1020:         $output.="</option>\n";
                   1021:     }
                   1022:     $output.="</select>";
                   1023:     return $output;
                   1024: }
                   1025: 
1.792     raeburn  1026: sub select_language {
1.1256    raeburn  1027:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1028:     my %langchoices;
                   1029:     if ($includeempty) {
1.1117    raeburn  1030:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1031:     }
                   1032:     foreach my $id (&languageids()) {
                   1033:         my $code = &supportedlanguagecode($id);
                   1034:         if ($code) {
                   1035:             $langchoices{$code} = &plainlanguagedescription($id);
                   1036:         }
                   1037:     }
1.1117    raeburn  1038:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1039:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1040: }
                   1041: 
1.42      matthew  1042: =pod
1.36      matthew  1043: 
1.1088    foxr     1044: 
                   1045: =item * &list_languages()
                   1046: 
                   1047: Returns an array reference that is suitable for use in language prompters.
                   1048: Each array element is itself a two element array.  The first element
                   1049: is the language code.  The second element a descsriptiuon of the 
                   1050: language itself.  This is suitable for use in e.g.
                   1051: &Apache::edit::select_arg (once dereferenced that is).
                   1052: 
                   1053: =cut 
                   1054: 
                   1055: sub list_languages {
                   1056:     my @lang_choices;
                   1057: 
                   1058:     foreach my $id (&languageids()) {
                   1059: 	my $code = &supportedlanguagecode($id);
                   1060: 	if ($code) {
                   1061: 	    my $selector    = $supported_codes{$id};
                   1062: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1063: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1064: 	}
                   1065:     }
                   1066:     return \@lang_choices;
                   1067: }
                   1068: 
                   1069: =pod
                   1070: 
1.648     raeburn  1071: =item * &linked_select_forms(...)
1.36      matthew  1072: 
                   1073: linked_select_forms returns a string containing a <script></script> block
                   1074: and html for two <select> menus.  The select menus will be linked in that
                   1075: changing the value of the first menu will result in new values being placed
                   1076: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1077: order unless a defined order is provided.
1.36      matthew  1078: 
                   1079: linked_select_forms takes the following ordered inputs:
                   1080: 
                   1081: =over 4
                   1082: 
1.112     bowersj2 1083: =item * $formname, the name of the <form> tag
1.36      matthew  1084: 
1.112     bowersj2 1085: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1086: 
1.112     bowersj2 1087: =item * $firstdefault, the default value for the first menu
1.36      matthew  1088: 
1.112     bowersj2 1089: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1090: 
1.112     bowersj2 1091: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1094: 
1.609     raeburn  1095: =item * $menuorder, the order of values in the first menu
                   1096: 
1.1115    raeburn  1097: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1098:         event for the first <select> tag
                   1099: 
                   1100: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1101:         event for the second <select> tag
                   1102: 
1.1245    raeburn  1103: =item * $suffix, to differentiate separate uses of select2data javascript
                   1104:         objects in a page.
                   1105: 
1.41      ng       1106: =back 
                   1107: 
1.36      matthew  1108: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1109: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1110: values for the first select menu.  The text that coincides with the 
1.41      ng       1111: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1112: and text for the second menu are given in the hash pointed to by 
                   1113: $menu{$choice1}->{'select2'}.  
                   1114: 
1.112     bowersj2 1115:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1116:                        default => "B3",
                   1117:                        select2 => { 
                   1118:                            B1 => "Choice B1",
                   1119:                            B2 => "Choice B2",
                   1120:                            B3 => "Choice B3",
                   1121:                            B4 => "Choice B4"
1.609     raeburn  1122:                            },
                   1123:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1124:                    },
                   1125:                A2 => { text =>"Choice A2" ,
                   1126:                        default => "C2",
                   1127:                        select2 => { 
                   1128:                            C1 => "Choice C1",
                   1129:                            C2 => "Choice C2",
                   1130:                            C3 => "Choice C3"
1.609     raeburn  1131:                            },
                   1132:                        order => ['C2','C1','C3'],
1.112     bowersj2 1133:                    },
                   1134:                A3 => { text =>"Choice A3" ,
                   1135:                        default => "D6",
                   1136:                        select2 => { 
                   1137:                            D1 => "Choice D1",
                   1138:                            D2 => "Choice D2",
                   1139:                            D3 => "Choice D3",
                   1140:                            D4 => "Choice D4",
                   1141:                            D5 => "Choice D5",
                   1142:                            D6 => "Choice D6",
                   1143:                            D7 => "Choice D7"
1.609     raeburn  1144:                            },
                   1145:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1146:                    }
                   1147:                );
1.36      matthew  1148: 
                   1149: =cut
                   1150: 
                   1151: sub linked_select_forms {
                   1152:     my ($formname,
                   1153:         $middletext,
                   1154:         $firstdefault,
                   1155:         $firstselectname,
                   1156:         $secondselectname, 
1.609     raeburn  1157:         $hashref,
                   1158:         $menuorder,
1.1115    raeburn  1159:         $onchangefirst,
1.1245    raeburn  1160:         $onchangesecond,
                   1161:         $suffix
1.36      matthew  1162:         ) = @_;
                   1163:     my $second = "document.$formname.$secondselectname";
                   1164:     my $first = "document.$formname.$firstselectname";
                   1165:     # output the javascript to do the changing
                   1166:     my $result = '';
1.776     bisitz   1167:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1168:     $result.="// <![CDATA[\n";
1.1245    raeburn  1169:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1170:     $" = '","';
                   1171:     my $debug = '';
                   1172:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1173:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1174:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1175:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1176:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1177:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1178:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1179:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1180:         }
1.36      matthew  1181:         $result.="\"@s2values\");\n";
1.1245    raeburn  1182:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1183:         my @s2texts;
                   1184:         foreach my $value (@s2values) {
1.1263    raeburn  1185:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1186:         }
                   1187:         $result.="\"@s2texts\");\n";
                   1188:     }
                   1189:     $"=' ';
                   1190:     $result.= <<"END";
                   1191: 
1.1245    raeburn  1192: function select1${suffix}_changed() {
1.36      matthew  1193:     // Determine new choice
1.1245    raeburn  1194:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1195:     // update select2
1.1245    raeburn  1196:     var values     = select2data${suffix}[newvalue].values;
                   1197:     var texts      = select2data${suffix}[newvalue].texts;
                   1198:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1199:     var i;
                   1200:     // out with the old
1.1245    raeburn  1201:     $second.options.length = 0;
                   1202:     // in with the new
1.36      matthew  1203:     for (i=0;i<values.length; i++) {
                   1204:         $second.options[i] = new Option(values[i]);
1.143     matthew  1205:         $second.options[i].value = values[i];
1.36      matthew  1206:         $second.options[i].text = texts[i];
                   1207:         if (values[i] == select2def) {
                   1208:             $second.options[i].selected = true;
                   1209:         }
                   1210:     }
                   1211: }
1.824     bisitz   1212: // ]]>
1.36      matthew  1213: </script>
                   1214: END
                   1215:     # output the initial values for the selection lists
1.1245    raeburn  1216:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1217:     my @order = sort(keys(%{$hashref}));
                   1218:     if (ref($menuorder) eq 'ARRAY') {
                   1219:         @order = @{$menuorder};
                   1220:     }
                   1221:     foreach my $value (@order) {
1.36      matthew  1222:         $result.="    <option value=\"$value\" ";
1.253     albertel 1223:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1224:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1225:     }
                   1226:     $result .= "</select>\n";
                   1227:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1228:     $result .= $middletext;
1.1115    raeburn  1229:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1230:     if ($onchangesecond) {
                   1231:         $result .= ' onchange="'.$onchangesecond.'"';
                   1232:     }
                   1233:     $result .= ">\n";
1.36      matthew  1234:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1235:     
                   1236:     my @secondorder = sort(keys(%select2));
                   1237:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1238:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1239:     }
                   1240:     foreach my $value (@secondorder) {
1.36      matthew  1241:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1242:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1243:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1244:     }
                   1245:     $result .= "</select>\n";
                   1246:     #    return $debug;
                   1247:     return $result;
                   1248: }   #  end of sub linked_select_forms {
                   1249: 
1.45      matthew  1250: =pod
1.44      bowersj2 1251: 
1.973     raeburn  1252: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1253: 
1.112     bowersj2 1254: Returns a string corresponding to an HTML link to the given help
                   1255: $topic, where $topic corresponds to the name of a .tex file in
                   1256: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1257: spaces. 
                   1258: 
                   1259: $text will optionally be linked to the same topic, allowing you to
                   1260: link text in addition to the graphic. If you do not want to link
                   1261: text, but wish to specify one of the later parameters, pass an
                   1262: empty string. 
                   1263: 
                   1264: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1265: the link will not open a new window. If false, the link will open
                   1266: a new window using Javascript. (Default is false.) 
                   1267: 
                   1268: $width and $height are optional numerical parameters that will
                   1269: override the width and height of the popped up window, which may
1.973     raeburn  1270: be useful for certain help topics with big pictures included.
                   1271: 
                   1272: $imgid is the id of the img tag used for the help icon. This may be
                   1273: used in a javascript call to switch the image src.  See 
                   1274: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1275: 
                   1276: =cut
                   1277: 
                   1278: sub help_open_topic {
1.973     raeburn  1279:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1280:     $text = "" if (not defined $text);
1.44      bowersj2 1281:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1282:     $width = 500 if (not defined $width);
1.44      bowersj2 1283:     $height = 400 if (not defined $height);
                   1284:     my $filename = $topic;
                   1285:     $filename =~ s/ /_/g;
                   1286: 
1.48      bowersj2 1287:     my $template = "";
                   1288:     my $link;
1.572     banghart 1289:     
1.159     www      1290:     $topic=~s/\W/\_/g;
1.44      bowersj2 1291: 
1.572     banghart 1292:     if (!$stayOnPage) {
1.1033    www      1293: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1294:     } elsif ($stayOnPage eq 'popup') {
                   1295:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1296:     } else {
1.48      bowersj2 1297: 	$link = "/adm/help/${filename}.hlp";
                   1298:     }
                   1299: 
                   1300:     # Add the text
1.1314    raeburn  1301:     my $target = ' target="_top"';
                   1302:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1303:         $target = '';
                   1304:     }
1.755     neumanie 1305:     if ($text ne "") {	
1.763     bisitz   1306: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1307:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1308:                   .$text.'</a>';
1.48      bowersj2 1309:     }
                   1310: 
1.763     bisitz   1311:     # (Always) Add the graphic
1.179     matthew  1312:     my $title = &mt('Online Help');
1.667     raeburn  1313:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1314:     if ($imgid ne '') {
                   1315:         $imgid = ' id="'.$imgid.'"';
                   1316:     }
1.1314    raeburn  1317:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1318:               .'<img src="'.$helpicon.'" border="0"'
                   1319:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1320:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1321:               .' /></a>';
                   1322:     if ($text ne "") {	
                   1323:         $template.='</span>';
                   1324:     }
1.44      bowersj2 1325:     return $template;
                   1326: 
1.106     bowersj2 1327: }
                   1328: 
                   1329: # This is a quicky function for Latex cheatsheet editing, since it 
                   1330: # appears in at least four places
                   1331: sub helpLatexCheatsheet {
1.1037    www      1332:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1333:     my $out;
1.106     bowersj2 1334:     my $addOther = '';
1.732     raeburn  1335:     if ($topic) {
1.1037    www      1336: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1337:     }
                   1338:     $out = '<span>' # Start cheatsheet
                   1339: 	  .$addOther
                   1340:           .'<span>'
1.1037    www      1341: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1342: 	  .'</span> <span>'
1.1037    www      1343: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1344: 	  .'</span>';
1.732     raeburn  1345:     unless ($not_author) {
1.1186    kruse    1346:         $out .= '<span>'
                   1347:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1348:                .'</span> <span>'
                   1349:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1350: 	       .'</span>';
1.732     raeburn  1351:     }
1.763     bisitz   1352:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1353:     return $out;
1.172     www      1354: }
                   1355: 
1.430     albertel 1356: sub general_help {
                   1357:     my $helptopic='Student_Intro';
                   1358:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1359: 	$helptopic='Authoring_Intro';
1.907     raeburn  1360:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1361: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1362:     } elsif ($env{'request.role'}=~/^dc/) {
                   1363:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1364:     }
                   1365:     return $helptopic;
                   1366: }
                   1367: 
                   1368: sub update_help_link {
                   1369:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1370:     my $origurl = $ENV{'REQUEST_URI'};
                   1371:     $origurl=~s|^/~|/priv/|;
                   1372:     my $timestamp = time;
                   1373:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1374:         $$datum = &escape($$datum);
                   1375:     }
                   1376: 
                   1377:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1378:     my $output .= <<"ENDOUTPUT";
                   1379: <script type="text/javascript">
1.824     bisitz   1380: // <![CDATA[
1.430     albertel 1381: banner_link = '$banner_link';
1.824     bisitz   1382: // ]]>
1.430     albertel 1383: </script>
                   1384: ENDOUTPUT
                   1385:     return $output;
                   1386: }
                   1387: 
                   1388: # now just updates the help link and generates a blue icon
1.193     raeburn  1389: sub help_open_menu {
1.430     albertel 1390:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1391: 	= @_;    
1.949     droeschl 1392:     $stayOnPage = 1;
1.430     albertel 1393:     my $output;
                   1394:     if ($component_help) {
                   1395: 	if (!$text) {
                   1396: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1397: 				       $width,$height);
                   1398: 	} else {
                   1399: 	    my $help_text;
                   1400: 	    $help_text=&unescape($topic);
                   1401: 	    $output='<table><tr><td>'.
                   1402: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1403: 				 $width,$height).'</td></tr></table>';
                   1404: 	}
                   1405:     }
                   1406:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1407:     return $output.$banner_link;
                   1408: }
                   1409: 
                   1410: sub top_nav_help {
                   1411:     my ($text) = @_;
1.436     albertel 1412:     $text = &mt($text);
1.949     droeschl 1413:     my $stay_on_page = 1;
                   1414: 
1.1168    raeburn  1415:     my ($link,$banner_link);
                   1416:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1417:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1418: 	                         : "javascript:helpMenu('open')";
                   1419:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1420:     }
1.201     raeburn  1421:     my $title = &mt('Get help');
1.1168    raeburn  1422:     if ($link) {
                   1423:         return <<"END";
1.436     albertel 1424: $banner_link
1.1159    raeburn  1425: <a href="$link" title="$title">$text</a>
1.436     albertel 1426: END
1.1168    raeburn  1427:     } else {
                   1428:         return '&nbsp;'.$text.'&nbsp;';
                   1429:     }
1.436     albertel 1430: }
                   1431: 
                   1432: sub help_menu_js {
1.1154    raeburn  1433:     my ($httphost) = @_;
1.949     droeschl 1434:     my $stayOnPage = 1;
1.436     albertel 1435:     my $width = 620;
                   1436:     my $height = 600;
1.430     albertel 1437:     my $helptopic=&general_help();
1.1154    raeburn  1438:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1439:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1440:     my $start_page =
                   1441:         &Apache::loncommon::start_page('Help Menu', undef,
                   1442: 				       {'frameset'    => 1,
                   1443: 					'js_ready'    => 1,
1.1154    raeburn  1444:                                         'use_absolute' => $httphost,
1.331     albertel 1445: 					'add_entries' => {
1.1168    raeburn  1446: 					    'border' => '0', 
1.579     raeburn  1447: 					    'rows'   => "110,*",},});
1.331     albertel 1448:     my $end_page =
                   1449:         &Apache::loncommon::end_page({'frameset' => 1,
                   1450: 				      'js_ready' => 1,});
                   1451: 
1.436     albertel 1452:     my $template .= <<"ENDTEMPLATE";
                   1453: <script type="text/javascript">
1.877     bisitz   1454: // <![CDATA[
1.253     albertel 1455: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1456: var banner_link = '';
1.243     raeburn  1457: function helpMenu(target) {
                   1458:     var caller = this;
                   1459:     if (target == 'open') {
                   1460:         var newWindow = null;
                   1461:         try {
1.262     albertel 1462:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1463:         }
                   1464:         catch(error) {
                   1465:             writeHelp(caller);
                   1466:             return;
                   1467:         }
                   1468:         if (newWindow) {
                   1469:             caller = newWindow;
                   1470:         }
1.193     raeburn  1471:     }
1.243     raeburn  1472:     writeHelp(caller);
                   1473:     return;
                   1474: }
                   1475: function writeHelp(caller) {
1.1168    raeburn  1476:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1477:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1478:     caller.document.close();
                   1479:     caller.focus();
1.193     raeburn  1480: }
1.877     bisitz   1481: // END LON-CAPA Internal -->
1.253     albertel 1482: // ]]>
1.436     albertel 1483: </script>
1.193     raeburn  1484: ENDTEMPLATE
                   1485:     return $template;
                   1486: }
                   1487: 
1.172     www      1488: sub help_open_bug {
                   1489:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1490:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1491:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1492:     $text = "" if (not defined $text);
                   1493: 	$stayOnPage=1;
1.184     albertel 1494:     $width = 600 if (not defined $width);
                   1495:     $height = 600 if (not defined $height);
1.172     www      1496: 
                   1497:     $topic=~s/\W+/\+/g;
                   1498:     my $link='';
                   1499:     my $template='';
1.379     albertel 1500:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1501: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1502:     if (!$stayOnPage)
                   1503:     {
                   1504: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1505:     }
                   1506:     else
                   1507:     {
                   1508: 	$link = $url;
                   1509:     }
1.1314    raeburn  1510: 
                   1511:     my $target = ' target="_top"';
                   1512:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1513:         $target = '';
                   1514:     }
1.172     www      1515:     # Add the text
                   1516:     if ($text ne "")
                   1517:     {
                   1518: 	$template .= 
                   1519:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1520:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1521:     }
                   1522: 
                   1523:     # Add the graphic
1.179     matthew  1524:     my $title = &mt('Report a Bug');
1.215     albertel 1525:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1526:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1527:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1528: ENDTEMPLATE
                   1529:     if ($text ne '') { $template.='</td></tr></table>' };
                   1530:     return $template;
                   1531: 
                   1532: }
                   1533: 
                   1534: sub help_open_faq {
                   1535:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1536:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1537:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1538:     $text = "" if (not defined $text);
                   1539: 	$stayOnPage=1;
                   1540:     $width = 350 if (not defined $width);
                   1541:     $height = 400 if (not defined $height);
                   1542: 
                   1543:     $topic=~s/\W+/\+/g;
                   1544:     my $link='';
                   1545:     my $template='';
                   1546:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1547:     if (!$stayOnPage)
                   1548:     {
                   1549: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1550:     }
                   1551:     else
                   1552:     {
                   1553: 	$link = $url;
                   1554:     }
                   1555: 
                   1556:     # Add the text
                   1557:     if ($text ne "")
                   1558:     {
                   1559: 	$template .= 
1.173     www      1560:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1561:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1562:     }
                   1563: 
                   1564:     # Add the graphic
1.179     matthew  1565:     my $title = &mt('View the FAQ');
1.215     albertel 1566:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1567:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1568:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1569: ENDTEMPLATE
                   1570:     if ($text ne '') { $template.='</td></tr></table>' };
                   1571:     return $template;
                   1572: 
1.44      bowersj2 1573: }
1.37      matthew  1574: 
1.180     matthew  1575: ###############################################################
                   1576: ###############################################################
                   1577: 
1.45      matthew  1578: =pod
                   1579: 
1.648     raeburn  1580: =item * &change_content_javascript():
1.256     matthew  1581: 
                   1582: This and the next function allow you to create small sections of an
                   1583: otherwise static HTML page that you can update on the fly with
                   1584: Javascript, even in Netscape 4.
                   1585: 
                   1586: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1587: must be written to the HTML page once. It will prove the Javascript
                   1588: function "change(name, content)". Calling the change function with the
                   1589: name of the section 
                   1590: you want to update, matching the name passed to C<changable_area>, and
                   1591: the new content you want to put in there, will put the content into
                   1592: that area.
                   1593: 
                   1594: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1595: to contain room for the original contents. You need to "make space"
                   1596: for whatever changes you wish to make, and be B<sure> to check your
                   1597: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1598: it's adequate for updating a one-line status display, but little more.
                   1599: This script will set the space to 100% width, so you only need to
                   1600: worry about height in Netscape 4.
                   1601: 
                   1602: Modern browsers are much less limiting, and if you can commit to the
                   1603: user not using Netscape 4, this feature may be used freely with
                   1604: pretty much any HTML.
                   1605: 
                   1606: =cut
                   1607: 
                   1608: sub change_content_javascript {
                   1609:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1610:     if ($env{'browser.type'} eq 'netscape' &&
                   1611: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1612: 	return (<<NETSCAPE4);
                   1613: 	function change(name, content) {
                   1614: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1615: 	    doc.open();
                   1616: 	    doc.write(content);
                   1617: 	    doc.close();
                   1618: 	}
                   1619: NETSCAPE4
                   1620:     } else {
                   1621: 	# Otherwise, we need to use semi-standards-compliant code
                   1622: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1623: 	# is really scary, and every useful browser supports it
                   1624: 	return (<<DOMBASED);
                   1625: 	function change(name, content) {
                   1626: 	    element = document.getElementById(name);
                   1627: 	    element.innerHTML = content;
                   1628: 	}
                   1629: DOMBASED
                   1630:     }
                   1631: }
                   1632: 
                   1633: =pod
                   1634: 
1.648     raeburn  1635: =item * &changable_area($name,$origContent):
1.256     matthew  1636: 
                   1637: This provides a "changable area" that can be modified on the fly via
                   1638: the Javascript code provided in C<change_content_javascript>. $name is
                   1639: the name you will use to reference the area later; do not repeat the
                   1640: same name on a given HTML page more then once. $origContent is what
                   1641: the area will originally contain, which can be left blank.
                   1642: 
                   1643: =cut
                   1644: 
                   1645: sub changable_area {
                   1646:     my ($name, $origContent) = @_;
                   1647: 
1.258     albertel 1648:     if ($env{'browser.type'} eq 'netscape' &&
                   1649: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1650: 	# If this is netscape 4, we need to use the Layer tag
                   1651: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1652:     } else {
                   1653: 	return "<span id='$name'>$origContent</span>";
                   1654:     }
                   1655: }
                   1656: 
                   1657: =pod
                   1658: 
1.648     raeburn  1659: =item * &viewport_geometry_js 
1.590     raeburn  1660: 
                   1661: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1662: 
                   1663: =cut
                   1664: 
                   1665: 
                   1666: sub viewport_geometry_js { 
                   1667:     return <<"GEOMETRY";
                   1668: var Geometry = {};
                   1669: function init_geometry() {
                   1670:     if (Geometry.init) { return };
                   1671:     Geometry.init=1;
                   1672:     if (window.innerHeight) {
                   1673:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1674:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1675:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1676:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1677:     }
                   1678:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1679:         Geometry.getViewportHeight =
                   1680:             function() { return document.documentElement.clientHeight; };
                   1681:         Geometry.getViewportWidth =
                   1682:             function() { return document.documentElement.clientWidth; };
                   1683: 
                   1684:         Geometry.getHorizontalScroll =
                   1685:             function() { return document.documentElement.scrollLeft; };
                   1686:         Geometry.getVerticalScroll =
                   1687:             function() { return document.documentElement.scrollTop; };
                   1688:     }
                   1689:     else if (document.body.clientHeight) {
                   1690:         Geometry.getViewportHeight =
                   1691:             function() { return document.body.clientHeight; };
                   1692:         Geometry.getViewportWidth =
                   1693:             function() { return document.body.clientWidth; };
                   1694:         Geometry.getHorizontalScroll =
                   1695:             function() { return document.body.scrollLeft; };
                   1696:         Geometry.getVerticalScroll =
                   1697:             function() { return document.body.scrollTop; };
                   1698:     }
                   1699: }
                   1700: 
                   1701: GEOMETRY
                   1702: }
                   1703: 
                   1704: =pod
                   1705: 
1.648     raeburn  1706: =item * &viewport_size_js()
1.590     raeburn  1707: 
                   1708: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1709: 
                   1710: =cut
                   1711: 
                   1712: sub viewport_size_js {
                   1713:     my $geometry = &viewport_geometry_js();
                   1714:     return <<"DIMS";
                   1715: 
                   1716: $geometry
                   1717: 
                   1718: function getViewportDims(width,height) {
                   1719:     init_geometry();
                   1720:     width.value = Geometry.getViewportWidth();
                   1721:     height.value = Geometry.getViewportHeight();
                   1722:     return;
                   1723: }
                   1724: 
                   1725: DIMS
                   1726: }
                   1727: 
                   1728: =pod
                   1729: 
1.648     raeburn  1730: =item * &resize_textarea_js()
1.565     albertel 1731: 
                   1732: emits the needed javascript to resize a textarea to be as big as possible
                   1733: 
                   1734: creates a function resize_textrea that takes two IDs first should be
                   1735: the id of the element to resize, second should be the id of a div that
                   1736: surrounds everything that comes after the textarea, this routine needs
                   1737: to be attached to the <body> for the onload and onresize events.
                   1738: 
1.648     raeburn  1739: =back
1.565     albertel 1740: 
                   1741: =cut
                   1742: 
                   1743: sub resize_textarea_js {
1.590     raeburn  1744:     my $geometry = &viewport_geometry_js();
1.565     albertel 1745:     return <<"RESIZE";
                   1746:     <script type="text/javascript">
1.824     bisitz   1747: // <![CDATA[
1.590     raeburn  1748: $geometry
1.565     albertel 1749: 
1.588     albertel 1750: function getX(element) {
                   1751:     var x = 0;
                   1752:     while (element) {
                   1753: 	x += element.offsetLeft;
                   1754: 	element = element.offsetParent;
                   1755:     }
                   1756:     return x;
                   1757: }
                   1758: function getY(element) {
                   1759:     var y = 0;
                   1760:     while (element) {
                   1761: 	y += element.offsetTop;
                   1762: 	element = element.offsetParent;
                   1763:     }
                   1764:     return y;
                   1765: }
                   1766: 
                   1767: 
1.565     albertel 1768: function resize_textarea(textarea_id,bottom_id) {
                   1769:     init_geometry();
                   1770:     var textarea        = document.getElementById(textarea_id);
                   1771:     //alert(textarea);
                   1772: 
1.588     albertel 1773:     var textarea_top    = getY(textarea);
1.565     albertel 1774:     var textarea_height = textarea.offsetHeight;
                   1775:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1776:     var bottom_top      = getY(bottom);
1.565     albertel 1777:     var bottom_height   = bottom.offsetHeight;
                   1778:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1779:     var fudge           = 23;
1.565     albertel 1780:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1781:     if (new_height < 300) {
                   1782: 	new_height = 300;
                   1783:     }
                   1784:     textarea.style.height=new_height+'px';
                   1785: }
1.824     bisitz   1786: // ]]>
1.565     albertel 1787: </script>
                   1788: RESIZE
                   1789: 
                   1790: }
                   1791: 
1.1205    golterma 1792: sub colorfuleditor_js {
1.1248    raeburn  1793:     my $browse_or_search;
                   1794:     my $respath;
                   1795:     my ($cnum,$cdom) = &crsauthor_url();
                   1796:     if ($cnum) {
                   1797:         $respath = "/res/$cdom/$cnum/";
                   1798:         my %js_lt = &Apache::lonlocal::texthash(
                   1799:             sunm => 'Sub-directory name',
                   1800:             save => 'Save page to make this permanent',
                   1801:         );
                   1802:         &js_escape(\%js_lt);
                   1803:         $browse_or_search = <<"END";
                   1804: 
                   1805:     function toggleChooser(form,element,titleid,only,search) {
                   1806:         var disp = 'none';
                   1807:         if (document.getElementById('chooser_'+element)) {
                   1808:             var curr = document.getElementById('chooser_'+element).style.display;
                   1809:             if (curr == 'none') {
                   1810:                 disp='inline';
                   1811:                 if (form.elements['chooser_'+element].length) {
                   1812:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1813:                         form.elements['chooser_'+element][i].checked = false;
                   1814:                     }
                   1815:                 }
                   1816:                 toggleResImport(form,element);
                   1817:             }
                   1818:             document.getElementById('chooser_'+element).style.display = disp;
                   1819:         }
                   1820:     }
                   1821: 
                   1822:     function toggleCrsFile(form,element,numdirs) {
                   1823:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1824:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1825:             if (curr == 'none') {
                   1826:                 if (numdirs) {
                   1827:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1828:                     if (numdirs > 1) {
                   1829:                         window['select1'+element+'_changed']();
                   1830:                     }
                   1831:                 }
                   1832:             } 
                   1833:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1834:             
                   1835:         }
                   1836:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1837:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1838:             if (document.getElementById('uploadcrsres_'+element)) {
                   1839:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1840:             }
                   1841:         }
                   1842:         return;
                   1843:     }
                   1844: 
                   1845:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1846:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1847:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1848:         }
                   1849:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1850:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1851:             if (curr == 'none') {
                   1852:                 if (numcrsdirs) {
                   1853:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1854:                    form.elements['newsubdir_'+element][0].checked = true;
                   1855:                    toggleNewsubdir(form,element);
                   1856:                 }
                   1857:             }
                   1858:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1859:         }
                   1860:         return;
                   1861:     }
                   1862: 
                   1863:     function toggleResImport(form,element) {
                   1864:         var choices = new Array('crsres','upload');
                   1865:         for (var i=0; i<choices.length; i++) {
                   1866:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1867:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1868:             }
                   1869:         }
                   1870:     }
                   1871: 
                   1872:     function toggleNewsubdir(form,element) {
                   1873:         var newsub = form.elements['newsubdir_'+element];
                   1874:         if (newsub) {
                   1875:             if (newsub.length) {
                   1876:                 for (var j=0; j<newsub.length; j++) {
                   1877:                     if (newsub[j].checked) {
                   1878:                         if (document.getElementById('newsubdirname_'+element)) {
                   1879:                             if (newsub[j].value == '1') {
                   1880:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1881:                                 if (document.getElementById('newsubdir_'+element)) {
                   1882:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1883:                                 }
                   1884:                             } else {
                   1885:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1886:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1887:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1888:                             }
                   1889:                         }
                   1890:                         break; 
                   1891:                     }
                   1892:                 }
                   1893:             }
                   1894:         }
                   1895:     }
                   1896: 
                   1897:     function updateCrsFile(form,element) {
                   1898:         var directory = form.elements['coursepath_'+element];
                   1899:         var filename = form.elements['coursefile_'+element];
                   1900:         var path = directory.options[directory.selectedIndex].value;
                   1901:         var file = filename.options[filename.selectedIndex].value;
                   1902:         form.elements[element].value = '$respath';
                   1903:         if (path == '/') {
                   1904:             form.elements[element].value += file;
                   1905:         } else {
                   1906:             form.elements[element].value += path+'/'+file;
                   1907:         }
                   1908:         unClean();
                   1909:         if (document.getElementById('previewimg_'+element)) {
                   1910:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1911:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1912:         }
                   1913:         if (document.getElementById('showimg_'+element)) {
                   1914:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1915:         }
                   1916:         toggleChooser(form,element);
                   1917:         return;
                   1918:     }
                   1919: 
                   1920:     function uploadDone(suffix,name) {
                   1921:         if (name) {
                   1922: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1923:             unClean();
                   1924:             toggleChooser(document.forms["lonhomework"],suffix);
                   1925:         }
                   1926:     }
                   1927: 
                   1928: \$(document).ready(function(){
                   1929: 
                   1930:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1931:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1932:             var buttonId = this.id;
                   1933:             var suffix = buttonId.toString();
                   1934:             suffix = suffix.replace(/^crsupload_/,'');
                   1935:             event.preventDefault();
                   1936:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1937:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1938:             \$(this.form).submit();
                   1939:             document.lonhomework.target = '';
                   1940:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1941:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1942:             }
                   1943:             return false;
                   1944:         }
                   1945:     });
                   1946: });
                   1947: END
                   1948:     }
1.1205    golterma 1949:     return <<"COLORFULEDIT"
                   1950: <script type="text/javascript">
                   1951: // <![CDATA[>
                   1952:     function fold_box(curDepth, lastresource){
                   1953: 
                   1954:     // we need a list because there can be several blocks you need to fold in one tag
                   1955:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1956:     // but there is only one folding button per tag
                   1957:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1958: 
                   1959:         if(block.item(0).style.display == 'none'){
                   1960: 
                   1961:             foldbutton.value = '@{[&mt("Hide")]}';
                   1962:             for (i = 0; i < block.length; i++){
                   1963:                 block.item(i).style.display = '';
                   1964:             }
                   1965:         }else{
                   1966: 
                   1967:             foldbutton.value = '@{[&mt("Show")]}';
                   1968:             for (i = 0; i < block.length; i++){
                   1969:                 // block.item(i).style.visibility = 'collapse';
                   1970:                 block.item(i).style.display = 'none';
                   1971:             }
                   1972:         };
                   1973:         saveState(lastresource);
                   1974:     }
                   1975: 
                   1976:     function saveState (lastresource) {
                   1977: 
                   1978:         var tag_list = getTagList();
                   1979:         if(tag_list != null){
                   1980:             var timestamp = new Date().getTime();
                   1981:             var key = lastresource;
                   1982: 
                   1983:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1984:             // starting with timestamp
                   1985:             var value = timestamp+';';
                   1986: 
                   1987:             // building the list of key-value pairs
                   1988:             for(var i = 0; i < tag_list.length; i++){
                   1989:                 value += tag_list[i]+',';
                   1990:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1991:             }
                   1992: 
                   1993:             // only iterate whole storage if nothing to override
                   1994:             if(localStorage.getItem(key) == null){        
                   1995: 
                   1996:                 // prevent storage from growing large
                   1997:                 if(localStorage.length > 50){
                   1998:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1999:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2000:                     var oldest_key;
                   2001:                     
                   2002:                     for(var i = 1; i < localStorage.length; i++){
                   2003:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2004:                             oldest_key = localStorage.key(i);
                   2005:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2006:                         }
                   2007:                     }
                   2008:                     localStorage.removeItem(oldest_key);
                   2009:                 }
                   2010:             }
                   2011:             localStorage.setItem(key,value);
                   2012:         }
                   2013:     }
                   2014: 
                   2015:     // restore folding status of blocks (on page load)
                   2016:     function restoreState (lastresource) {
                   2017:         if(localStorage.getItem(lastresource) != null){
                   2018:             var key = lastresource;
                   2019:             var value = localStorage.getItem(key);
                   2020:             var regex_delTimestamp = /^\d+;/;
                   2021: 
                   2022:             value.replace(regex_delTimestamp, '');
                   2023: 
                   2024:             var valueArr = value.split(';');
                   2025:             var pairs;
                   2026:             var elements;
                   2027:             for (var i = 0; i < valueArr.length; i++){
                   2028:                 pairs = valueArr[i].split(',');
                   2029:                 elements = document.getElementsByName(pairs[0]);
                   2030: 
                   2031:                 for (var j = 0; j < elements.length; j++){  
                   2032:                     elements[j].style.display = pairs[1];
                   2033:                     if (pairs[1] == "none"){
                   2034:                         var regex_id = /([_\\d]+)\$/;
                   2035:                         regex_id.exec(pairs[0]);
                   2036:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2037:                     }
                   2038:                 }
                   2039:             }
                   2040:         }
                   2041:     }
                   2042: 
                   2043:     function getTagList () {
                   2044:         
                   2045:         var stringToSearch = document.lonhomework.innerHTML;
                   2046: 
                   2047:         var ret = new Array();
                   2048:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2049:         var tag_list = stringToSearch.match(regex_findBlock);
                   2050: 
                   2051:         if(tag_list != null){
                   2052:             for(var i = 0; i < tag_list.length; i++){            
                   2053:                 ret.push(tag_list[i].replace(/"/, ''));
                   2054:             }
                   2055:         }
                   2056:         return ret;
                   2057:     }
                   2058: 
                   2059:     function saveScrollPosition (resource) {
                   2060:         var tag_list = getTagList();
                   2061: 
                   2062:         // we dont always want to jump to the first block
                   2063:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2064:         if(\$(window).scrollTop() > 170){
                   2065:             if(tag_list != null){
                   2066:                 var result;
                   2067:                 for(var i = 0; i < tag_list.length; i++){
                   2068:                     if(isElementInViewport(tag_list[i])){
                   2069:                         result += tag_list[i]+';';
                   2070:                     }
                   2071:                 }
                   2072:                 sessionStorage.setItem('anchor_'+resource, result);
                   2073:             }
                   2074:         } else {
                   2075:             // we dont need to save zero, just delete the item to leave everything tidy
                   2076:             sessionStorage.removeItem('anchor_'+resource);
                   2077:         }
                   2078:     }
                   2079: 
                   2080:     function restoreScrollPosition(resource){
                   2081: 
                   2082:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2083:         if(elem != null){
                   2084:             var tag_list = elem.split(';');
                   2085:             var elem_list;
                   2086: 
                   2087:             for(var i = 0; i < tag_list.length; i++){
                   2088:                 elem_list = document.getElementsByName(tag_list[i]);
                   2089:                 
                   2090:                 if(elem_list.length > 0){
                   2091:                     elem = elem_list[0];
                   2092:                     break;
                   2093:                 }
                   2094:             }
                   2095:             elem.scrollIntoView();
                   2096:         }
                   2097:     }
                   2098: 
                   2099:     function isElementInViewport(el) {
                   2100: 
                   2101:         // change to last element instead of first
                   2102:         var elem = document.getElementsByName(el);
                   2103:         var rect = elem[0].getBoundingClientRect();
                   2104: 
                   2105:         return (
                   2106:             rect.top >= 0 &&
                   2107:             rect.left >= 0 &&
                   2108:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2109:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2110:         );
                   2111:     }
                   2112:     
                   2113:     function autosize(depth){
                   2114:         var cmInst = window['cm'+depth];
                   2115:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2116: 
                   2117:         // is fixed size, switching to dynamic
                   2118:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2119:             cmInst.setSize("","auto");
                   2120:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2121:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2122: 
                   2123:         // is dynamic size, switching to fixed
                   2124:         } else {
                   2125:             cmInst.setSize("","300px");
                   2126:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2127:             sessionStorage.removeItem("autosized_"+depth);
                   2128:         }
                   2129:     }
                   2130: 
1.1248    raeburn  2131: $browse_or_search
1.1205    golterma 2132: 
                   2133: // ]]>
                   2134: </script>
                   2135: COLORFULEDIT
                   2136: }
                   2137: 
                   2138: sub xmleditor_js {
                   2139:     return <<XMLEDIT
                   2140: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2141: <script type="text/javascript">
                   2142: // <![CDATA[>
                   2143: 
                   2144:     function saveScrollPosition (resource) {
                   2145: 
                   2146:         var scrollPos = \$(window).scrollTop();
                   2147:         sessionStorage.setItem(resource,scrollPos);
                   2148:     }
                   2149: 
                   2150:     function restoreScrollPosition(resource){
                   2151: 
                   2152:         var scrollPos = sessionStorage.getItem(resource);
                   2153:         \$(window).scrollTop(scrollPos);
                   2154:     }
                   2155: 
                   2156:     // unless internet explorer
                   2157:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2158: 
                   2159:         \$(document).ready(function() {
                   2160:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2161:         });
                   2162:     }
                   2163: 
                   2164:     // inserts text at cursor position into codemirror (xml editor only)
                   2165:     function insertText(text){
                   2166:         cm.focus();
                   2167:         var curPos = cm.getCursor();
                   2168:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2169:     }
                   2170: // ]]>
                   2171: </script>
                   2172: XMLEDIT
                   2173: }
                   2174: 
                   2175: sub insert_folding_button {
                   2176:     my $curDepth = $Apache::lonxml::curdepth;
                   2177:     my $lastresource = $env{'request.ambiguous'};
                   2178: 
                   2179:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2180:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2181: }
                   2182: 
1.1248    raeburn  2183: sub crsauthor_url {
                   2184:     my ($url) = @_;
                   2185:     if ($url eq '') {
                   2186:         $url = $ENV{'REQUEST_URI'};
                   2187:     }
                   2188:     my ($cnum,$cdom);
                   2189:     if ($env{'request.course.id'}) {
                   2190:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2191:         if ($audom ne '' && $auname ne '') {
                   2192:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2193:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2194:                 $cnum = $auname;
                   2195:                 $cdom = $audom;
                   2196:             }
                   2197:         }
                   2198:     }
                   2199:     return ($cnum,$cdom);
                   2200: }
                   2201: 
                   2202: sub import_crsauthor_form {
1.1265    raeburn  2203:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2204:     return (0) unless ($env{'request.course.id'});
                   2205:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2206:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2207:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2208:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2209:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2210:     my @ids=&Apache::lonnet::current_machine_ids();
                   2211:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2212:     
                   2213:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2214:         $is_home = 1;
                   2215:     }
                   2216:     $relpath = "/priv/$cdom/$cnum";
                   2217:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2218:     my %lt = &Apache::lonlocal::texthash (
                   2219:         fnam => 'Filename',
                   2220:         dire => 'Directory',
                   2221:     );
                   2222:     my $numdirs = scalar(keys(%files));
                   2223:     my (%possexts,$singledir,@singledirfiles);
                   2224:     if ($only) {
                   2225:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2226:     }
                   2227:     my (%nonemptydirs,$possdirs);
                   2228:     if ($numdirs > 1) {
                   2229:         my @order;
                   2230:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2231:             if (ref($files{$key}) eq 'HASH') {
                   2232:                 my $shown = $key;
                   2233:                 if ($key eq '') {
                   2234:                     $shown = '/';
                   2235:                 }
                   2236:                 my @ordered = ();
                   2237:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2238:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2239:                     if ($only) {
                   2240:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2241:                         unless ($possexts{lc($ext)}) {
                   2242:                             next;
                   2243:                         }
                   2244:                     }
                   2245:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2246:                     push(@ordered,$file);
                   2247:                 }
                   2248:                 if (@ordered) {
                   2249:                     push(@order,$key);
                   2250:                     $nonemptydirs{$key} = 1;
                   2251:                     $selimport_menus{$key}->{'text'} = $shown;
                   2252:                     $selimport_menus{$key}->{'default'} = '';
                   2253:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2254:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2255:                 }
                   2256:             }
                   2257:         }
                   2258:         $possdirs = scalar(keys(%nonemptydirs));
                   2259:         if ($possdirs > 1) {
                   2260:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2261:             $output = $lt{'dire'}.
                   2262:                       &linked_select_forms($form,'<br />'.
                   2263:                                            $lt{'fnam'},'',
                   2264:                                            $firstselectname,$secondselectname,
                   2265:                                            \%selimport_menus,\@order,
                   2266:                                            $onchangefirst,'',$suffix).'<br />';
                   2267:         } elsif ($possdirs == 1) {
                   2268:             $singledir = (keys(%nonemptydirs))[0];
                   2269:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2270:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2271:             }
                   2272:             delete($selimport_menus{$singledir});
                   2273:         }
                   2274:     } elsif ($numdirs == 1) {
                   2275:         $singledir = (keys(%files))[0];
                   2276:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2277:             if ($only) {
                   2278:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2279:                 unless ($possexts{lc($ext)}) {
                   2280:                     next;
                   2281:                 }
1.1315    raeburn  2282:             } else {
                   2283:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2284:             }
                   2285:             push(@singledirfiles,$file);
                   2286:         }
                   2287:         if (@singledirfiles) {
1.1315    raeburn  2288:             $possdirs = 1;
1.1248    raeburn  2289:         }
                   2290:     }
                   2291:     if (($possdirs == 1) && (@singledirfiles)) {
                   2292:         my $showdir = $singledir;
                   2293:         if ($singledir eq '') {
                   2294:             $showdir = '/';
                   2295:         }
                   2296:         $output = $lt{'dire'}.
                   2297:                   '<select name="'.$firstselectname.'">'.
                   2298:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2299:                   '</select><br />'.
                   2300:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2301:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2302:         foreach my $file (@singledirfiles) {
                   2303:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2304:         }
                   2305:         $output .= '</select><br />'."\n";
                   2306:     }
                   2307:     return ($possdirs,$output);
                   2308: }
                   2309: 
1.565     albertel 2310: =pod
                   2311: 
1.256     matthew  2312: =head1 Excel and CSV file utility routines
                   2313: 
                   2314: =cut
                   2315: 
                   2316: ###############################################################
                   2317: ###############################################################
                   2318: 
                   2319: =pod
                   2320: 
1.1162    raeburn  2321: =over 4
                   2322: 
1.648     raeburn  2323: =item * &csv_translate($text) 
1.37      matthew  2324: 
1.185     www      2325: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2326: format.
                   2327: 
                   2328: =cut
                   2329: 
1.180     matthew  2330: ###############################################################
                   2331: ###############################################################
1.37      matthew  2332: sub csv_translate {
                   2333:     my $text = shift;
                   2334:     $text =~ s/\"/\"\"/g;
1.209     albertel 2335:     $text =~ s/\n/ /g;
1.37      matthew  2336:     return $text;
                   2337: }
1.180     matthew  2338: 
                   2339: ###############################################################
                   2340: ###############################################################
                   2341: 
                   2342: =pod
                   2343: 
1.648     raeburn  2344: =item * &define_excel_formats()
1.180     matthew  2345: 
                   2346: Define some commonly used Excel cell formats.
                   2347: 
                   2348: Currently supported formats:
                   2349: 
                   2350: =over 4
                   2351: 
                   2352: =item header
                   2353: 
                   2354: =item bold
                   2355: 
                   2356: =item h1
                   2357: 
                   2358: =item h2
                   2359: 
                   2360: =item h3
                   2361: 
1.256     matthew  2362: =item h4
                   2363: 
                   2364: =item i
                   2365: 
1.180     matthew  2366: =item date
                   2367: 
                   2368: =back
                   2369: 
                   2370: Inputs: $workbook
                   2371: 
                   2372: Returns: $format, a hash reference.
                   2373: 
1.1057    foxr     2374: 
1.180     matthew  2375: =cut
                   2376: 
                   2377: ###############################################################
                   2378: ###############################################################
                   2379: sub define_excel_formats {
                   2380:     my ($workbook) = @_;
                   2381:     my $format;
                   2382:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2383:                                                 bottom    => 1,
                   2384:                                                 align     => 'center');
                   2385:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2386:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2387:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2388:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2389:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2390:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2391:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2392:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2393:     return $format;
                   2394: }
                   2395: 
                   2396: ###############################################################
                   2397: ###############################################################
1.113     bowersj2 2398: 
                   2399: =pod
                   2400: 
1.648     raeburn  2401: =item * &create_workbook()
1.255     matthew  2402: 
                   2403: Create an Excel worksheet.  If it fails, output message on the
                   2404: request object and return undefs.
                   2405: 
                   2406: Inputs: Apache request object
                   2407: 
                   2408: Returns (undef) on failure, 
                   2409:     Excel worksheet object, scalar with filename, and formats 
                   2410:     from &Apache::loncommon::define_excel_formats on success
                   2411: 
                   2412: =cut
                   2413: 
                   2414: ###############################################################
                   2415: ###############################################################
                   2416: sub create_workbook {
                   2417:     my ($r) = @_;
                   2418:         #
                   2419:     # Create the excel spreadsheet
                   2420:     my $filename = '/prtspool/'.
1.258     albertel 2421:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2422:         time.'_'.rand(1000000000).'.xls';
                   2423:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2424:     if (! defined($workbook)) {
                   2425:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2426:         $r->print(
                   2427:             '<p class="LC_error">'
                   2428:            .&mt('Problems occurred in creating the new Excel file.')
                   2429:            .' '.&mt('This error has been logged.')
                   2430:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2431:            .'</p>'
                   2432:         );
1.255     matthew  2433:         return (undef);
                   2434:     }
                   2435:     #
1.1014    foxr     2436:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2437:     #
                   2438:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2439:     return ($workbook,$filename,$format);
                   2440: }
                   2441: 
                   2442: ###############################################################
                   2443: ###############################################################
                   2444: 
                   2445: =pod
                   2446: 
1.648     raeburn  2447: =item * &create_text_file()
1.113     bowersj2 2448: 
1.542     raeburn  2449: Create a file to write to and eventually make available to the user.
1.256     matthew  2450: If file creation fails, outputs an error message on the request object and 
                   2451: return undefs.
1.113     bowersj2 2452: 
1.256     matthew  2453: Inputs: Apache request object, and file suffix
1.113     bowersj2 2454: 
1.256     matthew  2455: Returns (undef) on failure, 
                   2456:     Filehandle and filename on success.
1.113     bowersj2 2457: 
                   2458: =cut
                   2459: 
1.256     matthew  2460: ###############################################################
                   2461: ###############################################################
                   2462: sub create_text_file {
                   2463:     my ($r,$suffix) = @_;
                   2464:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2465:     my $fh;
                   2466:     my $filename = '/prtspool/'.
1.258     albertel 2467:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2468:         time.'_'.rand(1000000000).'.'.$suffix;
                   2469:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2470:     if (! defined($fh)) {
                   2471:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2472:         $r->print(
                   2473:             '<p class="LC_error">'
                   2474:            .&mt('Problems occurred in creating the output file.')
                   2475:            .' '.&mt('This error has been logged.')
                   2476:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2477:            .'</p>'
                   2478:         );
1.113     bowersj2 2479:     }
1.256     matthew  2480:     return ($fh,$filename)
1.113     bowersj2 2481: }
                   2482: 
                   2483: 
1.256     matthew  2484: =pod 
1.113     bowersj2 2485: 
                   2486: =back
                   2487: 
                   2488: =cut
1.37      matthew  2489: 
                   2490: ###############################################################
1.33      matthew  2491: ##        Home server <option> list generating code          ##
                   2492: ###############################################################
1.35      matthew  2493: 
1.169     www      2494: # ------------------------------------------
                   2495: 
                   2496: sub domain_select {
1.1289    raeburn  2497:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2498:     my @possdoms;
                   2499:     if (ref($incdoms) eq 'ARRAY') {
                   2500:         @possdoms = @{$incdoms};
                   2501:     } else {
                   2502:         @possdoms = &Apache::lonnet::all_domains();
                   2503:     }
                   2504: 
1.169     www      2505:     my %domains=map { 
1.514     albertel 2506: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2507:     } @possdoms;
                   2508: 
                   2509:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2510:         foreach my $dom (@{$excdoms}) {
                   2511:             delete($domains{$dom});
                   2512:         }
                   2513:     }
                   2514: 
1.169     www      2515:     if ($multiple) {
                   2516: 	$domains{''}=&mt('Any domain');
1.550     albertel 2517: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2518: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2519:     } else {
1.550     albertel 2520: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2521: 	return &select_form($name,$value,\%domains);
1.169     www      2522:     }
                   2523: }
                   2524: 
1.282     albertel 2525: #-------------------------------------------
                   2526: 
                   2527: =pod
                   2528: 
1.519     raeburn  2529: =head1 Routines for form select boxes
                   2530: 
                   2531: =over 4
                   2532: 
1.648     raeburn  2533: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2534: 
                   2535: Returns a string containing a <select> element int multiple mode
                   2536: 
                   2537: 
                   2538: Args:
                   2539:   $name - name of the <select> element
1.506     raeburn  2540:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2541:   $size - number of rows long the select element is
1.283     albertel 2542:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2543:           (shown text should already have been &mt())
1.506     raeburn  2544:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2545: 
1.282     albertel 2546: =cut
                   2547: 
                   2548: #-------------------------------------------
1.169     www      2549: sub multiple_select_form {
1.284     albertel 2550:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2551:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2552:     my $output='';
1.191     matthew  2553:     if (! defined($size)) {
                   2554:         $size = 4;
1.283     albertel 2555:         if (scalar(keys(%$hash))<4) {
                   2556:             $size = scalar(keys(%$hash));
1.191     matthew  2557:         }
                   2558:     }
1.734     bisitz   2559:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2560:     my @order;
1.506     raeburn  2561:     if (ref($order) eq 'ARRAY')  {
                   2562:         @order = @{$order};
                   2563:     } else {
                   2564:         @order = sort(keys(%$hash));
1.501     banghart 2565:     }
                   2566:     if (exists($$hash{'select_form_order'})) {
                   2567:         @order = @{$$hash{'select_form_order'}};
                   2568:     }
                   2569:         
1.284     albertel 2570:     foreach my $key (@order) {
1.356     albertel 2571:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2572:         $output.='selected="selected" ' if ($selected{$key});
                   2573:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2574:     }
                   2575:     $output.="</select>\n";
                   2576:     return $output;
                   2577: }
                   2578: 
1.88      www      2579: #-------------------------------------------
                   2580: 
                   2581: =pod
                   2582: 
1.1254    raeburn  2583: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2584: 
                   2585: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2586: allow a user to select options from a ref to a hash containing:
                   2587: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2588: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2589: An optional arg -- $readonly -- if true will cause the select form
                   2590: to be disabled, e.g., for the case where an instructor has a section-
                   2591: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2592: 
1.88      www      2593: See lonrights.pm for an example invocation and use.
                   2594: 
                   2595: =cut
                   2596: 
                   2597: #-------------------------------------------
                   2598: sub select_form {
1.1228    raeburn  2599:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2600:     return unless (ref($hashref) eq 'HASH');
                   2601:     if ($onchange) {
                   2602:         $onchange = ' onchange="'.$onchange.'"';
                   2603:     }
1.1228    raeburn  2604:     my $disabled;
                   2605:     if ($readonly) {
                   2606:         $disabled = ' disabled="disabled"';
                   2607:     }
                   2608:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2609:     my @keys;
1.970     raeburn  2610:     if (exists($hashref->{'select_form_order'})) {
                   2611: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2612:     } else {
1.970     raeburn  2613: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2614:     }
1.356     albertel 2615:     foreach my $key (@keys) {
                   2616:         $selectform.=
                   2617: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2618:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2619:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2620:     }
                   2621:     $selectform.="</select>";
                   2622:     return $selectform;
                   2623: }
                   2624: 
1.475     www      2625: # For display filters
                   2626: 
                   2627: sub display_filter {
1.1074    raeburn  2628:     my ($context) = @_;
1.475     www      2629:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2630:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2631:     my $phraseinput = 'hidden';
                   2632:     my $includeinput = 'hidden';
                   2633:     my ($checked,$includetypestext);
                   2634:     if ($env{'form.displayfilter'} eq 'containing') {
                   2635:         $phraseinput = 'text'; 
                   2636:         if ($context eq 'parmslog') {
                   2637:             $includeinput = 'checkbox';
                   2638:             if ($env{'form.includetypes'}) {
                   2639:                 $checked = ' checked="checked"';
                   2640:             }
                   2641:             $includetypestext = &mt('Include parameter types');
                   2642:         }
                   2643:     } else {
                   2644:         $includetypestext = '&nbsp;';
                   2645:     }
                   2646:     my ($additional,$secondid,$thirdid);
                   2647:     if ($context eq 'parmslog') {
                   2648:         $additional = 
                   2649:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2650:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2651:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2652:             '</label>';
                   2653:         $secondid = 'includetypes';
                   2654:         $thirdid = 'includetypestext';
                   2655:     }
                   2656:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2657:                                                     '$secondid','$thirdid')";
                   2658:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2659: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2660: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2661: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2662:            &mt('Filter: [_1]',
1.477     www      2663: 	   &select_form($env{'form.displayfilter'},
                   2664: 			'displayfilter',
1.970     raeburn  2665: 			{'currentfolder' => 'Current folder/page',
1.477     www      2666: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2667: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2668: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2669:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2670:                          '" />'.$additional;
                   2671: }
                   2672: 
                   2673: sub display_filter_js {
                   2674:     my $includetext = &mt('Include parameter types');
                   2675:     return <<"ENDJS";
                   2676:   
                   2677: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2678:     var firstType = 'hidden';
                   2679:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2680:         firstType = 'text';
                   2681:     }
                   2682:     firstObject = document.getElementById(firstid);
                   2683:     if (typeof(firstObject) == 'object') {
                   2684:         if (firstObject.type != firstType) {
                   2685:             changeInputType(firstObject,firstType);
                   2686:         }
                   2687:     }
                   2688:     if (context == 'parmslog') {
                   2689:         var secondType = 'hidden';
                   2690:         if (firstType == 'text') {
                   2691:             secondType = 'checkbox';
                   2692:         }
                   2693:         secondObject = document.getElementById(secondid);  
                   2694:         if (typeof(secondObject) == 'object') {
                   2695:             if (secondObject.type != secondType) {
                   2696:                 changeInputType(secondObject,secondType);
                   2697:             }
                   2698:         }
                   2699:         var textItem = document.getElementById(thirdid);
                   2700:         var currtext = textItem.innerHTML;
                   2701:         var newtext;
                   2702:         if (firstType == 'text') {
                   2703:             newtext = '$includetext';
                   2704:         } else {
                   2705:             newtext = '&nbsp;';
                   2706:         }
                   2707:         if (currtext != newtext) {
                   2708:             textItem.innerHTML = newtext;
                   2709:         }
                   2710:     }
                   2711:     return;
                   2712: }
                   2713: 
                   2714: function changeInputType(oldObject,newType) {
                   2715:     var newObject = document.createElement('input');
                   2716:     newObject.type = newType;
                   2717:     if (oldObject.size) {
                   2718:         newObject.size = oldObject.size;
                   2719:     }
                   2720:     if (oldObject.value) {
                   2721:         newObject.value = oldObject.value;
                   2722:     }
                   2723:     if (oldObject.name) {
                   2724:         newObject.name = oldObject.name;
                   2725:     }
                   2726:     if (oldObject.id) {
                   2727:         newObject.id = oldObject.id;
                   2728:     }
                   2729:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2730:     return;
                   2731: }
                   2732: 
                   2733: ENDJS
1.475     www      2734: }
                   2735: 
1.167     www      2736: sub gradeleveldescription {
                   2737:     my $gradelevel=shift;
                   2738:     my %gradelevels=(0 => 'Not specified',
                   2739: 		     1 => 'Grade 1',
                   2740: 		     2 => 'Grade 2',
                   2741: 		     3 => 'Grade 3',
                   2742: 		     4 => 'Grade 4',
                   2743: 		     5 => 'Grade 5',
                   2744: 		     6 => 'Grade 6',
                   2745: 		     7 => 'Grade 7',
                   2746: 		     8 => 'Grade 8',
                   2747: 		     9 => 'Grade 9',
                   2748: 		     10 => 'Grade 10',
                   2749: 		     11 => 'Grade 11',
                   2750: 		     12 => 'Grade 12',
                   2751: 		     13 => 'Grade 13',
                   2752: 		     14 => '100 Level',
                   2753: 		     15 => '200 Level',
                   2754: 		     16 => '300 Level',
                   2755: 		     17 => '400 Level',
                   2756: 		     18 => 'Graduate Level');
                   2757:     return &mt($gradelevels{$gradelevel});
                   2758: }
                   2759: 
1.163     www      2760: sub select_level_form {
                   2761:     my ($deflevel,$name)=@_;
                   2762:     unless ($deflevel) { $deflevel=0; }
1.167     www      2763:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2764:     for (my $i=0; $i<=18; $i++) {
                   2765:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2766:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2767:                 ">".&gradeleveldescription($i)."</option>\n";
                   2768:     }
                   2769:     $selectform.="</select>";
                   2770:     return $selectform;
1.163     www      2771: }
1.167     www      2772: 
1.35      matthew  2773: #-------------------------------------------
                   2774: 
1.45      matthew  2775: =pod
                   2776: 
1.1256    raeburn  2777: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2778: 
                   2779: Returns a string containing a <select name='$name' size='1'> form to 
                   2780: allow a user to select the domain to preform an operation in.  
                   2781: See loncreateuser.pm for an example invocation and use.
                   2782: 
1.90      www      2783: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2784: selected");
                   2785: 
1.743     raeburn  2786: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2787: 
1.910     raeburn  2788: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2789: 
1.1121    raeburn  2790: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2791: 
                   2792: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2793: 
1.1256    raeburn  2794: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2795: 
1.35      matthew  2796: =cut
                   2797: 
                   2798: #-------------------------------------------
1.34      matthew  2799: sub select_dom_form {
1.1256    raeburn  2800:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2801:     if ($onchange) {
1.874     raeburn  2802:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2803:     }
1.1256    raeburn  2804:     if ($disabled) {
                   2805:         $disabled = ' disabled="disabled"';
                   2806:     }
1.1121    raeburn  2807:     my (@domains,%exclude);
1.910     raeburn  2808:     if (ref($incdoms) eq 'ARRAY') {
                   2809:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2810:     } else {
                   2811:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2812:     }
1.90      www      2813:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2814:     if (ref($excdoms) eq 'ARRAY') {
                   2815:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2816:     }
1.1256    raeburn  2817:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2818:     foreach my $dom (@domains) {
1.1121    raeburn  2819:         next if ($exclude{$dom});
1.356     albertel 2820:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2821:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2822:         if ($showdomdesc) {
                   2823:             if ($dom ne '') {
                   2824:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2825:                 if ($domdesc ne '') {
                   2826:                     $selectdomain .= ' ('.$domdesc.')';
                   2827:                 }
                   2828:             } 
                   2829:         }
                   2830:         $selectdomain .= "</option>\n";
1.34      matthew  2831:     }
                   2832:     $selectdomain.="</select>";
                   2833:     return $selectdomain;
                   2834: }
                   2835: 
1.35      matthew  2836: #-------------------------------------------
                   2837: 
1.45      matthew  2838: =pod
                   2839: 
1.648     raeburn  2840: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2841: 
1.586     raeburn  2842: input: 4 arguments (two required, two optional) - 
                   2843:     $domain - domain of new user
                   2844:     $name - name of form element
                   2845:     $default - Value of 'default' causes a default item to be first 
                   2846:                             option, and selected by default. 
                   2847:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2848:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2849: output: returns 2 items: 
1.586     raeburn  2850: (a) form element which contains either:
                   2851:    (i) <select name="$name">
                   2852:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2853:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2854:        </select>
                   2855:        form item if there are multiple library servers in $domain, or
                   2856:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2857:        if there is only one library server in $domain.
                   2858: 
                   2859: (b) number of library servers found.
                   2860: 
                   2861: See loncreateuser.pm for example of use.
1.35      matthew  2862: 
                   2863: =cut
                   2864: 
                   2865: #-------------------------------------------
1.586     raeburn  2866: sub home_server_form_item {
                   2867:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2868:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2869:     my $result;
                   2870:     my $numlib = keys(%servers);
                   2871:     if ($numlib > 1) {
                   2872:         $result .= '<select name="'.$name.'" />'."\n";
                   2873:         if ($default) {
1.804     bisitz   2874:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2875:                        '</option>'."\n";
                   2876:         }
                   2877:         foreach my $hostid (sort(keys(%servers))) {
                   2878:             $result.= '<option value="'.$hostid.'">'.
                   2879: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2880:         }
                   2881:         $result .= '</select>'."\n";
                   2882:     } elsif ($numlib == 1) {
                   2883:         my $hostid;
                   2884:         foreach my $item (keys(%servers)) {
                   2885:             $hostid = $item;
                   2886:         }
                   2887:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2888:                    $hostid.'" />';
                   2889:                    if (!$hide) {
                   2890:                        $result .= $hostid.' '.$servers{$hostid};
                   2891:                    }
                   2892:                    $result .= "\n";
                   2893:     } elsif ($default) {
                   2894:         $result .= '<input type="hidden" name="'.$name.
                   2895:                    '" value="default" />';
                   2896:                    if (!$hide) {
                   2897:                        $result .= &mt('default');
                   2898:                    }
                   2899:                    $result .= "\n";
1.33      matthew  2900:     }
1.586     raeburn  2901:     return ($result,$numlib);
1.33      matthew  2902: }
1.112     bowersj2 2903: 
                   2904: =pod
                   2905: 
1.534     albertel 2906: =back 
                   2907: 
1.112     bowersj2 2908: =cut
1.87      matthew  2909: 
                   2910: ###############################################################
1.112     bowersj2 2911: ##                  Decoding User Agent                      ##
1.87      matthew  2912: ###############################################################
                   2913: 
                   2914: =pod
                   2915: 
1.112     bowersj2 2916: =head1 Decoding the User Agent
                   2917: 
                   2918: =over 4
                   2919: 
                   2920: =item * &decode_user_agent()
1.87      matthew  2921: 
                   2922: Inputs: $r
                   2923: 
                   2924: Outputs:
                   2925: 
                   2926: =over 4
                   2927: 
1.112     bowersj2 2928: =item * $httpbrowser
1.87      matthew  2929: 
1.112     bowersj2 2930: =item * $clientbrowser
1.87      matthew  2931: 
1.112     bowersj2 2932: =item * $clientversion
1.87      matthew  2933: 
1.112     bowersj2 2934: =item * $clientmathml
1.87      matthew  2935: 
1.112     bowersj2 2936: =item * $clientunicode
1.87      matthew  2937: 
1.112     bowersj2 2938: =item * $clientos
1.87      matthew  2939: 
1.1137    raeburn  2940: =item * $clientmobile
                   2941: 
1.1141    raeburn  2942: =item * $clientinfo
                   2943: 
1.1194    raeburn  2944: =item * $clientosversion
                   2945: 
1.87      matthew  2946: =back
                   2947: 
1.157     matthew  2948: =back 
                   2949: 
1.87      matthew  2950: =cut
                   2951: 
                   2952: ###############################################################
                   2953: ###############################################################
                   2954: sub decode_user_agent {
1.247     albertel 2955:     my ($r)=@_;
1.87      matthew  2956:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2957:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2958:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2959:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2960:     my $clientbrowser='unknown';
                   2961:     my $clientversion='0';
                   2962:     my $clientmathml='';
                   2963:     my $clientunicode='0';
1.1137    raeburn  2964:     my $clientmobile=0;
1.1194    raeburn  2965:     my $clientosversion='';
1.87      matthew  2966:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2967:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2968: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2969: 	    $clientbrowser=$bname;
                   2970:             $httpbrowser=~/$vreg/i;
                   2971: 	    $clientversion=$1;
                   2972:             $clientmathml=($clientversion>=$minv);
                   2973:             $clientunicode=($clientversion>=$univ);
                   2974: 	}
                   2975:     }
                   2976:     my $clientos='unknown';
1.1141    raeburn  2977:     my $clientinfo;
1.87      matthew  2978:     if (($httpbrowser=~/linux/i) ||
                   2979:         ($httpbrowser=~/unix/i) ||
                   2980:         ($httpbrowser=~/ux/i) ||
                   2981:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2982:     if (($httpbrowser=~/vax/i) ||
                   2983:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2984:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2985:     if (($httpbrowser=~/mac/i) ||
                   2986:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2987:     if ($httpbrowser=~/win/i) {
                   2988:         $clientos='win';
                   2989:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2990:             $clientosversion = $1;
                   2991:         }
                   2992:     }
1.87      matthew  2993:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2994:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2995:         $clientmobile=lc($1);
                   2996:     }
1.1141    raeburn  2997:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2998:         $clientinfo = 'firefox-'.$1;
                   2999:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3000:         $clientinfo = 'chromeframe-'.$1;
                   3001:     }
1.87      matthew  3002:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3003:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3004:             $clientosversion);
1.87      matthew  3005: }
                   3006: 
1.32      matthew  3007: ###############################################################
                   3008: ##    Authentication changing form generation subroutines    ##
                   3009: ###############################################################
                   3010: ##
                   3011: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3012: ## hash, and have reasonable default values.
                   3013: ##
                   3014: ##    formname = the name given in the <form> tag.
1.35      matthew  3015: #-------------------------------------------
                   3016: 
1.45      matthew  3017: =pod
                   3018: 
1.112     bowersj2 3019: =head1 Authentication Routines
                   3020: 
                   3021: =over 4
                   3022: 
1.648     raeburn  3023: =item * &authform_xxxxxx()
1.35      matthew  3024: 
                   3025: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3026: handle some of the conveniences required for authentication forms.  
                   3027: This is not an optimal method, but it works.  
                   3028: 
                   3029: =over 4
                   3030: 
1.112     bowersj2 3031: =item * authform_header
1.35      matthew  3032: 
1.112     bowersj2 3033: =item * authform_authorwarning
1.35      matthew  3034: 
1.112     bowersj2 3035: =item * authform_nochange
1.35      matthew  3036: 
1.112     bowersj2 3037: =item * authform_kerberos
1.35      matthew  3038: 
1.112     bowersj2 3039: =item * authform_internal
1.35      matthew  3040: 
1.112     bowersj2 3041: =item * authform_filesystem
1.35      matthew  3042: 
1.1310    raeburn  3043: =item * authform_lti
                   3044: 
1.35      matthew  3045: =back
                   3046: 
1.648     raeburn  3047: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3048: 
1.35      matthew  3049: =cut
                   3050: 
                   3051: #-------------------------------------------
1.32      matthew  3052: sub authform_header{  
                   3053:     my %in = (
                   3054:         formname => 'cu',
1.80      albertel 3055:         kerb_def_dom => '',
1.32      matthew  3056:         @_,
                   3057:     );
                   3058:     $in{'formname'} = 'document.' . $in{'formname'};
                   3059:     my $result='';
1.80      albertel 3060: 
                   3061: #---------------------------------------------- Code for upper case translation
                   3062:     my $Javascript_toUpperCase;
                   3063:     unless ($in{kerb_def_dom}) {
                   3064:         $Javascript_toUpperCase =<<"END";
                   3065:         switch (choice) {
                   3066:            case 'krb': currentform.elements[choicearg].value =
                   3067:                currentform.elements[choicearg].value.toUpperCase();
                   3068:                break;
                   3069:            default:
                   3070:         }
                   3071: END
                   3072:     } else {
                   3073:         $Javascript_toUpperCase = "";
                   3074:     }
                   3075: 
1.165     raeburn  3076:     my $radioval = "'nochange'";
1.591     raeburn  3077:     if (defined($in{'curr_authtype'})) {
                   3078:         if ($in{'curr_authtype'} ne '') {
                   3079:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3080:         }
1.174     matthew  3081:     }
1.165     raeburn  3082:     my $argfield = 'null';
1.591     raeburn  3083:     if (defined($in{'mode'})) {
1.165     raeburn  3084:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3085:             if (defined($in{'curr_autharg'})) {
                   3086:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3087:                     $argfield = "'$in{'curr_autharg'}'";
                   3088:                 }
                   3089:             }
                   3090:         }
                   3091:     }
                   3092: 
1.32      matthew  3093:     $result.=<<"END";
                   3094: var current = new Object();
1.165     raeburn  3095: current.radiovalue = $radioval;
                   3096: current.argfield = $argfield;
1.32      matthew  3097: 
                   3098: function changed_radio(choice,currentform) {
                   3099:     var choicearg = choice + 'arg';
                   3100:     // If a radio button in changed, we need to change the argfield
                   3101:     if (current.radiovalue != choice) {
                   3102:         current.radiovalue = choice;
                   3103:         if (current.argfield != null) {
                   3104:             currentform.elements[current.argfield].value = '';
                   3105:         }
                   3106:         if (choice == 'nochange') {
                   3107:             current.argfield = null;
                   3108:         } else {
                   3109:             current.argfield = choicearg;
                   3110:             switch(choice) {
                   3111:                 case 'krb': 
                   3112:                     currentform.elements[current.argfield].value = 
                   3113:                         "$in{'kerb_def_dom'}";
                   3114:                 break;
                   3115:               default:
                   3116:                 break;
                   3117:             }
                   3118:         }
                   3119:     }
                   3120:     return;
                   3121: }
1.22      www      3122: 
1.32      matthew  3123: function changed_text(choice,currentform) {
                   3124:     var choicearg = choice + 'arg';
                   3125:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3126:         $Javascript_toUpperCase
1.32      matthew  3127:         // clear old field
                   3128:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3129:             currentform.elements[current.argfield].value = '';
                   3130:         }
                   3131:         current.argfield = choicearg;
                   3132:     }
                   3133:     set_auth_radio_buttons(choice,currentform);
                   3134:     return;
1.20      www      3135: }
1.32      matthew  3136: 
                   3137: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3138:     var numauthchoices = currentform.login.length;
                   3139:     if (typeof numauthchoices  == "undefined") {
                   3140:         return;
                   3141:     } 
1.32      matthew  3142:     var i=0;
1.986     raeburn  3143:     while (i < numauthchoices) {
1.32      matthew  3144:         if (currentform.login[i].value == newvalue) { break; }
                   3145:         i++;
                   3146:     }
1.986     raeburn  3147:     if (i == numauthchoices) {
1.32      matthew  3148:         return;
                   3149:     }
                   3150:     current.radiovalue = newvalue;
                   3151:     currentform.login[i].checked = true;
                   3152:     return;
                   3153: }
                   3154: END
                   3155:     return $result;
                   3156: }
                   3157: 
1.1106    raeburn  3158: sub authform_authorwarning {
1.32      matthew  3159:     my $result='';
1.144     matthew  3160:     $result='<i>'.
                   3161:         &mt('As a general rule, only authors or co-authors should be '.
                   3162:             'filesystem authenticated '.
                   3163:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3164:     return $result;
                   3165: }
                   3166: 
1.1106    raeburn  3167: sub authform_nochange {
1.32      matthew  3168:     my %in = (
                   3169:               formname => 'document.cu',
                   3170:               kerb_def_dom => 'MSU.EDU',
                   3171:               @_,
                   3172:           );
1.1106    raeburn  3173:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3174:     my $result;
1.1104    raeburn  3175:     if (!$authnum) {
1.1105    raeburn  3176:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3177:     } else {
                   3178:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3179:                   '<input type="radio" name="login" value="nochange" '.
                   3180:                   'checked="checked" onclick="'.
1.281     albertel 3181:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3182: 	    '</label>';
1.586     raeburn  3183:     }
1.32      matthew  3184:     return $result;
                   3185: }
                   3186: 
1.591     raeburn  3187: sub authform_kerberos {
1.32      matthew  3188:     my %in = (
                   3189:               formname => 'document.cu',
                   3190:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3191:               kerb_def_auth => 'krb4',
1.32      matthew  3192:               @_,
                   3193:               );
1.586     raeburn  3194:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3195:         $autharg,$jscall,$disabled);
1.1106    raeburn  3196:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3197:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3198:        $check5 = ' checked="checked"';
1.80      albertel 3199:     } else {
1.772     bisitz   3200:        $check4 = ' checked="checked"';
1.80      albertel 3201:     }
1.1259    raeburn  3202:     if ($in{'readonly'}) {
                   3203:         $disabled = ' disabled="disabled"';
                   3204:     }
1.165     raeburn  3205:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3206:     if (defined($in{'curr_authtype'})) {
                   3207:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3208:             $krbcheck = ' checked="checked"';
1.623     raeburn  3209:             if (defined($in{'mode'})) {
                   3210:                 if ($in{'mode'} eq 'modifyuser') {
                   3211:                     $krbcheck = '';
                   3212:                 }
                   3213:             }
1.591     raeburn  3214:             if (defined($in{'curr_kerb_ver'})) {
                   3215:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3216:                     $check5 = ' checked="checked"';
1.591     raeburn  3217:                     $check4 = '';
                   3218:                 } else {
1.772     bisitz   3219:                     $check4 = ' checked="checked"';
1.591     raeburn  3220:                     $check5 = '';
                   3221:                 }
1.586     raeburn  3222:             }
1.591     raeburn  3223:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3224:                 $krbarg = $in{'curr_autharg'};
                   3225:             }
1.586     raeburn  3226:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3227:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3228:                     $result = 
                   3229:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3230:         $in{'curr_autharg'},$krbver);
                   3231:                 } else {
                   3232:                     $result =
                   3233:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3234:                 }
                   3235:                 return $result; 
                   3236:             }
                   3237:         }
                   3238:     } else {
                   3239:         if ($authnum == 1) {
1.784     bisitz   3240:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3241:         }
                   3242:     }
1.586     raeburn  3243:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3244:         return;
1.587     raeburn  3245:     } elsif ($authtype eq '') {
1.591     raeburn  3246:         if (defined($in{'mode'})) {
1.587     raeburn  3247:             if ($in{'mode'} eq 'modifycourse') {
                   3248:                 if ($authnum == 1) {
1.1259    raeburn  3249:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3250:                 }
                   3251:             }
                   3252:         }
1.586     raeburn  3253:     }
                   3254:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3255:     if ($authtype eq '') {
                   3256:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3257:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3258:                     $krbcheck.$disabled.' />';
1.586     raeburn  3259:     }
                   3260:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3261:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3262:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3263:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3264:          $in{'curr_authtype'} eq 'krb4')) {
                   3265:         $result .= &mt
1.144     matthew  3266:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3267:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3268:          '<label>'.$authtype,
1.281     albertel 3269:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3270:              'value="'.$krbarg.'" '.
1.1259    raeburn  3271:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3272:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3273:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3274: 	 '</label>');
1.586     raeburn  3275:     } elsif ($can_assign{'krb4'}) {
                   3276:         $result .= &mt
                   3277:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3278:          '[_3] Version 4 [_4]',
                   3279:          '<label>'.$authtype,
                   3280:          '</label><input type="text" size="10" name="krbarg" '.
                   3281:              'value="'.$krbarg.'" '.
1.1259    raeburn  3282:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3283:          '<label><input type="hidden" name="krbver" value="4" />',
                   3284:          '</label>');
                   3285:     } elsif ($can_assign{'krb5'}) {
                   3286:         $result .= &mt
                   3287:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3288:          '[_3] Version 5 [_4]',
                   3289:          '<label>'.$authtype,
                   3290:          '</label><input type="text" size="10" name="krbarg" '.
                   3291:              'value="'.$krbarg.'" '.
1.1259    raeburn  3292:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3293:          '<label><input type="hidden" name="krbver" value="5" />',
                   3294:          '</label>');
                   3295:     }
1.32      matthew  3296:     return $result;
                   3297: }
                   3298: 
1.1106    raeburn  3299: sub authform_internal {
1.586     raeburn  3300:     my %in = (
1.32      matthew  3301:                 formname => 'document.cu',
                   3302:                 kerb_def_dom => 'MSU.EDU',
                   3303:                 @_,
                   3304:                 );
1.1259    raeburn  3305:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3306:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3307:     if ($in{'readonly'}) {
                   3308:         $disabled = ' disabled="disabled"';
                   3309:     }
1.591     raeburn  3310:     if (defined($in{'curr_authtype'})) {
                   3311:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3312:             if ($can_assign{'int'}) {
1.772     bisitz   3313:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3314:                 if (defined($in{'mode'})) {
                   3315:                     if ($in{'mode'} eq 'modifyuser') {
                   3316:                         $intcheck = '';
                   3317:                     }
                   3318:                 }
1.591     raeburn  3319:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3320:                     $intarg = $in{'curr_autharg'};
                   3321:                 }
                   3322:             } else {
                   3323:                 $result = &mt('Currently internally authenticated.');
                   3324:                 return $result;
1.165     raeburn  3325:             }
                   3326:         }
1.586     raeburn  3327:     } else {
                   3328:         if ($authnum == 1) {
1.784     bisitz   3329:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3330:         }
                   3331:     }
                   3332:     if (!$can_assign{'int'}) {
                   3333:         return;
1.587     raeburn  3334:     } elsif ($authtype eq '') {
1.591     raeburn  3335:         if (defined($in{'mode'})) {
1.587     raeburn  3336:             if ($in{'mode'} eq 'modifycourse') {
                   3337:                 if ($authnum == 1) {
1.1259    raeburn  3338:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3339:                 }
                   3340:             }
                   3341:         }
1.165     raeburn  3342:     }
1.586     raeburn  3343:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3344:     if ($authtype eq '') {
                   3345:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3346:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3347:     }
1.605     bisitz   3348:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3349:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3350:     $result = &mt
1.144     matthew  3351:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3352:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3353:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3354:     return $result;
                   3355: }
                   3356: 
1.1104    raeburn  3357: sub authform_local {
1.32      matthew  3358:     my %in = (
                   3359:               formname => 'document.cu',
                   3360:               kerb_def_dom => 'MSU.EDU',
                   3361:               @_,
                   3362:               );
1.1259    raeburn  3363:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3364:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3365:     if ($in{'readonly'}) {
                   3366:         $disabled = ' disabled="disabled"';
                   3367:     } 
1.591     raeburn  3368:     if (defined($in{'curr_authtype'})) {
                   3369:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3370:             if ($can_assign{'loc'}) {
1.772     bisitz   3371:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3372:                 if (defined($in{'mode'})) {
                   3373:                     if ($in{'mode'} eq 'modifyuser') {
                   3374:                         $loccheck = '';
                   3375:                     }
                   3376:                 }
1.591     raeburn  3377:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3378:                     $locarg = $in{'curr_autharg'};
                   3379:                 }
                   3380:             } else {
                   3381:                 $result = &mt('Currently using local (institutional) authentication.');
                   3382:                 return $result;
1.165     raeburn  3383:             }
                   3384:         }
1.586     raeburn  3385:     } else {
                   3386:         if ($authnum == 1) {
1.784     bisitz   3387:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3388:         }
                   3389:     }
                   3390:     if (!$can_assign{'loc'}) {
                   3391:         return;
1.587     raeburn  3392:     } elsif ($authtype eq '') {
1.591     raeburn  3393:         if (defined($in{'mode'})) {
1.587     raeburn  3394:             if ($in{'mode'} eq 'modifycourse') {
                   3395:                 if ($authnum == 1) {
1.1259    raeburn  3396:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3397:                 }
                   3398:             }
                   3399:         }
1.165     raeburn  3400:     }
1.586     raeburn  3401:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3402:     if ($authtype eq '') {
                   3403:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3404:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3405:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3406:     }
                   3407:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3408:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3409:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3410:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3411:     return $result;
                   3412: }
                   3413: 
1.1106    raeburn  3414: sub authform_filesystem {
1.32      matthew  3415:     my %in = (
                   3416:               formname => 'document.cu',
                   3417:               kerb_def_dom => 'MSU.EDU',
                   3418:               @_,
                   3419:               );
1.1259    raeburn  3420:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3421:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3422:     if ($in{'readonly'}) {
                   3423:         $disabled = ' disabled="disabled"';
                   3424:     }
1.591     raeburn  3425:     if (defined($in{'curr_authtype'})) {
                   3426:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3427:             if ($can_assign{'fsys'}) {
1.772     bisitz   3428:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3429:                 if (defined($in{'mode'})) {
                   3430:                     if ($in{'mode'} eq 'modifyuser') {
                   3431:                         $fsyscheck = '';
                   3432:                     }
                   3433:                 }
1.586     raeburn  3434:             } else {
                   3435:                 $result = &mt('Currently Filesystem Authenticated.');
                   3436:                 return $result;
1.1259    raeburn  3437:             }
1.586     raeburn  3438:         }
                   3439:     } else {
                   3440:         if ($authnum == 1) {
1.784     bisitz   3441:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3442:         }
                   3443:     }
                   3444:     if (!$can_assign{'fsys'}) {
                   3445:         return;
1.587     raeburn  3446:     } elsif ($authtype eq '') {
1.591     raeburn  3447:         if (defined($in{'mode'})) {
1.587     raeburn  3448:             if ($in{'mode'} eq 'modifycourse') {
                   3449:                 if ($authnum == 1) {
1.1259    raeburn  3450:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3451:                 }
                   3452:             }
                   3453:         }
1.586     raeburn  3454:     }
                   3455:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3456:     if ($authtype eq '') {
                   3457:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3458:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3459:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3460:     }
1.1310    raeburn  3461:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3462:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3463:     $result = &mt
1.144     matthew  3464:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3465:          '<label>'.$authtype,'</label>'.$autharg);
                   3466:     return $result;
                   3467: }
                   3468: 
                   3469: sub authform_lti {
                   3470:     my %in = (
                   3471:               formname => 'document.cu',
                   3472:               kerb_def_dom => 'MSU.EDU',
                   3473:               @_,
                   3474:               );
                   3475:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3476:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3477:     if ($in{'readonly'}) {
                   3478:         $disabled = ' disabled="disabled"';
                   3479:     }
                   3480:     if (defined($in{'curr_authtype'})) {
                   3481:         if ($in{'curr_authtype'} eq 'lti') {
                   3482:             if ($can_assign{'lti'}) {
                   3483:                 $lticheck = 'checked="checked" ';
                   3484:                 if (defined($in{'mode'})) {
                   3485:                     if ($in{'mode'} eq 'modifyuser') {
                   3486:                         $lticheck = '';
                   3487:                     }
                   3488:                 }
                   3489:             } else {
                   3490:                 $result = &mt('Currently LTI Authenticated.');
                   3491:                 return $result;
                   3492:             }
                   3493:         }
                   3494:     } else {
                   3495:         if ($authnum == 1) {
                   3496:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3497:         }
                   3498:     }
                   3499:     if (!$can_assign{'lti'}) {
                   3500:         return;
                   3501:     } elsif ($authtype eq '') {
                   3502:         if (defined($in{'mode'})) {
                   3503:             if ($in{'mode'} eq 'modifycourse') {
                   3504:                 if ($authnum == 1) {
                   3505:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3506:                 }
                   3507:             }
                   3508:         }
                   3509:     }
                   3510:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3511:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3512:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3513:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3514:                     $jscall.'"'.$disabled.' />';
                   3515:     }
                   3516:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3517:     if ($authtype) {
                   3518:         $result = &mt('[_1] LTI Authenticated',
                   3519:                       '<label>'.$authtype.'</label>'.$autharg);
                   3520:     } else {
                   3521:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3522:                   $autharg;
                   3523:     }
1.32      matthew  3524:     return $result;
                   3525: }
                   3526: 
1.586     raeburn  3527: sub get_assignable_auth {
                   3528:     my ($dom) = @_;
                   3529:     if ($dom eq '') {
                   3530:         $dom = $env{'request.role.domain'};
                   3531:     }
                   3532:     my %can_assign = (
                   3533:                           krb4 => 1,
                   3534:                           krb5 => 1,
                   3535:                           int  => 1,
                   3536:                           loc  => 1,
1.1310    raeburn  3537:                           lti  => 1,
1.586     raeburn  3538:                      );
                   3539:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3540:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3541:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3542:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3543:             my $context;
                   3544:             if ($env{'request.role'} =~ /^au/) {
                   3545:                 $context = 'author';
1.1259    raeburn  3546:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3547:                 $context = 'domain';
                   3548:             } elsif ($env{'request.course.id'}) {
                   3549:                 $context = 'course';
                   3550:             }
                   3551:             if ($context) {
                   3552:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3553:                    %can_assign = %{$authhash->{$context}}; 
                   3554:                 }
                   3555:             }
                   3556:         }
                   3557:     }
                   3558:     my $authnum = 0;
                   3559:     foreach my $key (keys(%can_assign)) {
                   3560:         if ($can_assign{$key}) {
                   3561:             $authnum ++;
                   3562:         }
                   3563:     }
                   3564:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3565:         $authnum --;
                   3566:     }
                   3567:     return ($authnum,%can_assign);
                   3568: }
                   3569: 
1.1331    raeburn  3570: sub check_passwd_rules {
                   3571:     my ($domain,$plainpass) = @_;
                   3572:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3573:     my ($min,$max,@chars,@brokerule,$warning);
                   3574:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3575:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3576:             $min = $passwdconf{'min'};
                   3577:         }
                   3578:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3579:             $max = $passwdconf{'max'};
                   3580:         }
                   3581:         @chars = @{$passwdconf{'chars'}};
                   3582:     } else {
                   3583:         $min = 7;
                   3584:     }
                   3585:     if (($min) && (length($plainpass) < $min)) {
                   3586:         push(@brokerule,'min');
                   3587:     }
                   3588:     if (($max) && (length($plainpass) > $max)) {
                   3589:         push(@brokerule,'max');
                   3590:     }
                   3591:     if (@chars) {
                   3592:         my %rules;
                   3593:         map { $rules{$_} = 1; } @chars;
                   3594:         if ($rules{'uc'}) {
                   3595:             unless ($plainpass =~ /[A-Z]/) {
                   3596:                 push(@brokerule,'uc');
                   3597:             }
                   3598:         }
                   3599:         if ($rules{'lc'}) {
1.1332  ! raeburn  3600:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3601:                 push(@brokerule,'lc');
                   3602:             }
                   3603:         }
                   3604:         if ($rules{'num'}) {
                   3605:             unless ($plainpass =~ /\d/) {
                   3606:                 push(@brokerule,'num');
                   3607:             }
                   3608:         }
                   3609:         if ($rules{'spec'}) {
                   3610:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3611:                 push(@brokerule,'spec');
                   3612:             }
                   3613:         }
                   3614:     }
                   3615:     if (@brokerule) {
                   3616:         my %rulenames = &Apache::lonlocal::texthash(
                   3617:             uc   => 'At least one upper case letter',
                   3618:             lc   => 'At least one lower case letter',
                   3619:             num  => 'At least one number',
                   3620:             spec => 'At least one non-alphanumeric',
                   3621:         );
                   3622:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3623:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3624:         $rulenames{'num'} .= ': 0123456789';
                   3625:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3626:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3627:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3628:         $warning = &mt('Password did not satisfy the following:').'<ul>';
                   3629:         foreach my $rule ('min','max','uc','ls','num','spec') {
                   3630:             if (grep(/^$rule$/,@brokerule)) {
                   3631:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3632:             }
                   3633:         }
                   3634:         $warning .= '</ul>';
                   3635:     }
1.1332  ! raeburn  3636:     if (wantarray) {
        !          3637:         return @brokerule;
        !          3638:     }
1.1331    raeburn  3639:     return $warning;
                   3640: }
                   3641: 
1.80      albertel 3642: ###############################################################
                   3643: ##    Get Kerberos Defaults for Domain                 ##
                   3644: ###############################################################
                   3645: ##
                   3646: ## Returns default kerberos version and an associated argument
                   3647: ## as listed in file domain.tab. If not listed, provides
                   3648: ## appropriate default domain and kerberos version.
                   3649: ##
                   3650: #-------------------------------------------
                   3651: 
                   3652: =pod
                   3653: 
1.648     raeburn  3654: =item * &get_kerberos_defaults()
1.80      albertel 3655: 
                   3656: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3657: version and domain. If not found, it defaults to version 4 and the 
                   3658: domain of the server.
1.80      albertel 3659: 
1.648     raeburn  3660: =over 4
                   3661: 
1.80      albertel 3662: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3663: 
1.648     raeburn  3664: =back
                   3665: 
                   3666: =back
                   3667: 
1.80      albertel 3668: =cut
                   3669: 
                   3670: #-------------------------------------------
                   3671: sub get_kerberos_defaults {
                   3672:     my $domain=shift;
1.641     raeburn  3673:     my ($krbdef,$krbdefdom);
                   3674:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3675:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3676:         $krbdef = $domdefaults{'auth_def'};
                   3677:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3678:     } else {
1.80      albertel 3679:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3680:         my $krbdefdom=$1;
                   3681:         $krbdefdom=~tr/a-z/A-Z/;
                   3682:         $krbdef = "krb4";
                   3683:     }
                   3684:     return ($krbdef,$krbdefdom);
                   3685: }
1.112     bowersj2 3686: 
1.32      matthew  3687: 
1.46      matthew  3688: ###############################################################
                   3689: ##                Thesaurus Functions                        ##
                   3690: ###############################################################
1.20      www      3691: 
1.46      matthew  3692: =pod
1.20      www      3693: 
1.112     bowersj2 3694: =head1 Thesaurus Functions
                   3695: 
                   3696: =over 4
                   3697: 
1.648     raeburn  3698: =item * &initialize_keywords()
1.46      matthew  3699: 
                   3700: Initializes the package variable %Keywords if it is empty.  Uses the
                   3701: package variable $thesaurus_db_file.
                   3702: 
                   3703: =cut
                   3704: 
                   3705: ###################################################
                   3706: 
                   3707: sub initialize_keywords {
                   3708:     return 1 if (scalar keys(%Keywords));
                   3709:     # If we are here, %Keywords is empty, so fill it up
                   3710:     #   Make sure the file we need exists...
                   3711:     if (! -e $thesaurus_db_file) {
                   3712:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3713:                                  " failed because it does not exist");
                   3714:         return 0;
                   3715:     }
                   3716:     #   Set up the hash as a database
                   3717:     my %thesaurus_db;
                   3718:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3719:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3720:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3721:                                  $thesaurus_db_file);
                   3722:         return 0;
                   3723:     } 
                   3724:     #  Get the average number of appearances of a word.
                   3725:     my $avecount = $thesaurus_db{'average.count'};
                   3726:     #  Put keywords (those that appear > average) into %Keywords
                   3727:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3728:         my ($count,undef) = split /:/,$data;
                   3729:         $Keywords{$word}++ if ($count > $avecount);
                   3730:     }
                   3731:     untie %thesaurus_db;
                   3732:     # Remove special values from %Keywords.
1.356     albertel 3733:     foreach my $value ('total.count','average.count') {
                   3734:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3735:   }
1.46      matthew  3736:     return 1;
                   3737: }
                   3738: 
                   3739: ###################################################
                   3740: 
                   3741: =pod
                   3742: 
1.648     raeburn  3743: =item * &keyword($word)
1.46      matthew  3744: 
                   3745: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3746: than the average number of times in the thesaurus database.  Calls 
                   3747: &initialize_keywords
                   3748: 
                   3749: =cut
                   3750: 
                   3751: ###################################################
1.20      www      3752: 
                   3753: sub keyword {
1.46      matthew  3754:     return if (!&initialize_keywords());
                   3755:     my $word=lc(shift());
                   3756:     $word=~s/\W//g;
                   3757:     return exists($Keywords{$word});
1.20      www      3758: }
1.46      matthew  3759: 
                   3760: ###############################################################
                   3761: 
                   3762: =pod 
1.20      www      3763: 
1.648     raeburn  3764: =item * &get_related_words()
1.46      matthew  3765: 
1.160     matthew  3766: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3767: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3768: will be returned.  The order of the words returned is determined by the
                   3769: database which holds them.
                   3770: 
                   3771: Uses global $thesaurus_db_file.
                   3772: 
1.1057    foxr     3773: 
1.46      matthew  3774: =cut
                   3775: 
                   3776: ###############################################################
                   3777: sub get_related_words {
                   3778:     my $keyword = shift;
                   3779:     my %thesaurus_db;
                   3780:     if (! -e $thesaurus_db_file) {
                   3781:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3782:                                  "failed because the file does not exist");
                   3783:         return ();
                   3784:     }
                   3785:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3786:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3787:         return ();
                   3788:     } 
                   3789:     my @Words=();
1.429     www      3790:     my $count=0;
1.46      matthew  3791:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3792: 	# The first element is the number of times
                   3793: 	# the word appears.  We do not need it now.
1.429     www      3794: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3795: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3796: 	my $threshold=$mostfrequentcount/10;
                   3797:         foreach my $possibleword (@RelatedWords) {
                   3798:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3799:             if ($wordcount>$threshold) {
                   3800: 		push(@Words,$word);
                   3801:                 $count++;
                   3802:                 if ($count>10) { last; }
                   3803: 	    }
1.20      www      3804:         }
                   3805:     }
1.46      matthew  3806:     untie %thesaurus_db;
                   3807:     return @Words;
1.14      harris41 3808: }
1.1090    foxr     3809: ###############################################################
                   3810: #
                   3811: #  Spell checking
                   3812: #
                   3813: 
                   3814: =pod
                   3815: 
1.1142    raeburn  3816: =back
                   3817: 
1.1090    foxr     3818: =head1 Spell checking
                   3819: 
                   3820: =over 4
                   3821: 
                   3822: =item * &check_spelling($wordlist $language)
                   3823: 
                   3824: Takes a string containing words and feeds it to an external
                   3825: spellcheck program via a pipeline. Returns a string containing
                   3826: them mis-spelled words.
                   3827: 
                   3828: Parameters:
                   3829: 
                   3830: =over 4
                   3831: 
                   3832: =item - $wordlist
                   3833: 
                   3834: String that will be fed into the spellcheck program.
                   3835: 
                   3836: =item - $language
                   3837: 
                   3838: Language string that specifies the language for which the spell
                   3839: check will be performed.
                   3840: 
                   3841: =back
                   3842: 
                   3843: =back
                   3844: 
                   3845: Note: This sub assumes that aspell is installed.
                   3846: 
                   3847: 
                   3848: =cut
                   3849: 
1.46      matthew  3850: 
1.1090    foxr     3851: sub check_spelling {
                   3852:     my ($wordlist, $language) = @_;
1.1091    foxr     3853:     my @misspellings;
                   3854:     
                   3855:     # Generate the speller and set the langauge.
                   3856:     # if explicitly selected:
1.1090    foxr     3857: 
1.1091    foxr     3858:     my $speller = Text::Aspell->new;
1.1090    foxr     3859:     if ($language) {
1.1091    foxr     3860: 	$speller->set_option('lang', $language);
1.1090    foxr     3861:     }
                   3862: 
1.1091    foxr     3863:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3864: 
1.1091    foxr     3865:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3866: 
1.1091    foxr     3867:     foreach my $word (@words) {
                   3868: 	if(! $speller->check($word)) {
                   3869: 	    push(@misspellings, $word);
1.1090    foxr     3870: 	}
                   3871:     }
1.1091    foxr     3872:     return join(' ', @misspellings);
                   3873:     
1.1090    foxr     3874: }
                   3875: 
1.61      www      3876: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3877: =pod
                   3878: 
1.112     bowersj2 3879: =head1 User Name Functions
                   3880: 
                   3881: =over 4
                   3882: 
1.648     raeburn  3883: =item * &plainname($uname,$udom,$first)
1.81      albertel 3884: 
1.112     bowersj2 3885: Takes a users logon name and returns it as a string in
1.226     albertel 3886: "first middle last generation" form 
                   3887: if $first is set to 'lastname' then it returns it as
                   3888: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3889: 
                   3890: =cut
1.61      www      3891: 
1.295     www      3892: 
1.81      albertel 3893: ###############################################################
1.61      www      3894: sub plainname {
1.226     albertel 3895:     my ($uname,$udom,$first)=@_;
1.537     albertel 3896:     return if (!defined($uname) || !defined($udom));
1.295     www      3897:     my %names=&getnames($uname,$udom);
1.226     albertel 3898:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3899: 					  $names{'middlename'},
                   3900: 					  $names{'lastname'},
                   3901: 					  $names{'generation'},$first);
                   3902:     $name=~s/^\s+//;
1.62      www      3903:     $name=~s/\s+$//;
                   3904:     $name=~s/\s+/ /g;
1.353     albertel 3905:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3906:     return $name;
1.61      www      3907: }
1.66      www      3908: 
                   3909: # -------------------------------------------------------------------- Nickname
1.81      albertel 3910: =pod
                   3911: 
1.648     raeburn  3912: =item * &nickname($uname,$udom)
1.81      albertel 3913: 
                   3914: Gets a users name and returns it as a string as
                   3915: 
                   3916: "&quot;nickname&quot;"
1.66      www      3917: 
1.81      albertel 3918: if the user has a nickname or
                   3919: 
                   3920: "first middle last generation"
                   3921: 
                   3922: if the user does not
                   3923: 
                   3924: =cut
1.66      www      3925: 
                   3926: sub nickname {
                   3927:     my ($uname,$udom)=@_;
1.537     albertel 3928:     return if (!defined($uname) || !defined($udom));
1.295     www      3929:     my %names=&getnames($uname,$udom);
1.68      albertel 3930:     my $name=$names{'nickname'};
1.66      www      3931:     if ($name) {
                   3932:        $name='&quot;'.$name.'&quot;'; 
                   3933:     } else {
                   3934:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3935: 	     $names{'lastname'}.' '.$names{'generation'};
                   3936:        $name=~s/\s+$//;
                   3937:        $name=~s/\s+/ /g;
                   3938:     }
                   3939:     return $name;
                   3940: }
                   3941: 
1.295     www      3942: sub getnames {
                   3943:     my ($uname,$udom)=@_;
1.537     albertel 3944:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3945:     if ($udom eq 'public' && $uname eq 'public') {
                   3946: 	return ('lastname' => &mt('Public'));
                   3947:     }
1.295     www      3948:     my $id=$uname.':'.$udom;
                   3949:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3950:     if ($cached) {
                   3951: 	return %{$names};
                   3952:     } else {
                   3953: 	my %loadnames=&Apache::lonnet::get('environment',
                   3954:                     ['firstname','middlename','lastname','generation','nickname'],
                   3955: 					 $udom,$uname);
                   3956: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3957: 	return %loadnames;
                   3958:     }
                   3959: }
1.61      www      3960: 
1.542     raeburn  3961: # -------------------------------------------------------------------- getemails
1.648     raeburn  3962: 
1.542     raeburn  3963: =pod
                   3964: 
1.648     raeburn  3965: =item * &getemails($uname,$udom)
1.542     raeburn  3966: 
                   3967: Gets a user's email information and returns it as a hash with keys:
                   3968: notification, critnotification, permanentemail
                   3969: 
                   3970: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3971: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3972:  
1.648     raeburn  3973: 
1.542     raeburn  3974: =cut
                   3975: 
1.648     raeburn  3976: 
1.466     albertel 3977: sub getemails {
                   3978:     my ($uname,$udom)=@_;
                   3979:     if ($udom eq 'public' && $uname eq 'public') {
                   3980: 	return;
                   3981:     }
1.467     www      3982:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3983:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3984:     my $id=$uname.':'.$udom;
                   3985:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3986:     if ($cached) {
                   3987: 	return %{$names};
                   3988:     } else {
                   3989: 	my %loadnames=&Apache::lonnet::get('environment',
                   3990:                     			   ['notification','critnotification',
                   3991: 					    'permanentemail'],
                   3992: 					   $udom,$uname);
                   3993: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3994: 	return %loadnames;
                   3995:     }
                   3996: }
                   3997: 
1.551     albertel 3998: sub flush_email_cache {
                   3999:     my ($uname,$udom)=@_;
                   4000:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4001:     if (!$uname) { $uname=$env{'user.name'};   }
                   4002:     return if ($udom eq 'public' && $uname eq 'public');
                   4003:     my $id=$uname.':'.$udom;
                   4004:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4005: }
                   4006: 
1.728     raeburn  4007: # -------------------------------------------------------------------- getlangs
                   4008: 
                   4009: =pod
                   4010: 
                   4011: =item * &getlangs($uname,$udom)
                   4012: 
                   4013: Gets a user's language preference and returns it as a hash with key:
                   4014: language.
                   4015: 
                   4016: =cut
                   4017: 
                   4018: 
                   4019: sub getlangs {
                   4020:     my ($uname,$udom) = @_;
                   4021:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4022:     if (!$uname) { $uname=$env{'user.name'};   }
                   4023:     my $id=$uname.':'.$udom;
                   4024:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4025:     if ($cached) {
                   4026:         return %{$langs};
                   4027:     } else {
                   4028:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4029:                                            $udom,$uname);
                   4030:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4031:         return %loadlangs;
                   4032:     }
                   4033: }
                   4034: 
                   4035: sub flush_langs_cache {
                   4036:     my ($uname,$udom)=@_;
                   4037:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4038:     if (!$uname) { $uname=$env{'user.name'};   }
                   4039:     return if ($udom eq 'public' && $uname eq 'public');
                   4040:     my $id=$uname.':'.$udom;
                   4041:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4042: }
                   4043: 
1.61      www      4044: # ------------------------------------------------------------------ Screenname
1.81      albertel 4045: 
                   4046: =pod
                   4047: 
1.648     raeburn  4048: =item * &screenname($uname,$udom)
1.81      albertel 4049: 
                   4050: Gets a users screenname and returns it as a string
                   4051: 
                   4052: =cut
1.61      www      4053: 
                   4054: sub screenname {
                   4055:     my ($uname,$udom)=@_;
1.258     albertel 4056:     if ($uname eq $env{'user.name'} &&
                   4057: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4058:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4059:     return $names{'screenname'};
1.62      www      4060: }
                   4061: 
1.212     albertel 4062: 
1.802     bisitz   4063: # ------------------------------------------------------------- Confirm Wrapper
                   4064: =pod
                   4065: 
1.1142    raeburn  4066: =item * &confirmwrapper($message)
1.802     bisitz   4067: 
                   4068: Wrap messages about completion of operation in box
                   4069: 
                   4070: =cut
                   4071: 
                   4072: sub confirmwrapper {
                   4073:     my ($message)=@_;
                   4074:     if ($message) {
                   4075:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4076:                .$message."\n"
                   4077:                .'</div>'."\n";
                   4078:     } else {
                   4079:         return $message;
                   4080:     }
                   4081: }
                   4082: 
1.62      www      4083: # ------------------------------------------------------------- Message Wrapper
                   4084: 
                   4085: sub messagewrapper {
1.369     www      4086:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4087:     return 
1.441     albertel 4088:         '<a href="/adm/email?compose=individual&amp;'.
                   4089:         'recname='.$username.'&amp;recdom='.$domain.
                   4090: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4091:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4092: }
1.802     bisitz   4093: 
1.74      www      4094: # --------------------------------------------------------------- Notes Wrapper
                   4095: 
                   4096: sub noteswrapper {
                   4097:     my ($link,$un,$do)=@_;
                   4098:     return 
1.896     amueller 4099: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4100: }
1.802     bisitz   4101: 
1.62      www      4102: # ------------------------------------------------------------- Aboutme Wrapper
                   4103: 
                   4104: sub aboutmewrapper {
1.1070    raeburn  4105:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4106:     if (!defined($username)  && !defined($domain)) {
                   4107:         return;
                   4108:     }
1.1096    raeburn  4109:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4110: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4111: }
                   4112: 
                   4113: # ------------------------------------------------------------ Syllabus Wrapper
                   4114: 
                   4115: sub syllabuswrapper {
1.707     bisitz   4116:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4117:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4118: }
1.14      harris41 4119: 
1.802     bisitz   4120: # -----------------------------------------------------------------------------
                   4121: 
1.208     matthew  4122: sub track_student_link {
1.887     raeburn  4123:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4124:     my $link ="/adm/trackstudent?";
1.208     matthew  4125:     my $title = 'View recent activity';
                   4126:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4127:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4128:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4129:         $title .= ' of this student';
1.268     albertel 4130:     } 
1.208     matthew  4131:     if (defined($target) && $target !~ /^\s*$/) {
                   4132:         $target = qq{target="$target"};
                   4133:     } else {
                   4134:         $target = '';
                   4135:     }
1.268     albertel 4136:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4137:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4138:     $title = &mt($title);
                   4139:     $linktext = &mt($linktext);
1.448     albertel 4140:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4141: 	&help_open_topic('View_recent_activity');
1.208     matthew  4142: }
                   4143: 
1.781     raeburn  4144: sub slot_reservations_link {
                   4145:     my ($linktext,$sname,$sdom,$target) = @_;
                   4146:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4147:     my $title = 'View slot reservation history';
                   4148:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4149:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4150:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4151:         $title .= ' of this student';
                   4152:     }
                   4153:     if (defined($target) && $target !~ /^\s*$/) {
                   4154:         $target = qq{target="$target"};
                   4155:     } else {
                   4156:         $target = '';
                   4157:     }
                   4158:     $title = &mt($title);
                   4159:     $linktext = &mt($linktext);
                   4160:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4161: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4162: 
                   4163: }
                   4164: 
1.508     www      4165: # ===================================================== Display a student photo
                   4166: 
                   4167: 
1.509     albertel 4168: sub student_image_tag {
1.508     www      4169:     my ($domain,$user)=@_;
                   4170:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4171:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4172: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4173:     } else {
                   4174: 	return '';
                   4175:     }
                   4176: }
                   4177: 
1.112     bowersj2 4178: =pod
                   4179: 
                   4180: =back
                   4181: 
                   4182: =head1 Access .tab File Data
                   4183: 
                   4184: =over 4
                   4185: 
1.648     raeburn  4186: =item * &languageids() 
1.112     bowersj2 4187: 
                   4188: returns list of all language ids
                   4189: 
                   4190: =cut
                   4191: 
1.14      harris41 4192: sub languageids {
1.16      harris41 4193:     return sort(keys(%language));
1.14      harris41 4194: }
                   4195: 
1.112     bowersj2 4196: =pod
                   4197: 
1.648     raeburn  4198: =item * &languagedescription() 
1.112     bowersj2 4199: 
                   4200: returns description of a specified language id
                   4201: 
                   4202: =cut
                   4203: 
1.14      harris41 4204: sub languagedescription {
1.125     www      4205:     my $code=shift;
                   4206:     return  ($supported_language{$code}?'* ':'').
                   4207:             $language{$code}.
1.126     www      4208: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4209: }
                   4210: 
1.1048    foxr     4211: =pod
                   4212: 
                   4213: =item * &plainlanguagedescription
                   4214: 
                   4215: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4216: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4217: 
                   4218: =cut
                   4219: 
1.145     www      4220: sub plainlanguagedescription {
                   4221:     my $code=shift;
                   4222:     return $language{$code};
                   4223: }
                   4224: 
1.1048    foxr     4225: =pod
                   4226: 
                   4227: =item * &supportedlanguagecode
                   4228: 
                   4229: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4230: code.
                   4231: 
                   4232: =cut
                   4233: 
1.145     www      4234: sub supportedlanguagecode {
                   4235:     my $code=shift;
                   4236:     return $supported_language{$code};
1.97      www      4237: }
                   4238: 
1.112     bowersj2 4239: =pod
                   4240: 
1.1048    foxr     4241: =item * &latexlanguage()
                   4242: 
                   4243: Given a language key code returns the correspondnig language to use
                   4244: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4245: is no supported hyphenation for the language code.
                   4246: 
                   4247: =cut
                   4248: 
                   4249: sub latexlanguage {
                   4250:     my $code = shift;
                   4251:     return $latex_language{$code};
                   4252: }
                   4253: 
                   4254: =pod
                   4255: 
                   4256: =item * &latexhyphenation()
                   4257: 
                   4258: Same as above but what's supplied is the language as it might be stored
                   4259: in the metadata.
                   4260: 
                   4261: =cut
                   4262: 
                   4263: sub latexhyphenation {
                   4264:     my $key = shift;
                   4265:     return $latex_language_bykey{$key};
                   4266: }
                   4267: 
                   4268: =pod
                   4269: 
1.648     raeburn  4270: =item * &copyrightids() 
1.112     bowersj2 4271: 
                   4272: returns list of all copyrights
                   4273: 
                   4274: =cut
                   4275: 
                   4276: sub copyrightids {
                   4277:     return sort(keys(%cprtag));
                   4278: }
                   4279: 
                   4280: =pod
                   4281: 
1.648     raeburn  4282: =item * &copyrightdescription() 
1.112     bowersj2 4283: 
                   4284: returns description of a specified copyright id
                   4285: 
                   4286: =cut
                   4287: 
                   4288: sub copyrightdescription {
1.166     www      4289:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4290: }
1.197     matthew  4291: 
                   4292: =pod
                   4293: 
1.648     raeburn  4294: =item * &source_copyrightids() 
1.192     taceyjo1 4295: 
                   4296: returns list of all source copyrights
                   4297: 
                   4298: =cut
                   4299: 
                   4300: sub source_copyrightids {
                   4301:     return sort(keys(%scprtag));
                   4302: }
                   4303: 
                   4304: =pod
                   4305: 
1.648     raeburn  4306: =item * &source_copyrightdescription() 
1.192     taceyjo1 4307: 
                   4308: returns description of a specified source copyright id
                   4309: 
                   4310: =cut
                   4311: 
                   4312: sub source_copyrightdescription {
                   4313:     return &mt($scprtag{shift(@_)});
                   4314: }
1.112     bowersj2 4315: 
                   4316: =pod
                   4317: 
1.648     raeburn  4318: =item * &filecategories() 
1.112     bowersj2 4319: 
                   4320: returns list of all file categories
                   4321: 
                   4322: =cut
                   4323: 
                   4324: sub filecategories {
                   4325:     return sort(keys(%category_extensions));
                   4326: }
                   4327: 
                   4328: =pod
                   4329: 
1.648     raeburn  4330: =item * &filecategorytypes() 
1.112     bowersj2 4331: 
                   4332: returns list of file types belonging to a given file
                   4333: category
                   4334: 
                   4335: =cut
                   4336: 
                   4337: sub filecategorytypes {
1.356     albertel 4338:     my ($cat) = @_;
1.1248    raeburn  4339:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4340:         return @{$category_extensions{lc($cat)}};
                   4341:     } else {
                   4342:         return ();
                   4343:     }
1.112     bowersj2 4344: }
                   4345: 
                   4346: =pod
                   4347: 
1.648     raeburn  4348: =item * &fileembstyle() 
1.112     bowersj2 4349: 
                   4350: returns embedding style for a specified file type
                   4351: 
                   4352: =cut
                   4353: 
                   4354: sub fileembstyle {
                   4355:     return $fe{lc(shift(@_))};
1.169     www      4356: }
                   4357: 
1.351     www      4358: sub filemimetype {
                   4359:     return $fm{lc(shift(@_))};
                   4360: }
                   4361: 
1.169     www      4362: 
                   4363: sub filecategoryselect {
                   4364:     my ($name,$value)=@_;
1.189     matthew  4365:     return &select_form($value,$name,
1.970     raeburn  4366:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4367: }
                   4368: 
                   4369: =pod
                   4370: 
1.648     raeburn  4371: =item * &filedescription() 
1.112     bowersj2 4372: 
                   4373: returns description for a specified file type
                   4374: 
                   4375: =cut
                   4376: 
                   4377: sub filedescription {
1.188     matthew  4378:     my $file_description = $fd{lc(shift())};
                   4379:     $file_description =~ s:([\[\]]):~$1:g;
                   4380:     return &mt($file_description);
1.112     bowersj2 4381: }
                   4382: 
                   4383: =pod
                   4384: 
1.648     raeburn  4385: =item * &filedescriptionex() 
1.112     bowersj2 4386: 
                   4387: returns description for a specified file type with
                   4388: extra formatting
                   4389: 
                   4390: =cut
                   4391: 
                   4392: sub filedescriptionex {
                   4393:     my $ex=shift;
1.188     matthew  4394:     my $file_description = $fd{lc($ex)};
                   4395:     $file_description =~ s:([\[\]]):~$1:g;
                   4396:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4397: }
                   4398: 
                   4399: # End of .tab access
                   4400: =pod
                   4401: 
                   4402: =back
                   4403: 
                   4404: =cut
                   4405: 
                   4406: # ------------------------------------------------------------------ File Types
                   4407: sub fileextensions {
                   4408:     return sort(keys(%fe));
                   4409: }
                   4410: 
1.97      www      4411: # ----------------------------------------------------------- Display Languages
                   4412: # returns a hash with all desired display languages
                   4413: #
                   4414: 
                   4415: sub display_languages {
                   4416:     my %languages=();
1.695     raeburn  4417:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4418: 	$languages{$lang}=1;
1.97      www      4419:     }
                   4420:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4421:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4422: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4423: 	    $languages{$lang}=1;
1.97      www      4424:         }
                   4425:     }
                   4426:     return %languages;
1.14      harris41 4427: }
                   4428: 
1.582     albertel 4429: sub languages {
                   4430:     my ($possible_langs) = @_;
1.695     raeburn  4431:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4432:     if (!ref($possible_langs)) {
                   4433: 	if( wantarray ) {
                   4434: 	    return @preferred_langs;
                   4435: 	} else {
                   4436: 	    return $preferred_langs[0];
                   4437: 	}
                   4438:     }
                   4439:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4440:     my @preferred_possibilities;
                   4441:     foreach my $preferred_lang (@preferred_langs) {
                   4442: 	if (exists($possibilities{$preferred_lang})) {
                   4443: 	    push(@preferred_possibilities, $preferred_lang);
                   4444: 	}
                   4445:     }
                   4446:     if( wantarray ) {
                   4447: 	return @preferred_possibilities;
                   4448:     }
                   4449:     return $preferred_possibilities[0];
                   4450: }
                   4451: 
1.742     raeburn  4452: sub user_lang {
                   4453:     my ($touname,$toudom,$fromcid) = @_;
                   4454:     my @userlangs;
                   4455:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4456:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4457:                     $env{'course.'.$fromcid.'.languages'}));
                   4458:     } else {
                   4459:         my %langhash = &getlangs($touname,$toudom);
                   4460:         if ($langhash{'languages'} ne '') {
                   4461:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4462:         } else {
                   4463:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4464:             if ($domdefs{'lang_def'} ne '') {
                   4465:                 @userlangs = ($domdefs{'lang_def'});
                   4466:             }
                   4467:         }
                   4468:     }
                   4469:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4470:     my $user_lh = Apache::localize->get_handle(@languages);
                   4471:     return $user_lh;
                   4472: }
                   4473: 
                   4474: 
1.112     bowersj2 4475: ###############################################################
                   4476: ##               Student Answer Attempts                     ##
                   4477: ###############################################################
                   4478: 
                   4479: =pod
                   4480: 
                   4481: =head1 Alternate Problem Views
                   4482: 
                   4483: =over 4
                   4484: 
1.648     raeburn  4485: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4486:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4487: 
                   4488: Return string with previous attempt on problem. Arguments:
                   4489: 
                   4490: =over 4
                   4491: 
                   4492: =item * $symb: Problem, including path
                   4493: 
                   4494: =item * $username: username of the desired student
                   4495: 
                   4496: =item * $domain: domain of the desired student
1.14      harris41 4497: 
1.112     bowersj2 4498: =item * $course: Course ID
1.14      harris41 4499: 
1.112     bowersj2 4500: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4501:     something
1.14      harris41 4502: 
1.112     bowersj2 4503: =item * $regexp: if string matches this regexp, the string will be
                   4504:     sent to $gradesub
1.14      harris41 4505: 
1.112     bowersj2 4506: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4507: 
1.1199    raeburn  4508: =item * $usec: section of the desired student
                   4509: 
                   4510: =item * $identifier: counter for student (multiple students one problem) or 
                   4511:     problem (one student; whole sequence).
                   4512: 
1.112     bowersj2 4513: =back
1.14      harris41 4514: 
1.112     bowersj2 4515: The output string is a table containing all desired attempts, if any.
1.16      harris41 4516: 
1.112     bowersj2 4517: =cut
1.1       albertel 4518: 
                   4519: sub get_previous_attempt {
1.1199    raeburn  4520:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4521:   my $prevattempts='';
1.43      ng       4522:   no strict 'refs';
1.1       albertel 4523:   if ($symb) {
1.3       albertel 4524:     my (%returnhash)=
                   4525:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4526:     if ($returnhash{'version'}) {
                   4527:       my %lasthash=();
                   4528:       my $version;
                   4529:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4530:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4531:             if ($key =~ /\.rawrndseed$/) {
                   4532:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4533:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4534:             } else {
                   4535:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4536:             }
1.19      harris41 4537:         }
1.1       albertel 4538:       }
1.596     albertel 4539:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4540:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4541:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4542:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4543:       foreach my $key (sort(keys(%lasthash))) {
                   4544: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4545: 	if ($#parts > 0) {
1.31      albertel 4546: 	  my $data=$parts[-1];
1.989     raeburn  4547:           next if ($data eq 'foilorder');
1.31      albertel 4548: 	  pop(@parts);
1.1010    www      4549:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4550:           if ($data eq 'type') {
                   4551:               unless ($showsurv) {
                   4552:                   my $id = join(',',@parts);
                   4553:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4554:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4555:                       $lasthidden{$ign.'.'.$id} = 1;
                   4556:                   }
1.945     raeburn  4557:               }
1.1199    raeburn  4558:               if ($identifier ne '') {
                   4559:                   my $id = join(',',@parts);
                   4560:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4561:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4562:                       $hidestatus{$ign.'.'.$id} = 1;
                   4563:                   }
                   4564:               }
                   4565:           } elsif ($data eq 'regrader') {
                   4566:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4567:                   my $id = join(',',@parts);
                   4568:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4569:               }
1.1010    www      4570:           } 
1.31      albertel 4571: 	} else {
1.41      ng       4572: 	  if ($#parts == 0) {
                   4573: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4574: 	  } else {
                   4575: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4576: 	  }
1.31      albertel 4577: 	}
1.16      harris41 4578:       }
1.596     albertel 4579:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4580:       if ($getattempt eq '') {
1.1199    raeburn  4581:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4582:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4583:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4584:                 foreach my $id (keys(%regraded)) {
                   4585:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4586:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4587:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4588:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4589:                     }
                   4590:                 }
                   4591:             }
1.1200    raeburn  4592:         }
                   4593: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4594:             my (@hidden,@unsolved);
1.945     raeburn  4595:             if (%typeparts) {
                   4596:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4597:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4598:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4599:                         push(@hidden,$id);
1.1199    raeburn  4600:                     } elsif ($identifier ne '') {
                   4601:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4602:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4603:                                 ($hidestatus{$id})) {
1.1200    raeburn  4604:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4605:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4606:                                 push(@{$solved{$id}},$version);
                   4607:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4608:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4609:                                 my $skip;
                   4610:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4611:                                     foreach my $reset (@{$resets{$id}}) {
                   4612:                                         if ($reset > $solved{$id}[-1]) {
                   4613:                                             $skip=1;
                   4614:                                             last;
                   4615:                                         }
                   4616:                                     }
                   4617:                                 }
                   4618:                                 unless ($skip) {
                   4619:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4620:                                     push(@unsolved,$partslist);
                   4621:                                 }
                   4622:                             }
                   4623:                         }
1.945     raeburn  4624:                     }
                   4625:                 }
                   4626:             }
                   4627:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4628:                            '<td>'.&mt('Transaction [_1]',$version);
                   4629:             if (@unsolved) {
                   4630:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4631:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4632:                                  &mt('Hide').'</label></span>';
                   4633:             }
                   4634:             $prevattempts .= '</td>';
1.945     raeburn  4635:             if (@hidden) {
                   4636:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4637:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4638:                     my $hide;
                   4639:                     foreach my $id (@hidden) {
                   4640:                         if ($key =~ /^\Q$id\E/) {
                   4641:                             $hide = 1;
                   4642:                             last;
                   4643:                         }
                   4644:                     }
                   4645:                     if ($hide) {
                   4646:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4647:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4648:                             my $value = &format_previous_attempt_value($key,
                   4649:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4650:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4651:                         } else {
                   4652:                             $prevattempts.='<td>&nbsp;</td>';
                   4653:                         }
                   4654:                     } else {
                   4655:                         if ($key =~ /\./) {
1.1212    raeburn  4656:                             my $value = $returnhash{$version.':'.$key};
                   4657:                             if ($key =~ /\.rndseed$/) {
                   4658:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4659:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4660:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4661:                                 }
                   4662:                             }
                   4663:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4664:                                            '&nbsp;</td>';
1.945     raeburn  4665:                         } else {
                   4666:                             $prevattempts.='<td>&nbsp;</td>';
                   4667:                         }
                   4668:                     }
                   4669:                 }
                   4670:             } else {
                   4671: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4672:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4673:                     my $value = $returnhash{$version.':'.$key};
                   4674:                     if ($key =~ /\.rndseed$/) {
                   4675:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4676:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4677:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4678:                         }
                   4679:                     }
                   4680:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4681:                                    '&nbsp;</td>';
1.945     raeburn  4682: 	        }
                   4683:             }
                   4684: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4685: 	 }
1.1       albertel 4686:       }
1.945     raeburn  4687:       my @currhidden = keys(%lasthidden);
1.596     albertel 4688:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4689:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4690:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4691:           if (%typeparts) {
                   4692:               my $hidden;
                   4693:               foreach my $id (@currhidden) {
                   4694:                   if ($key =~ /^\Q$id\E/) {
                   4695:                       $hidden = 1;
                   4696:                       last;
                   4697:                   }
                   4698:               }
                   4699:               if ($hidden) {
                   4700:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4701:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4702:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4703:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4704:                           $value = &$gradesub($value);
                   4705:                       }
1.1173    kruse    4706:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4707:                   } else {
                   4708:                       $prevattempts.='<td>&nbsp;</td>';
                   4709:                   }
                   4710:               } else {
                   4711:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4712:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4713:                       $value = &$gradesub($value);
                   4714:                   }
1.1173    kruse    4715:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4716:               }
                   4717:           } else {
                   4718: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4719: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4720:                   $value = &$gradesub($value);
                   4721:               }
1.1173    kruse    4722: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4723:           }
1.16      harris41 4724:       }
1.596     albertel 4725:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4726:     } else {
1.1305    raeburn  4727:       my $msg;
                   4728:       if ($symb =~ /ext\.tool$/) {
                   4729:           $msg = &mt('No grade passed back.');
                   4730:       } else {
                   4731:           $msg = &mt('Nothing submitted - no attempts.');
                   4732:       }
1.596     albertel 4733:       $prevattempts=
                   4734: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4735: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4736: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4737:     }
                   4738:   } else {
1.596     albertel 4739:     $prevattempts=
                   4740: 	  &start_data_table().&start_data_table_row().
                   4741: 	  '<td>'.&mt('No data.').'</td>'.
                   4742: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4743:   }
1.10      albertel 4744: }
                   4745: 
1.581     albertel 4746: sub format_previous_attempt_value {
                   4747:     my ($key,$value) = @_;
1.1011    www      4748:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4749:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4750:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4751:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4752:     } elsif ($key =~ /answerstring$/) {
                   4753:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4754:         my @answer = %answers;
                   4755:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4756:         my @anskeys = sort(keys(%answers));
                   4757:         if (@anskeys == 1) {
                   4758:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4759:             if ($answer =~ m{\0}) {
                   4760:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4761:             }
                   4762:             my $tag_internal_answer_name = 'INTERNAL';
                   4763:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4764:                 $value = $answer; 
                   4765:             } else {
                   4766:                 $value = $anskeys[0].'='.$answer;
                   4767:             }
                   4768:         } else {
                   4769:             foreach my $ans (@anskeys) {
                   4770:                 my $answer = $answers{$ans};
1.1001    raeburn  4771:                 if ($answer =~ m{\0}) {
                   4772:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4773:                 }
                   4774:                 $value .=  $ans.'='.$answer.'<br />';;
                   4775:             } 
                   4776:         }
1.581     albertel 4777:     } else {
1.1173    kruse    4778:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4779:     }
                   4780:     return $value;
                   4781: }
                   4782: 
                   4783: 
1.107     albertel 4784: sub relative_to_absolute {
                   4785:     my ($url,$output)=@_;
                   4786:     my $parser=HTML::TokeParser->new(\$output);
                   4787:     my $token;
                   4788:     my $thisdir=$url;
                   4789:     my @rlinks=();
                   4790:     while ($token=$parser->get_token) {
                   4791: 	if ($token->[0] eq 'S') {
                   4792: 	    if ($token->[1] eq 'a') {
                   4793: 		if ($token->[2]->{'href'}) {
                   4794: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4795: 		}
                   4796: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4797: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4798: 	    } elsif ($token->[1] eq 'base') {
                   4799: 		$thisdir=$token->[2]->{'href'};
                   4800: 	    }
                   4801: 	}
                   4802:     }
                   4803:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4804:     foreach my $link (@rlinks) {
1.726     raeburn  4805: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4806: 		($link=~/^\//) ||
                   4807: 		($link=~/^javascript:/i) ||
                   4808: 		($link=~/^mailto:/i) ||
                   4809: 		($link=~/^\#/)) {
                   4810: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4811: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4812: 	}
                   4813:     }
                   4814: # -------------------------------------------------- Deal with Applet codebases
                   4815:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4816:     return $output;
                   4817: }
                   4818: 
1.112     bowersj2 4819: =pod
                   4820: 
1.648     raeburn  4821: =item * &get_student_view()
1.112     bowersj2 4822: 
                   4823: show a snapshot of what student was looking at
                   4824: 
                   4825: =cut
                   4826: 
1.10      albertel 4827: sub get_student_view {
1.186     albertel 4828:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4829:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4830:   my (%form);
1.10      albertel 4831:   my @elements=('symb','courseid','domain','username');
                   4832:   foreach my $element (@elements) {
1.186     albertel 4833:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4834:   }
1.186     albertel 4835:   if (defined($moreenv)) {
                   4836:       %form=(%form,%{$moreenv});
                   4837:   }
1.236     albertel 4838:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4839:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  4840:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   4841:       $feedurl =~ s{^/adm/wrapper}{};
                   4842:   }
1.650     www      4843:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4844:   $userview=~s/\<body[^\>]*\>//gi;
                   4845:   $userview=~s/\<\/body\>//gi;
                   4846:   $userview=~s/\<html\>//gi;
                   4847:   $userview=~s/\<\/html\>//gi;
                   4848:   $userview=~s/\<head\>//gi;
                   4849:   $userview=~s/\<\/head\>//gi;
                   4850:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4851:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4852:   if (wantarray) {
                   4853:      return ($userview,$response);
                   4854:   } else {
                   4855:      return $userview;
                   4856:   }
                   4857: }
                   4858: 
                   4859: sub get_student_view_with_retries {
                   4860:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4861: 
                   4862:     my $ok = 0;                 # True if we got a good response.
                   4863:     my $content;
                   4864:     my $response;
                   4865: 
                   4866:     # Try to get the student_view done. within the retries count:
                   4867:     
                   4868:     do {
                   4869:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4870:          $ok      = $response->is_success;
                   4871:          if (!$ok) {
                   4872:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4873:          }
                   4874:          $retries--;
                   4875:     } while (!$ok && ($retries > 0));
                   4876:     
                   4877:     if (!$ok) {
                   4878:        $content = '';          # On error return an empty content.
                   4879:     }
1.651     www      4880:     if (wantarray) {
                   4881:        return ($content, $response);
                   4882:     } else {
                   4883:        return $content;
                   4884:     }
1.11      albertel 4885: }
                   4886: 
1.112     bowersj2 4887: =pod
                   4888: 
1.648     raeburn  4889: =item * &get_student_answers() 
1.112     bowersj2 4890: 
                   4891: show a snapshot of how student was answering problem
                   4892: 
                   4893: =cut
                   4894: 
1.11      albertel 4895: sub get_student_answers {
1.100     sakharuk 4896:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4897:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4898:   my (%moreenv);
1.11      albertel 4899:   my @elements=('symb','courseid','domain','username');
                   4900:   foreach my $element (@elements) {
1.186     albertel 4901:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4902:   }
1.186     albertel 4903:   $moreenv{'grade_target'}='answer';
                   4904:   %moreenv=(%form,%moreenv);
1.497     raeburn  4905:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4906:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4907:   return $userview;
1.1       albertel 4908: }
1.116     albertel 4909: 
                   4910: =pod
                   4911: 
                   4912: =item * &submlink()
                   4913: 
1.242     albertel 4914: Inputs: $text $uname $udom $symb $target
1.116     albertel 4915: 
                   4916: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4917: 
                   4918: =cut
                   4919: 
                   4920: ###############################################
                   4921: sub submlink {
1.242     albertel 4922:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4923:     if (!($uname && $udom)) {
                   4924: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4925: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4926: 	if (!$symb) { $symb=$cursymb; }
                   4927:     }
1.254     matthew  4928:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4929:     $symb=&escape($symb);
1.960     bisitz   4930:     if ($target) { $target=" target=\"$target\""; }
                   4931:     return
                   4932:         '<a href="/adm/grades?command=submission'.
                   4933:         '&amp;symb='.$symb.
                   4934:         '&amp;student='.$uname.
                   4935:         '&amp;userdom='.$udom.'"'.
                   4936:         $target.'>'.$text.'</a>';
1.242     albertel 4937: }
                   4938: ##############################################
                   4939: 
                   4940: =pod
                   4941: 
                   4942: =item * &pgrdlink()
                   4943: 
                   4944: Inputs: $text $uname $udom $symb $target
                   4945: 
                   4946: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4947: 
                   4948: =cut
                   4949: 
                   4950: ###############################################
                   4951: sub pgrdlink {
                   4952:     my $link=&submlink(@_);
                   4953:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4954:     return $link;
                   4955: }
                   4956: ##############################################
                   4957: 
                   4958: =pod
                   4959: 
                   4960: =item * &pprmlink()
                   4961: 
                   4962: Inputs: $text $uname $udom $symb $target
                   4963: 
                   4964: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4965: student and a specific resource
1.242     albertel 4966: 
                   4967: =cut
                   4968: 
                   4969: ###############################################
                   4970: sub pprmlink {
                   4971:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4972:     if (!($uname && $udom)) {
                   4973: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4974: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4975: 	if (!$symb) { $symb=$cursymb; }
                   4976:     }
1.254     matthew  4977:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4978:     $symb=&escape($symb);
1.242     albertel 4979:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4980:     return '<a href="/adm/parmset?command=set&amp;'.
                   4981: 	'symb='.$symb.'&amp;uname='.$uname.
                   4982: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4983: }
                   4984: ##############################################
1.37      matthew  4985: 
1.112     bowersj2 4986: =pod
                   4987: 
                   4988: =back
                   4989: 
                   4990: =cut
                   4991: 
1.37      matthew  4992: ###############################################
1.51      www      4993: 
                   4994: 
                   4995: sub timehash {
1.687     raeburn  4996:     my ($thistime) = @_;
                   4997:     my $timezone = &Apache::lonlocal::gettimezone();
                   4998:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4999:                      ->set_time_zone($timezone);
                   5000:     my $wday = $dt->day_of_week();
                   5001:     if ($wday == 7) { $wday = 0; }
                   5002:     return ( 'second' => $dt->second(),
                   5003:              'minute' => $dt->minute(),
                   5004:              'hour'   => $dt->hour(),
                   5005:              'day'     => $dt->day_of_month(),
                   5006:              'month'   => $dt->month(),
                   5007:              'year'    => $dt->year(),
                   5008:              'weekday' => $wday,
                   5009:              'dayyear' => $dt->day_of_year(),
                   5010:              'dlsav'   => $dt->is_dst() );
1.51      www      5011: }
                   5012: 
1.370     www      5013: sub utc_string {
                   5014:     my ($date)=@_;
1.371     www      5015:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5016: }
                   5017: 
1.51      www      5018: sub maketime {
                   5019:     my %th=@_;
1.687     raeburn  5020:     my ($epoch_time,$timezone,$dt);
                   5021:     $timezone = &Apache::lonlocal::gettimezone();
                   5022:     eval {
                   5023:         $dt = DateTime->new( year   => $th{'year'},
                   5024:                              month  => $th{'month'},
                   5025:                              day    => $th{'day'},
                   5026:                              hour   => $th{'hour'},
                   5027:                              minute => $th{'minute'},
                   5028:                              second => $th{'second'},
                   5029:                              time_zone => $timezone,
                   5030:                          );
                   5031:     };
                   5032:     if (!$@) {
                   5033:         $epoch_time = $dt->epoch;
                   5034:         if ($epoch_time) {
                   5035:             return $epoch_time;
                   5036:         }
                   5037:     }
1.51      www      5038:     return POSIX::mktime(
                   5039:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5040:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5041: }
                   5042: 
                   5043: #########################################
1.51      www      5044: 
                   5045: sub findallcourses {
1.482     raeburn  5046:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5047:     my %roles;
                   5048:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5049:     my %courses;
1.51      www      5050:     my $now=time;
1.482     raeburn  5051:     if (!defined($uname)) {
                   5052:         $uname = $env{'user.name'};
                   5053:     }
                   5054:     if (!defined($udom)) {
                   5055:         $udom = $env{'user.domain'};
                   5056:     }
                   5057:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5058:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5059:         if (!%roles) {
                   5060:             %roles = (
                   5061:                        cc => 1,
1.907     raeburn  5062:                        co => 1,
1.482     raeburn  5063:                        in => 1,
                   5064:                        ep => 1,
                   5065:                        ta => 1,
                   5066:                        cr => 1,
                   5067:                        st => 1,
                   5068:              );
                   5069:         }
                   5070:         foreach my $entry (keys(%roleshash)) {
                   5071:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5072:             if ($trole =~ /^cr/) { 
                   5073:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5074:             } else {
                   5075:                 next if (!exists($roles{$trole}));
                   5076:             }
                   5077:             if ($tend) {
                   5078:                 next if ($tend < $now);
                   5079:             }
                   5080:             if ($tstart) {
                   5081:                 next if ($tstart > $now);
                   5082:             }
1.1058    raeburn  5083:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5084:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5085:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5086:             if ($secpart eq '') {
                   5087:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5088:                 $sec = 'none';
1.1058    raeburn  5089:                 $value .= $cnum.'/';
1.482     raeburn  5090:             } else {
                   5091:                 $cnum = $cnumpart;
                   5092:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5093:                 $value .= $cnum.'/'.$sec;
                   5094:             }
                   5095:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5096:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5097:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5098:                 }
                   5099:             } else {
                   5100:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5101:             }
1.482     raeburn  5102:         }
                   5103:     } else {
                   5104:         foreach my $key (keys(%env)) {
1.483     albertel 5105: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5106:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5107: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5108: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5109: 	        next if (%roles && !exists($roles{$role}));
                   5110: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5111:                 my $active=1;
                   5112:                 if ($starttime) {
                   5113: 		    if ($now<$starttime) { $active=0; }
                   5114:                 }
                   5115:                 if ($endtime) {
                   5116:                     if ($now>$endtime) { $active=0; }
                   5117:                 }
                   5118:                 if ($active) {
1.1058    raeburn  5119:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5120:                     if ($sec eq '') {
                   5121:                         $sec = 'none';
1.1058    raeburn  5122:                     } else {
                   5123:                         $value .= $sec;
                   5124:                     }
                   5125:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5126:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5127:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5128:                         }
                   5129:                     } else {
                   5130:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5131:                     }
1.474     raeburn  5132:                 }
                   5133:             }
1.51      www      5134:         }
                   5135:     }
1.474     raeburn  5136:     return %courses;
1.51      www      5137: }
1.37      matthew  5138: 
1.54      www      5139: ###############################################
1.474     raeburn  5140: 
                   5141: sub blockcheck {
1.1189    raeburn  5142:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  5143: 
1.1189    raeburn  5144:     if (defined($udom) && defined($uname)) {
                   5145:         # If uname and udom are for a course, check for blocks in the course.
                   5146:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5147:             my ($startblock,$endblock,$triggerblock) =
                   5148:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   5149:             return ($startblock,$endblock,$triggerblock);
                   5150:         }
                   5151:     } else {
1.490     raeburn  5152:         $udom = $env{'user.domain'};
                   5153:         $uname = $env{'user.name'};
                   5154:     }
                   5155: 
1.502     raeburn  5156:     my $startblock = 0;
                   5157:     my $endblock = 0;
1.1062    raeburn  5158:     my $triggerblock = '';
1.482     raeburn  5159:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  5160: 
1.490     raeburn  5161:     # If uname is for a user, and activity is course-specific, i.e.,
                   5162:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5163: 
1.490     raeburn  5164:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5165:          $activity eq 'groups' || $activity eq 'printout' ||
                   5166:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5167:         ($env{'request.course.id'})) {
1.490     raeburn  5168:         foreach my $key (keys(%live_courses)) {
                   5169:             if ($key ne $env{'request.course.id'}) {
                   5170:                 delete($live_courses{$key});
                   5171:             }
                   5172:         }
                   5173:     }
                   5174: 
                   5175:     my $otheruser = 0;
                   5176:     my %own_courses;
                   5177:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5178:         # Resource belongs to user other than current user.
                   5179:         $otheruser = 1;
                   5180:         # Gather courses for current user
                   5181:         %own_courses = 
                   5182:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5183:     }
                   5184: 
                   5185:     # Gather active course roles - course coordinator, instructor, 
                   5186:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5187: 
                   5188:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5189:         my ($cdom,$cnum);
                   5190:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5191:             $cdom = $env{'course.'.$course.'.domain'};
                   5192:             $cnum = $env{'course.'.$course.'.num'};
                   5193:         } else {
1.490     raeburn  5194:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5195:         }
                   5196:         my $no_ownblock = 0;
                   5197:         my $no_userblock = 0;
1.533     raeburn  5198:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5199:             # Check if current user has 'evb' priv for this
                   5200:             if (defined($own_courses{$course})) {
                   5201:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5202:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5203:                     if ($sec ne 'none') {
                   5204:                         $checkrole .= '/'.$sec;
                   5205:                     }
                   5206:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5207:                         $no_ownblock = 1;
                   5208:                         last;
                   5209:                     }
                   5210:                 }
                   5211:             }
                   5212:             # if they have 'evb' priv and are currently not playing student
                   5213:             next if (($no_ownblock) &&
                   5214:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5215:         }
1.474     raeburn  5216:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5217:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5218:             if ($sec ne 'none') {
1.482     raeburn  5219:                 $checkrole .= '/'.$sec;
1.474     raeburn  5220:             }
1.490     raeburn  5221:             if ($otheruser) {
                   5222:                 # Resource belongs to user other than current user.
                   5223:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5224:                 my (%allroles,%userroles);
                   5225:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5226:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5227:                         my ($trole,$tdom,$tnum,$tsec);
                   5228:                         if ($entry =~ /^cr/) {
                   5229:                             ($trole,$tdom,$tnum,$tsec) = 
                   5230:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5231:                         } else {
                   5232:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5233:                         }
                   5234:                         my ($spec,$area,$trest);
                   5235:                         $area = '/'.$tdom.'/'.$tnum;
                   5236:                         $trest = $tnum;
                   5237:                         if ($tsec ne '') {
                   5238:                             $area .= '/'.$tsec;
                   5239:                             $trest .= '/'.$tsec;
                   5240:                         }
                   5241:                         $spec = $trole.'.'.$area;
                   5242:                         if ($trole =~ /^cr/) {
                   5243:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5244:                                                               $tdom,$spec,$trest,$area);
                   5245:                         } else {
                   5246:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5247:                                                                 $tdom,$spec,$trest,$area);
                   5248:                         }
                   5249:                     }
1.1276    raeburn  5250:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5251:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5252:                         if ($1) {
                   5253:                             $no_userblock = 1;
                   5254:                             last;
                   5255:                         }
1.486     raeburn  5256:                     }
                   5257:                 }
1.490     raeburn  5258:             } else {
                   5259:                 # Resource belongs to current user
                   5260:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5261:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5262:                     $no_ownblock = 1;
                   5263:                     last;
                   5264:                 }
1.474     raeburn  5265:             }
                   5266:         }
                   5267:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5268:         next if (($no_ownblock) &&
1.491     albertel 5269:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5270:         next if ($no_userblock);
1.474     raeburn  5271: 
1.1303    raeburn  5272:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5273:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5274: 
1.1062    raeburn  5275:         my ($start,$end,$trigger) = 
                   5276:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5277:         if (($start != 0) && 
                   5278:             (($startblock == 0) || ($startblock > $start))) {
                   5279:             $startblock = $start;
1.1062    raeburn  5280:             if ($trigger ne '') {
                   5281:                 $triggerblock = $trigger;
                   5282:             }
1.502     raeburn  5283:         }
                   5284:         if (($end != 0)  &&
                   5285:             (($endblock == 0) || ($endblock < $end))) {
                   5286:             $endblock = $end;
1.1062    raeburn  5287:             if ($trigger ne '') {
                   5288:                 $triggerblock = $trigger;
                   5289:             }
1.502     raeburn  5290:         }
1.490     raeburn  5291:     }
1.1062    raeburn  5292:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5293: }
                   5294: 
                   5295: sub get_blocks {
1.1062    raeburn  5296:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5297:     my $startblock = 0;
                   5298:     my $endblock = 0;
1.1062    raeburn  5299:     my $triggerblock = '';
1.490     raeburn  5300:     my $course = $cdom.'_'.$cnum;
                   5301:     $setters->{$course} = {};
                   5302:     $setters->{$course}{'staff'} = [];
                   5303:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5304:     $setters->{$course}{'triggers'} = [];
                   5305:     my (@blockers,%triggered);
                   5306:     my $now = time;
                   5307:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5308:     if ($activity eq 'docs') {
                   5309:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5310:         foreach my $block (@blockers) {
                   5311:             if ($block =~ /^firstaccess____(.+)$/) {
                   5312:                 my $item = $1;
                   5313:                 my $type = 'map';
                   5314:                 my $timersymb = $item;
                   5315:                 if ($item eq 'course') {
                   5316:                     $type = 'course';
                   5317:                 } elsif ($item =~ /___\d+___/) {
                   5318:                     $type = 'resource';
                   5319:                 } else {
                   5320:                     $timersymb = &Apache::lonnet::symbread($item);
                   5321:                 }
                   5322:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5323:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5324:                 $triggered{$block} = {
                   5325:                                        start => $start,
                   5326:                                        end   => $end,
                   5327:                                        type  => $type,
                   5328:                                      };
                   5329:             }
                   5330:         }
                   5331:     } else {
                   5332:         foreach my $block (keys(%commblocks)) {
                   5333:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5334:                 my ($start,$end) = ($1,$2);
                   5335:                 if ($start <= time && $end >= time) {
                   5336:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5337:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5338:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5339:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5340:                                     push(@blockers,$block);
                   5341:                                 }
                   5342:                             }
                   5343:                         }
                   5344:                     }
                   5345:                 }
                   5346:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5347:                 my $item = $1;
                   5348:                 my $timersymb = $item; 
                   5349:                 my $type = 'map';
                   5350:                 if ($item eq 'course') {
                   5351:                     $type = 'course';
                   5352:                 } elsif ($item =~ /___\d+___/) {
                   5353:                     $type = 'resource';
                   5354:                 } else {
                   5355:                     $timersymb = &Apache::lonnet::symbread($item);
                   5356:                 }
                   5357:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5358:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5359:                 if ($start && $end) {
                   5360:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5361:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5362:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5363:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5364:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5365:                                         push(@blockers,$block);
                   5366:                                         $triggered{$block} = {
                   5367:                                                                start => $start,
                   5368:                                                                end   => $end,
                   5369:                                                                type  => $type,
                   5370:                                                              };
                   5371:                                     }
                   5372:                                 }
                   5373:                             }
1.1062    raeburn  5374:                         }
                   5375:                     }
1.490     raeburn  5376:                 }
1.1062    raeburn  5377:             }
                   5378:         }
                   5379:     }
                   5380:     foreach my $blocker (@blockers) {
                   5381:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5382:             &parse_block_record($commblocks{$blocker});
                   5383:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5384:         my ($start,$end,$triggertype);
                   5385:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5386:             ($start,$end) = ($1,$2);
                   5387:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5388:             $start = $triggered{$blocker}{'start'};
                   5389:             $end = $triggered{$blocker}{'end'};
                   5390:             $triggertype = $triggered{$blocker}{'type'};
                   5391:         }
                   5392:         if ($start) {
                   5393:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5394:             if ($triggertype) {
                   5395:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5396:             } else {
                   5397:                 push(@{$$setters{$course}{'triggers'}},0);
                   5398:             }
                   5399:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5400:                 $startblock = $start;
                   5401:                 if ($triggertype) {
                   5402:                     $triggerblock = $blocker;
1.474     raeburn  5403:                 }
                   5404:             }
1.1062    raeburn  5405:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5406:                $endblock = $end;
                   5407:                if ($triggertype) {
                   5408:                    $triggerblock = $blocker;
                   5409:                }
                   5410:             }
1.474     raeburn  5411:         }
                   5412:     }
1.1062    raeburn  5413:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5414: }
                   5415: 
                   5416: sub parse_block_record {
                   5417:     my ($record) = @_;
                   5418:     my ($setuname,$setudom,$title,$blocks);
                   5419:     if (ref($record) eq 'HASH') {
                   5420:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5421:         $title = &unescape($record->{'event'});
                   5422:         $blocks = $record->{'blocks'};
                   5423:     } else {
                   5424:         my @data = split(/:/,$record,3);
                   5425:         if (scalar(@data) eq 2) {
                   5426:             $title = $data[1];
                   5427:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5428:         } else {
                   5429:             ($setuname,$setudom,$title) = @data;
                   5430:         }
                   5431:         $blocks = { 'com' => 'on' };
                   5432:     }
                   5433:     return ($setuname,$setudom,$title,$blocks);
                   5434: }
                   5435: 
1.854     kalberla 5436: sub blocking_status {
1.1189    raeburn  5437:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5438:     my %setters;
1.890     droeschl 5439: 
1.1061    raeburn  5440: # check for active blocking
1.1062    raeburn  5441:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5442:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5443:     my $blocked = 0;
                   5444:     if ($startblock && $endblock) {
                   5445:         $blocked = 1;
                   5446:     }
1.890     droeschl 5447: 
1.1061    raeburn  5448: # caller just wants to know whether a block is active
                   5449:     if (!wantarray) { return $blocked; }
                   5450: 
                   5451: # build a link to a popup window containing the details
                   5452:     my $querystring  = "?activity=$activity";
                   5453: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5454:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5455:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5456:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5457:     } elsif ($activity eq 'docs') {
                   5458:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5459:     }
1.1061    raeburn  5460: 
                   5461:     my $output .= <<'END_MYBLOCK';
                   5462: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5463:     var options = "width=" + w + ",height=" + h + ",";
                   5464:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5465:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5466:     var newWin = window.open(url, wdwName, options);
                   5467:     newWin.focus();
                   5468: }
1.890     droeschl 5469: END_MYBLOCK
1.854     kalberla 5470: 
1.1061    raeburn  5471:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5472:   
1.1061    raeburn  5473:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5474:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5475:     my $class = 'LC_comblock';
1.1062    raeburn  5476:     if ($activity eq 'docs') {
                   5477:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5478:         $class = '';
1.1063    raeburn  5479:     } elsif ($activity eq 'printout') {
                   5480:         $text = &mt('Printing Blocked');
1.1232    raeburn  5481:     } elsif ($activity eq 'passwd') {
                   5482:         $text = &mt('Password Changing Blocked');
1.1282    raeburn  5483:     } elsif ($activity eq 'alert') {
                   5484:         $text = &mt('Checking Critical Messages Blocked');
                   5485:     } elsif ($activity eq 'reinit') {
                   5486:         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5487:     }
1.1061    raeburn  5488:     $output .= <<"END_BLOCK";
1.1217    raeburn  5489: <div class='$class'>
1.869     kalberla 5490:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5491:   title='$text'>
                   5492:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5493:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5494:   title='$text'>$text</a>
1.867     kalberla 5495: </div>
                   5496: 
                   5497: END_BLOCK
1.474     raeburn  5498: 
1.1061    raeburn  5499:     return ($blocked, $output);
1.854     kalberla 5500: }
1.490     raeburn  5501: 
1.60      matthew  5502: ###############################################
                   5503: 
1.682     raeburn  5504: sub check_ip_acc {
1.1201    raeburn  5505:     my ($acc,$clientip)=@_;
1.682     raeburn  5506:     &Apache::lonxml::debug("acc is $acc");
                   5507:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5508:         return 1;
                   5509:     }
1.1219    raeburn  5510:     my $allowed;
1.1252    raeburn  5511:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5512: 
                   5513:     my $name;
1.1219    raeburn  5514:     my %access = (
                   5515:                      allowfrom => 1,
                   5516:                      denyfrom  => 0,
                   5517:                  );
                   5518:     my @allows;
                   5519:     my @denies;
                   5520:     foreach my $item (split(',',$acc)) {
                   5521:         $item =~ s/^\s*//;
                   5522:         $item =~ s/\s*$//;
                   5523:         my $pattern;
                   5524:         if ($item =~ /^\!(.+)$/) {
                   5525:             push(@denies,$1);
                   5526:         } else {
                   5527:             push(@allows,$item);
                   5528:         }
                   5529:    }
                   5530:    my $numdenies = scalar(@denies);
                   5531:    my $numallows = scalar(@allows);
                   5532:    my $count = 0;
                   5533:    foreach my $pattern (@denies,@allows) {
                   5534:         $count ++; 
                   5535:         my $acctype = 'allowfrom';
                   5536:         if ($count <= $numdenies) {
                   5537:             $acctype = 'denyfrom';
                   5538:         }
1.682     raeburn  5539:         if ($pattern =~ /\*$/) {
                   5540:             #35.8.*
                   5541:             $pattern=~s/\*//;
1.1219    raeburn  5542:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5543:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5544:             #35.8.3.[34-56]
                   5545:             my $low=$2;
                   5546:             my $high=$3;
                   5547:             $pattern=$1;
                   5548:             if ($ip =~ /^\Q$pattern\E/) {
                   5549:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5550:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5551:             }
                   5552:         } elsif ($pattern =~ /^\*/) {
                   5553:             #*.msu.edu
                   5554:             $pattern=~s/\*//;
                   5555:             if (!defined($name)) {
                   5556:                 use Socket;
                   5557:                 my $netaddr=inet_aton($ip);
                   5558:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5559:             }
1.1219    raeburn  5560:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5561:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5562:             #127.0.0.1
1.1219    raeburn  5563:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5564:         } else {
                   5565:             #some.name.com
                   5566:             if (!defined($name)) {
                   5567:                 use Socket;
                   5568:                 my $netaddr=inet_aton($ip);
                   5569:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5570:             }
1.1219    raeburn  5571:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5572:         }
                   5573:         if ($allowed =~ /^(0|1)$/) { last; }
                   5574:     }
                   5575:     if ($allowed eq '') {
                   5576:         if ($numdenies && !$numallows) {
                   5577:             $allowed = 1;
                   5578:         } else {
                   5579:             $allowed = 0;
1.682     raeburn  5580:         }
                   5581:     }
                   5582:     return $allowed;
                   5583: }
                   5584: 
                   5585: ###############################################
                   5586: 
1.60      matthew  5587: =pod
                   5588: 
1.112     bowersj2 5589: =head1 Domain Template Functions
                   5590: 
                   5591: =over 4
                   5592: 
                   5593: =item * &determinedomain()
1.60      matthew  5594: 
                   5595: Inputs: $domain (usually will be undef)
                   5596: 
1.63      www      5597: Returns: Determines which domain should be used for designs
1.60      matthew  5598: 
                   5599: =cut
1.54      www      5600: 
1.60      matthew  5601: ###############################################
1.63      www      5602: sub determinedomain {
                   5603:     my $domain=shift;
1.531     albertel 5604:     if (! $domain) {
1.60      matthew  5605:         # Determine domain if we have not been given one
1.893     raeburn  5606:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5607:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5608:         if ($env{'request.role.domain'}) { 
                   5609:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5610:         }
                   5611:     }
1.63      www      5612:     return $domain;
                   5613: }
                   5614: ###############################################
1.517     raeburn  5615: 
1.518     albertel 5616: sub devalidate_domconfig_cache {
                   5617:     my ($udom)=@_;
                   5618:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5619: }
                   5620: 
                   5621: # ---------------------- Get domain configuration for a domain
                   5622: sub get_domainconf {
                   5623:     my ($udom) = @_;
                   5624:     my $cachetime=1800;
                   5625:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5626:     if (defined($cached)) { return %{$result}; }
                   5627: 
                   5628:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5629: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5630:     my (%designhash,%legacy);
1.518     albertel 5631:     if (keys(%domconfig) > 0) {
                   5632:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5633:             if (keys(%{$domconfig{'login'}})) {
                   5634:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5635:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5636:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5637:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5638:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5639:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5640:                                         if ($key eq 'loginvia') {
                   5641:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5642:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5643:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5644:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5645: 
                   5646:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5647:                                                 } else {
                   5648:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5649:                                                 }
1.948     raeburn  5650:                                             }
1.1208    raeburn  5651:                                         } elsif ($key eq 'headtag') {
                   5652:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5653:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5654:                                             }
1.946     raeburn  5655:                                         }
1.1208    raeburn  5656:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5657:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5658:                                         }
1.946     raeburn  5659:                                     }
                   5660:                                 }
                   5661:                             }
                   5662:                         } else {
                   5663:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5664:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5665:                                     $domconfig{'login'}{$key}{$img};
                   5666:                             }
1.699     raeburn  5667:                         }
                   5668:                     } else {
                   5669:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5670:                     }
1.632     raeburn  5671:                 }
                   5672:             } else {
                   5673:                 $legacy{'login'} = 1;
1.518     albertel 5674:             }
1.632     raeburn  5675:         } else {
                   5676:             $legacy{'login'} = 1;
1.518     albertel 5677:         }
                   5678:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5679:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5680:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5681:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5682:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5683:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5684:                         }
1.518     albertel 5685:                     }
                   5686:                 }
1.632     raeburn  5687:             } else {
                   5688:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5689:             }
1.632     raeburn  5690:         } else {
                   5691:             $legacy{'rolecolors'} = 1;
1.518     albertel 5692:         }
1.948     raeburn  5693:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5694:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5695:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5696:             }
                   5697:         }
1.632     raeburn  5698:         if (keys(%legacy) > 0) {
                   5699:             my %legacyhash = &get_legacy_domconf($udom);
                   5700:             foreach my $item (keys(%legacyhash)) {
                   5701:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5702:                     if ($legacy{'login'}) { 
                   5703:                         $designhash{$item} = $legacyhash{$item};
                   5704:                     }
                   5705:                 } else {
                   5706:                     if ($legacy{'rolecolors'}) {
                   5707:                         $designhash{$item} = $legacyhash{$item};
                   5708:                     }
1.518     albertel 5709:                 }
                   5710:             }
                   5711:         }
1.632     raeburn  5712:     } else {
                   5713:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5714:     }
                   5715:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5716: 				  $cachetime);
                   5717:     return %designhash;
                   5718: }
                   5719: 
1.632     raeburn  5720: sub get_legacy_domconf {
                   5721:     my ($udom) = @_;
                   5722:     my %legacyhash;
                   5723:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5724:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5725:     if (-e $designfile) {
1.1317    raeburn  5726:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5727:             while (my $line = <$fh>) {
                   5728:                 next if ($line =~ /^\#/);
                   5729:                 chomp($line);
                   5730:                 my ($key,$val)=(split(/\=/,$line));
                   5731:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5732:             }
                   5733:             close($fh);
                   5734:         }
                   5735:     }
1.1026    raeburn  5736:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5737:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5738:     }
                   5739:     return %legacyhash;
                   5740: }
                   5741: 
1.63      www      5742: =pod
                   5743: 
1.112     bowersj2 5744: =item * &domainlogo()
1.63      www      5745: 
                   5746: Inputs: $domain (usually will be undef)
                   5747: 
                   5748: Returns: A link to a domain logo, if the domain logo exists.
                   5749: If the domain logo does not exist, a description of the domain.
                   5750: 
                   5751: =cut
1.112     bowersj2 5752: 
1.63      www      5753: ###############################################
                   5754: sub domainlogo {
1.517     raeburn  5755:     my $domain = &determinedomain(shift);
1.518     albertel 5756:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5757:     # See if there is a logo
                   5758:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5759:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5760:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5761: 	    if ($imgsrc =~ m{^/res/}) {
                   5762: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5763: 		&Apache::lonnet::repcopy($local_name);
                   5764: 	    }
                   5765: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5766:         } 
                   5767:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5768:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5769:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5770:     } else {
1.60      matthew  5771:         return '';
1.59      www      5772:     }
                   5773: }
1.63      www      5774: ##############################################
                   5775: 
                   5776: =pod
                   5777: 
1.112     bowersj2 5778: =item * &designparm()
1.63      www      5779: 
                   5780: Inputs: $which parameter; $domain (usually will be undef)
                   5781: 
                   5782: Returns: value of designparamter $which
                   5783: 
                   5784: =cut
1.112     bowersj2 5785: 
1.397     albertel 5786: 
1.400     albertel 5787: ##############################################
1.397     albertel 5788: sub designparm {
                   5789:     my ($which,$domain)=@_;
                   5790:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5791:         return $env{'environment.color.'.$which};
1.96      www      5792:     }
1.63      www      5793:     $domain=&determinedomain($domain);
1.1016    raeburn  5794:     my %domdesign;
                   5795:     unless ($domain eq 'public') {
                   5796:         %domdesign = &get_domainconf($domain);
                   5797:     }
1.520     raeburn  5798:     my $output;
1.517     raeburn  5799:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5800:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5801:     } else {
1.520     raeburn  5802:         $output = $defaultdesign{$which};
                   5803:     }
                   5804:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5805:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5806:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5807:             if ($output =~ m{^/res/}) {
                   5808:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5809:                 &Apache::lonnet::repcopy($local_name);
                   5810:             }
1.520     raeburn  5811:             $output = &lonhttpdurl($output);
                   5812:         }
1.63      www      5813:     }
1.520     raeburn  5814:     return $output;
1.63      www      5815: }
1.59      www      5816: 
1.822     bisitz   5817: ##############################################
                   5818: =pod
                   5819: 
1.832     bisitz   5820: =item * &authorspace()
                   5821: 
1.1028    raeburn  5822: Inputs: $url (usually will be undef).
1.832     bisitz   5823: 
1.1132    raeburn  5824: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5825:          directory being viewed (or for which action is being taken). 
                   5826:          If $url is provided, and begins /priv/<domain>/<uname>
                   5827:          the path will be that portion of the $context argument.
                   5828:          Otherwise the path will be for the author space of the current
                   5829:          user when the current role is author, or for that of the 
                   5830:          co-author/assistant co-author space when the current role 
                   5831:          is co-author or assistant co-author.
1.832     bisitz   5832: 
                   5833: =cut
                   5834: 
                   5835: sub authorspace {
1.1028    raeburn  5836:     my ($url) = @_;
                   5837:     if ($url ne '') {
                   5838:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5839:            return $1;
                   5840:         }
                   5841:     }
1.832     bisitz   5842:     my $caname = '';
1.1024    www      5843:     my $cadom = '';
1.1028    raeburn  5844:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5845:         ($cadom,$caname) =
1.832     bisitz   5846:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5847:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5848:         $caname = $env{'user.name'};
1.1024    www      5849:         $cadom = $env{'user.domain'};
1.832     bisitz   5850:     }
1.1028    raeburn  5851:     if (($caname ne '') && ($cadom ne '')) {
                   5852:         return "/priv/$cadom/$caname/";
                   5853:     }
                   5854:     return;
1.832     bisitz   5855: }
                   5856: 
                   5857: ##############################################
                   5858: =pod
                   5859: 
1.822     bisitz   5860: =item * &head_subbox()
                   5861: 
                   5862: Inputs: $content (contains HTML code with page functions, etc.)
                   5863: 
                   5864: Returns: HTML div with $content
                   5865:          To be included in page header
                   5866: 
                   5867: =cut
                   5868: 
                   5869: sub head_subbox {
                   5870:     my ($content)=@_;
                   5871:     my $output =
1.993     raeburn  5872:         '<div class="LC_head_subbox">'
1.822     bisitz   5873:        .$content
                   5874:        .'</div>'
                   5875: }
                   5876: 
                   5877: ##############################################
                   5878: =pod
                   5879: 
                   5880: =item * &CSTR_pageheader()
                   5881: 
1.1026    raeburn  5882: Input: (optional) filename from which breadcrumb trail is built.
                   5883:        In most cases no input as needed, as $env{'request.filename'}
                   5884:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5885: 
                   5886: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5887:          To be included on Authoring Space pages
1.822     bisitz   5888: 
                   5889: =cut
                   5890: 
                   5891: sub CSTR_pageheader {
1.1026    raeburn  5892:     my ($trailfile) = @_;
                   5893:     if ($trailfile eq '') {
                   5894:         $trailfile = $env{'request.filename'};
                   5895:     }
                   5896: 
                   5897: # this is for resources; directories have customtitle, and crumbs
                   5898: # and select recent are created in lonpubdir.pm
                   5899: 
                   5900:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5901:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5902:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5903:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5904:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5905: 
                   5906:     my $parentpath = '';
                   5907:     my $lastitem = '';
                   5908:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5909:         $parentpath = $1;
                   5910:         $lastitem = $2;
                   5911:     } else {
                   5912:         $lastitem = $thisdisfn;
                   5913:     }
1.921     bisitz   5914: 
1.1246    raeburn  5915:     my ($crsauthor,$title);
                   5916:     if (($env{'request.course.id'}) &&
                   5917:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5918:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5919:         $crsauthor = 1;
                   5920:         $title = &mt('Course Authoring Space');
                   5921:     } else {
                   5922:         $title = &mt('Authoring Space');
                   5923:     }
                   5924: 
1.1314    raeburn  5925:     my ($target,$crumbtarget) = (' target="_top"','_top'); #FIXME lonpubdir: target="_parent"
1.1313    raeburn  5926:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  5927:         $target = '';
                   5928:         $crumbtarget = '';
1.1313    raeburn  5929:     }
                   5930: 
1.921     bisitz   5931:     my $output =
1.822     bisitz   5932:          '<div>'
                   5933:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5934:         .'<b>'.$title.'</b> '
1.1314    raeburn  5935:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   5936:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   5937: 
                   5938:     if ($lastitem) {
                   5939:         $output .=
                   5940:              '<span class="LC_filename">'
                   5941:             .$lastitem
                   5942:             .'</span>';
                   5943:     }
1.1245    raeburn  5944: 
1.1246    raeburn  5945:     if ($crsauthor) {
                   5946:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5947:     } else {
                   5948:         $output .=
                   5949:              '<br />'
1.1314    raeburn  5950:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  5951:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5952:             .'</form>'
                   5953:             .&Apache::lonmenu::constspaceform();
                   5954:     }
                   5955:     $output .= '</div>';
1.921     bisitz   5956: 
                   5957:     return $output;
1.822     bisitz   5958: }
                   5959: 
1.60      matthew  5960: ###############################################
                   5961: ###############################################
                   5962: 
                   5963: =pod
                   5964: 
1.112     bowersj2 5965: =back
                   5966: 
1.549     albertel 5967: =head1 HTML Helpers
1.112     bowersj2 5968: 
                   5969: =over 4
                   5970: 
                   5971: =item * &bodytag()
1.60      matthew  5972: 
                   5973: Returns a uniform header for LON-CAPA web pages.
                   5974: 
                   5975: Inputs: 
                   5976: 
1.112     bowersj2 5977: =over 4
                   5978: 
                   5979: =item * $title, A title to be displayed on the page.
                   5980: 
                   5981: =item * $function, the current role (can be undef).
                   5982: 
                   5983: =item * $addentries, extra parameters for the <body> tag.
                   5984: 
                   5985: =item * $bodyonly, if defined, only return the <body> tag.
                   5986: 
                   5987: =item * $domain, if defined, force a given domain.
                   5988: 
                   5989: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5990:             text interface only)
1.60      matthew  5991: 
1.814     bisitz   5992: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5993:                      navigational links
1.317     albertel 5994: 
1.338     albertel 5995: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5996: 
1.460     albertel 5997: =item * $args, optional argument valid values are
                   5998:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  5999:             use_absolute     -> for external resource or syllabus, this will
                   6000:                                 contain https://<hostname> if server uses
                   6001:                                 https (as per hosts.tab), but request is for http
                   6002:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6003: 
1.1096    raeburn  6004: =item * $advtoolsref, optional argument, ref to an array containing
                   6005:             inlineremote items to be added in "Functions" menu below
                   6006:             breadcrumbs.
                   6007: 
1.1316    raeburn  6008: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6009:             course, if LON-CAPA is in LTI Provider context. Value is
                   6010:             the scope of use, i.e., launch was for access to a single, a map
                   6011:             or the entire course.
                   6012: 
                   6013: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6014:             context, this will contain the URL for the landing item in
                   6015:             the course, after launch from an LTI Consumer
                   6016: 
1.1318    raeburn  6017: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6018:             context, this will contain a reference to hash of items
                   6019:             to be included in the page header and/or inline menu.
                   6020: 
1.112     bowersj2 6021: =back
                   6022: 
1.60      matthew  6023: Returns: A uniform header for LON-CAPA web pages.  
                   6024: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6025: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6026: other decorations will be returned.
                   6027: 
                   6028: =cut
                   6029: 
1.54      www      6030: sub bodytag {
1.831     bisitz   6031:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1318    raeburn  6032:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,$ltimenu)=@_;
1.339     albertel 6033: 
1.954     raeburn  6034:     my $public;
                   6035:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6036:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6037:         $public = 1;
                   6038:     }
1.460     albertel 6039:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6040:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6041:     my $hostname = $args->{'hostname'};
1.339     albertel 6042: 
1.183     matthew  6043:     $function = &get_users_function() if (!$function);
1.339     albertel 6044:     my $img =    &designparm($function.'.img',$domain);
                   6045:     my $font =   &designparm($function.'.font',$domain);
                   6046:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6047: 
1.803     bisitz   6048:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6049: 		   'bgcolor' => $pgbg,
1.339     albertel 6050: 		   'text'    => $font,
                   6051:                    'alink'   => &designparm($function.'.alink',$domain),
                   6052: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6053: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6054:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6055: 
1.63      www      6056:  # role and realm
1.1178    raeburn  6057:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6058:     if ($realm) {
                   6059:         $realm = '/'.$realm;
                   6060:     }
1.378     raeburn  6061:     if ($role  eq 'ca') {
1.479     albertel 6062:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6063:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6064:     } 
1.55      www      6065: # realm
1.258     albertel 6066:     if ($env{'request.course.id'}) {
1.378     raeburn  6067:         if ($env{'request.role'} !~ /^cr/) {
                   6068:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6069:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6070:             if ($env{'request.role.desc'}) {
                   6071:                 $role = $env{'request.role.desc'};
                   6072:             } else {
                   6073:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6074:             }
1.1257    raeburn  6075:         } else {
                   6076:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6077:         }
1.898     raeburn  6078:         if ($env{'request.course.sec'}) {
                   6079:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   6080:         }   
1.359     albertel 6081: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  6082:     } else {
                   6083:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6084:     }
1.433     albertel 6085: 
1.359     albertel 6086:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6087: 
1.438     albertel 6088:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6089: 
1.101     www      6090: # construct main body tag
1.359     albertel 6091:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6092: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6093: 
1.1131    raeburn  6094:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6095: 
1.1130    raeburn  6096:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6097:         return $bodytag;
1.1130    raeburn  6098:     }
1.359     albertel 6099: 
1.954     raeburn  6100:     if ($public) {
1.433     albertel 6101: 	undef($role);
                   6102:     }
1.1318    raeburn  6103: 
                   6104:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   6105:         if (ref($ltimenu) eq 'HASH') {
                   6106:             unless ($ltimenu->{'role'}) {
                   6107:                 undef($role);
                   6108:             }
                   6109:             unless ($ltimenu->{'coursetitle'}) {
                   6110:                 $realm='&nbsp;';
                   6111:             }
                   6112:         }
                   6113:     }
                   6114: 
1.762     bisitz   6115:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6116:     #
                   6117:     # Extra info if you are the DC
                   6118:     my $dc_info = '';
                   6119:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   6120:                         $env{'course.'.$env{'request.course.id'}.
                   6121:                                  '.domain'}.'/'})) {
                   6122:         my $cid = $env{'request.course.id'};
1.917     raeburn  6123:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6124:         $dc_info =~ s/\s+$//;
1.359     albertel 6125:     }
                   6126: 
1.1237    raeburn  6127:     my $crstype;
                   6128:     if ($env{'request.course.id'}) {
                   6129:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   6130:     } elsif ($args->{'crstype'}) {
                   6131:         $crstype = $args->{'crstype'};
                   6132:     }
                   6133:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6134:         undef($role);
                   6135:     } else {
1.1242    raeburn  6136:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6137:     }
1.853     droeschl 6138: 
1.903     droeschl 6139:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6140: 
                   6141:         #    if ($env{'request.state'} eq 'construct') {
                   6142:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6143:         #    }
                   6144: 
1.1130    raeburn  6145:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6146:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6147: 
1.1318    raeburn  6148:         unless ($args->{'no_primary_menu'}) {
                   6149:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu);
1.359     albertel 6150: 
1.1318    raeburn  6151:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6152:                 if ($dc_info) {
                   6153:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6154:                 }
                   6155:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6156:                                <em>$realm</em> $dc_info</div>|;
                   6157:                 return $bodytag;
                   6158:             }
1.894     droeschl 6159: 
1.1318    raeburn  6160:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6161:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6162:             }
1.916     droeschl 6163: 
1.1318    raeburn  6164:             $bodytag .= $right;
1.852     droeschl 6165: 
1.1318    raeburn  6166:             if ($dc_info) {
                   6167:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6168:             }
                   6169:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6170:         }
1.916     droeschl 6171: 
1.1169    raeburn  6172:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6173:         if ($args->{'no_secondary_menu'}) {
                   6174:             return $bodytag;
                   6175:         }
1.1169    raeburn  6176:         #don't show menus for public users
1.954     raeburn  6177:         if (!$public){
1.1318    raeburn  6178:             unless ($args->{'no_inline_menu'}) {
                   6179:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6180:                                                             $args->{'no_primary_menu'});
                   6181:             }
1.903     droeschl 6182:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6183:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6184:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6185:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6186:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6187:             } elsif ($forcereg) {
                   6188:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6189:                                                             $args->{'group'},
1.1274    raeburn  6190:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6191:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6192:             } else {
                   6193:                 $bodytag .= 
                   6194:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6195:                                                         $forcereg,$args->{'group'},
                   6196:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6197:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6198:             }
1.903     droeschl 6199:         }else{
                   6200:             # this is to seperate menu from content when there's no secondary
                   6201:             # menu. Especially needed for public accessible ressources.
                   6202:             $bodytag .= '<hr style="clear:both" />';
                   6203:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6204:         }
1.903     droeschl 6205: 
1.235     raeburn  6206:         return $bodytag;
1.182     matthew  6207: }
                   6208: 
1.917     raeburn  6209: sub dc_courseid_toggle {
                   6210:     my ($dc_info) = @_;
1.980     raeburn  6211:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6212:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6213:            &mt('(More ...)').'</a></span>'.
                   6214:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6215: }
                   6216: 
1.330     albertel 6217: sub make_attr_string {
                   6218:     my ($register,$attr_ref) = @_;
                   6219: 
                   6220:     if ($attr_ref && !ref($attr_ref)) {
                   6221: 	die("addentries Must be a hash ref ".
                   6222: 	    join(':',caller(1))." ".
                   6223: 	    join(':',caller(0))." ");
                   6224:     }
                   6225: 
                   6226:     if ($register) {
1.339     albertel 6227: 	my ($on_load,$on_unload);
                   6228: 	foreach my $key (keys(%{$attr_ref})) {
                   6229: 	    if      (lc($key) eq 'onload') {
                   6230: 		$on_load.=$attr_ref->{$key}.';';
                   6231: 		delete($attr_ref->{$key});
                   6232: 
                   6233: 	    } elsif (lc($key) eq 'onunload') {
                   6234: 		$on_unload.=$attr_ref->{$key}.';';
                   6235: 		delete($attr_ref->{$key});
                   6236: 	    }
                   6237: 	}
1.953     droeschl 6238: 	$attr_ref->{'onload'}  = $on_load;
                   6239: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6240:     }
1.339     albertel 6241: 
1.330     albertel 6242:     my $attr_string;
1.1159    raeburn  6243:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6244: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6245:     }
                   6246:     return $attr_string;
                   6247: }
                   6248: 
                   6249: 
1.182     matthew  6250: ###############################################
1.251     albertel 6251: ###############################################
                   6252: 
                   6253: =pod
                   6254: 
                   6255: =item * &endbodytag()
                   6256: 
                   6257: Returns a uniform footer for LON-CAPA web pages.
                   6258: 
1.635     raeburn  6259: Inputs: 1 - optional reference to an args hash
                   6260: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6261: a 'Continue' link is not displayed if the page contains an
                   6262: internal redirect in the <head></head> section,
                   6263: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6264: 
                   6265: =cut
                   6266: 
                   6267: sub endbodytag {
1.635     raeburn  6268:     my ($args) = @_;
1.1080    raeburn  6269:     my $endbodytag;
                   6270:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6271:         $endbodytag='</body>';
                   6272:     }
1.315     albertel 6273:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6274:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6275: 	    $endbodytag=
                   6276: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6277: 	        &mt('Continue').'</a>'.
                   6278: 	        $endbodytag;
                   6279:         }
1.315     albertel 6280:     }
1.251     albertel 6281:     return $endbodytag;
                   6282: }
                   6283: 
1.352     albertel 6284: =pod
                   6285: 
                   6286: =item * &standard_css()
                   6287: 
                   6288: Returns a style sheet
                   6289: 
                   6290: Inputs: (all optional)
                   6291:             domain         -> force to color decorate a page for a specific
                   6292:                                domain
                   6293:             function       -> force usage of a specific rolish color scheme
                   6294:             bgcolor        -> override the default page bgcolor
                   6295: 
                   6296: =cut
                   6297: 
1.343     albertel 6298: sub standard_css {
1.345     albertel 6299:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6300:     $function  = &get_users_function() if (!$function);
                   6301:     my $img    = &designparm($function.'.img',   $domain);
                   6302:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6303:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6304:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6305: #second colour for later usage
1.345     albertel 6306:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6307:     my $pgbg_or_bgcolor =
                   6308: 	         $bgcolor ||
1.352     albertel 6309: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6310:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6311:     my $alink  = &designparm($function.'.alink', $domain);
                   6312:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6313:     my $link   = &designparm($function.'.link',  $domain);
                   6314: 
1.602     albertel 6315:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6316:     my $mono                 = 'monospace';
1.850     bisitz   6317:     my $data_table_head      = $sidebg;
                   6318:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6319:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6320:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6321:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6322:     my $mail_new             = '#FFBB77';
                   6323:     my $mail_new_hover       = '#DD9955';
                   6324:     my $mail_read            = '#BBBB77';
                   6325:     my $mail_read_hover      = '#999944';
                   6326:     my $mail_replied         = '#AAAA88';
                   6327:     my $mail_replied_hover   = '#888855';
                   6328:     my $mail_other           = '#99BBBB';
                   6329:     my $mail_other_hover     = '#669999';
1.391     albertel 6330:     my $table_header         = '#DDDDDD';
1.489     raeburn  6331:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6332:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6333:     my $button_hover         = '#BF2317';
1.392     albertel 6334: 
1.608     albertel 6335:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6336:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6337:                                              : '0 3px 0 4px';
1.448     albertel 6338: 
1.523     albertel 6339: 
1.343     albertel 6340:     return <<END;
1.947     droeschl 6341: 
                   6342: /* needed for iframe to allow 100% height in FF */
                   6343: body, html { 
                   6344:     margin: 0;
                   6345:     padding: 0 0.5%;
                   6346:     height: 99%; /* to avoid scrollbars */
                   6347: }
                   6348: 
1.795     www      6349: body {
1.911     bisitz   6350:   font-family: $sans;
                   6351:   line-height:130%;
                   6352:   font-size:0.83em;
                   6353:   color:$font;
1.795     www      6354: }
                   6355: 
1.959     onken    6356: a:focus,
                   6357: a:focus img {
1.795     www      6358:   color: red;
                   6359: }
1.698     harmsja  6360: 
1.911     bisitz   6361: form, .inline {
                   6362:   display: inline;
1.795     www      6363: }
1.721     harmsja  6364: 
1.795     www      6365: .LC_right {
1.911     bisitz   6366:   text-align:right;
1.795     www      6367: }
                   6368: 
                   6369: .LC_middle {
1.911     bisitz   6370:   vertical-align:middle;
1.795     www      6371: }
1.721     harmsja  6372: 
1.1130    raeburn  6373: .LC_floatleft {
                   6374:   float: left;
                   6375: }
                   6376: 
                   6377: .LC_floatright {
                   6378:   float: right;
                   6379: }
                   6380: 
1.911     bisitz   6381: .LC_400Box {
                   6382:   width:400px;
                   6383: }
1.721     harmsja  6384: 
1.947     droeschl 6385: .LC_iframecontainer {
                   6386:     width: 98%;
                   6387:     margin: 0;
                   6388:     position: fixed;
                   6389:     top: 8.5em;
                   6390:     bottom: 0;
                   6391: }
                   6392: 
                   6393: .LC_iframecontainer iframe{
                   6394:     border: none;
                   6395:     width: 100%;
                   6396:     height: 100%;
                   6397: }
                   6398: 
1.778     bisitz   6399: .LC_filename {
                   6400:   font-family: $mono;
                   6401:   white-space:pre;
1.921     bisitz   6402:   font-size: 120%;
1.778     bisitz   6403: }
                   6404: 
                   6405: .LC_fileicon {
                   6406:   border: none;
                   6407:   height: 1.3em;
                   6408:   vertical-align: text-bottom;
                   6409:   margin-right: 0.3em;
                   6410:   text-decoration:none;
                   6411: }
                   6412: 
1.1008    www      6413: .LC_setting {
                   6414:   text-decoration:underline;
                   6415: }
                   6416: 
1.350     albertel 6417: .LC_error {
                   6418:   color: red;
                   6419: }
1.795     www      6420: 
1.1097    bisitz   6421: .LC_warning {
                   6422:   color: darkorange;
                   6423: }
                   6424: 
1.457     albertel 6425: .LC_diff_removed {
1.733     bisitz   6426:   color: red;
1.394     albertel 6427: }
1.532     albertel 6428: 
                   6429: .LC_info,
1.457     albertel 6430: .LC_success,
                   6431: .LC_diff_added {
1.350     albertel 6432:   color: green;
                   6433: }
1.795     www      6434: 
1.802     bisitz   6435: div.LC_confirm_box {
                   6436:   background-color: #FAFAFA;
                   6437:   border: 1px solid $lg_border_color;
                   6438:   margin-right: 0;
                   6439:   padding: 5px;
                   6440: }
                   6441: 
                   6442: div.LC_confirm_box .LC_error img,
                   6443: div.LC_confirm_box .LC_success img {
                   6444:   vertical-align: middle;
                   6445: }
                   6446: 
1.1242    raeburn  6447: .LC_maxwidth {
                   6448:   max-width: 100%;
                   6449:   height: auto;
                   6450: }
                   6451: 
1.1243    raeburn  6452: .LC_textsize_mobile {
                   6453:   \@media only screen and (max-device-width: 480px) {
                   6454:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6455:   }
                   6456: }
                   6457: 
1.440     albertel 6458: .LC_icon {
1.771     droeschl 6459:   border: none;
1.790     droeschl 6460:   vertical-align: middle;
1.771     droeschl 6461: }
                   6462: 
1.543     albertel 6463: .LC_docs_spacer {
                   6464:   width: 25px;
                   6465:   height: 1px;
1.771     droeschl 6466:   border: none;
1.543     albertel 6467: }
1.346     albertel 6468: 
1.532     albertel 6469: .LC_internal_info {
1.735     bisitz   6470:   color: #999999;
1.532     albertel 6471: }
                   6472: 
1.794     www      6473: .LC_discussion {
1.1050    www      6474:   background: $data_table_dark;
1.911     bisitz   6475:   border: 1px solid black;
                   6476:   margin: 2px;
1.794     www      6477: }
                   6478: 
                   6479: .LC_disc_action_left {
1.1050    www      6480:   background: $sidebg;
1.911     bisitz   6481:   text-align: left;
1.1050    www      6482:   padding: 4px;
                   6483:   margin: 2px;
1.794     www      6484: }
                   6485: 
                   6486: .LC_disc_action_right {
1.1050    www      6487:   background: $sidebg;
1.911     bisitz   6488:   text-align: right;
1.1050    www      6489:   padding: 4px;
                   6490:   margin: 2px;
1.794     www      6491: }
                   6492: 
                   6493: .LC_disc_new_item {
1.911     bisitz   6494:   background: white;
                   6495:   border: 2px solid red;
1.1050    www      6496:   margin: 4px;
                   6497:   padding: 4px;
1.794     www      6498: }
                   6499: 
                   6500: .LC_disc_old_item {
1.911     bisitz   6501:   background: white;
1.1050    www      6502:   margin: 4px;
                   6503:   padding: 4px;
1.794     www      6504: }
                   6505: 
1.458     albertel 6506: table.LC_pastsubmission {
                   6507:   border: 1px solid black;
                   6508:   margin: 2px;
                   6509: }
                   6510: 
1.924     bisitz   6511: table#LC_menubuttons {
1.345     albertel 6512:   width: 100%;
                   6513:   background: $pgbg;
1.392     albertel 6514:   border: 2px;
1.402     albertel 6515:   border-collapse: separate;
1.803     bisitz   6516:   padding: 0;
1.345     albertel 6517: }
1.392     albertel 6518: 
1.801     tempelho 6519: table#LC_title_bar a {
                   6520:   color: $fontmenu;
                   6521: }
1.836     bisitz   6522: 
1.807     droeschl 6523: table#LC_title_bar {
1.819     tempelho 6524:   clear: both;
1.836     bisitz   6525:   display: none;
1.807     droeschl 6526: }
                   6527: 
1.795     www      6528: table#LC_title_bar,
1.933     droeschl 6529: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6530: table#LC_title_bar.LC_with_remote {
1.359     albertel 6531:   width: 100%;
1.392     albertel 6532:   border-color: $pgbg;
                   6533:   border-style: solid;
                   6534:   border-width: $border;
1.379     albertel 6535:   background: $pgbg;
1.801     tempelho 6536:   color: $fontmenu;
1.392     albertel 6537:   border-collapse: collapse;
1.803     bisitz   6538:   padding: 0;
1.819     tempelho 6539:   margin: 0;
1.359     albertel 6540: }
1.795     www      6541: 
1.933     droeschl 6542: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6543:     margin: 0;
                   6544:     padding: 0;
1.933     droeschl 6545:     position: relative;
                   6546:     list-style: none;
1.913     droeschl 6547: }
1.933     droeschl 6548: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6549:     display: inline;
                   6550: }
1.933     droeschl 6551: 
                   6552: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6553:     padding: 0;
1.933     droeschl 6554:     margin: 0;
                   6555:     float: left;
1.913     droeschl 6556: }
1.933     droeschl 6557: .LC_breadcrumb_tools_tools {
                   6558:     padding: 0;
                   6559:     margin: 0;
1.913     droeschl 6560:     float: right;
                   6561: }
                   6562: 
1.1240    raeburn  6563: .LC_placement_prog {
                   6564:     padding-right: 20px;
                   6565:     font-weight: bold;
                   6566:     font-size: 90%;
                   6567: }
                   6568: 
1.359     albertel 6569: table#LC_title_bar td {
                   6570:   background: $tabbg;
                   6571: }
1.795     www      6572: 
1.911     bisitz   6573: table#LC_menubuttons img {
1.803     bisitz   6574:   border: none;
1.346     albertel 6575: }
1.795     www      6576: 
1.842     droeschl 6577: .LC_breadcrumbs_component {
1.911     bisitz   6578:   float: right;
                   6579:   margin: 0 1em;
1.357     albertel 6580: }
1.842     droeschl 6581: .LC_breadcrumbs_component img {
1.911     bisitz   6582:   vertical-align: middle;
1.777     tempelho 6583: }
1.795     www      6584: 
1.1243    raeburn  6585: .LC_breadcrumbs_hoverable {
                   6586:   background: $sidebg;
                   6587: }
                   6588: 
1.383     albertel 6589: td.LC_table_cell_checkbox {
                   6590:   text-align: center;
                   6591: }
1.795     www      6592: 
                   6593: .LC_fontsize_small {
1.911     bisitz   6594:   font-size: 70%;
1.705     tempelho 6595: }
                   6596: 
1.844     bisitz   6597: #LC_breadcrumbs {
1.911     bisitz   6598:   clear:both;
                   6599:   background: $sidebg;
                   6600:   border-bottom: 1px solid $lg_border_color;
                   6601:   line-height: 2.5em;
1.933     droeschl 6602:   overflow: hidden;
1.911     bisitz   6603:   margin: 0;
                   6604:   padding: 0;
1.995     raeburn  6605:   text-align: left;
1.819     tempelho 6606: }
1.862     bisitz   6607: 
1.1098    bisitz   6608: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6609:   clear:both;
                   6610:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6611:   border: 1px solid $sidebg;
1.1098    bisitz   6612:   margin: 0 0 10px 0;
1.966     bisitz   6613:   padding: 3px;
1.995     raeburn  6614:   text-align: left;
1.822     bisitz   6615: }
                   6616: 
1.795     www      6617: .LC_fontsize_medium {
1.911     bisitz   6618:   font-size: 85%;
1.705     tempelho 6619: }
                   6620: 
1.795     www      6621: .LC_fontsize_large {
1.911     bisitz   6622:   font-size: 120%;
1.705     tempelho 6623: }
                   6624: 
1.346     albertel 6625: .LC_menubuttons_inline_text {
                   6626:   color: $font;
1.698     harmsja  6627:   font-size: 90%;
1.701     harmsja  6628:   padding-left:3px;
1.346     albertel 6629: }
                   6630: 
1.934     droeschl 6631: .LC_menubuttons_inline_text img{
                   6632:   vertical-align: middle;
                   6633: }
                   6634: 
1.1051    www      6635: li.LC_menubuttons_inline_text img {
1.951     onken    6636:   cursor:pointer;
1.1002    droeschl 6637:   text-decoration: none;
1.951     onken    6638: }
                   6639: 
1.526     www      6640: .LC_menubuttons_link {
                   6641:   text-decoration: none;
                   6642: }
1.795     www      6643: 
1.522     albertel 6644: .LC_menubuttons_category {
1.521     www      6645:   color: $font;
1.526     www      6646:   background: $pgbg;
1.521     www      6647:   font-size: larger;
                   6648:   font-weight: bold;
                   6649: }
                   6650: 
1.346     albertel 6651: td.LC_menubuttons_text {
1.911     bisitz   6652:   color: $font;
1.346     albertel 6653: }
1.706     harmsja  6654: 
1.346     albertel 6655: .LC_current_location {
                   6656:   background: $tabbg;
                   6657: }
1.795     www      6658: 
1.1286    raeburn  6659: td.LC_zero_height {
                   6660:   line-height: 0; 
                   6661:   cellpadding: 0;
                   6662: }
                   6663: 
1.938     bisitz   6664: table.LC_data_table {
1.347     albertel 6665:   border: 1px solid #000000;
1.402     albertel 6666:   border-collapse: separate;
1.426     albertel 6667:   border-spacing: 1px;
1.610     albertel 6668:   background: $pgbg;
1.347     albertel 6669: }
1.795     www      6670: 
1.422     albertel 6671: .LC_data_table_dense {
                   6672:   font-size: small;
                   6673: }
1.795     www      6674: 
1.507     raeburn  6675: table.LC_nested_outer {
                   6676:   border: 1px solid #000000;
1.589     raeburn  6677:   border-collapse: collapse;
1.803     bisitz   6678:   border-spacing: 0;
1.507     raeburn  6679:   width: 100%;
                   6680: }
1.795     www      6681: 
1.879     raeburn  6682: table.LC_innerpickbox,
1.507     raeburn  6683: table.LC_nested {
1.803     bisitz   6684:   border: none;
1.589     raeburn  6685:   border-collapse: collapse;
1.803     bisitz   6686:   border-spacing: 0;
1.507     raeburn  6687:   width: 100%;
                   6688: }
1.795     www      6689: 
1.911     bisitz   6690: table.LC_data_table tr th,
                   6691: table.LC_calendar tr th,
1.879     raeburn  6692: table.LC_prior_tries tr th,
                   6693: table.LC_innerpickbox tr th {
1.349     albertel 6694:   font-weight: bold;
                   6695:   background-color: $data_table_head;
1.801     tempelho 6696:   color:$fontmenu;
1.701     harmsja  6697:   font-size:90%;
1.347     albertel 6698: }
1.795     www      6699: 
1.879     raeburn  6700: table.LC_innerpickbox tr th,
                   6701: table.LC_innerpickbox tr td {
                   6702:   vertical-align: top;
                   6703: }
                   6704: 
1.711     raeburn  6705: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6706:   background-color: #CCCCCC;
1.711     raeburn  6707:   font-weight: bold;
                   6708:   text-align: left;
                   6709: }
1.795     www      6710: 
1.912     bisitz   6711: table.LC_data_table tr.LC_odd_row > td {
                   6712:   background-color: $data_table_light;
                   6713:   padding: 2px;
                   6714:   vertical-align: top;
                   6715: }
                   6716: 
1.809     bisitz   6717: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6718:   background-color: $data_table_light;
1.912     bisitz   6719:   vertical-align: top;
                   6720: }
                   6721: 
                   6722: table.LC_data_table tr.LC_even_row > td {
                   6723:   background-color: $data_table_dark;
1.425     albertel 6724:   padding: 2px;
1.900     bisitz   6725:   vertical-align: top;
1.347     albertel 6726: }
1.795     www      6727: 
1.809     bisitz   6728: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6729:   background-color: $data_table_dark;
1.900     bisitz   6730:   vertical-align: top;
1.347     albertel 6731: }
1.795     www      6732: 
1.425     albertel 6733: table.LC_data_table tr.LC_data_table_highlight td {
                   6734:   background-color: $data_table_darker;
                   6735: }
1.795     www      6736: 
1.639     raeburn  6737: table.LC_data_table tr td.LC_leftcol_header {
                   6738:   background-color: $data_table_head;
                   6739:   font-weight: bold;
                   6740: }
1.795     www      6741: 
1.451     albertel 6742: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6743: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6744:   font-weight: bold;
                   6745:   font-style: italic;
                   6746:   text-align: center;
                   6747:   padding: 8px;
1.347     albertel 6748: }
1.795     www      6749: 
1.1114    raeburn  6750: table.LC_data_table tr.LC_empty_row td,
                   6751: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6752:   background-color: $sidebg;
                   6753: }
                   6754: 
                   6755: table.LC_nested tr.LC_empty_row td {
                   6756:   background-color: #FFFFFF;
                   6757: }
                   6758: 
1.890     droeschl 6759: table.LC_caption {
                   6760: }
                   6761: 
1.507     raeburn  6762: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6763:   padding: 4ex
                   6764: }
1.795     www      6765: 
1.507     raeburn  6766: table.LC_nested_outer tr th {
                   6767:   font-weight: bold;
1.801     tempelho 6768:   color:$fontmenu;
1.507     raeburn  6769:   background-color: $data_table_head;
1.701     harmsja  6770:   font-size: small;
1.507     raeburn  6771:   border-bottom: 1px solid #000000;
                   6772: }
1.795     www      6773: 
1.507     raeburn  6774: table.LC_nested_outer tr td.LC_subheader {
                   6775:   background-color: $data_table_head;
                   6776:   font-weight: bold;
                   6777:   font-size: small;
                   6778:   border-bottom: 1px solid #000000;
                   6779:   text-align: right;
1.451     albertel 6780: }
1.795     www      6781: 
1.507     raeburn  6782: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6783:   background-color: #CCCCCC;
1.451     albertel 6784:   font-weight: bold;
                   6785:   font-size: small;
1.507     raeburn  6786:   text-align: center;
                   6787: }
1.795     www      6788: 
1.589     raeburn  6789: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6790: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6791:   text-align: left;
1.451     albertel 6792: }
1.795     www      6793: 
1.507     raeburn  6794: table.LC_nested td {
1.735     bisitz   6795:   background-color: #FFFFFF;
1.451     albertel 6796:   font-size: small;
1.507     raeburn  6797: }
1.795     www      6798: 
1.507     raeburn  6799: table.LC_nested_outer tr th.LC_right_item,
                   6800: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6801: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6802: table.LC_nested tr td.LC_right_item {
1.451     albertel 6803:   text-align: right;
                   6804: }
                   6805: 
1.507     raeburn  6806: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6807:   background-color: #EEEEEE;
1.451     albertel 6808: }
                   6809: 
1.473     raeburn  6810: table.LC_createuser {
                   6811: }
                   6812: 
                   6813: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6814:   font-size: small;
1.473     raeburn  6815: }
                   6816: 
                   6817: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6818:   background-color: #CCCCCC;
1.473     raeburn  6819:   font-weight: bold;
                   6820:   text-align: center;
                   6821: }
                   6822: 
1.349     albertel 6823: table.LC_calendar {
                   6824:   border: 1px solid #000000;
                   6825:   border-collapse: collapse;
1.917     raeburn  6826:   width: 98%;
1.349     albertel 6827: }
1.795     www      6828: 
1.349     albertel 6829: table.LC_calendar_pickdate {
                   6830:   font-size: xx-small;
                   6831: }
1.795     www      6832: 
1.349     albertel 6833: table.LC_calendar tr td {
                   6834:   border: 1px solid #000000;
                   6835:   vertical-align: top;
1.917     raeburn  6836:   width: 14%;
1.349     albertel 6837: }
1.795     www      6838: 
1.349     albertel 6839: table.LC_calendar tr td.LC_calendar_day_empty {
                   6840:   background-color: $data_table_dark;
                   6841: }
1.795     www      6842: 
1.779     bisitz   6843: table.LC_calendar tr td.LC_calendar_day_current {
                   6844:   background-color: $data_table_highlight;
1.777     tempelho 6845: }
1.795     www      6846: 
1.938     bisitz   6847: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6848:   background-color: $mail_new;
                   6849: }
1.795     www      6850: 
1.938     bisitz   6851: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6852:   background-color: $mail_new_hover;
                   6853: }
1.795     www      6854: 
1.938     bisitz   6855: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6856:   background-color: $mail_read;
                   6857: }
1.795     www      6858: 
1.938     bisitz   6859: /*
                   6860: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6861:   background-color: $mail_read_hover;
                   6862: }
1.938     bisitz   6863: */
1.795     www      6864: 
1.938     bisitz   6865: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6866:   background-color: $mail_replied;
                   6867: }
1.795     www      6868: 
1.938     bisitz   6869: /*
                   6870: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6871:   background-color: $mail_replied_hover;
                   6872: }
1.938     bisitz   6873: */
1.795     www      6874: 
1.938     bisitz   6875: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6876:   background-color: $mail_other;
                   6877: }
1.795     www      6878: 
1.938     bisitz   6879: /*
                   6880: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6881:   background-color: $mail_other_hover;
                   6882: }
1.938     bisitz   6883: */
1.494     raeburn  6884: 
1.777     tempelho 6885: table.LC_data_table tr > td.LC_browser_file,
                   6886: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6887:   background: #AAEE77;
1.389     albertel 6888: }
1.795     www      6889: 
1.777     tempelho 6890: table.LC_data_table tr > td.LC_browser_file_locked,
                   6891: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6892:   background: #FFAA99;
1.387     albertel 6893: }
1.795     www      6894: 
1.777     tempelho 6895: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6896:   background: #888888;
1.779     bisitz   6897: }
1.795     www      6898: 
1.777     tempelho 6899: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6900: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6901:   background: #F8F866;
1.777     tempelho 6902: }
1.795     www      6903: 
1.696     bisitz   6904: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6905:   background: #E0E8FF;
1.387     albertel 6906: }
1.696     bisitz   6907: 
1.707     bisitz   6908: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6909:   /* background: #77FF77; */
1.707     bisitz   6910: }
1.795     www      6911: 
1.707     bisitz   6912: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6913:   border-right: 8px solid #FFFF77;
1.707     bisitz   6914: }
1.795     www      6915: 
1.707     bisitz   6916: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6917:   border-right: 8px solid #FFAA77;
1.707     bisitz   6918: }
1.795     www      6919: 
1.707     bisitz   6920: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6921:   border-right: 8px solid #FF7777;
1.707     bisitz   6922: }
1.795     www      6923: 
1.707     bisitz   6924: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6925:   border-right: 8px solid #AAFF77;
1.707     bisitz   6926: }
1.795     www      6927: 
1.707     bisitz   6928: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6929:   border-right: 8px solid #11CC55;
1.707     bisitz   6930: }
                   6931: 
1.388     albertel 6932: span.LC_current_location {
1.701     harmsja  6933:   font-size:larger;
1.388     albertel 6934:   background: $pgbg;
                   6935: }
1.387     albertel 6936: 
1.1029    www      6937: span.LC_current_nav_location {
                   6938:   font-weight:bold;
                   6939:   background: $sidebg;
                   6940: }
                   6941: 
1.395     albertel 6942: span.LC_parm_menu_item {
                   6943:   font-size: larger;
                   6944: }
1.795     www      6945: 
1.395     albertel 6946: span.LC_parm_scope_all {
                   6947:   color: red;
                   6948: }
1.795     www      6949: 
1.395     albertel 6950: span.LC_parm_scope_folder {
                   6951:   color: green;
                   6952: }
1.795     www      6953: 
1.395     albertel 6954: span.LC_parm_scope_resource {
                   6955:   color: orange;
                   6956: }
1.795     www      6957: 
1.395     albertel 6958: span.LC_parm_part {
                   6959:   color: blue;
                   6960: }
1.795     www      6961: 
1.911     bisitz   6962: span.LC_parm_folder,
                   6963: span.LC_parm_symb {
1.395     albertel 6964:   font-size: x-small;
                   6965:   font-family: $mono;
                   6966:   color: #AAAAAA;
                   6967: }
                   6968: 
1.977     bisitz   6969: ul.LC_parm_parmlist li {
                   6970:   display: inline-block;
                   6971:   padding: 0.3em 0.8em;
                   6972:   vertical-align: top;
                   6973:   width: 150px;
                   6974:   border-top:1px solid $lg_border_color;
                   6975: }
                   6976: 
1.795     www      6977: td.LC_parm_overview_level_menu,
                   6978: td.LC_parm_overview_map_menu,
                   6979: td.LC_parm_overview_parm_selectors,
                   6980: td.LC_parm_overview_restrictions  {
1.396     albertel 6981:   border: 1px solid black;
                   6982:   border-collapse: collapse;
                   6983: }
1.795     www      6984: 
1.1285    raeburn  6985: span.LC_parm_recursive,
                   6986: td.LC_parm_recursive {
                   6987:   font-weight: bold;
                   6988:   font-size: smaller;
                   6989: }
                   6990: 
1.396     albertel 6991: table.LC_parm_overview_restrictions td {
                   6992:   border-width: 1px 4px 1px 4px;
                   6993:   border-style: solid;
                   6994:   border-color: $pgbg;
                   6995:   text-align: center;
                   6996: }
1.795     www      6997: 
1.396     albertel 6998: table.LC_parm_overview_restrictions th {
                   6999:   background: $tabbg;
                   7000:   border-width: 1px 4px 1px 4px;
                   7001:   border-style: solid;
                   7002:   border-color: $pgbg;
                   7003: }
1.795     www      7004: 
1.398     albertel 7005: table#LC_helpmenu {
1.803     bisitz   7006:   border: none;
1.398     albertel 7007:   height: 55px;
1.803     bisitz   7008:   border-spacing: 0;
1.398     albertel 7009: }
                   7010: 
                   7011: table#LC_helpmenu fieldset legend {
                   7012:   font-size: larger;
                   7013: }
1.795     www      7014: 
1.397     albertel 7015: table#LC_helpmenu_links {
                   7016:   width: 100%;
                   7017:   border: 1px solid black;
                   7018:   background: $pgbg;
1.803     bisitz   7019:   padding: 0;
1.397     albertel 7020:   border-spacing: 1px;
                   7021: }
1.795     www      7022: 
1.397     albertel 7023: table#LC_helpmenu_links tr td {
                   7024:   padding: 1px;
                   7025:   background: $tabbg;
1.399     albertel 7026:   text-align: center;
                   7027:   font-weight: bold;
1.397     albertel 7028: }
1.396     albertel 7029: 
1.795     www      7030: table#LC_helpmenu_links a:link,
                   7031: table#LC_helpmenu_links a:visited,
1.397     albertel 7032: table#LC_helpmenu_links a:active {
                   7033:   text-decoration: none;
                   7034:   color: $font;
                   7035: }
1.795     www      7036: 
1.397     albertel 7037: table#LC_helpmenu_links a:hover {
                   7038:   text-decoration: underline;
                   7039:   color: $vlink;
                   7040: }
1.396     albertel 7041: 
1.417     albertel 7042: .LC_chrt_popup_exists {
                   7043:   border: 1px solid #339933;
                   7044:   margin: -1px;
                   7045: }
1.795     www      7046: 
1.417     albertel 7047: .LC_chrt_popup_up {
                   7048:   border: 1px solid yellow;
                   7049:   margin: -1px;
                   7050: }
1.795     www      7051: 
1.417     albertel 7052: .LC_chrt_popup {
                   7053:   border: 1px solid #8888FF;
                   7054:   background: #CCCCFF;
                   7055: }
1.795     www      7056: 
1.421     albertel 7057: table.LC_pick_box {
                   7058:   border-collapse: separate;
                   7059:   background: white;
                   7060:   border: 1px solid black;
                   7061:   border-spacing: 1px;
                   7062: }
1.795     www      7063: 
1.421     albertel 7064: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7065:   background: $sidebg;
1.421     albertel 7066:   font-weight: bold;
1.900     bisitz   7067:   text-align: left;
1.740     bisitz   7068:   vertical-align: top;
1.421     albertel 7069:   width: 184px;
                   7070:   padding: 8px;
                   7071: }
1.795     www      7072: 
1.579     raeburn  7073: table.LC_pick_box td.LC_pick_box_value {
                   7074:   text-align: left;
                   7075:   padding: 8px;
                   7076: }
1.795     www      7077: 
1.579     raeburn  7078: table.LC_pick_box td.LC_pick_box_select {
                   7079:   text-align: left;
                   7080:   padding: 8px;
                   7081: }
1.795     www      7082: 
1.424     albertel 7083: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7084:   padding: 0;
1.421     albertel 7085:   height: 1px;
                   7086:   background: black;
                   7087: }
1.795     www      7088: 
1.421     albertel 7089: table.LC_pick_box td.LC_pick_box_submit {
                   7090:   text-align: right;
                   7091: }
1.795     www      7092: 
1.579     raeburn  7093: table.LC_pick_box td.LC_evenrow_value {
                   7094:   text-align: left;
                   7095:   padding: 8px;
                   7096:   background-color: $data_table_light;
                   7097: }
1.795     www      7098: 
1.579     raeburn  7099: table.LC_pick_box td.LC_oddrow_value {
                   7100:   text-align: left;
                   7101:   padding: 8px;
                   7102:   background-color: $data_table_light;
                   7103: }
1.795     www      7104: 
1.579     raeburn  7105: span.LC_helpform_receipt_cat {
                   7106:   font-weight: bold;
                   7107: }
1.795     www      7108: 
1.424     albertel 7109: table.LC_group_priv_box {
                   7110:   background: white;
                   7111:   border: 1px solid black;
                   7112:   border-spacing: 1px;
                   7113: }
1.795     www      7114: 
1.424     albertel 7115: table.LC_group_priv_box td.LC_pick_box_title {
                   7116:   background: $tabbg;
                   7117:   font-weight: bold;
                   7118:   text-align: right;
                   7119:   width: 184px;
                   7120: }
1.795     www      7121: 
1.424     albertel 7122: table.LC_group_priv_box td.LC_groups_fixed {
                   7123:   background: $data_table_light;
                   7124:   text-align: center;
                   7125: }
1.795     www      7126: 
1.424     albertel 7127: table.LC_group_priv_box td.LC_groups_optional {
                   7128:   background: $data_table_dark;
                   7129:   text-align: center;
                   7130: }
1.795     www      7131: 
1.424     albertel 7132: table.LC_group_priv_box td.LC_groups_functionality {
                   7133:   background: $data_table_darker;
                   7134:   text-align: center;
                   7135:   font-weight: bold;
                   7136: }
1.795     www      7137: 
1.424     albertel 7138: table.LC_group_priv td {
                   7139:   text-align: left;
1.803     bisitz   7140:   padding: 0;
1.424     albertel 7141: }
                   7142: 
                   7143: .LC_navbuttons {
                   7144:   margin: 2ex 0ex 2ex 0ex;
                   7145: }
1.795     www      7146: 
1.423     albertel 7147: .LC_topic_bar {
                   7148:   font-weight: bold;
                   7149:   background: $tabbg;
1.918     wenzelju 7150:   margin: 1em 0em 1em 2em;
1.805     bisitz   7151:   padding: 3px;
1.918     wenzelju 7152:   font-size: 1.2em;
1.423     albertel 7153: }
1.795     www      7154: 
1.423     albertel 7155: .LC_topic_bar span {
1.918     wenzelju 7156:   left: 0.5em;
                   7157:   position: absolute;
1.423     albertel 7158:   vertical-align: middle;
1.918     wenzelju 7159:   font-size: 1.2em;
1.423     albertel 7160: }
1.795     www      7161: 
1.423     albertel 7162: table.LC_course_group_status {
                   7163:   margin: 20px;
                   7164: }
1.795     www      7165: 
1.423     albertel 7166: table.LC_status_selector td {
                   7167:   vertical-align: top;
                   7168:   text-align: center;
1.424     albertel 7169:   padding: 4px;
                   7170: }
1.795     www      7171: 
1.599     albertel 7172: div.LC_feedback_link {
1.616     albertel 7173:   clear: both;
1.829     kalberla 7174:   background: $sidebg;
1.779     bisitz   7175:   width: 100%;
1.829     kalberla 7176:   padding-bottom: 10px;
                   7177:   border: 1px $tabbg solid;
1.833     kalberla 7178:   height: 22px;
                   7179:   line-height: 22px;
                   7180:   padding-top: 5px;
                   7181: }
                   7182: 
                   7183: div.LC_feedback_link img {
                   7184:   height: 22px;
1.867     kalberla 7185:   vertical-align:middle;
1.829     kalberla 7186: }
                   7187: 
1.911     bisitz   7188: div.LC_feedback_link a {
1.829     kalberla 7189:   text-decoration: none;
1.489     raeburn  7190: }
1.795     www      7191: 
1.867     kalberla 7192: div.LC_comblock {
1.911     bisitz   7193:   display:inline;
1.867     kalberla 7194:   color:$font;
                   7195:   font-size:90%;
                   7196: }
                   7197: 
                   7198: div.LC_feedback_link div.LC_comblock {
                   7199:   padding-left:5px;
                   7200: }
                   7201: 
                   7202: div.LC_feedback_link div.LC_comblock a {
                   7203:   color:$font;
                   7204: }
                   7205: 
1.489     raeburn  7206: span.LC_feedback_link {
1.858     bisitz   7207:   /* background: $feedback_link_bg; */
1.599     albertel 7208:   font-size: larger;
                   7209: }
1.795     www      7210: 
1.599     albertel 7211: span.LC_message_link {
1.858     bisitz   7212:   /* background: $feedback_link_bg; */
1.599     albertel 7213:   font-size: larger;
                   7214:   position: absolute;
                   7215:   right: 1em;
1.489     raeburn  7216: }
1.421     albertel 7217: 
1.515     albertel 7218: table.LC_prior_tries {
1.524     albertel 7219:   border: 1px solid #000000;
                   7220:   border-collapse: separate;
                   7221:   border-spacing: 1px;
1.515     albertel 7222: }
1.523     albertel 7223: 
1.515     albertel 7224: table.LC_prior_tries td {
1.524     albertel 7225:   padding: 2px;
1.515     albertel 7226: }
1.523     albertel 7227: 
                   7228: .LC_answer_correct {
1.795     www      7229:   background: lightgreen;
                   7230:   color: darkgreen;
                   7231:   padding: 6px;
1.523     albertel 7232: }
1.795     www      7233: 
1.523     albertel 7234: .LC_answer_charged_try {
1.797     www      7235:   background: #FFAAAA;
1.795     www      7236:   color: darkred;
                   7237:   padding: 6px;
1.523     albertel 7238: }
1.795     www      7239: 
1.779     bisitz   7240: .LC_answer_not_charged_try,
1.523     albertel 7241: .LC_answer_no_grade,
                   7242: .LC_answer_late {
1.795     www      7243:   background: lightyellow;
1.523     albertel 7244:   color: black;
1.795     www      7245:   padding: 6px;
1.523     albertel 7246: }
1.795     www      7247: 
1.523     albertel 7248: .LC_answer_previous {
1.795     www      7249:   background: lightblue;
                   7250:   color: darkblue;
                   7251:   padding: 6px;
1.523     albertel 7252: }
1.795     www      7253: 
1.779     bisitz   7254: .LC_answer_no_message {
1.777     tempelho 7255:   background: #FFFFFF;
                   7256:   color: black;
1.795     www      7257:   padding: 6px;
1.779     bisitz   7258: }
1.795     www      7259: 
1.779     bisitz   7260: .LC_answer_unknown {
                   7261:   background: orange;
                   7262:   color: black;
1.795     www      7263:   padding: 6px;
1.777     tempelho 7264: }
1.795     www      7265: 
1.529     albertel 7266: span.LC_prior_numerical,
                   7267: span.LC_prior_string,
                   7268: span.LC_prior_custom,
                   7269: span.LC_prior_reaction,
                   7270: span.LC_prior_math {
1.925     bisitz   7271:   font-family: $mono;
1.523     albertel 7272:   white-space: pre;
                   7273: }
                   7274: 
1.525     albertel 7275: span.LC_prior_string {
1.925     bisitz   7276:   font-family: $mono;
1.525     albertel 7277:   white-space: pre;
                   7278: }
                   7279: 
1.523     albertel 7280: table.LC_prior_option {
                   7281:   width: 100%;
                   7282:   border-collapse: collapse;
                   7283: }
1.795     www      7284: 
1.911     bisitz   7285: table.LC_prior_rank,
1.795     www      7286: table.LC_prior_match {
1.528     albertel 7287:   border-collapse: collapse;
                   7288: }
1.795     www      7289: 
1.528     albertel 7290: table.LC_prior_option tr td,
                   7291: table.LC_prior_rank tr td,
                   7292: table.LC_prior_match tr td {
1.524     albertel 7293:   border: 1px solid #000000;
1.515     albertel 7294: }
                   7295: 
1.855     bisitz   7296: .LC_nobreak {
1.544     albertel 7297:   white-space: nowrap;
1.519     raeburn  7298: }
                   7299: 
1.576     raeburn  7300: span.LC_cusr_emph {
                   7301:   font-style: italic;
                   7302: }
                   7303: 
1.633     raeburn  7304: span.LC_cusr_subheading {
                   7305:   font-weight: normal;
                   7306:   font-size: 85%;
                   7307: }
                   7308: 
1.861     bisitz   7309: div.LC_docs_entry_move {
1.859     bisitz   7310:   border: 1px solid #BBBBBB;
1.545     albertel 7311:   background: #DDDDDD;
1.861     bisitz   7312:   width: 22px;
1.859     bisitz   7313:   padding: 1px;
                   7314:   margin: 0;
1.545     albertel 7315: }
                   7316: 
1.861     bisitz   7317: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7318: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7319:   font-size: x-small;
                   7320: }
1.795     www      7321: 
1.861     bisitz   7322: .LC_docs_entry_parameter {
                   7323:   white-space: nowrap;
                   7324: }
                   7325: 
1.544     albertel 7326: .LC_docs_copy {
1.545     albertel 7327:   color: #000099;
1.544     albertel 7328: }
1.795     www      7329: 
1.544     albertel 7330: .LC_docs_cut {
1.545     albertel 7331:   color: #550044;
1.544     albertel 7332: }
1.795     www      7333: 
1.544     albertel 7334: .LC_docs_rename {
1.545     albertel 7335:   color: #009900;
1.544     albertel 7336: }
1.795     www      7337: 
1.544     albertel 7338: .LC_docs_remove {
1.545     albertel 7339:   color: #990000;
                   7340: }
                   7341: 
1.1284    raeburn  7342: .LC_docs_alias {
                   7343:   color: #440055;  
                   7344: }
                   7345: 
1.1286    raeburn  7346: .LC_domprefs_email,
1.1284    raeburn  7347: .LC_docs_alias_name,
1.547     albertel 7348: .LC_docs_reinit_warn,
                   7349: .LC_docs_ext_edit {
                   7350:   font-size: x-small;
                   7351: }
                   7352: 
1.545     albertel 7353: table.LC_docs_adddocs td,
                   7354: table.LC_docs_adddocs th {
                   7355:   border: 1px solid #BBBBBB;
                   7356:   padding: 4px;
                   7357:   background: #DDDDDD;
1.543     albertel 7358: }
                   7359: 
1.584     albertel 7360: table.LC_sty_begin {
                   7361:   background: #BBFFBB;
                   7362: }
1.795     www      7363: 
1.584     albertel 7364: table.LC_sty_end {
                   7365:   background: #FFBBBB;
                   7366: }
                   7367: 
1.589     raeburn  7368: table.LC_double_column {
1.803     bisitz   7369:   border-width: 0;
1.589     raeburn  7370:   border-collapse: collapse;
                   7371:   width: 100%;
                   7372:   padding: 2px;
                   7373: }
                   7374: 
                   7375: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7376:   top: 2px;
1.589     raeburn  7377:   left: 2px;
                   7378:   width: 47%;
                   7379:   vertical-align: top;
                   7380: }
                   7381: 
                   7382: table.LC_double_column tr td.LC_right_col {
                   7383:   top: 2px;
1.779     bisitz   7384:   right: 2px;
1.589     raeburn  7385:   width: 47%;
                   7386:   vertical-align: top;
                   7387: }
                   7388: 
1.591     raeburn  7389: div.LC_left_float {
                   7390:   float: left;
                   7391:   padding-right: 5%;
1.597     albertel 7392:   padding-bottom: 4px;
1.591     raeburn  7393: }
                   7394: 
                   7395: div.LC_clear_float_header {
1.597     albertel 7396:   padding-bottom: 2px;
1.591     raeburn  7397: }
                   7398: 
                   7399: div.LC_clear_float_footer {
1.597     albertel 7400:   padding-top: 10px;
1.591     raeburn  7401:   clear: both;
                   7402: }
                   7403: 
1.597     albertel 7404: div.LC_grade_show_user {
1.941     bisitz   7405: /*  border-left: 5px solid $sidebg; */
                   7406:   border-top: 5px solid #000000;
                   7407:   margin: 50px 0 0 0;
1.936     bisitz   7408:   padding: 15px 0 5px 10px;
1.597     albertel 7409: }
1.795     www      7410: 
1.936     bisitz   7411: div.LC_grade_show_user_odd_row {
1.941     bisitz   7412: /*  border-left: 5px solid #000000; */
                   7413: }
                   7414: 
                   7415: div.LC_grade_show_user div.LC_Box {
                   7416:   margin-right: 50px;
1.597     albertel 7417: }
                   7418: 
                   7419: div.LC_grade_submissions,
                   7420: div.LC_grade_message_center,
1.936     bisitz   7421: div.LC_grade_info_links {
1.597     albertel 7422:   margin: 5px;
                   7423:   width: 99%;
                   7424:   background: #FFFFFF;
                   7425: }
1.795     www      7426: 
1.597     albertel 7427: div.LC_grade_submissions_header,
1.936     bisitz   7428: div.LC_grade_message_center_header {
1.705     tempelho 7429:   font-weight: bold;
                   7430:   font-size: large;
1.597     albertel 7431: }
1.795     www      7432: 
1.597     albertel 7433: div.LC_grade_submissions_body,
1.936     bisitz   7434: div.LC_grade_message_center_body {
1.597     albertel 7435:   border: 1px solid black;
                   7436:   width: 99%;
                   7437:   background: #FFFFFF;
                   7438: }
1.795     www      7439: 
1.613     albertel 7440: table.LC_scantron_action {
                   7441:   width: 100%;
                   7442: }
1.795     www      7443: 
1.613     albertel 7444: table.LC_scantron_action tr th {
1.698     harmsja  7445:   font-weight:bold;
                   7446:   font-style:normal;
1.613     albertel 7447: }
1.795     www      7448: 
1.779     bisitz   7449: .LC_edit_problem_header,
1.614     albertel 7450: div.LC_edit_problem_footer {
1.705     tempelho 7451:   font-weight: normal;
                   7452:   font-size:  medium;
1.602     albertel 7453:   margin: 2px;
1.1060    bisitz   7454:   background-color: $sidebg;
1.600     albertel 7455: }
1.795     www      7456: 
1.600     albertel 7457: div.LC_edit_problem_header,
1.602     albertel 7458: div.LC_edit_problem_header div,
1.614     albertel 7459: div.LC_edit_problem_footer,
                   7460: div.LC_edit_problem_footer div,
1.602     albertel 7461: div.LC_edit_problem_editxml_header,
                   7462: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7463:   z-index: 100;
1.600     albertel 7464: }
1.795     www      7465: 
1.600     albertel 7466: div.LC_edit_problem_header_title {
1.705     tempelho 7467:   font-weight: bold;
                   7468:   font-size: larger;
1.602     albertel 7469:   background: $tabbg;
                   7470:   padding: 3px;
1.1060    bisitz   7471:   margin: 0 0 5px 0;
1.602     albertel 7472: }
1.795     www      7473: 
1.602     albertel 7474: table.LC_edit_problem_header_title {
                   7475:   width: 100%;
1.600     albertel 7476:   background: $tabbg;
1.602     albertel 7477: }
                   7478: 
1.1205    golterma 7479: div.LC_edit_actionbar {
                   7480:     background-color: $sidebg;
1.1218    droeschl 7481:     margin: 0;
                   7482:     padding: 0;
                   7483:     line-height: 200%;
1.602     albertel 7484: }
1.795     www      7485: 
1.1218    droeschl 7486: div.LC_edit_actionbar div{
                   7487:     padding: 0;
                   7488:     margin: 0;
                   7489:     display: inline-block;
1.600     albertel 7490: }
1.795     www      7491: 
1.1124    bisitz   7492: .LC_edit_opt {
                   7493:   padding-left: 1em;
                   7494:   white-space: nowrap;
                   7495: }
                   7496: 
1.1152    golterma 7497: .LC_edit_problem_latexhelper{
                   7498:     text-align: right;
                   7499: }
                   7500: 
                   7501: #LC_edit_problem_colorful div{
                   7502:     margin-left: 40px;
                   7503: }
                   7504: 
1.1205    golterma 7505: #LC_edit_problem_codemirror div{
                   7506:     margin-left: 0px;
                   7507: }
                   7508: 
1.911     bisitz   7509: img.stift {
1.803     bisitz   7510:   border-width: 0;
                   7511:   vertical-align: middle;
1.677     riegler  7512: }
1.680     riegler  7513: 
1.923     bisitz   7514: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7515:   vertical-align: top;
1.777     tempelho 7516: }
1.795     www      7517: 
1.716     raeburn  7518: div.LC_createcourse {
1.911     bisitz   7519:   margin: 10px 10px 10px 10px;
1.716     raeburn  7520: }
                   7521: 
1.917     raeburn  7522: .LC_dccid {
1.1130    raeburn  7523:   float: right;
1.917     raeburn  7524:   margin: 0.2em 0 0 0;
                   7525:   padding: 0;
                   7526:   font-size: 90%;
                   7527:   display:none;
                   7528: }
                   7529: 
1.897     wenzelju 7530: ol.LC_primary_menu a:hover,
1.721     harmsja  7531: ol#LC_MenuBreadcrumbs a:hover,
                   7532: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7533: ul#LC_secondary_menu a:hover,
1.721     harmsja  7534: .LC_FormSectionClearButton input:hover
1.795     www      7535: ul.LC_TabContent   li:hover a {
1.952     onken    7536:   color:$button_hover;
1.911     bisitz   7537:   text-decoration:none;
1.693     droeschl 7538: }
                   7539: 
1.779     bisitz   7540: h1 {
1.911     bisitz   7541:   padding: 0;
                   7542:   line-height:130%;
1.693     droeschl 7543: }
1.698     harmsja  7544: 
1.911     bisitz   7545: h2,
                   7546: h3,
                   7547: h4,
                   7548: h5,
                   7549: h6 {
                   7550:   margin: 5px 0 5px 0;
                   7551:   padding: 0;
                   7552:   line-height:130%;
1.693     droeschl 7553: }
1.795     www      7554: 
                   7555: .LC_hcell {
1.911     bisitz   7556:   padding:3px 15px 3px 15px;
                   7557:   margin: 0;
                   7558:   background-color:$tabbg;
                   7559:   color:$fontmenu;
                   7560:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7561: }
1.795     www      7562: 
1.840     bisitz   7563: .LC_Box > .LC_hcell {
1.911     bisitz   7564:   margin: 0 -10px 10px -10px;
1.835     bisitz   7565: }
                   7566: 
1.721     harmsja  7567: .LC_noBorder {
1.911     bisitz   7568:   border: 0;
1.698     harmsja  7569: }
1.693     droeschl 7570: 
1.721     harmsja  7571: .LC_FormSectionClearButton input {
1.911     bisitz   7572:   background-color:transparent;
                   7573:   border: none;
                   7574:   cursor:pointer;
                   7575:   text-decoration:underline;
1.693     droeschl 7576: }
1.763     bisitz   7577: 
                   7578: .LC_help_open_topic {
1.911     bisitz   7579:   color: #FFFFFF;
                   7580:   background-color: #EEEEFF;
                   7581:   margin: 1px;
                   7582:   padding: 4px;
                   7583:   border: 1px solid #000033;
                   7584:   white-space: nowrap;
                   7585:   /* vertical-align: middle; */
1.759     neumanie 7586: }
1.693     droeschl 7587: 
1.911     bisitz   7588: dl,
                   7589: ul,
                   7590: div,
                   7591: fieldset {
                   7592:   margin: 10px 10px 10px 0;
                   7593:   /* overflow: hidden; */
1.693     droeschl 7594: }
1.795     www      7595: 
1.1211    raeburn  7596: article.geogebraweb div {
                   7597:     margin: 0;
                   7598: }
                   7599: 
1.838     bisitz   7600: fieldset > legend {
1.911     bisitz   7601:   font-weight: bold;
                   7602:   padding: 0 5px 0 5px;
1.838     bisitz   7603: }
                   7604: 
1.813     bisitz   7605: #LC_nav_bar {
1.911     bisitz   7606:   float: left;
1.995     raeburn  7607:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7608:   margin: 0 0 2px 0;
1.807     droeschl 7609: }
                   7610: 
1.916     droeschl 7611: #LC_realm {
                   7612:   margin: 0.2em 0 0 0;
                   7613:   padding: 0;
                   7614:   font-weight: bold;
                   7615:   text-align: center;
1.995     raeburn  7616:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7617: }
                   7618: 
1.911     bisitz   7619: #LC_nav_bar em {
                   7620:   font-weight: bold;
                   7621:   font-style: normal;
1.807     droeschl 7622: }
                   7623: 
1.897     wenzelju 7624: ol.LC_primary_menu {
1.934     droeschl 7625:   margin: 0;
1.1076    raeburn  7626:   padding: 0;
1.807     droeschl 7627: }
                   7628: 
1.852     droeschl 7629: ol#LC_PathBreadcrumbs {
1.911     bisitz   7630:   margin: 0;
1.693     droeschl 7631: }
                   7632: 
1.897     wenzelju 7633: ol.LC_primary_menu li {
1.1076    raeburn  7634:   color: RGB(80, 80, 80);
                   7635:   vertical-align: middle;
                   7636:   text-align: left;
                   7637:   list-style: none;
1.1205    golterma 7638:   position: relative;
1.1076    raeburn  7639:   float: left;
1.1205    golterma 7640:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7641:   line-height: 1.5em;
1.1076    raeburn  7642: }
                   7643: 
1.1205    golterma 7644: ol.LC_primary_menu li a,
                   7645: ol.LC_primary_menu li p {
1.1076    raeburn  7646:   display: block;
                   7647:   margin: 0;
                   7648:   padding: 0 5px 0 10px;
                   7649:   text-decoration: none;
                   7650: }
                   7651: 
1.1205    golterma 7652: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7653:   display: inline-block;
                   7654:   width: 95%;
                   7655:   text-align: left;
                   7656: }
                   7657: 
                   7658: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7659:   display: inline-block;	
                   7660:   width: 5%;
                   7661:   float: right;
                   7662:   text-align: right;
                   7663:   font-size: 70%;
                   7664: }
                   7665: 
                   7666: ol.LC_primary_menu ul {
1.1076    raeburn  7667:   display: none;
1.1205    golterma 7668:   width: 15em;
1.1076    raeburn  7669:   background-color: $data_table_light;
1.1205    golterma 7670:   position: absolute;
                   7671:   top: 100%;
1.1076    raeburn  7672: }
                   7673: 
1.1205    golterma 7674: ol.LC_primary_menu ul ul {
                   7675:   left: 100%;
                   7676:   top: 0;
                   7677: }
                   7678: 
                   7679: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7680:   display: block;
                   7681:   position: absolute;
                   7682:   margin: 0;
                   7683:   padding: 0;
1.1078    raeburn  7684:   z-index: 2;
1.1076    raeburn  7685: }
                   7686: 
                   7687: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7688: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7689:   font-size: 90%;
1.911     bisitz   7690:   vertical-align: top;
1.1076    raeburn  7691:   float: none;
1.1079    raeburn  7692:   border-left: 1px solid black;
                   7693:   border-right: 1px solid black;
1.1205    golterma 7694: /* A dark bottom border to visualize different menu options; 
                   7695: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7696:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7697: }
                   7698: 
1.1205    golterma 7699: ol.LC_primary_menu li li p:hover {
                   7700:   color:$button_hover;
                   7701:   text-decoration:none;
                   7702:   background-color:$data_table_dark;
1.1076    raeburn  7703: }
                   7704: 
                   7705: ol.LC_primary_menu li li a:hover {
                   7706:    color:$button_hover;
                   7707:    background-color:$data_table_dark;
1.693     droeschl 7708: }
                   7709: 
1.1205    golterma 7710: /* Font-size equal to the size of the predecessors*/
                   7711: ol.LC_primary_menu li:hover li li {
                   7712:   font-size: 100%;
                   7713: }
                   7714: 
1.897     wenzelju 7715: ol.LC_primary_menu li img {
1.911     bisitz   7716:   vertical-align: bottom;
1.934     droeschl 7717:   height: 1.1em;
1.1077    raeburn  7718:   margin: 0.2em 0 0 0;
1.693     droeschl 7719: }
                   7720: 
1.897     wenzelju 7721: ol.LC_primary_menu a {
1.911     bisitz   7722:   color: RGB(80, 80, 80);
                   7723:   text-decoration: none;
1.693     droeschl 7724: }
1.795     www      7725: 
1.949     droeschl 7726: ol.LC_primary_menu a.LC_new_message {
                   7727:   font-weight:bold;
                   7728:   color: darkred;
                   7729: }
                   7730: 
1.975     raeburn  7731: ol.LC_docs_parameters {
                   7732:   margin-left: 0;
                   7733:   padding: 0;
                   7734:   list-style: none;
                   7735: }
                   7736: 
                   7737: ol.LC_docs_parameters li {
                   7738:   margin: 0;
                   7739:   padding-right: 20px;
                   7740:   display: inline;
                   7741: }
                   7742: 
1.976     raeburn  7743: ol.LC_docs_parameters li:before {
                   7744:   content: "\\002022 \\0020";
                   7745: }
                   7746: 
                   7747: li.LC_docs_parameters_title {
                   7748:   font-weight: bold;
                   7749: }
                   7750: 
                   7751: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7752:   content: "";
                   7753: }
                   7754: 
1.897     wenzelju 7755: ul#LC_secondary_menu {
1.1107    raeburn  7756:   clear: right;
1.911     bisitz   7757:   color: $fontmenu;
                   7758:   background: $tabbg;
                   7759:   list-style: none;
                   7760:   padding: 0;
                   7761:   margin: 0;
                   7762:   width: 100%;
1.995     raeburn  7763:   text-align: left;
1.1107    raeburn  7764:   float: left;
1.808     droeschl 7765: }
                   7766: 
1.897     wenzelju 7767: ul#LC_secondary_menu li {
1.911     bisitz   7768:   font-weight: bold;
                   7769:   line-height: 1.8em;
1.1107    raeburn  7770:   border-right: 1px solid black;
                   7771:   float: left;
                   7772: }
                   7773: 
                   7774: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7775:   background-color: $data_table_light;
                   7776: }
                   7777: 
                   7778: ul#LC_secondary_menu li a {
1.911     bisitz   7779:   padding: 0 0.8em;
1.1107    raeburn  7780: }
                   7781: 
                   7782: ul#LC_secondary_menu li ul {
                   7783:   display: none;
                   7784: }
                   7785: 
                   7786: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7787:   display: block;
                   7788:   position: absolute;
                   7789:   margin: 0;
                   7790:   padding: 0;
                   7791:   list-style:none;
                   7792:   float: none;
                   7793:   background-color: $data_table_light;
                   7794:   z-index: 2;
                   7795:   margin-left: -1px;
                   7796: }
                   7797: 
                   7798: ul#LC_secondary_menu li ul li {
                   7799:   font-size: 90%;
                   7800:   vertical-align: top;
                   7801:   border-left: 1px solid black;
1.911     bisitz   7802:   border-right: 1px solid black;
1.1119    raeburn  7803:   background-color: $data_table_light;
1.1107    raeburn  7804:   list-style:none;
                   7805:   float: none;
                   7806: }
                   7807: 
                   7808: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7809:   background-color: $data_table_dark;
1.807     droeschl 7810: }
                   7811: 
1.847     tempelho 7812: ul.LC_TabContent {
1.911     bisitz   7813:   display:block;
                   7814:   background: $sidebg;
                   7815:   border-bottom: solid 1px $lg_border_color;
                   7816:   list-style:none;
1.1020    raeburn  7817:   margin: -1px -10px 0 -10px;
1.911     bisitz   7818:   padding: 0;
1.693     droeschl 7819: }
                   7820: 
1.795     www      7821: ul.LC_TabContent li,
                   7822: ul.LC_TabContentBigger li {
1.911     bisitz   7823:   float:left;
1.741     harmsja  7824: }
1.795     www      7825: 
1.897     wenzelju 7826: ul#LC_secondary_menu li a {
1.911     bisitz   7827:   color: $fontmenu;
                   7828:   text-decoration: none;
1.693     droeschl 7829: }
1.795     www      7830: 
1.721     harmsja  7831: ul.LC_TabContent {
1.952     onken    7832:   min-height:20px;
1.721     harmsja  7833: }
1.795     www      7834: 
                   7835: ul.LC_TabContent li {
1.911     bisitz   7836:   vertical-align:middle;
1.959     onken    7837:   padding: 0 16px 0 10px;
1.911     bisitz   7838:   background-color:$tabbg;
                   7839:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7840:   border-left: solid 1px $font;
1.721     harmsja  7841: }
1.795     www      7842: 
1.847     tempelho 7843: ul.LC_TabContent .right {
1.911     bisitz   7844:   float:right;
1.847     tempelho 7845: }
                   7846: 
1.911     bisitz   7847: ul.LC_TabContent li a,
                   7848: ul.LC_TabContent li {
                   7849:   color:rgb(47,47,47);
                   7850:   text-decoration:none;
                   7851:   font-size:95%;
                   7852:   font-weight:bold;
1.952     onken    7853:   min-height:20px;
                   7854: }
                   7855: 
1.959     onken    7856: ul.LC_TabContent li a:hover,
                   7857: ul.LC_TabContent li a:focus {
1.952     onken    7858:   color: $button_hover;
1.959     onken    7859:   background:none;
                   7860:   outline:none;
1.952     onken    7861: }
                   7862: 
                   7863: ul.LC_TabContent li:hover {
                   7864:   color: $button_hover;
                   7865:   cursor:pointer;
1.721     harmsja  7866: }
1.795     www      7867: 
1.911     bisitz   7868: ul.LC_TabContent li.active {
1.952     onken    7869:   color: $font;
1.911     bisitz   7870:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7871:   border-bottom:solid 1px #FFFFFF;
                   7872:   cursor: default;
1.744     ehlerst  7873: }
1.795     www      7874: 
1.959     onken    7875: ul.LC_TabContent li.active a {
                   7876:   color:$font;
                   7877:   background:#FFFFFF;
                   7878:   outline: none;
                   7879: }
1.1047    raeburn  7880: 
                   7881: ul.LC_TabContent li.goback {
                   7882:   float: left;
                   7883:   border-left: none;
                   7884: }
                   7885: 
1.870     tempelho 7886: #maincoursedoc {
1.911     bisitz   7887:   clear:both;
1.870     tempelho 7888: }
                   7889: 
                   7890: ul.LC_TabContentBigger {
1.911     bisitz   7891:   display:block;
                   7892:   list-style:none;
                   7893:   padding: 0;
1.870     tempelho 7894: }
                   7895: 
1.795     www      7896: ul.LC_TabContentBigger li {
1.911     bisitz   7897:   vertical-align:bottom;
                   7898:   height: 30px;
                   7899:   font-size:110%;
                   7900:   font-weight:bold;
                   7901:   color: #737373;
1.841     tempelho 7902: }
                   7903: 
1.957     onken    7904: ul.LC_TabContentBigger li.active {
                   7905:   position: relative;
                   7906:   top: 1px;
                   7907: }
                   7908: 
1.870     tempelho 7909: ul.LC_TabContentBigger li a {
1.911     bisitz   7910:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7911:   height: 30px;
                   7912:   line-height: 30px;
                   7913:   text-align: center;
                   7914:   display: block;
                   7915:   text-decoration: none;
1.958     onken    7916:   outline: none;  
1.741     harmsja  7917: }
1.795     www      7918: 
1.870     tempelho 7919: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7920:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7921:   color:$font;
1.744     ehlerst  7922: }
1.795     www      7923: 
1.870     tempelho 7924: ul.LC_TabContentBigger li b {
1.911     bisitz   7925:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7926:   display: block;
                   7927:   float: left;
                   7928:   padding: 0 30px;
1.957     onken    7929:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7930: }
                   7931: 
1.956     onken    7932: ul.LC_TabContentBigger li:hover b {
                   7933:   color:$button_hover;
                   7934: }
                   7935: 
1.870     tempelho 7936: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7937:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7938:   color:$font;
1.957     onken    7939:   border: 0;
1.741     harmsja  7940: }
1.693     droeschl 7941: 
1.870     tempelho 7942: 
1.862     bisitz   7943: ul.LC_CourseBreadcrumbs {
                   7944:   background: $sidebg;
1.1020    raeburn  7945:   height: 2em;
1.862     bisitz   7946:   padding-left: 10px;
1.1020    raeburn  7947:   margin: 0;
1.862     bisitz   7948:   list-style-position: inside;
                   7949: }
                   7950: 
1.911     bisitz   7951: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7952: ol#LC_PathBreadcrumbs {
1.911     bisitz   7953:   padding-left: 10px;
                   7954:   margin: 0;
1.933     droeschl 7955:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7956: }
                   7957: 
1.911     bisitz   7958: ol#LC_MenuBreadcrumbs li,
                   7959: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7960: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7961:   display: inline;
1.933     droeschl 7962:   white-space: normal;  
1.693     droeschl 7963: }
                   7964: 
1.823     bisitz   7965: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7966: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7967:   text-decoration: none;
                   7968:   font-size:90%;
1.693     droeschl 7969: }
1.795     www      7970: 
1.969     droeschl 7971: ol#LC_MenuBreadcrumbs h1 {
                   7972:   display: inline;
                   7973:   font-size: 90%;
                   7974:   line-height: 2.5em;
                   7975:   margin: 0;
                   7976:   padding: 0;
                   7977: }
                   7978: 
1.795     www      7979: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7980:   text-decoration:none;
                   7981:   font-size:100%;
                   7982:   font-weight:bold;
1.693     droeschl 7983: }
1.795     www      7984: 
1.840     bisitz   7985: .LC_Box {
1.911     bisitz   7986:   border: solid 1px $lg_border_color;
                   7987:   padding: 0 10px 10px 10px;
1.746     neumanie 7988: }
1.795     www      7989: 
1.1020    raeburn  7990: .LC_DocsBox {
                   7991:   border: solid 1px $lg_border_color;
                   7992:   padding: 0 0 10px 10px;
                   7993: }
                   7994: 
1.795     www      7995: .LC_AboutMe_Image {
1.911     bisitz   7996:   float:left;
                   7997:   margin-right:10px;
1.747     neumanie 7998: }
1.795     www      7999: 
                   8000: .LC_Clear_AboutMe_Image {
1.911     bisitz   8001:   clear:left;
1.747     neumanie 8002: }
1.795     www      8003: 
1.721     harmsja  8004: dl.LC_ListStyleClean dt {
1.911     bisitz   8005:   padding-right: 5px;
                   8006:   display: table-header-group;
1.693     droeschl 8007: }
                   8008: 
1.721     harmsja  8009: dl.LC_ListStyleClean dd {
1.911     bisitz   8010:   display: table-row;
1.693     droeschl 8011: }
                   8012: 
1.721     harmsja  8013: .LC_ListStyleClean,
                   8014: .LC_ListStyleSimple,
                   8015: .LC_ListStyleNormal,
1.795     www      8016: .LC_ListStyleSpecial {
1.911     bisitz   8017:   /* display:block; */
                   8018:   list-style-position: inside;
                   8019:   list-style-type: none;
                   8020:   overflow: hidden;
                   8021:   padding: 0;
1.693     droeschl 8022: }
                   8023: 
1.721     harmsja  8024: .LC_ListStyleSimple li,
                   8025: .LC_ListStyleSimple dd,
                   8026: .LC_ListStyleNormal li,
                   8027: .LC_ListStyleNormal dd,
                   8028: .LC_ListStyleSpecial li,
1.795     www      8029: .LC_ListStyleSpecial dd {
1.911     bisitz   8030:   margin: 0;
                   8031:   padding: 5px 5px 5px 10px;
                   8032:   clear: both;
1.693     droeschl 8033: }
                   8034: 
1.721     harmsja  8035: .LC_ListStyleClean li,
                   8036: .LC_ListStyleClean dd {
1.911     bisitz   8037:   padding-top: 0;
                   8038:   padding-bottom: 0;
1.693     droeschl 8039: }
                   8040: 
1.721     harmsja  8041: .LC_ListStyleSimple dd,
1.795     www      8042: .LC_ListStyleSimple li {
1.911     bisitz   8043:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8044: }
                   8045: 
1.721     harmsja  8046: .LC_ListStyleSpecial li,
                   8047: .LC_ListStyleSpecial dd {
1.911     bisitz   8048:   list-style-type: none;
                   8049:   background-color: RGB(220, 220, 220);
                   8050:   margin-bottom: 4px;
1.693     droeschl 8051: }
                   8052: 
1.721     harmsja  8053: table.LC_SimpleTable {
1.911     bisitz   8054:   margin:5px;
                   8055:   border:solid 1px $lg_border_color;
1.795     www      8056: }
1.693     droeschl 8057: 
1.721     harmsja  8058: table.LC_SimpleTable tr {
1.911     bisitz   8059:   padding: 0;
                   8060:   border:solid 1px $lg_border_color;
1.693     droeschl 8061: }
1.795     www      8062: 
                   8063: table.LC_SimpleTable thead {
1.911     bisitz   8064:   background:rgb(220,220,220);
1.693     droeschl 8065: }
                   8066: 
1.721     harmsja  8067: div.LC_columnSection {
1.911     bisitz   8068:   display: block;
                   8069:   clear: both;
                   8070:   overflow: hidden;
                   8071:   margin: 0;
1.693     droeschl 8072: }
                   8073: 
1.721     harmsja  8074: div.LC_columnSection>* {
1.911     bisitz   8075:   float: left;
                   8076:   margin: 10px 20px 10px 0;
                   8077:   overflow:hidden;
1.693     droeschl 8078: }
1.721     harmsja  8079: 
1.795     www      8080: table em {
1.911     bisitz   8081:   font-weight: bold;
                   8082:   font-style: normal;
1.748     schulted 8083: }
1.795     www      8084: 
1.779     bisitz   8085: table.LC_tableBrowseRes,
1.795     www      8086: table.LC_tableOfContent {
1.911     bisitz   8087:   border:none;
                   8088:   border-spacing: 1px;
                   8089:   padding: 3px;
                   8090:   background-color: #FFFFFF;
                   8091:   font-size: 90%;
1.753     droeschl 8092: }
1.789     droeschl 8093: 
1.911     bisitz   8094: table.LC_tableOfContent {
                   8095:   border-collapse: collapse;
1.789     droeschl 8096: }
                   8097: 
1.771     droeschl 8098: table.LC_tableBrowseRes a,
1.768     schulted 8099: table.LC_tableOfContent a {
1.911     bisitz   8100:   background-color: transparent;
                   8101:   text-decoration: none;
1.753     droeschl 8102: }
                   8103: 
1.795     www      8104: table.LC_tableOfContent img {
1.911     bisitz   8105:   border: none;
                   8106:   height: 1.3em;
                   8107:   vertical-align: text-bottom;
                   8108:   margin-right: 0.3em;
1.753     droeschl 8109: }
1.757     schulted 8110: 
1.795     www      8111: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8112:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8113: }
                   8114: 
1.795     www      8115: a#LC_content_toolbar_everything {
1.911     bisitz   8116:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8117: }
                   8118: 
1.795     www      8119: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8120:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8121: }
                   8122: 
1.795     www      8123: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8124:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8125: }
                   8126: 
1.795     www      8127: a#LC_content_toolbar_changefolder {
1.911     bisitz   8128:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8129: }
                   8130: 
1.795     www      8131: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8132:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8133: }
                   8134: 
1.1043    raeburn  8135: a#LC_content_toolbar_edittoplevel {
                   8136:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8137: }
                   8138: 
1.795     www      8139: ul#LC_toolbar li a:hover {
1.911     bisitz   8140:   background-position: bottom center;
1.757     schulted 8141: }
                   8142: 
1.795     www      8143: ul#LC_toolbar {
1.911     bisitz   8144:   padding: 0;
                   8145:   margin: 2px;
                   8146:   list-style:none;
                   8147:   position:relative;
                   8148:   background-color:white;
1.1082    raeburn  8149:   overflow: auto;
1.757     schulted 8150: }
                   8151: 
1.795     www      8152: ul#LC_toolbar li {
1.911     bisitz   8153:   border:1px solid white;
                   8154:   padding: 0;
                   8155:   margin: 0;
                   8156:   float: left;
                   8157:   display:inline;
                   8158:   vertical-align:middle;
1.1082    raeburn  8159:   white-space: nowrap;
1.911     bisitz   8160: }
1.757     schulted 8161: 
1.783     amueller 8162: 
1.795     www      8163: a.LC_toolbarItem {
1.911     bisitz   8164:   display:block;
                   8165:   padding: 0;
                   8166:   margin: 0;
                   8167:   height: 32px;
                   8168:   width: 32px;
                   8169:   color:white;
                   8170:   border: none;
                   8171:   background-repeat:no-repeat;
                   8172:   background-color:transparent;
1.757     schulted 8173: }
                   8174: 
1.915     droeschl 8175: ul.LC_funclist {
                   8176:     margin: 0;
                   8177:     padding: 0.5em 1em 0.5em 0;
                   8178: }
                   8179: 
1.933     droeschl 8180: ul.LC_funclist > li:first-child {
                   8181:     font-weight:bold; 
                   8182:     margin-left:0.8em;
                   8183: }
                   8184: 
1.915     droeschl 8185: ul.LC_funclist + ul.LC_funclist {
                   8186:     /* 
                   8187:        left border as a seperator if we have more than
                   8188:        one list 
                   8189:     */
                   8190:     border-left: 1px solid $sidebg;
                   8191:     /* 
                   8192:        this hides the left border behind the border of the 
                   8193:        outer box if element is wrapped to the next 'line' 
                   8194:     */
                   8195:     margin-left: -1px;
                   8196: }
                   8197: 
1.843     bisitz   8198: ul.LC_funclist li {
1.915     droeschl 8199:   display: inline;
1.782     bisitz   8200:   white-space: nowrap;
1.915     droeschl 8201:   margin: 0 0 0 25px;
                   8202:   line-height: 150%;
1.782     bisitz   8203: }
                   8204: 
1.974     wenzelju 8205: .LC_hidden {
                   8206:   display: none;
                   8207: }
                   8208: 
1.1030    www      8209: .LCmodal-overlay {
                   8210: 		position:fixed;
                   8211: 		top:0;
                   8212: 		right:0;
                   8213: 		bottom:0;
                   8214: 		left:0;
                   8215: 		height:100%;
                   8216: 		width:100%;
                   8217: 		margin:0;
                   8218: 		padding:0;
                   8219: 		background:#999;
                   8220: 		opacity:.75;
                   8221: 		filter: alpha(opacity=75);
                   8222: 		-moz-opacity: 0.75;
                   8223: 		z-index:101;
                   8224: }
                   8225: 
                   8226: * html .LCmodal-overlay {   
                   8227: 		position: absolute;
                   8228: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8229: }
                   8230: 
                   8231: .LCmodal-window {
                   8232: 		position:fixed;
                   8233: 		top:50%;
                   8234: 		left:50%;
                   8235: 		margin:0;
                   8236: 		padding:0;
                   8237: 		z-index:102;
                   8238: 	}
                   8239: 
                   8240: * html .LCmodal-window {
                   8241: 		position:absolute;
                   8242: }
                   8243: 
                   8244: .LCclose-window {
                   8245: 		position:absolute;
                   8246: 		width:32px;
                   8247: 		height:32px;
                   8248: 		right:8px;
                   8249: 		top:8px;
                   8250: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8251: 		text-indent:-99999px;
                   8252: 		overflow:hidden;
                   8253: 		cursor:pointer;
                   8254: }
                   8255: 
1.1100    raeburn  8256: /*
1.1231    damieng  8257:   styles used for response display
                   8258: */
                   8259: div.LC_radiofoil, div.LC_rankfoil {
                   8260:   margin: .5em 0em .5em 0em;
                   8261: }
                   8262: table.LC_itemgroup {
                   8263:   margin-top: 1em;
                   8264: }
                   8265: 
                   8266: /*
1.1100    raeburn  8267:   styles used by TTH when "Default set of options to pass to tth/m
                   8268:   when converting TeX" in course settings has been set
                   8269: 
                   8270:   option passed: -t
                   8271: 
                   8272: */
                   8273: 
                   8274: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8275: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8276: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8277: td div.norm {line-height:normal;}
                   8278: 
                   8279: /*
                   8280:   option passed -y3
                   8281: */
                   8282: 
                   8283: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8284: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8285: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8286: 
1.1230    damieng  8287: /*
                   8288:   sections with roles, for content only
                   8289: */
                   8290: section[class^="role-"] {
                   8291:   padding-left: 10px;
                   8292:   padding-right: 5px;
                   8293:   margin-top: 8px;
                   8294:   margin-bottom: 8px;
                   8295:   border: 1px solid #2A4;
                   8296:   border-radius: 5px;
                   8297:   box-shadow: 0px 1px 1px #BBB;
                   8298: }
                   8299: section[class^="role-"]>h1 {
                   8300:   position: relative;
                   8301:   margin: 0px;
                   8302:   padding-top: 10px;
                   8303:   padding-left: 40px;
                   8304: }
                   8305: section[class^="role-"]>h1:before {
                   8306:   position: absolute;
                   8307:   left: -5px;
                   8308:   top: 5px;
                   8309: }
                   8310: section.role-activity>h1:before {
                   8311:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8312: }
                   8313: section.role-advice>h1:before {
                   8314:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8315: }
                   8316: section.role-bibliography>h1:before {
                   8317:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8318: }
                   8319: section.role-citation>h1:before {
                   8320:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8321: }
                   8322: section.role-conclusion>h1:before {
                   8323:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8324: }
                   8325: section.role-definition>h1:before {
                   8326:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8327: }
                   8328: section.role-demonstration>h1:before {
                   8329:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8330: }
                   8331: section.role-example>h1:before {
                   8332:   content:url('/adm/daxe/images/section_icons/example.png');
                   8333: }
                   8334: section.role-explanation>h1:before {
                   8335:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8336: }
                   8337: section.role-introduction>h1:before {
                   8338:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8339: }
                   8340: section.role-method>h1:before {
                   8341:   content:url('/adm/daxe/images/section_icons/method.png');
                   8342: }
                   8343: section.role-more_information>h1:before {
                   8344:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8345: }
                   8346: section.role-objectives>h1:before {
                   8347:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8348: }
                   8349: section.role-prerequisites>h1:before {
                   8350:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8351: }
                   8352: section.role-remark>h1:before {
                   8353:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8354: }
                   8355: section.role-reminder>h1:before {
                   8356:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8357: }
                   8358: section.role-summary>h1:before {
                   8359:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8360: }
                   8361: section.role-syntax>h1:before {
                   8362:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8363: }
                   8364: section.role-warning>h1:before {
                   8365:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8366: }
                   8367: 
1.1269    raeburn  8368: #LC_minitab_header {
                   8369:   float:left;
                   8370:   width:100%;
                   8371:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8372:   font-size:93%;
                   8373:   line-height:normal;
                   8374:   margin: 0.5em 0 0.5em 0;
                   8375: }
                   8376: #LC_minitab_header ul {
                   8377:   margin:0;
                   8378:   padding:10px 10px 0;
                   8379:   list-style:none;
                   8380: }
                   8381: #LC_minitab_header li {
                   8382:   float:left;
                   8383:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8384:   margin:0;
                   8385:   padding:0 0 0 9px;
                   8386: }
                   8387: #LC_minitab_header a {
                   8388:   display:block;
                   8389:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8390:   padding:5px 15px 4px 6px;
                   8391: }
                   8392: #LC_minitab_header #LC_current_minitab {
                   8393:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8394: }
                   8395: #LC_minitab_header #LC_current_minitab a {
                   8396:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8397:   padding-bottom:5px;
                   8398: }
                   8399: 
                   8400: 
1.343     albertel 8401: END
                   8402: }
                   8403: 
1.306     albertel 8404: =pod
                   8405: 
                   8406: =item * &headtag()
                   8407: 
                   8408: Returns a uniform footer for LON-CAPA web pages.
                   8409: 
1.307     albertel 8410: Inputs: $title - optional title for the head
                   8411:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8412:         $args - optional arguments
1.319     albertel 8413:             force_register - if is true call registerurl so the remote is 
                   8414:                              informed
1.415     albertel 8415:             redirect       -> array ref of
                   8416:                                    1- seconds before redirect occurs
                   8417:                                    2- url to redirect to
                   8418:                                    3- whether the side effect should occur
1.315     albertel 8419:                            (side effect of setting 
                   8420:                                $env{'internal.head.redirect'} to the url 
                   8421:                                redirected too)
1.352     albertel 8422:             domain         -> force to color decorate a page for a specific
                   8423:                                domain
                   8424:             function       -> force usage of a specific rolish color scheme
                   8425:             bgcolor        -> override the default page bgcolor
1.460     albertel 8426:             no_auto_mt_title
                   8427:                            -> prevent &mt()ing the title arg
1.464     albertel 8428: 
1.306     albertel 8429: =cut
                   8430: 
                   8431: sub headtag {
1.313     albertel 8432:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8433:     
1.363     albertel 8434:     my $function = $args->{'function'} || &get_users_function();
                   8435:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8436:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8437:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8438:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8439: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8440: 		   #time(),
1.418     albertel 8441: 		   $env{'environment.color.timestamp'},
1.363     albertel 8442: 		   $function,$domain,$bgcolor);
                   8443: 
1.369     www      8444:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8445: 
1.308     albertel 8446:     my $result =
                   8447: 	'<head>'.
1.1160    raeburn  8448: 	&font_settings($args);
1.319     albertel 8449: 
1.1188    raeburn  8450:     my $inhibitprint;
                   8451:     if ($args->{'print_suppress'}) {
                   8452:         $inhibitprint = &print_suppression();
                   8453:     }
1.1064    raeburn  8454: 
1.461     albertel 8455:     if (!$args->{'frameset'}) {
                   8456: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8457:     }
1.962     droeschl 8458:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8459:         $result .= Apache::lonxml::display_title();
1.319     albertel 8460:     }
1.436     albertel 8461:     if (!$args->{'no_nav_bar'} 
                   8462: 	&& !$args->{'only_body'}
                   8463: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8464: 	$result .= &help_menu_js($httphost);
1.1032    www      8465:         $result.=&modal_window();
1.1038    www      8466:         $result.=&togglebox_script();
1.1034    www      8467:         $result.=&wishlist_window();
1.1041    www      8468:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8469:     } else {
                   8470:         if ($args->{'add_modal'}) {
                   8471:            $result.=&modal_window();
                   8472:         }
                   8473:         if ($args->{'add_wishlist'}) {
                   8474:            $result.=&wishlist_window();
                   8475:         }
1.1038    www      8476:         if ($args->{'add_togglebox'}) {
                   8477:            $result.=&togglebox_script();
                   8478:         }
1.1041    www      8479:         if ($args->{'add_progressbar'}) {
                   8480:            $result.=&LCprogressbarUpdate_script();
                   8481:         }
1.436     albertel 8482:     }
1.314     albertel 8483:     if (ref($args->{'redirect'})) {
1.414     albertel 8484: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8485: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8486: 	if (!$inhibit_continue) {
                   8487: 	    $env{'internal.head.redirect'} = $url;
                   8488: 	}
1.313     albertel 8489: 	$result.=<<ADDMETA
                   8490: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8491: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8492: ADDMETA
1.1210    raeburn  8493:     } else {
                   8494:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8495:             my $requrl = $env{'request.uri'};
                   8496:             if ($requrl eq '') {
                   8497:                 $requrl = $ENV{'REQUEST_URI'};
                   8498:                 $requrl =~ s/\?.+$//;
                   8499:             }
                   8500:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8501:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8502:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8503:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8504:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8505:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8506:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8507:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8508:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8509:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8510:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8511:                                 my $numsec = 5;
                   8512:                                 my $timeout = $numsec * 1000;
                   8513:                                 my ($newurl,$locknum,%locks,$msg);
                   8514:                                 if ($env{'request.role.adv'}) {
                   8515:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8516:                                 }
                   8517:                                 my $disable_submit = 0;
                   8518:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8519:                                     $disable_submit = 1;
                   8520:                                 }
                   8521:                                 if ($locknum) {
                   8522:                                     my @lockinfo = sort(values(%locks));
                   8523:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8524:                                            join(", ",sort(values(%locks)))."\\n".
                   8525:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8526:                                 } else {
                   8527:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8528:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8529:                                     }
                   8530:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8531:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8532:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8533:                                         $newurl .= '&role='.$env{'request.role'};
                   8534:                                     }
                   8535:                                     if ($env{'request.symb'}) {
                   8536:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8537:                                     } else {
                   8538:                                         $newurl .= '&origurl='.$requrl;
                   8539:                                     }
                   8540:                                 }
1.1222    damieng  8541:                                 &js_escape(\$msg);
1.1210    raeburn  8542:                                 $result.=<<OFFLOAD
                   8543: <meta http-equiv="pragma" content="no-cache" />
                   8544: <script type="text/javascript">
1.1215    raeburn  8545: // <![CDATA[
1.1210    raeburn  8546: function LC_Offload_Now() {
                   8547:     var dest = "$newurl";
                   8548:     if (dest != '') {
                   8549:         window.location.href="$newurl";
                   8550:     }
                   8551: }
1.1214    raeburn  8552: \$(document).ready(function () {
                   8553:     window.alert('$msg');
                   8554:     if ($disable_submit) {
1.1210    raeburn  8555:         \$(".LC_hwk_submit").prop("disabled", true);
                   8556:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8557:     }
                   8558:     setTimeout('LC_Offload_Now()', $timeout);
                   8559: });
1.1215    raeburn  8560: // ]]>
1.1210    raeburn  8561: </script>
                   8562: OFFLOAD
                   8563:                             }
                   8564:                         }
                   8565:                     }
                   8566:                 }
                   8567:             }
                   8568:         }
1.313     albertel 8569:     }
1.306     albertel 8570:     if (!defined($title)) {
                   8571: 	$title = 'The LearningOnline Network with CAPA';
                   8572:     }
1.460     albertel 8573:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8574:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8575: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8576:     if (!$args->{'frameset'}) {
                   8577:         $result .= ' /';
                   8578:     }
                   8579:     $result .= '>' 
1.1064    raeburn  8580:         .$inhibitprint
1.414     albertel 8581: 	.$head_extra;
1.1242    raeburn  8582:     my $clientmobile;
                   8583:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8584:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8585:     } else {
                   8586:         $clientmobile = $env{'browser.mobile'};
                   8587:     }
                   8588:     if ($clientmobile) {
1.1137    raeburn  8589:         $result .= '
                   8590: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8591: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8592:     }
1.1278    raeburn  8593:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8594:     return $result.'</head>';
1.306     albertel 8595: }
                   8596: 
                   8597: =pod
                   8598: 
1.340     albertel 8599: =item * &font_settings()
                   8600: 
                   8601: Returns neccessary <meta> to set the proper encoding
                   8602: 
1.1160    raeburn  8603: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8604: 
                   8605: =cut
                   8606: 
                   8607: sub font_settings {
1.1160    raeburn  8608:     my ($args) = @_;
1.340     albertel 8609:     my $headerstring='';
1.1160    raeburn  8610:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8611:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8612:         $headerstring.=
                   8613:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8614:         if (!$args->{'frameset'}) {
                   8615: 	    $headerstring.= ' /';
                   8616:         }
                   8617: 	$headerstring .= '>'."\n";
1.340     albertel 8618:     }
                   8619:     return $headerstring;
                   8620: }
                   8621: 
1.341     albertel 8622: =pod
                   8623: 
1.1064    raeburn  8624: =item * &print_suppression()
                   8625: 
                   8626: In course context returns css which causes the body to be blank when media="print",
                   8627: if printout generation is unavailable for the current resource.
                   8628: 
                   8629: This could be because:
                   8630: 
                   8631: (a) printstartdate is in the future
                   8632: 
                   8633: (b) printenddate is in the past
                   8634: 
                   8635: (c) there is an active exam block with "printout"
                   8636: functionality blocked
                   8637: 
                   8638: Users with pav, pfo or evb privileges are exempt.
                   8639: 
                   8640: Inputs: none
                   8641: 
                   8642: =cut
                   8643: 
                   8644: 
                   8645: sub print_suppression {
                   8646:     my $noprint;
                   8647:     if ($env{'request.course.id'}) {
                   8648:         my $scope = $env{'request.course.id'};
                   8649:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8650:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8651:             return;
                   8652:         }
                   8653:         if ($env{'request.course.sec'} ne '') {
                   8654:             $scope .= "/$env{'request.course.sec'}";
                   8655:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8656:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8657:                 return;
1.1064    raeburn  8658:             }
                   8659:         }
                   8660:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8661:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8662:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8663:         if ($blocked) {
                   8664:             my $checkrole = "cm./$cdom/$cnum";
                   8665:             if ($env{'request.course.sec'} ne '') {
                   8666:                 $checkrole .= "/$env{'request.course.sec'}";
                   8667:             }
                   8668:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8669:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8670:                 $noprint = 1;
                   8671:             }
                   8672:         }
                   8673:         unless ($noprint) {
                   8674:             my $symb = &Apache::lonnet::symbread();
                   8675:             if ($symb ne '') {
                   8676:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8677:                 if (ref($navmap)) {
                   8678:                     my $res = $navmap->getBySymb($symb);
                   8679:                     if (ref($res)) {
                   8680:                         if (!$res->resprintable()) {
                   8681:                             $noprint = 1;
                   8682:                         }
                   8683:                     }
                   8684:                 }
                   8685:             }
                   8686:         }
                   8687:         if ($noprint) {
                   8688:             return <<"ENDSTYLE";
                   8689: <style type="text/css" media="print">
                   8690:     body { display:none }
                   8691: </style>
                   8692: ENDSTYLE
                   8693:         }
                   8694:     }
                   8695:     return;
                   8696: }
                   8697: 
                   8698: =pod
                   8699: 
1.341     albertel 8700: =item * &xml_begin()
                   8701: 
                   8702: Returns the needed doctype and <html>
                   8703: 
                   8704: Inputs: none
                   8705: 
                   8706: =cut
                   8707: 
                   8708: sub xml_begin {
1.1168    raeburn  8709:     my ($is_frameset) = @_;
1.341     albertel 8710:     my $output='';
                   8711: 
                   8712:     if ($env{'browser.mathml'}) {
                   8713: 	$output='<?xml version="1.0"?>'
                   8714:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8715: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8716:             
                   8717: #	    .'<!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">] >'
                   8718: 	    .'<!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">'
                   8719:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8720: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8721:     } elsif ($is_frameset) {
                   8722:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8723:                 '<html>'."\n";
1.341     albertel 8724:     } else {
1.1168    raeburn  8725: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8726:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8727:     }
                   8728:     return $output;
                   8729: }
1.340     albertel 8730: 
                   8731: =pod
                   8732: 
1.306     albertel 8733: =item * &start_page()
                   8734: 
                   8735: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8736: 
1.648     raeburn  8737: Inputs:
                   8738: 
                   8739: =over 4
                   8740: 
                   8741: $title - optional title for the page
                   8742: 
                   8743: $head_extra - optional extra HTML to incude inside the <head>
                   8744: 
                   8745: $args - additional optional args supported are:
                   8746: 
                   8747: =over 8
                   8748: 
                   8749:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8750:                                     arg on
1.814     bisitz   8751:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8752:              add_entries    -> additional attributes to add to the  <body>
                   8753:              domain         -> force to color decorate a page for a 
1.317     albertel 8754:                                     specific domain
1.648     raeburn  8755:              function       -> force usage of a specific rolish color
1.317     albertel 8756:                                     scheme
1.648     raeburn  8757:              redirect       -> see &headtag()
                   8758:              bgcolor        -> override the default page bg color
                   8759:              js_ready       -> return a string ready for being used in 
1.317     albertel 8760:                                     a javascript writeln
1.648     raeburn  8761:              html_encode    -> return a string ready for being used in 
1.320     albertel 8762:                                     a html attribute
1.648     raeburn  8763:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8764:                                     $forcereg arg
1.648     raeburn  8765:              frameset       -> if true will start with a <frameset>
1.330     albertel 8766:                                     rather than <body>
1.648     raeburn  8767:              skip_phases    -> hash ref of 
1.338     albertel 8768:                                     head -> skip the <html><head> generation
                   8769:                                     body -> skip all <body> generation
1.648     raeburn  8770:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8771:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8772:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8773:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8774:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8775:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8776:                                specific group
                   8777:              use_absolute   -> for request for external resource or syllabus, this
                   8778:                                will contain https://<hostname> if server uses
                   8779:                                https (as per hosts.tab), but request is for http
                   8780:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8781: 
1.648     raeburn  8782: =back
1.460     albertel 8783: 
1.648     raeburn  8784: =back
1.562     albertel 8785: 
1.306     albertel 8786: =cut
                   8787: 
                   8788: sub start_page {
1.309     albertel 8789:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8790:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8791: 
1.315     albertel 8792:     $env{'internal.start_page'}++;
1.1318    raeburn  8793:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu);
1.964     droeschl 8794: 
1.338     albertel 8795:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8796:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8797:     }
1.1316    raeburn  8798: 
                   8799:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  8800:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8801:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8802:                 $args->{'no_primary_menu'} = 1;
                   8803:             }
                   8804:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8805:                 $args->{'no_inline_menu'} = 1;
                   8806:             }
                   8807:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8808:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8809:             }
                   8810:         } else {
                   8811:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8812:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8813:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8814:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   8815:                     $args->{'no_primary_menu'} = 1;
                   8816:                 }
                   8817:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   8818:                     $args->{'no_inline_menu'} = 1;
                   8819:                 }
                   8820:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   8821:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   8822:                 }
                   8823:             }
                   8824:         }
1.1316    raeburn  8825:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   8826:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   8827:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   8828:     }
1.338     albertel 8829:     
                   8830:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8831: 	if ($args->{'frameset'}) {
                   8832: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8833: 						$args->{'add_entries'});
                   8834: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8835:         } else {
                   8836:             $result .=
                   8837:                 &bodytag($title, 
                   8838:                          $args->{'function'},       $args->{'add_entries'},
                   8839:                          $args->{'only_body'},      $args->{'domain'},
                   8840:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8841:                          $args->{'bgcolor'},        $args,
1.1318    raeburn  8842:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu);
1.831     bisitz   8843:         }
1.330     albertel 8844:     }
1.338     albertel 8845: 
1.315     albertel 8846:     if ($args->{'js_ready'}) {
1.713     kaisler  8847: 		$result = &js_ready($result);
1.315     albertel 8848:     }
1.320     albertel 8849:     if ($args->{'html_encode'}) {
1.713     kaisler  8850: 		$result = &html_encode($result);
                   8851:     }
                   8852: 
1.813     bisitz   8853:     # Preparation for new and consistent functionlist at top of screen
                   8854:     # if ($args->{'functionlist'}) {
                   8855:     #            $result .= &build_functionlist();
                   8856:     #}
                   8857: 
1.964     droeschl 8858:     # Don't add anything more if only_body wanted or in const space
                   8859:     return $result if    $args->{'only_body'} 
                   8860:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8861: 
                   8862:     #Breadcrumbs
1.758     kaisler  8863:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8864: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8865: 		#if any br links exists, add them to the breadcrumbs
                   8866: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8867: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8868: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8869: 			}
                   8870: 		}
1.1096    raeburn  8871:                 # if @advtools array contains items add then to the breadcrumbs
                   8872:                 if (@advtools > 0) {
                   8873:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8874:                 }
1.1272    raeburn  8875:                 my $menulink;
                   8876:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8877:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  8878:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  8879:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8880:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8881:                      (!$env{'request.role.adv'}))) {
                   8882:                     $menulink = 0;
                   8883:                 } else {
                   8884:                     undef($menulink);
                   8885:                 }
1.758     kaisler  8886: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8887: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8888: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8889:                 } else {
1.1272    raeburn  8890: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8891: 		}
1.320     albertel 8892:     }
1.315     albertel 8893:     return $result;
1.306     albertel 8894: }
                   8895: 
                   8896: sub end_page {
1.315     albertel 8897:     my ($args) = @_;
                   8898:     $env{'internal.end_page'}++;
1.330     albertel 8899:     my $result;
1.335     albertel 8900:     if ($args->{'discussion'}) {
                   8901: 	my ($target,$parser);
                   8902: 	if (ref($args->{'discussion'})) {
                   8903: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8904: 				$args->{'discussion'}{'parser'});
                   8905: 	}
                   8906: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8907:     }
1.330     albertel 8908:     if ($args->{'frameset'}) {
                   8909: 	$result .= '</frameset>';
                   8910:     } else {
1.635     raeburn  8911: 	$result .= &endbodytag($args);
1.330     albertel 8912:     }
1.1080    raeburn  8913:     unless ($args->{'notbody'}) {
                   8914:         $result .= "\n</html>";
                   8915:     }
1.330     albertel 8916: 
1.315     albertel 8917:     if ($args->{'js_ready'}) {
1.317     albertel 8918: 	$result = &js_ready($result);
1.315     albertel 8919:     }
1.335     albertel 8920: 
1.320     albertel 8921:     if ($args->{'html_encode'}) {
                   8922: 	$result = &html_encode($result);
                   8923:     }
1.335     albertel 8924: 
1.315     albertel 8925:     return $result;
                   8926: }
                   8927: 
1.1034    www      8928: sub wishlist_window {
                   8929:     return(<<'ENDWISHLIST');
1.1046    raeburn  8930: <script type="text/javascript">
1.1034    www      8931: // <![CDATA[
                   8932: // <!-- BEGIN LON-CAPA Internal
                   8933: function set_wishlistlink(title, path) {
                   8934:     if (!title) {
                   8935:         title = document.title;
                   8936:         title = title.replace(/^LON-CAPA /,'');
                   8937:     }
1.1175    raeburn  8938:     title = encodeURIComponent(title);
1.1203    raeburn  8939:     title = title.replace("'","\\\'");
1.1034    www      8940:     if (!path) {
                   8941:         path = location.pathname;
                   8942:     }
1.1175    raeburn  8943:     path = encodeURIComponent(path);
1.1203    raeburn  8944:     path = path.replace("'","\\\'");
1.1034    www      8945:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8946:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8947: }
                   8948: // END LON-CAPA Internal -->
                   8949: // ]]>
                   8950: </script>
                   8951: ENDWISHLIST
                   8952: }
                   8953: 
1.1030    www      8954: sub modal_window {
                   8955:     return(<<'ENDMODAL');
1.1046    raeburn  8956: <script type="text/javascript">
1.1030    www      8957: // <![CDATA[
                   8958: // <!-- BEGIN LON-CAPA Internal
                   8959: var modalWindow = {
                   8960: 	parent:"body",
                   8961: 	windowId:null,
                   8962: 	content:null,
                   8963: 	width:null,
                   8964: 	height:null,
                   8965: 	close:function()
                   8966: 	{
                   8967: 	        $(".LCmodal-window").remove();
                   8968: 	        $(".LCmodal-overlay").remove();
                   8969: 	},
                   8970: 	open:function()
                   8971: 	{
                   8972: 		var modal = "";
                   8973: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8974: 		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;\">";
                   8975: 		modal += this.content;
                   8976: 		modal += "</div>";	
                   8977: 
                   8978: 		$(this.parent).append(modal);
                   8979: 
                   8980: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8981: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8982: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8983: 	}
                   8984: };
1.1140    raeburn  8985: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8986: 	{
1.1266    raeburn  8987:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8988: 		modalWindow.windowId = "myModal";
                   8989: 		modalWindow.width = width;
                   8990: 		modalWindow.height = height;
1.1196    raeburn  8991: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8992: 		modalWindow.open();
1.1208    raeburn  8993: 	};
1.1030    www      8994: // END LON-CAPA Internal -->
                   8995: // ]]>
                   8996: </script>
                   8997: ENDMODAL
                   8998: }
                   8999: 
                   9000: sub modal_link {
1.1140    raeburn  9001:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9002:     unless ($width) { $width=480; }
                   9003:     unless ($height) { $height=400; }
1.1031    www      9004:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9005:     unless ($transparency) { $transparency='true'; }
                   9006: 
1.1074    raeburn  9007:     my $target_attr;
                   9008:     if (defined($target)) {
                   9009:         $target_attr = 'target="'.$target.'"';
                   9010:     }
                   9011:     return <<"ENDLINK";
1.1140    raeburn  9012: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  9013:            $linktext</a>
                   9014: ENDLINK
1.1030    www      9015: }
                   9016: 
1.1032    www      9017: sub modal_adhoc_script {
                   9018:     my ($funcname,$width,$height,$content)=@_;
                   9019:     return (<<ENDADHOC);
1.1046    raeburn  9020: <script type="text/javascript">
1.1032    www      9021: // <![CDATA[
                   9022:         var $funcname = function()
                   9023:         {
                   9024:                 modalWindow.windowId = "myModal";
                   9025:                 modalWindow.width = $width;
                   9026:                 modalWindow.height = $height;
                   9027:                 modalWindow.content = '$content';
                   9028:                 modalWindow.open();
                   9029:         };  
                   9030: // ]]>
                   9031: </script>
                   9032: ENDADHOC
                   9033: }
                   9034: 
1.1041    www      9035: sub modal_adhoc_inner {
                   9036:     my ($funcname,$width,$height,$content)=@_;
                   9037:     my $innerwidth=$width-20;
                   9038:     $content=&js_ready(
1.1140    raeburn  9039:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9040:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9041:                  $content.
1.1041    www      9042:                  &end_scrollbox().
1.1140    raeburn  9043:                  &end_page()
1.1041    www      9044:              );
                   9045:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   9046: }
                   9047: 
                   9048: sub modal_adhoc_window {
                   9049:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   9050:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   9051:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9052: }
                   9053: 
                   9054: sub modal_adhoc_launch {
                   9055:     my ($funcname,$width,$height,$content)=@_;
                   9056:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9057: <script type="text/javascript">
                   9058: // <![CDATA[
                   9059: $funcname();
                   9060: // ]]>
                   9061: </script>
                   9062: ENDLAUNCH
                   9063: }
                   9064: 
                   9065: sub modal_adhoc_close {
                   9066:     return (<<ENDCLOSE);
                   9067: <script type="text/javascript">
                   9068: // <![CDATA[
                   9069: modalWindow.close();
                   9070: // ]]>
                   9071: </script>
                   9072: ENDCLOSE
                   9073: }
                   9074: 
1.1038    www      9075: sub togglebox_script {
                   9076:    return(<<ENDTOGGLE);
                   9077: <script type="text/javascript"> 
                   9078: // <![CDATA[
                   9079: function LCtoggleDisplay(id,hidetext,showtext) {
                   9080:    link = document.getElementById(id + "link").childNodes[0];
                   9081:    with (document.getElementById(id).style) {
                   9082:       if (display == "none" ) {
                   9083:           display = "inline";
                   9084:           link.nodeValue = hidetext;
                   9085:         } else {
                   9086:           display = "none";
                   9087:           link.nodeValue = showtext;
                   9088:        }
                   9089:    }
                   9090: }
                   9091: // ]]>
                   9092: </script>
                   9093: ENDTOGGLE
                   9094: }
                   9095: 
1.1039    www      9096: sub start_togglebox {
                   9097:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9098:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9099:     unless ($showtext) { $showtext=&mt('show'); }
                   9100:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9101:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9102:     return &start_data_table().
                   9103:            &start_data_table_header_row().
                   9104:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9105:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9106:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9107:            &end_data_table_header_row().
                   9108:            '<tr id="'.$id.'" style="display:none""><td>';
                   9109: }
                   9110: 
                   9111: sub end_togglebox {
                   9112:     return '</td></tr>'.&end_data_table();
                   9113: }
                   9114: 
1.1041    www      9115: sub LCprogressbar_script {
1.1302    raeburn  9116:    my ($id,$number_to_do)=@_;
                   9117:    if ($number_to_do) {
                   9118:        return(<<ENDPROGRESS);
1.1041    www      9119: <script type="text/javascript">
                   9120: // <![CDATA[
1.1045    www      9121: \$('#progressbar$id').progressbar({
1.1041    www      9122:   value: 0,
                   9123:   change: function(event, ui) {
                   9124:     var newVal = \$(this).progressbar('option', 'value');
                   9125:     \$('.pblabel', this).text(LCprogressTxt);
                   9126:   }
                   9127: });
                   9128: // ]]>
                   9129: </script>
                   9130: ENDPROGRESS
1.1302    raeburn  9131:    } else {
                   9132:        return(<<ENDPROGRESS);
                   9133: <script type="text/javascript">
                   9134: // <![CDATA[
                   9135: \$('#progressbar$id').progressbar({
                   9136:   value: false,
                   9137:   create: function(event, ui) {
                   9138:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9139:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9140:   }
                   9141: });
                   9142: // ]]>
                   9143: </script>
                   9144: ENDPROGRESS
                   9145:    }
1.1041    www      9146: }
                   9147: 
                   9148: sub LCprogressbarUpdate_script {
                   9149:    return(<<ENDPROGRESSUPDATE);
                   9150: <style type="text/css">
                   9151: .ui-progressbar { position:relative; }
1.1302    raeburn  9152: .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      9153: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9154: </style>
                   9155: <script type="text/javascript">
                   9156: // <![CDATA[
1.1045    www      9157: var LCprogressTxt='---';
                   9158: 
1.1302    raeburn  9159: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9160:    LCprogressTxt=progresstext;
1.1302    raeburn  9161:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9162:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9163:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9164:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9165:    } else {
                   9166:        \$('#progressbar'+id).progressbar('value',percent);
                   9167:    }
1.1041    www      9168: }
                   9169: // ]]>
                   9170: </script>
                   9171: ENDPROGRESSUPDATE
                   9172: }
                   9173: 
1.1042    www      9174: my $LClastpercent;
1.1045    www      9175: my $LCidcnt;
                   9176: my $LCcurrentid;
1.1042    www      9177: 
1.1041    www      9178: sub LCprogressbar {
1.1302    raeburn  9179:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9180:     $LClastpercent=0;
1.1045    www      9181:     $LCidcnt++;
                   9182:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9183:     my ($starting,$content);
                   9184:     if ($number_to_do) {
                   9185:         $starting=&mt('Starting');
                   9186:         $content=(<<ENDPROGBAR);
                   9187: $preamble
1.1045    www      9188:   <div id="progressbar$LCcurrentid">
1.1041    www      9189:     <span class="pblabel">$starting</span>
                   9190:   </div>
                   9191: ENDPROGBAR
1.1302    raeburn  9192:     } else {
                   9193:         $starting=&mt('Loading...');
                   9194:         $LClastpercent='false';
                   9195:         $content=(<<ENDPROGBAR);
                   9196: $preamble
                   9197:   <div id="progressbar$LCcurrentid">
                   9198:       <div class="progress-label">$starting</div>
                   9199:   </div>
                   9200: ENDPROGBAR
                   9201:     }
                   9202:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9203: }
                   9204: 
                   9205: sub LCprogressbarUpdate {
1.1302    raeburn  9206:     my ($r,$val,$text,$number_to_do)=@_;
                   9207:     if ($number_to_do) {
                   9208:         unless ($val) { 
                   9209:             if ($LClastpercent) {
                   9210:                 $val=$LClastpercent;
                   9211:             } else {
                   9212:                 $val=0;
                   9213:             }
                   9214:         }
                   9215:         if ($val<0) { $val=0; }
                   9216:         if ($val>100) { $val=0; }
                   9217:         $LClastpercent=$val;
                   9218:         unless ($text) { $text=$val.'%'; }
                   9219:     } else {
                   9220:         $val = 'false';
1.1042    www      9221:     }
1.1041    www      9222:     $text=&js_ready($text);
1.1044    www      9223:     &r_print($r,<<ENDUPDATE);
1.1041    www      9224: <script type="text/javascript">
                   9225: // <![CDATA[
1.1302    raeburn  9226: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9227: // ]]>
                   9228: </script>
                   9229: ENDUPDATE
1.1035    www      9230: }
                   9231: 
1.1042    www      9232: sub LCprogressbarClose {
                   9233:     my ($r)=@_;
                   9234:     $LClastpercent=0;
1.1044    www      9235:     &r_print($r,<<ENDCLOSE);
1.1042    www      9236: <script type="text/javascript">
                   9237: // <![CDATA[
1.1045    www      9238: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9239: // ]]>
                   9240: </script>
                   9241: ENDCLOSE
1.1044    www      9242: }
                   9243: 
                   9244: sub r_print {
                   9245:     my ($r,$to_print)=@_;
                   9246:     if ($r) {
                   9247:       $r->print($to_print);
                   9248:       $r->rflush();
                   9249:     } else {
                   9250:       print($to_print);
                   9251:     }
1.1042    www      9252: }
                   9253: 
1.320     albertel 9254: sub html_encode {
                   9255:     my ($result) = @_;
                   9256: 
1.322     albertel 9257:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9258:     
                   9259:     return $result;
                   9260: }
1.1044    www      9261: 
1.317     albertel 9262: sub js_ready {
                   9263:     my ($result) = @_;
                   9264: 
1.323     albertel 9265:     $result =~ s/[\n\r]/ /xmsg;
                   9266:     $result =~ s/\\/\\\\/xmsg;
                   9267:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9268:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9269:     
                   9270:     return $result;
                   9271: }
                   9272: 
1.315     albertel 9273: sub validate_page {
                   9274:     if (  exists($env{'internal.start_page'})
1.316     albertel 9275: 	  &&     $env{'internal.start_page'} > 1) {
                   9276: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9277: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9278: 				 $ENV{'request.filename'});
1.315     albertel 9279:     }
                   9280:     if (  exists($env{'internal.end_page'})
1.316     albertel 9281: 	  &&     $env{'internal.end_page'} > 1) {
                   9282: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9283: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9284: 				 $env{'request.filename'});
1.315     albertel 9285:     }
                   9286:     if (     exists($env{'internal.start_page'})
                   9287: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9288: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9289: 				 $env{'request.filename'});
1.315     albertel 9290:     }
                   9291:     if (   ! exists($env{'internal.start_page'})
                   9292: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9293: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9294: 				 $env{'request.filename'});
1.315     albertel 9295:     }
1.306     albertel 9296: }
1.315     albertel 9297: 
1.996     www      9298: 
                   9299: sub start_scrollbox {
1.1140    raeburn  9300:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9301:     unless ($outerwidth) { $outerwidth='520px'; }
                   9302:     unless ($width) { $width='500px'; }
                   9303:     unless ($height) { $height='200px'; }
1.1075    raeburn  9304:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9305:     if ($id ne '') {
1.1140    raeburn  9306:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9307:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9308:     }
1.1075    raeburn  9309:     if ($bgcolor ne '') {
                   9310:         $tdcol = "background-color: $bgcolor;";
                   9311:     }
1.1137    raeburn  9312:     my $nicescroll_js;
                   9313:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9314:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9315:     }
                   9316:     return <<"END";
                   9317: $nicescroll_js
                   9318: 
                   9319: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9320: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9321: END
                   9322: }
                   9323: 
                   9324: sub end_scrollbox {
                   9325:     return '</div></td></tr></table>';
                   9326: }
                   9327: 
                   9328: sub nicescroll_javascript {
                   9329:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9330:     my %options;
                   9331:     if (ref($cursor) eq 'HASH') {
                   9332:         %options = %{$cursor};
                   9333:     }
                   9334:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9335:         $options{'railalign'} = 'left';
                   9336:     }
                   9337:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9338:         my $function  = &get_users_function();
                   9339:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9340:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9341:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9342:         }
1.1140    raeburn  9343:     }
                   9344:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9345:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9346:             $options{'cursoropacity'}='1.0';
                   9347:         }
1.1140    raeburn  9348:     } else {
                   9349:         $options{'cursoropacity'}='1.0';
                   9350:     }
                   9351:     if ($options{'cursorfixedheight'} eq 'none') {
                   9352:         delete($options{'cursorfixedheight'});
                   9353:     } else {
                   9354:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9355:     }
                   9356:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9357:         delete($options{'railoffset'});
                   9358:     }
                   9359:     my @niceoptions;
                   9360:     while (my($key,$value) = each(%options)) {
                   9361:         if ($value =~ /^\{.+\}$/) {
                   9362:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9363:         } else {
1.1140    raeburn  9364:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9365:         }
1.1140    raeburn  9366:     }
                   9367:     my $nicescroll_js = '
1.1137    raeburn  9368: $(document).ready(
1.1140    raeburn  9369:       function() {
                   9370:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9371:       }
1.1137    raeburn  9372: );
                   9373: ';
1.1140    raeburn  9374:     if ($framecheck) {
                   9375:         $nicescroll_js .= '
                   9376: function expand_div(caller) {
                   9377:     if (top === self) {
                   9378:         document.getElementById("'.$id.'").style.width = "auto";
                   9379:         document.getElementById("'.$id.'").style.height = "auto";
                   9380:     } else {
                   9381:         try {
                   9382:             if (parent.frames) {
                   9383:                 if (parent.frames.length > 1) {
                   9384:                     var framesrc = parent.frames[1].location.href;
                   9385:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9386:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9387:                         document.getElementById("'.$id.'").style.width = "auto";
                   9388:                         document.getElementById("'.$id.'").style.height = "auto";
                   9389:                     }
                   9390:                 }
                   9391:             }
                   9392:         } catch (e) {
                   9393:             return;
                   9394:         }
1.1137    raeburn  9395:     }
1.1140    raeburn  9396:     return;
1.996     www      9397: }
1.1140    raeburn  9398: ';
                   9399:     }
                   9400:     if ($needjsready) {
                   9401:         $nicescroll_js = '
                   9402: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9403:     } else {
                   9404:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9405:     }
                   9406:     return $nicescroll_js;
1.996     www      9407: }
                   9408: 
1.318     albertel 9409: sub simple_error_page {
1.1150    bisitz   9410:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  9411:     my %displayargs;
1.1151    raeburn  9412:     if (ref($args) eq 'HASH') {
                   9413:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  9414:         if ($args->{'only_body'}) {
                   9415:             $displayargs{'only_body'} = 1;
                   9416:         }
                   9417:         if ($args->{'no_nav_bar'}) {
                   9418:             $displayargs{'no_nav_bar'} = 1;
                   9419:         }
1.1151    raeburn  9420:     } else {
                   9421:         $msg = &mt($msg);
                   9422:     }
1.1150    bisitz   9423: 
1.318     albertel 9424:     my $page =
1.1304    raeburn  9425: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   9426: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9427: 	&Apache::loncommon::end_page();
                   9428:     if (ref($r)) {
                   9429: 	$r->print($page);
1.327     albertel 9430: 	return;
1.318     albertel 9431:     }
                   9432:     return $page;
                   9433: }
1.347     albertel 9434: 
                   9435: {
1.610     albertel 9436:     my @row_count;
1.961     onken    9437: 
                   9438:     sub start_data_table_count {
                   9439:         unshift(@row_count, 0);
                   9440:         return;
                   9441:     }
                   9442: 
                   9443:     sub end_data_table_count {
                   9444:         shift(@row_count);
                   9445:         return;
                   9446:     }
                   9447: 
1.347     albertel 9448:     sub start_data_table {
1.1018    raeburn  9449: 	my ($add_class,$id) = @_;
1.422     albertel 9450: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9451:         my $table_id;
                   9452:         if (defined($id)) {
                   9453:             $table_id = ' id="'.$id.'"';
                   9454:         }
1.961     onken    9455: 	&start_data_table_count();
1.1018    raeburn  9456: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9457:     }
                   9458: 
                   9459:     sub end_data_table {
1.961     onken    9460: 	&end_data_table_count();
1.389     albertel 9461: 	return '</table>'."\n";;
1.347     albertel 9462:     }
                   9463: 
                   9464:     sub start_data_table_row {
1.974     wenzelju 9465: 	my ($add_class, $id) = @_;
1.610     albertel 9466: 	$row_count[0]++;
                   9467: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9468: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9469:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9470:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9471:     }
1.471     banghart 9472:     
                   9473:     sub continue_data_table_row {
1.974     wenzelju 9474: 	my ($add_class, $id) = @_;
1.610     albertel 9475: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9476: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9477:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9478:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9479:     }
1.347     albertel 9480: 
                   9481:     sub end_data_table_row {
1.389     albertel 9482: 	return '</tr>'."\n";;
1.347     albertel 9483:     }
1.367     www      9484: 
1.421     albertel 9485:     sub start_data_table_empty_row {
1.707     bisitz   9486: #	$row_count[0]++;
1.421     albertel 9487: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9488:     }
                   9489: 
                   9490:     sub end_data_table_empty_row {
                   9491: 	return '</tr>'."\n";;
                   9492:     }
                   9493: 
1.367     www      9494:     sub start_data_table_header_row {
1.389     albertel 9495: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9496:     }
                   9497: 
                   9498:     sub end_data_table_header_row {
1.389     albertel 9499: 	return '</tr>'."\n";;
1.367     www      9500:     }
1.890     droeschl 9501: 
                   9502:     sub data_table_caption {
                   9503:         my $caption = shift;
                   9504:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9505:     }
1.347     albertel 9506: }
                   9507: 
1.548     albertel 9508: =pod
                   9509: 
                   9510: =item * &inhibit_menu_check($arg)
                   9511: 
                   9512: Checks for a inhibitmenu state and generates output to preserve it
                   9513: 
                   9514: Inputs:         $arg - can be any of
                   9515:                      - undef - in which case the return value is a string 
                   9516:                                to add  into arguments list of a uri
                   9517:                      - 'input' - in which case the return value is a HTML
                   9518:                                  <form> <input> field of type hidden to
                   9519:                                  preserve the value
                   9520:                      - a url - in which case the return value is the url with
                   9521:                                the neccesary cgi args added to preserve the
                   9522:                                inhibitmenu state
                   9523:                      - a ref to a url - no return value, but the string is
                   9524:                                         updated to include the neccessary cgi
                   9525:                                         args to preserve the inhibitmenu state
                   9526: 
                   9527: =cut
                   9528: 
                   9529: sub inhibit_menu_check {
                   9530:     my ($arg) = @_;
                   9531:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9532:     if ($arg eq 'input') {
                   9533: 	if ($env{'form.inhibitmenu'}) {
                   9534: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9535: 	} else {
                   9536: 	    return
                   9537: 	}
                   9538:     }
                   9539:     if ($env{'form.inhibitmenu'}) {
                   9540: 	if (ref($arg)) {
                   9541: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9542: 	} elsif ($arg eq '') {
                   9543: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9544: 	} else {
                   9545: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9546: 	}
                   9547:     }
                   9548:     if (!ref($arg)) {
                   9549: 	return $arg;
                   9550:     }
                   9551: }
                   9552: 
1.251     albertel 9553: ###############################################
1.182     matthew  9554: 
                   9555: =pod
                   9556: 
1.549     albertel 9557: =back
                   9558: 
                   9559: =head1 User Information Routines
                   9560: 
                   9561: =over 4
                   9562: 
1.405     albertel 9563: =item * &get_users_function()
1.182     matthew  9564: 
                   9565: Used by &bodytag to determine the current users primary role.
                   9566: Returns either 'student','coordinator','admin', or 'author'.
                   9567: 
                   9568: =cut
                   9569: 
                   9570: ###############################################
                   9571: sub get_users_function {
1.815     tempelho 9572:     my $function = 'norole';
1.818     tempelho 9573:     if ($env{'request.role'}=~/^(st)/) {
                   9574:         $function='student';
                   9575:     }
1.907     raeburn  9576:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9577:         $function='coordinator';
                   9578:     }
1.258     albertel 9579:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9580:         $function='admin';
                   9581:     }
1.826     bisitz   9582:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9583:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9584:         $function='author';
                   9585:     }
                   9586:     return $function;
1.54      www      9587: }
1.99      www      9588: 
                   9589: ###############################################
                   9590: 
1.233     raeburn  9591: =pod
                   9592: 
1.821     raeburn  9593: =item * &show_course()
                   9594: 
                   9595: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9596: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9597: 
                   9598: Inputs:
                   9599: None
                   9600: 
                   9601: Outputs:
                   9602: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9603: 
                   9604: =cut
                   9605: 
                   9606: ###############################################
                   9607: sub show_course {
                   9608:     my $course = !$env{'user.adv'};
                   9609:     if (!$env{'user.adv'}) {
                   9610:         foreach my $env (keys(%env)) {
                   9611:             next if ($env !~ m/^user\.priv\./);
                   9612:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9613:                 $course = 0;
                   9614:                 last;
                   9615:             }
                   9616:         }
                   9617:     }
                   9618:     return $course;
                   9619: }
                   9620: 
                   9621: ###############################################
                   9622: 
                   9623: =pod
                   9624: 
1.542     raeburn  9625: =item * &check_user_status()
1.274     raeburn  9626: 
                   9627: Determines current status of supplied role for a
                   9628: specific user. Roles can be active, previous or future.
                   9629: 
                   9630: Inputs: 
                   9631: user's domain, user's username, course's domain,
1.375     raeburn  9632: course's number, optional section ID.
1.274     raeburn  9633: 
                   9634: Outputs:
                   9635: role status: active, previous or future. 
                   9636: 
                   9637: =cut
                   9638: 
                   9639: sub check_user_status {
1.412     raeburn  9640:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9641:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9642:     my @uroles = keys(%userinfo);
1.274     raeburn  9643:     my $srchstr;
                   9644:     my $active_chk = 'none';
1.412     raeburn  9645:     my $now = time;
1.274     raeburn  9646:     if (@uroles > 0) {
1.908     raeburn  9647:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9648:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9649:         } else {
1.412     raeburn  9650:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9651:         }
                   9652:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9653:             my $role_end = 0;
                   9654:             my $role_start = 0;
                   9655:             $active_chk = 'active';
1.412     raeburn  9656:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9657:                 $role_end = $1;
                   9658:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9659:                     $role_start = $1;
1.274     raeburn  9660:                 }
                   9661:             }
                   9662:             if ($role_start > 0) {
1.412     raeburn  9663:                 if ($now < $role_start) {
1.274     raeburn  9664:                     $active_chk = 'future';
                   9665:                 }
                   9666:             }
                   9667:             if ($role_end > 0) {
1.412     raeburn  9668:                 if ($now > $role_end) {
1.274     raeburn  9669:                     $active_chk = 'previous';
                   9670:                 }
                   9671:             }
                   9672:         }
                   9673:     }
                   9674:     return $active_chk;
                   9675: }
                   9676: 
                   9677: ###############################################
                   9678: 
                   9679: =pod
                   9680: 
1.405     albertel 9681: =item * &get_sections()
1.233     raeburn  9682: 
                   9683: Determines all the sections for a course including
                   9684: sections with students and sections containing other roles.
1.419     raeburn  9685: Incoming parameters: 
                   9686: 
                   9687: 1. domain
                   9688: 2. course number 
                   9689: 3. reference to array containing roles for which sections should 
                   9690: be gathered (optional).
                   9691: 4. reference to array containing status types for which sections 
                   9692: should be gathered (optional).
                   9693: 
                   9694: If the third argument is undefined, sections are gathered for any role. 
                   9695: If the fourth argument is undefined, sections are gathered for any status.
                   9696: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9697:  
1.374     raeburn  9698: Returns section hash (keys are section IDs, values are
                   9699: number of users in each section), subject to the
1.419     raeburn  9700: optional roles filter, optional status filter 
1.233     raeburn  9701: 
                   9702: =cut
                   9703: 
                   9704: ###############################################
                   9705: sub get_sections {
1.419     raeburn  9706:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9707:     if (!defined($cdom) || !defined($cnum)) {
                   9708:         my $cid =  $env{'request.course.id'};
                   9709: 
                   9710: 	return if (!defined($cid));
                   9711: 
                   9712:         $cdom = $env{'course.'.$cid.'.domain'};
                   9713:         $cnum = $env{'course.'.$cid.'.num'};
                   9714:     }
                   9715: 
                   9716:     my %sectioncount;
1.419     raeburn  9717:     my $now = time;
1.240     albertel 9718: 
1.1118    raeburn  9719:     my $check_students = 1;
                   9720:     my $only_students = 0;
                   9721:     if (ref($possible_roles) eq 'ARRAY') {
                   9722:         if (grep(/^st$/,@{$possible_roles})) {
                   9723:             if (@{$possible_roles} == 1) {
                   9724:                 $only_students = 1;
                   9725:             }
                   9726:         } else {
                   9727:             $check_students = 0;
                   9728:         }
                   9729:     }
                   9730: 
                   9731:     if ($check_students) { 
1.276     albertel 9732: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9733: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9734: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9735:         my $start_index = &Apache::loncoursedata::CL_START();
                   9736:         my $end_index = &Apache::loncoursedata::CL_END();
                   9737:         my $status;
1.366     albertel 9738: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9739: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9740: 				                     $data->[$status_index],
                   9741:                                                      $data->[$start_index],
                   9742:                                                      $data->[$end_index]);
                   9743:             if ($stu_status eq 'Active') {
                   9744:                 $status = 'active';
                   9745:             } elsif ($end < $now) {
                   9746:                 $status = 'previous';
                   9747:             } elsif ($start > $now) {
                   9748:                 $status = 'future';
                   9749:             } 
                   9750: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9751:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9752:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9753: 		    $sectioncount{$section}++;
                   9754:                 }
1.240     albertel 9755: 	    }
                   9756: 	}
                   9757:     }
1.1118    raeburn  9758:     if ($only_students) {
                   9759:         return %sectioncount;
                   9760:     }
1.240     albertel 9761:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9762:     foreach my $user (sort(keys(%courseroles))) {
                   9763: 	if ($user !~ /^(\w{2})/) { next; }
                   9764: 	my ($role) = ($user =~ /^(\w{2})/);
                   9765: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9766: 	my ($section,$status);
1.240     albertel 9767: 	if ($role eq 'cr' &&
                   9768: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9769: 	    $section=$1;
                   9770: 	}
                   9771: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9772: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9773:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9774:         if ($end == -1 && $start == -1) {
                   9775:             next; #deleted role
                   9776:         }
                   9777:         if (!defined($possible_status)) { 
                   9778:             $sectioncount{$section}++;
                   9779:         } else {
                   9780:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9781:                 $status = 'active';
                   9782:             } elsif ($end < $now) {
                   9783:                 $status = 'future';
                   9784:             } elsif ($start > $now) {
                   9785:                 $status = 'previous';
                   9786:             }
                   9787:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9788:                 $sectioncount{$section}++;
                   9789:             }
                   9790:         }
1.233     raeburn  9791:     }
1.366     albertel 9792:     return %sectioncount;
1.233     raeburn  9793: }
                   9794: 
1.274     raeburn  9795: ###############################################
1.294     raeburn  9796: 
                   9797: =pod
1.405     albertel 9798: 
                   9799: =item * &get_course_users()
                   9800: 
1.275     raeburn  9801: Retrieves usernames:domains for users in the specified course
                   9802: with specific role(s), and access status. 
                   9803: 
                   9804: Incoming parameters:
1.277     albertel 9805: 1. course domain
                   9806: 2. course number
                   9807: 3. access status: users must have - either active, 
1.275     raeburn  9808: previous, future, or all.
1.277     albertel 9809: 4. reference to array of permissible roles
1.288     raeburn  9810: 5. reference to array of section restrictions (optional)
                   9811: 6. reference to results object (hash of hashes).
                   9812: 7. reference to optional userdata hash
1.609     raeburn  9813: 8. reference to optional statushash
1.630     raeburn  9814: 9. flag if privileged users (except those set to unhide in
                   9815:    course settings) should be excluded    
1.609     raeburn  9816: Keys of top level results hash are roles.
1.275     raeburn  9817: Keys of inner hashes are username:domain, with 
                   9818: values set to access type.
1.288     raeburn  9819: Optional userdata hash returns an array with arguments in the 
                   9820: same order as loncoursedata::get_classlist() for student data.
                   9821: 
1.609     raeburn  9822: Optional statushash returns
                   9823: 
1.288     raeburn  9824: Entries for end, start, section and status are blank because
                   9825: of the possibility of multiple values for non-student roles.
                   9826: 
1.275     raeburn  9827: =cut
1.405     albertel 9828: 
1.275     raeburn  9829: ###############################################
1.405     albertel 9830: 
1.275     raeburn  9831: sub get_course_users {
1.630     raeburn  9832:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9833:     my %idx = ();
1.419     raeburn  9834:     my %seclists;
1.288     raeburn  9835: 
                   9836:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9837:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9838:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9839:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9840:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9841:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9842:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9843:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9844: 
1.290     albertel 9845:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9846:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9847:         my $now = time;
1.277     albertel 9848:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9849:             my $match = 0;
1.412     raeburn  9850:             my $secmatch = 0;
1.419     raeburn  9851:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9852:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9853:             if ($section eq '') {
                   9854:                 $section = 'none';
                   9855:             }
1.291     albertel 9856:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9857:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9858:                     $secmatch = 1;
                   9859:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9860:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9861:                         $secmatch = 1;
                   9862:                     }
                   9863:                 } else {  
1.419     raeburn  9864: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9865: 		        $secmatch = 1;
                   9866:                     }
1.290     albertel 9867: 		}
1.412     raeburn  9868:                 if (!$secmatch) {
                   9869:                     next;
                   9870:                 }
1.419     raeburn  9871:             }
1.275     raeburn  9872:             if (defined($$types{'active'})) {
1.288     raeburn  9873:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9874:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9875:                     $match = 1;
1.275     raeburn  9876:                 }
                   9877:             }
                   9878:             if (defined($$types{'previous'})) {
1.609     raeburn  9879:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9880:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9881:                     $match = 1;
1.275     raeburn  9882:                 }
                   9883:             }
                   9884:             if (defined($$types{'future'})) {
1.609     raeburn  9885:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9886:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9887:                     $match = 1;
1.275     raeburn  9888:                 }
                   9889:             }
1.609     raeburn  9890:             if ($match) {
                   9891:                 push(@{$seclists{$student}},$section);
                   9892:                 if (ref($userdata) eq 'HASH') {
                   9893:                     $$userdata{$student} = $$classlist{$student};
                   9894:                 }
                   9895:                 if (ref($statushash) eq 'HASH') {
                   9896:                     $statushash->{$student}{'st'}{$section} = $status;
                   9897:                 }
1.288     raeburn  9898:             }
1.275     raeburn  9899:         }
                   9900:     }
1.412     raeburn  9901:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9902:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9903:         my $now = time;
1.609     raeburn  9904:         my %displaystatus = ( previous => 'Expired',
                   9905:                               active   => 'Active',
                   9906:                               future   => 'Future',
                   9907:                             );
1.1121    raeburn  9908:         my (%nothide,@possdoms);
1.630     raeburn  9909:         if ($hidepriv) {
                   9910:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9911:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9912:                 if ($user !~ /:/) {
                   9913:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9914:                 } else {
                   9915:                     $nothide{$user} = 1;
                   9916:                 }
                   9917:             }
1.1121    raeburn  9918:             my @possdoms = ($cdom);
                   9919:             if ($coursehash{'checkforpriv'}) {
                   9920:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9921:             }
1.630     raeburn  9922:         }
1.439     raeburn  9923:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9924:             my $match = 0;
1.412     raeburn  9925:             my $secmatch = 0;
1.439     raeburn  9926:             my $status;
1.412     raeburn  9927:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9928:             $user =~ s/:$//;
1.439     raeburn  9929:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9930:             if ($end == -1 || $start == -1) {
                   9931:                 next;
                   9932:             }
                   9933:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9934:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9935:                 my ($uname,$udom) = split(/:/,$user);
                   9936:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9937:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9938:                         $secmatch = 1;
                   9939:                     } elsif ($usec eq '') {
1.420     albertel 9940:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9941:                             $secmatch = 1;
                   9942:                         }
                   9943:                     } else {
                   9944:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9945:                             $secmatch = 1;
                   9946:                         }
                   9947:                     }
                   9948:                     if (!$secmatch) {
                   9949:                         next;
                   9950:                     }
1.288     raeburn  9951:                 }
1.419     raeburn  9952:                 if ($usec eq '') {
                   9953:                     $usec = 'none';
                   9954:                 }
1.275     raeburn  9955:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9956:                     if ($hidepriv) {
1.1121    raeburn  9957:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9958:                             (!$nothide{$uname.':'.$udom})) {
                   9959:                             next;
                   9960:                         }
                   9961:                     }
1.503     raeburn  9962:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9963:                         $status = 'previous';
                   9964:                     } elsif ($start > $now) {
                   9965:                         $status = 'future';
                   9966:                     } else {
                   9967:                         $status = 'active';
                   9968:                     }
1.277     albertel 9969:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9970:                         if ($status eq $type) {
1.420     albertel 9971:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9972:                                 push(@{$$users{$role}{$user}},$type);
                   9973:                             }
1.288     raeburn  9974:                             $match = 1;
                   9975:                         }
                   9976:                     }
1.419     raeburn  9977:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9978:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9979: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9980:                         }
1.420     albertel 9981:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9982:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9983:                         }
1.609     raeburn  9984:                         if (ref($statushash) eq 'HASH') {
                   9985:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9986:                         }
1.275     raeburn  9987:                     }
                   9988:                 }
                   9989:             }
                   9990:         }
1.290     albertel 9991:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9992:             if ((defined($cdom)) && (defined($cnum))) {
                   9993:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9994:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9995:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9996:                     next if ($owner eq '');
                   9997:                     my ($ownername,$ownerdom);
                   9998:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9999:                         $ownername = $1;
                   10000:                         $ownerdom = $2;
                   10001:                     } else {
                   10002:                         $ownername = $owner;
                   10003:                         $ownerdom = $cdom;
                   10004:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10005:                     }
                   10006:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10007:                     if (defined($userdata) && 
1.609     raeburn  10008: 			!exists($$userdata{$owner})) {
                   10009: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10010:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10011:                             push(@{$seclists{$owner}},'none');
                   10012:                         }
                   10013:                         if (ref($statushash) eq 'HASH') {
                   10014:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10015:                         }
1.290     albertel 10016: 		    }
1.279     raeburn  10017:                 }
                   10018:             }
                   10019:         }
1.419     raeburn  10020:         foreach my $user (keys(%seclists)) {
                   10021:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10022:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10023:         }
1.275     raeburn  10024:     }
                   10025:     return;
                   10026: }
                   10027: 
1.288     raeburn  10028: sub get_user_info {
                   10029:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10030:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10031: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10032:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10033:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10034:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10035:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10036:     return;
                   10037: }
1.275     raeburn  10038: 
1.472     raeburn  10039: ###############################################
                   10040: 
                   10041: =pod
                   10042: 
                   10043: =item * &get_user_quota()
                   10044: 
1.1134    raeburn  10045: Retrieves quota assigned for storage of user files.
                   10046: Default is to report quota for portfolio files.
1.472     raeburn  10047: 
                   10048: Incoming parameters:
                   10049: 1. user's username
                   10050: 2. user's domain
1.1134    raeburn  10051: 3. quota name - portfolio, author, or course
1.1136    raeburn  10052:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10053: 4. crstype - official, unofficial, textbook, placement or community, 
                   10054:    if quota name is course
1.472     raeburn  10055: 
                   10056: Returns:
1.1163    raeburn  10057: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10058: 2. (Optional) Type of setting: custom or default
                   10059:    (individually assigned or default for user's 
                   10060:    institutional status).
                   10061: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10062:    or student - types as defined in localenroll::inst_usertypes 
                   10063:    for user's domain, which determines default quota for user.
                   10064: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10065: 
                   10066: If a value has been stored in the user's environment, 
1.536     raeburn  10067: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10068: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10069: 
                   10070: =cut
                   10071: 
                   10072: ###############################################
                   10073: 
                   10074: 
                   10075: sub get_user_quota {
1.1136    raeburn  10076:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10077:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10078:     if (!defined($udom)) {
                   10079:         $udom = $env{'user.domain'};
                   10080:     }
                   10081:     if (!defined($uname)) {
                   10082:         $uname = $env{'user.name'};
                   10083:     }
                   10084:     if (($udom eq '' || $uname eq '') ||
                   10085:         ($udom eq 'public') && ($uname eq 'public')) {
                   10086:         $quota = 0;
1.536     raeburn  10087:         $quotatype = 'default';
                   10088:         $defquota = 0; 
1.472     raeburn  10089:     } else {
1.536     raeburn  10090:         my $inststatus;
1.1134    raeburn  10091:         if ($quotaname eq 'course') {
                   10092:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10093:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10094:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10095:             } else {
                   10096:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10097:                 $quota = $cenv{'internal.uploadquota'};
                   10098:             }
1.536     raeburn  10099:         } else {
1.1134    raeburn  10100:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10101:                 if ($quotaname eq 'author') {
                   10102:                     $quota = $env{'environment.authorquota'};
                   10103:                 } else {
                   10104:                     $quota = $env{'environment.portfolioquota'};
                   10105:                 }
                   10106:                 $inststatus = $env{'environment.inststatus'};
                   10107:             } else {
                   10108:                 my %userenv = 
                   10109:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10110:                                          'authorquota','inststatus'],$udom,$uname);
                   10111:                 my ($tmp) = keys(%userenv);
                   10112:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10113:                     if ($quotaname eq 'author') {
                   10114:                         $quota = $userenv{'authorquota'};
                   10115:                     } else {
                   10116:                         $quota = $userenv{'portfolioquota'};
                   10117:                     }
                   10118:                     $inststatus = $userenv{'inststatus'};
                   10119:                 } else {
                   10120:                     undef(%userenv);
                   10121:                 }
                   10122:             }
                   10123:         }
                   10124:         if ($quota eq '' || wantarray) {
                   10125:             if ($quotaname eq 'course') {
                   10126:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10127:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10128:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10129:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10130:                     $defquota = $domdefs{$crstype.'quota'};
                   10131:                 }
                   10132:                 if ($defquota eq '') {
                   10133:                     $defquota = 500;
                   10134:                 }
1.1134    raeburn  10135:             } else {
                   10136:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10137:             }
                   10138:             if ($quota eq '') {
                   10139:                 $quota = $defquota;
                   10140:                 $quotatype = 'default';
                   10141:             } else {
                   10142:                 $quotatype = 'custom';
                   10143:             }
1.472     raeburn  10144:         }
                   10145:     }
1.536     raeburn  10146:     if (wantarray) {
                   10147:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10148:     } else {
                   10149:         return $quota;
                   10150:     }
1.472     raeburn  10151: }
                   10152: 
                   10153: ###############################################
                   10154: 
                   10155: =pod
                   10156: 
                   10157: =item * &default_quota()
                   10158: 
1.536     raeburn  10159: Retrieves default quota assigned for storage of user portfolio files,
                   10160: given an (optional) user's institutional status.
1.472     raeburn  10161: 
                   10162: Incoming parameters:
1.1142    raeburn  10163: 
1.472     raeburn  10164: 1. domain
1.536     raeburn  10165: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10166:    status types (e.g., faculty, staff, student etc.)
                   10167:    which apply to the user for whom the default is being retrieved.
                   10168:    If the institutional status string in undefined, the domain
1.1134    raeburn  10169:    default quota will be returned.
                   10170: 3.  quota name - portfolio, author, or course
                   10171:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10172: 
                   10173: Returns:
1.1142    raeburn  10174: 
1.1163    raeburn  10175: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10176: 2. (Optional) institutional type which determined the value of the
                   10177:    default quota.
1.472     raeburn  10178: 
                   10179: If a value has been stored in the domain's configuration db,
                   10180: it will return that, otherwise it returns 20 (for backwards 
                   10181: compatibility with domains which have not set up a configuration
1.1163    raeburn  10182: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10183: 
1.536     raeburn  10184: If the user's status includes multiple types (e.g., staff and student),
                   10185: the largest default quota which applies to the user determines the
                   10186: default quota returned.
                   10187: 
1.472     raeburn  10188: =cut
                   10189: 
                   10190: ###############################################
                   10191: 
                   10192: 
                   10193: sub default_quota {
1.1134    raeburn  10194:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10195:     my ($defquota,$settingstatus);
                   10196:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10197:                                             ['quotas'],$udom);
1.1134    raeburn  10198:     my $key = 'defaultquota';
                   10199:     if ($quotaname eq 'author') {
                   10200:         $key = 'authorquota';
                   10201:     }
1.622     raeburn  10202:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10203:         if ($inststatus ne '') {
1.765     raeburn  10204:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10205:             foreach my $item (@statuses) {
1.1134    raeburn  10206:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10207:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10208:                         if ($defquota eq '') {
1.1134    raeburn  10209:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10210:                             $settingstatus = $item;
1.1134    raeburn  10211:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10212:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10213:                             $settingstatus = $item;
                   10214:                         }
                   10215:                     }
1.1134    raeburn  10216:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10217:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10218:                         if ($defquota eq '') {
                   10219:                             $defquota = $quotahash{'quotas'}{$item};
                   10220:                             $settingstatus = $item;
                   10221:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10222:                             $defquota = $quotahash{'quotas'}{$item};
                   10223:                             $settingstatus = $item;
                   10224:                         }
1.536     raeburn  10225:                     }
                   10226:                 }
                   10227:             }
                   10228:         }
                   10229:         if ($defquota eq '') {
1.1134    raeburn  10230:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10231:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10232:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10233:                 $defquota = $quotahash{'quotas'}{'default'};
                   10234:             }
1.536     raeburn  10235:             $settingstatus = 'default';
1.1139    raeburn  10236:             if ($defquota eq '') {
                   10237:                 if ($quotaname eq 'author') {
                   10238:                     $defquota = 500;
                   10239:                 }
                   10240:             }
1.536     raeburn  10241:         }
                   10242:     } else {
                   10243:         $settingstatus = 'default';
1.1134    raeburn  10244:         if ($quotaname eq 'author') {
                   10245:             $defquota = 500;
                   10246:         } else {
                   10247:             $defquota = 20;
                   10248:         }
1.536     raeburn  10249:     }
                   10250:     if (wantarray) {
                   10251:         return ($defquota,$settingstatus);
1.472     raeburn  10252:     } else {
1.536     raeburn  10253:         return $defquota;
1.472     raeburn  10254:     }
                   10255: }
                   10256: 
1.1135    raeburn  10257: ###############################################
                   10258: 
                   10259: =pod
                   10260: 
1.1136    raeburn  10261: =item * &excess_filesize_warning()
1.1135    raeburn  10262: 
                   10263: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10264: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10265: space to be exceeded.
1.1136    raeburn  10266: 
                   10267: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10268: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10269: 
1.1165    raeburn  10270: Inputs: 7 
1.1136    raeburn  10271: 1. username or coursenum
1.1135    raeburn  10272: 2. domain
1.1136    raeburn  10273: 3. context ('author' or 'course')
1.1135    raeburn  10274: 4. filename of file for which action is being requested
                   10275: 5. filesize (kB) of file
                   10276: 6. action being taken: copy or upload.
1.1237    raeburn  10277: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10278: 
                   10279: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10280:          otherwise return null.
                   10281: 
                   10282: =back
1.1135    raeburn  10283: 
                   10284: =cut
                   10285: 
1.1136    raeburn  10286: sub excess_filesize_warning {
1.1165    raeburn  10287:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10288:     my $current_disk_usage = 0;
1.1165    raeburn  10289:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10290:     if ($context eq 'author') {
                   10291:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10292:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10293:     } else {
                   10294:         foreach my $subdir ('docs','supplemental') {
                   10295:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10296:         }
                   10297:     }
1.1135    raeburn  10298:     $disk_quota = int($disk_quota * 1000);
                   10299:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10300:         return '<p class="LC_warning">'.
1.1135    raeburn  10301:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10302:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10303:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10304:                             $disk_quota,$current_disk_usage).
                   10305:                '</p>';
                   10306:     }
                   10307:     return;
                   10308: }
                   10309: 
                   10310: ###############################################
                   10311: 
                   10312: 
1.1136    raeburn  10313: 
                   10314: 
1.384     raeburn  10315: sub get_secgrprole_info {
                   10316:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10317:     my %sections_count = &get_sections($cdom,$cnum);
                   10318:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10319:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10320:     my @groups = sort(keys(%curr_groups));
                   10321:     my $allroles = [];
                   10322:     my $rolehash;
                   10323:     my $accesshash = {
                   10324:                      active => 'Currently has access',
                   10325:                      future => 'Will have future access',
                   10326:                      previous => 'Previously had access',
                   10327:                   };
                   10328:     if ($needroles) {
                   10329:         $rolehash = {'all' => 'all'};
1.385     albertel 10330:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10331: 	if (&Apache::lonnet::error(%user_roles)) {
                   10332: 	    undef(%user_roles);
                   10333: 	}
                   10334:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10335:             my ($role)=split(/\:/,$item,2);
                   10336:             if ($role eq 'cr') { next; }
                   10337:             if ($role =~ /^cr/) {
                   10338:                 $$rolehash{$role} = (split('/',$role))[3];
                   10339:             } else {
                   10340:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10341:             }
                   10342:         }
                   10343:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10344:             push(@{$allroles},$key);
                   10345:         }
                   10346:         push (@{$allroles},'st');
                   10347:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10348:     }
                   10349:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10350: }
                   10351: 
1.555     raeburn  10352: sub user_picker {
1.1279    raeburn  10353:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10354:     my $currdom = $dom;
1.1253    raeburn  10355:     my @alldoms = &Apache::lonnet::all_domains();
                   10356:     if (@alldoms == 1) {
                   10357:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10358:                                                ['directorysrch'],$alldoms[0]);
                   10359:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10360:         my $showdom = $domdesc;
                   10361:         if ($showdom eq '') {
                   10362:             $showdom = $dom;
                   10363:         }
                   10364:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10365:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10366:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10367:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10368:             }
                   10369:         }
                   10370:     }
1.555     raeburn  10371:     my %curr_selected = (
                   10372:                         srchin => 'dom',
1.580     raeburn  10373:                         srchby => 'lastname',
1.555     raeburn  10374:                       );
                   10375:     my $srchterm;
1.625     raeburn  10376:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10377:         if ($srch->{'srchby'} ne '') {
                   10378:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10379:         }
                   10380:         if ($srch->{'srchin'} ne '') {
                   10381:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10382:         }
                   10383:         if ($srch->{'srchtype'} ne '') {
                   10384:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10385:         }
                   10386:         if ($srch->{'srchdomain'} ne '') {
                   10387:             $currdom = $srch->{'srchdomain'};
                   10388:         }
                   10389:         $srchterm = $srch->{'srchterm'};
                   10390:     }
1.1222    damieng  10391:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10392:                     'usr'       => 'Search criteria',
1.563     raeburn  10393:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10394:                     'uname'     => 'username',
                   10395:                     'lastname'  => 'last name',
1.555     raeburn  10396:                     'lastfirst' => 'last name, first name',
1.558     albertel 10397:                     'crs'       => 'in this course',
1.576     raeburn  10398:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10399:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10400:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10401:                     'exact'     => 'is',
                   10402:                     'contains'  => 'contains',
1.569     raeburn  10403:                     'begins'    => 'begins with',
1.1222    damieng  10404:                                        );
                   10405:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10406:                     'youm'      => "You must include some text to search for.",
                   10407:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10408:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10409:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10410:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10411:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10412:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10413:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10414:                                        );
1.1222    damieng  10415:     &html_escape(\%html_lt);
                   10416:     &js_escape(\%js_lt);
1.1255    raeburn  10417:     my $domform;
1.1277    raeburn  10418:     my $allow_blank = 1;
1.1255    raeburn  10419:     if ($fixeddom) {
1.1277    raeburn  10420:         $allow_blank = 0;
                   10421:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10422:     } else {
1.1287    raeburn  10423:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  10424:         my ($trusted,$untrusted);
1.1287    raeburn  10425:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  10426:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  10427:         } elsif ($context eq 'author') {
1.1288    raeburn  10428:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  10429:         } elsif ($context eq 'domain') {
1.1288    raeburn  10430:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  10431:         }
1.1288    raeburn  10432:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  10433:     }
1.563     raeburn  10434:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10435: 
                   10436:     my @srchins = ('crs','dom','alc','instd');
                   10437: 
                   10438:     foreach my $option (@srchins) {
                   10439:         # FIXME 'alc' option unavailable until 
                   10440:         #       loncreateuser::print_user_query_page()
                   10441:         #       has been completed.
                   10442:         next if ($option eq 'alc');
1.880     raeburn  10443:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10444:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10445:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10446:         if ($curr_selected{'srchin'} eq $option) {
                   10447:             $srchinsel .= ' 
1.1222    damieng  10448:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10449:         } else {
                   10450:             $srchinsel .= '
1.1222    damieng  10451:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10452:         }
1.555     raeburn  10453:     }
1.563     raeburn  10454:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10455: 
                   10456:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10457:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10458:         if ($curr_selected{'srchby'} eq $option) {
                   10459:             $srchbysel .= '
1.1222    damieng  10460:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10461:         } else {
                   10462:             $srchbysel .= '
1.1222    damieng  10463:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10464:          }
                   10465:     }
                   10466:     $srchbysel .= "\n  </select>\n";
                   10467: 
                   10468:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10469:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10470:         if ($curr_selected{'srchtype'} eq $option) {
                   10471:             $srchtypesel .= '
1.1222    damieng  10472:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10473:         } else {
                   10474:             $srchtypesel .= '
1.1222    damieng  10475:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10476:         }
                   10477:     }
                   10478:     $srchtypesel .= "\n  </select>\n";
                   10479: 
1.558     albertel 10480:     my ($newuserscript,$new_user_create);
1.994     raeburn  10481:     my $context_dom = $env{'request.role.domain'};
                   10482:     if ($context eq 'requestcrs') {
                   10483:         if ($env{'form.coursedom'} ne '') { 
                   10484:             $context_dom = $env{'form.coursedom'};
                   10485:         }
                   10486:     }
1.556     raeburn  10487:     if ($forcenewuser) {
1.576     raeburn  10488:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10489:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10490:                 if ($cancreate) {
                   10491:                     $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>';
                   10492:                 } else {
1.799     bisitz   10493:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10494:                     my %usertypetext = (
                   10495:                         official   => 'institutional',
                   10496:                         unofficial => 'non-institutional',
                   10497:                     );
1.799     bisitz   10498:                     $new_user_create = '<p class="LC_warning">'
                   10499:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10500:                                       .' '
                   10501:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10502:                                           ,'<a href="'.$helplink.'">','</a>')
                   10503:                                       .'</p><br />';
1.627     raeburn  10504:                 }
1.576     raeburn  10505:             }
                   10506:         }
                   10507: 
1.556     raeburn  10508:         $newuserscript = <<"ENDSCRIPT";
                   10509: 
1.570     raeburn  10510: function setSearch(createnew,callingForm) {
1.556     raeburn  10511:     if (createnew == 1) {
1.570     raeburn  10512:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10513:             if (callingForm.srchby.options[i].value == 'uname') {
                   10514:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10515:             }
                   10516:         }
1.570     raeburn  10517:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10518:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10519: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10520:             }
                   10521:         }
1.570     raeburn  10522:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10523:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10524:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10525:             }
                   10526:         }
1.570     raeburn  10527:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10528:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10529:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10530:             }
                   10531:         }
                   10532:     }
                   10533: }
                   10534: ENDSCRIPT
1.558     albertel 10535: 
1.556     raeburn  10536:     }
                   10537: 
1.555     raeburn  10538:     my $output = <<"END_BLOCK";
1.556     raeburn  10539: <script type="text/javascript">
1.824     bisitz   10540: // <![CDATA[
1.570     raeburn  10541: function validateEntry(callingForm) {
1.558     albertel 10542: 
1.556     raeburn  10543:     var checkok = 1;
1.558     albertel 10544:     var srchin;
1.570     raeburn  10545:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10546: 	if ( callingForm.srchin[i].checked ) {
                   10547: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10548: 	}
                   10549:     }
                   10550: 
1.570     raeburn  10551:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10552:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10553:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10554:     var srchterm =  callingForm.srchterm.value;
                   10555:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10556:     var msg = "";
                   10557: 
                   10558:     if (srchterm == "") {
                   10559:         checkok = 0;
1.1222    damieng  10560:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10561:     }
                   10562: 
1.569     raeburn  10563:     if (srchtype== 'begins') {
                   10564:         if (srchterm.length < 2) {
                   10565:             checkok = 0;
1.1222    damieng  10566:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10567:         }
                   10568:     }
                   10569: 
1.556     raeburn  10570:     if (srchtype== 'contains') {
                   10571:         if (srchterm.length < 3) {
                   10572:             checkok = 0;
1.1222    damieng  10573:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10574:         }
                   10575:     }
                   10576:     if (srchin == 'instd') {
                   10577:         if (srchdomain == '') {
                   10578:             checkok = 0;
1.1222    damieng  10579:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10580:         }
                   10581:     }
                   10582:     if (srchin == 'dom') {
                   10583:         if (srchdomain == '') {
                   10584:             checkok = 0;
1.1222    damieng  10585:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10586:         }
                   10587:     }
                   10588:     if (srchby == 'lastfirst') {
                   10589:         if (srchterm.indexOf(",") == -1) {
                   10590:             checkok = 0;
1.1222    damieng  10591:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10592:         }
                   10593:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10594:             checkok = 0;
1.1222    damieng  10595:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10596:         }
                   10597:     }
                   10598:     if (checkok == 0) {
1.1222    damieng  10599:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10600:         return;
                   10601:     }
                   10602:     if (checkok == 1) {
1.570     raeburn  10603:         callingForm.submit();
1.556     raeburn  10604:     }
                   10605: }
                   10606: 
                   10607: $newuserscript
                   10608: 
1.824     bisitz   10609: // ]]>
1.556     raeburn  10610: </script>
1.558     albertel 10611: 
                   10612: $new_user_create
                   10613: 
1.555     raeburn  10614: END_BLOCK
1.558     albertel 10615: 
1.876     raeburn  10616:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10617:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10618:                $domform.
                   10619:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10620:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10621:                $srchbysel.
                   10622:                $srchtypesel. 
                   10623:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10624:                $srchinsel.
                   10625:                &Apache::lonhtmlcommon::row_closure(1). 
                   10626:                &Apache::lonhtmlcommon::end_pick_box().
                   10627:                '<br />';
1.1253    raeburn  10628:     return ($output,1);
1.555     raeburn  10629: }
                   10630: 
1.612     raeburn  10631: sub user_rule_check {
1.615     raeburn  10632:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10633:     my ($response,%inst_response);
1.612     raeburn  10634:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10635:         if (keys(%{$usershash}) > 1) {
                   10636:             my (%by_username,%by_id,%userdoms);
                   10637:             my $checkid; 
                   10638:             if (ref($checks) eq 'HASH') {
                   10639:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10640:                     $checkid = 1;
                   10641:                 }
                   10642:             }
                   10643:             foreach my $user (keys(%{$usershash})) {
                   10644:                 my ($uname,$udom) = split(/:/,$user);
                   10645:                 if ($checkid) {
                   10646:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10647:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10648:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10649:                             $userdoms{$udom} = 1;
1.1227    raeburn  10650:                             if (ref($inst_results) eq 'HASH') {
                   10651:                                 $inst_results->{$uname.':'.$udom} = {};
                   10652:                             }
1.1226    raeburn  10653:                         }
                   10654:                     }
                   10655:                 } else {
                   10656:                     $by_username{$udom}{$uname} = 1;
                   10657:                     $userdoms{$udom} = 1;
1.1227    raeburn  10658:                     if (ref($inst_results) eq 'HASH') {
                   10659:                         $inst_results->{$uname.':'.$udom} = {};
                   10660:                     }
1.1226    raeburn  10661:                 }
                   10662:             }
                   10663:             foreach my $udom (keys(%userdoms)) {
                   10664:                 if (!$got_rules->{$udom}) {
                   10665:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10666:                                                              ['usercreation'],$udom);
                   10667:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10668:                         foreach my $item ('username','id') {
                   10669:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10670:                                 $$curr_rules{$udom}{$item} =
                   10671:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10672:                             }
                   10673:                         }
                   10674:                     }
                   10675:                     $got_rules->{$udom} = 1;
                   10676:                 }
1.612     raeburn  10677:             }
1.1226    raeburn  10678:             if ($checkid) {
                   10679:                 foreach my $udom (keys(%by_id)) {
                   10680:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10681:                     if ($outcome eq 'ok') {
1.1227    raeburn  10682:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10683:                             my $uname = $by_id{$udom}{$id};
                   10684:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10685:                         }
1.1226    raeburn  10686:                         if (ref($results) eq 'HASH') {
                   10687:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10688:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10689:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10690:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10691:                                 }
1.1226    raeburn  10692:                             }
                   10693:                         }
                   10694:                     }
1.612     raeburn  10695:                 }
1.615     raeburn  10696:             } else {
1.1226    raeburn  10697:                 foreach my $udom (keys(%by_username)) {
                   10698:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10699:                     if ($outcome eq 'ok') {
1.1227    raeburn  10700:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10701:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10702:                         }
1.1226    raeburn  10703:                         if (ref($results) eq 'HASH') {
                   10704:                             foreach my $uname (keys(%{$results})) {
                   10705:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10706:                             }
                   10707:                         }
                   10708:                     }
                   10709:                 }
1.612     raeburn  10710:             }
1.1226    raeburn  10711:         } elsif (keys(%{$usershash}) == 1) {
                   10712:             my $user = (keys(%{$usershash}))[0];
                   10713:             my ($uname,$udom) = split(/:/,$user);
                   10714:             if (($udom ne '') && ($uname ne '')) {
                   10715:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10716:                     if (ref($checks) eq 'HASH') {
                   10717:                         if (defined($checks->{'username'})) {
                   10718:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10719:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10720:                         } elsif (defined($checks->{'id'})) {
                   10721:                             if ($usershash->{$user}->{'id'} ne '') {
                   10722:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10723:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10724:                                                                   $usershash->{$user}->{'id'});
                   10725:                             } else {
                   10726:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10727:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10728:                             }
1.585     raeburn  10729:                         }
1.1226    raeburn  10730:                     } else {
                   10731:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10732:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10733:                        return;
                   10734:                     }
                   10735:                     if (!$got_rules->{$udom}) {
                   10736:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10737:                                                                  ['usercreation'],$udom);
                   10738:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10739:                             foreach my $item ('username','id') {
                   10740:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10741:                                    $$curr_rules{$udom}{$item} = 
                   10742:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10743:                                 }
                   10744:                             }
                   10745:                         }
                   10746:                         $got_rules->{$udom} = 1;
1.585     raeburn  10747:                     }
                   10748:                 }
1.1226    raeburn  10749:             } else {
                   10750:                 return;
                   10751:             }
                   10752:         } else {
                   10753:             return;
                   10754:         }
                   10755:         foreach my $user (keys(%{$usershash})) {
                   10756:             my ($uname,$udom) = split(/:/,$user);
                   10757:             next if (($udom eq '') || ($uname eq ''));
                   10758:             my $id;
1.1227    raeburn  10759:             if (ref($inst_results) eq 'HASH') {
                   10760:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10761:                     $id = $inst_results->{$user}->{'id'};
                   10762:                 }
                   10763:             }
                   10764:             if ($id eq '') { 
                   10765:                 if (ref($usershash->{$user})) {
                   10766:                     $id = $usershash->{$user}->{'id'};
                   10767:                 }
1.585     raeburn  10768:             }
1.612     raeburn  10769:             foreach my $item (keys(%{$checks})) {
                   10770:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10771:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10772:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10773:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10774:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10775:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10776:                                 if ($rule_check{$rule}) {
                   10777:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10778:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10779:                                         if (ref($inst_results) eq 'HASH') {
                   10780:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10781:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10782:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10783:                                                 } elsif ($item eq 'id') {
                   10784:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10785:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10786:                                                     }
1.615     raeburn  10787:                                                 }
1.612     raeburn  10788:                                             }
                   10789:                                         }
1.615     raeburn  10790:                                     }
                   10791:                                     last;
1.585     raeburn  10792:                                 }
                   10793:                             }
                   10794:                         }
                   10795:                     }
                   10796:                 }
                   10797:             }
                   10798:         }
                   10799:     }
1.612     raeburn  10800:     return;
                   10801: }
                   10802: 
                   10803: sub user_rule_formats {
                   10804:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10805:     my %text = ( 
                   10806:                  'username' => 'Usernames',
                   10807:                  'id'       => 'IDs',
                   10808:                );
                   10809:     my $output;
                   10810:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10811:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10812:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10813:             $output = '<br />'.
                   10814:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10815:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10816:                       ' <ul>';
1.612     raeburn  10817:             foreach my $rule (@{$ruleorder}) {
                   10818:                 if (ref($curr_rules) eq 'ARRAY') {
                   10819:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10820:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10821:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10822:                                         $rules->{$rule}{'desc'}.'</li>';
                   10823:                         }
                   10824:                     }
                   10825:                 }
                   10826:             }
                   10827:             $output .= '</ul>';
                   10828:         }
                   10829:     }
                   10830:     return $output;
                   10831: }
                   10832: 
                   10833: sub instrule_disallow_msg {
1.615     raeburn  10834:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10835:     my $response;
                   10836:     my %text = (
                   10837:                   item   => 'username',
                   10838:                   items  => 'usernames',
                   10839:                   match  => 'matches',
                   10840:                   do     => 'does',
                   10841:                   action => 'a username',
                   10842:                   one    => 'one',
                   10843:                );
                   10844:     if ($count > 1) {
                   10845:         $text{'item'} = 'usernames';
                   10846:         $text{'match'} ='match';
                   10847:         $text{'do'} = 'do';
                   10848:         $text{'action'} = 'usernames',
                   10849:         $text{'one'} = 'ones';
                   10850:     }
                   10851:     if ($checkitem eq 'id') {
                   10852:         $text{'items'} = 'IDs';
                   10853:         $text{'item'} = 'ID';
                   10854:         $text{'action'} = 'an ID';
1.615     raeburn  10855:         if ($count > 1) {
                   10856:             $text{'item'} = 'IDs';
                   10857:             $text{'action'} = 'IDs';
                   10858:         }
1.612     raeburn  10859:     }
1.674     bisitz   10860:     $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  10861:     if ($mode eq 'upload') {
                   10862:         if ($checkitem eq 'username') {
                   10863:             $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'}.");
                   10864:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10865:             $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  10866:         }
1.669     raeburn  10867:     } elsif ($mode eq 'selfcreate') {
                   10868:         if ($checkitem eq 'id') {
                   10869:             $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.");
                   10870:         }
1.615     raeburn  10871:     } else {
                   10872:         if ($checkitem eq 'username') {
                   10873:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10874:         } elsif ($checkitem eq 'id') {
                   10875:             $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.");
                   10876:         }
1.612     raeburn  10877:     }
                   10878:     return $response;
1.585     raeburn  10879: }
                   10880: 
1.624     raeburn  10881: sub personal_data_fieldtitles {
                   10882:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10883:                         id => 'Student/Employee ID',
                   10884:                         permanentemail => 'E-mail address',
                   10885:                         lastname => 'Last Name',
                   10886:                         firstname => 'First Name',
                   10887:                         middlename => 'Middle Name',
                   10888:                         generation => 'Generation',
                   10889:                         gen => 'Generation',
1.765     raeburn  10890:                         inststatus => 'Affiliation',
1.624     raeburn  10891:                    );
                   10892:     return %fieldtitles;
                   10893: }
                   10894: 
1.642     raeburn  10895: sub sorted_inst_types {
                   10896:     my ($dom) = @_;
1.1185    raeburn  10897:     my ($usertypes,$order);
                   10898:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10899:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10900:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10901:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10902:     } else {
                   10903:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10904:     }
1.642     raeburn  10905:     my $othertitle = &mt('All users');
                   10906:     if ($env{'request.course.id'}) {
1.668     raeburn  10907:         $othertitle  = &mt('Any users');
1.642     raeburn  10908:     }
                   10909:     my @types;
                   10910:     if (ref($order) eq 'ARRAY') {
                   10911:         @types = @{$order};
                   10912:     }
                   10913:     if (@types == 0) {
                   10914:         if (ref($usertypes) eq 'HASH') {
                   10915:             @types = sort(keys(%{$usertypes}));
                   10916:         }
                   10917:     }
                   10918:     if (keys(%{$usertypes}) > 0) {
                   10919:         $othertitle = &mt('Other users');
                   10920:     }
                   10921:     return ($othertitle,$usertypes,\@types);
                   10922: }
                   10923: 
1.645     raeburn  10924: sub get_institutional_codes {
                   10925:     my ($settings,$allcourses,$LC_code) = @_;
                   10926: # Get complete list of course sections to update
                   10927:     my @currsections = ();
                   10928:     my @currxlists = ();
                   10929:     my $coursecode = $$settings{'internal.coursecode'};
                   10930: 
                   10931:     if ($$settings{'internal.sectionnums'} ne '') {
                   10932:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10933:     }
                   10934: 
                   10935:     if ($$settings{'internal.crosslistings'} ne '') {
                   10936:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10937:     }
                   10938: 
                   10939:     if (@currxlists > 0) {
                   10940:         foreach (@currxlists) {
                   10941:             if (m/^([^:]+):(\w*)$/) {
                   10942:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10943:                     push(@{$allcourses},$1);
1.645     raeburn  10944:                     $$LC_code{$1} = $2;
                   10945:                 }
                   10946:             }
                   10947:         }
                   10948:     }
                   10949:  
                   10950:     if (@currsections > 0) {
                   10951:         foreach (@currsections) {
                   10952:             if (m/^(\w+):(\w*)$/) {
                   10953:                 my $sec = $coursecode.$1;
                   10954:                 my $lc_sec = $2;
                   10955:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10956:                     push(@{$allcourses},$sec);
1.645     raeburn  10957:                     $$LC_code{$sec} = $lc_sec;
                   10958:                 }
                   10959:             }
                   10960:         }
                   10961:     }
                   10962:     return;
                   10963: }
                   10964: 
1.971     raeburn  10965: sub get_standard_codeitems {
                   10966:     return ('Year','Semester','Department','Number','Section');
                   10967: }
                   10968: 
1.112     bowersj2 10969: =pod
                   10970: 
1.780     raeburn  10971: =head1 Slot Helpers
                   10972: 
                   10973: =over 4
                   10974: 
                   10975: =item * sorted_slots()
                   10976: 
1.1040    raeburn  10977: Sorts an array of slot names in order of an optional sort key,
                   10978: default sort is by slot start time (earliest first). 
1.780     raeburn  10979: 
                   10980: Inputs:
                   10981: 
                   10982: =over 4
                   10983: 
                   10984: slotsarr  - Reference to array of unsorted slot names.
                   10985: 
                   10986: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10987: 
1.1040    raeburn  10988: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10989: 
1.549     albertel 10990: =back
                   10991: 
1.780     raeburn  10992: Returns:
                   10993: 
                   10994: =over 4
                   10995: 
1.1040    raeburn  10996: sorted   - An array of slot names sorted by a specified sort key 
                   10997:            (default sort key is start time of the slot).
1.780     raeburn  10998: 
                   10999: =back
                   11000: 
                   11001: =cut
                   11002: 
                   11003: 
                   11004: sub sorted_slots {
1.1040    raeburn  11005:     my ($slotsarr,$slots,$sortkey) = @_;
                   11006:     if ($sortkey eq '') {
                   11007:         $sortkey = 'starttime';
                   11008:     }
1.780     raeburn  11009:     my @sorted;
                   11010:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11011:         @sorted =
                   11012:             sort {
                   11013:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11014:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11015:                      }
                   11016:                      if (ref($slots->{$a})) { return -1;}
                   11017:                      if (ref($slots->{$b})) { return 1;}
                   11018:                      return 0;
                   11019:                  } @{$slotsarr};
                   11020:     }
                   11021:     return @sorted;
                   11022: }
                   11023: 
1.1040    raeburn  11024: =pod
                   11025: 
                   11026: =item * get_future_slots()
                   11027: 
                   11028: Inputs:
                   11029: 
                   11030: =over 4
                   11031: 
                   11032: cnum - course number
                   11033: 
                   11034: cdom - course domain
                   11035: 
                   11036: now - current UNIX time
                   11037: 
                   11038: symb - optional symb
                   11039: 
                   11040: =back
                   11041: 
                   11042: Returns:
                   11043: 
                   11044: =over 4
                   11045: 
                   11046: sorted_reservable - ref to array of student_schedulable slots currently 
                   11047:                     reservable, ordered by end date of reservation period.
                   11048: 
                   11049: reservable_now - ref to hash of student_schedulable slots currently
                   11050:                  reservable.
                   11051: 
                   11052:     Keys in inner hash are:
                   11053:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11054:     (b) endreserve: end date of reservation period.
                   11055:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11056:         selected.
1.1040    raeburn  11057: 
                   11058: sorted_future - ref to array of student_schedulable slots reservable in
                   11059:                 the future, ordered by start date of reservation period.
                   11060: 
                   11061: future_reservable - ref to hash of student_schedulable slots reservable
                   11062:                     in the future.
                   11063: 
                   11064:     Keys in inner hash are:
                   11065:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11066:     (b) startreserve: start date of reservation period.
                   11067:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11068:         selected.
1.1040    raeburn  11069: 
                   11070: =back
                   11071: 
                   11072: =cut
                   11073: 
                   11074: sub get_future_slots {
                   11075:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11076:     my $map;
                   11077:     if ($symb) {
                   11078:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11079:     }
1.1040    raeburn  11080:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11081:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11082:     foreach my $slot (keys(%slots)) {
                   11083:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11084:         if ($symb) {
1.1229    raeburn  11085:             if ($slots{$slot}->{'symb'} ne '') {
                   11086:                 my $canuse;
                   11087:                 my %oksymbs;
                   11088:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11089:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11090:                 if ($oksymbs{$symb}) {
                   11091:                     $canuse = 1;
                   11092:                 } else {
                   11093:                     foreach my $item (@slotsymbs) {
                   11094:                         if ($item =~ /\.(page|sequence)$/) {
                   11095:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11096:                             if (($map ne '') && ($map eq $sloturl)) {
                   11097:                                 $canuse = 1;
                   11098:                                 last;
                   11099:                             }
                   11100:                         }
                   11101:                     }
                   11102:                 }
                   11103:                 next unless ($canuse);
                   11104:             }
1.1040    raeburn  11105:         }
                   11106:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11107:             ($slots{$slot}->{'endtime'} > $now)) {
                   11108:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11109:                 my $userallowed = 0;
                   11110:                 if ($slots{$slot}->{'allowedsections'}) {
                   11111:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11112:                     if (!defined($env{'request.role.sec'})
                   11113:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11114:                         $userallowed=1;
                   11115:                     } else {
                   11116:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11117:                             $userallowed=1;
                   11118:                         }
                   11119:                     }
                   11120:                     unless ($userallowed) {
                   11121:                         if (defined($env{'request.course.groups'})) {
                   11122:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11123:                             foreach my $group (@groups) {
                   11124:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11125:                                     $userallowed=1;
                   11126:                                     last;
                   11127:                                 }
                   11128:                             }
                   11129:                         }
                   11130:                     }
                   11131:                 }
                   11132:                 if ($slots{$slot}->{'allowedusers'}) {
                   11133:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11134:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11135:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11136:                         $userallowed = 1;
                   11137:                     }
                   11138:                 }
                   11139:                 next unless($userallowed);
                   11140:             }
                   11141:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11142:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11143:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11144:             my $uniqueperiod;
                   11145:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11146:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11147:             }
1.1040    raeburn  11148:             if (($startreserve < $now) &&
                   11149:                 (!$endreserve || $endreserve > $now)) {
                   11150:                 my $lastres = $endreserve;
                   11151:                 if (!$lastres) {
                   11152:                     $lastres = $slots{$slot}->{'starttime'};
                   11153:                 }
                   11154:                 $reservable_now{$slot} = {
                   11155:                                            symb       => $symb,
1.1250    raeburn  11156:                                            endreserve => $lastres,
                   11157:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11158:                                          };
                   11159:             } elsif (($startreserve > $now) &&
                   11160:                      (!$endreserve || $endreserve > $startreserve)) {
                   11161:                 $future_reservable{$slot} = {
                   11162:                                               symb         => $symb,
1.1250    raeburn  11163:                                               startreserve => $startreserve,
                   11164:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11165:                                             };
                   11166:             }
                   11167:         }
                   11168:     }
                   11169:     my @unsorted_reservable = keys(%reservable_now);
                   11170:     if (@unsorted_reservable > 0) {
                   11171:         @sorted_reservable = 
                   11172:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11173:     }
                   11174:     my @unsorted_future = keys(%future_reservable);
                   11175:     if (@unsorted_future > 0) {
                   11176:         @sorted_future =
                   11177:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11178:     }
                   11179:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11180: }
1.780     raeburn  11181: 
                   11182: =pod
                   11183: 
1.1057    foxr     11184: =back
                   11185: 
1.549     albertel 11186: =head1 HTTP Helpers
                   11187: 
                   11188: =over 4
                   11189: 
1.648     raeburn  11190: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11191: 
1.258     albertel 11192: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11193: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11194: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11195: 
                   11196: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11197: $possible_names is an ref to an array of form element names.  As an example:
                   11198: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11199: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11200: 
                   11201: =cut
1.1       albertel 11202: 
1.6       albertel 11203: sub get_unprocessed_cgi {
1.25      albertel 11204:   my ($query,$possible_names)= @_;
1.26      matthew  11205:   # $Apache::lonxml::debug=1;
1.356     albertel 11206:   foreach my $pair (split(/&/,$query)) {
                   11207:     my ($name, $value) = split(/=/,$pair);
1.369     www      11208:     $name = &unescape($name);
1.25      albertel 11209:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11210:       $value =~ tr/+/ /;
                   11211:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11212:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11213:     }
1.16      harris41 11214:   }
1.6       albertel 11215: }
                   11216: 
1.112     bowersj2 11217: =pod
                   11218: 
1.648     raeburn  11219: =item * &cacheheader() 
1.112     bowersj2 11220: 
                   11221: returns cache-controlling header code
                   11222: 
                   11223: =cut
                   11224: 
1.7       albertel 11225: sub cacheheader {
1.258     albertel 11226:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11227:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11228:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11229:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11230:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11231:     return $output;
1.7       albertel 11232: }
                   11233: 
1.112     bowersj2 11234: =pod
                   11235: 
1.648     raeburn  11236: =item * &no_cache($r) 
1.112     bowersj2 11237: 
                   11238: specifies header code to not have cache
                   11239: 
                   11240: =cut
                   11241: 
1.9       albertel 11242: sub no_cache {
1.216     albertel 11243:     my ($r) = @_;
                   11244:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11245: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11246:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11247:     $r->no_cache(1);
                   11248:     $r->header_out("Expires" => $date);
                   11249:     $r->header_out("Pragma" => "no-cache");
1.123     www      11250: }
                   11251: 
                   11252: sub content_type {
1.181     albertel 11253:     my ($r,$type,$charset) = @_;
1.299     foxr     11254:     if ($r) {
                   11255: 	#  Note that printout.pl calls this with undef for $r.
                   11256: 	&no_cache($r);
                   11257:     }
1.258     albertel 11258:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11259:     unless ($charset) {
                   11260: 	$charset=&Apache::lonlocal::current_encoding;
                   11261:     }
                   11262:     if ($charset) { $type.='; charset='.$charset; }
                   11263:     if ($r) {
                   11264: 	$r->content_type($type);
                   11265:     } else {
                   11266: 	print("Content-type: $type\n\n");
                   11267:     }
1.9       albertel 11268: }
1.25      albertel 11269: 
1.112     bowersj2 11270: =pod
                   11271: 
1.648     raeburn  11272: =item * &add_to_env($name,$value) 
1.112     bowersj2 11273: 
1.258     albertel 11274: adds $name to the %env hash with value
1.112     bowersj2 11275: $value, if $name already exists, the entry is converted to an array
                   11276: reference and $value is added to the array.
                   11277: 
                   11278: =cut
                   11279: 
1.25      albertel 11280: sub add_to_env {
                   11281:   my ($name,$value)=@_;
1.258     albertel 11282:   if (defined($env{$name})) {
                   11283:     if (ref($env{$name})) {
1.25      albertel 11284:       #already have multiple values
1.258     albertel 11285:       push(@{ $env{$name} },$value);
1.25      albertel 11286:     } else {
                   11287:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11288:       my $first=$env{$name};
                   11289:       undef($env{$name});
                   11290:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11291:     }
                   11292:   } else {
1.258     albertel 11293:     $env{$name}=$value;
1.25      albertel 11294:   }
1.31      albertel 11295: }
1.149     albertel 11296: 
                   11297: =pod
                   11298: 
1.648     raeburn  11299: =item * &get_env_multiple($name) 
1.149     albertel 11300: 
1.258     albertel 11301: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11302: values may be defined and end up as an array ref.
                   11303: 
                   11304: returns an array of values
                   11305: 
                   11306: =cut
                   11307: 
                   11308: sub get_env_multiple {
                   11309:     my ($name) = @_;
                   11310:     my @values;
1.258     albertel 11311:     if (defined($env{$name})) {
1.149     albertel 11312:         # exists is it an array
1.258     albertel 11313:         if (ref($env{$name})) {
                   11314:             @values=@{ $env{$name} };
1.149     albertel 11315:         } else {
1.258     albertel 11316:             $values[0]=$env{$name};
1.149     albertel 11317:         }
                   11318:     }
                   11319:     return(@values);
                   11320: }
                   11321: 
1.1249    damieng  11322: # Looks at given dependencies, and returns something depending on the context.
                   11323: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11324: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11325: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11326: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11327: # $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.
                   11328: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11329: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11330: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11331: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11332: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11333: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11334: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11335: # @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)
                   11336: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11337: sub ask_for_embedded_content {
1.1249    damieng  11338:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11339:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11340:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11341:         %currsubfile,%unused,$rem);
1.1071    raeburn  11342:     my $counter = 0;
                   11343:     my $numnew = 0;
1.987     raeburn  11344:     my $numremref = 0;
                   11345:     my $numinvalid = 0;
                   11346:     my $numpathchg = 0;
                   11347:     my $numexisting = 0;
1.1071    raeburn  11348:     my $numunused = 0;
                   11349:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11350:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11351:     my $heading = &mt('Upload embedded files');
                   11352:     my $buttontext = &mt('Upload');
                   11353: 
1.1249    damieng  11354:     # fills these variables based on the context:
                   11355:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11356:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11357:     if ($env{'request.course.id'}) {
1.1123    raeburn  11358:         if ($actionurl eq '/adm/dependencies') {
                   11359:             $navmap = Apache::lonnavmaps::navmap->new();
                   11360:         }
                   11361:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11362:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11363:     }
1.1123    raeburn  11364:     if (($actionurl eq '/adm/portfolio') || 
                   11365:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11366:         my $current_path='/';
                   11367:         if ($env{'form.currentpath'}) {
                   11368:             $current_path = $env{'form.currentpath'};
                   11369:         }
                   11370:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11371:             $udom = $cdom;
                   11372:             $uname = $cnum;
1.984     raeburn  11373:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11374:         } else {
                   11375:             $udom = $env{'user.domain'};
                   11376:             $uname = $env{'user.name'};
                   11377:             $url = '/userfiles/portfolio';
                   11378:         }
1.987     raeburn  11379:         $toplevel = $url.'/';
1.984     raeburn  11380:         $url .= $current_path;
                   11381:         $getpropath = 1;
1.987     raeburn  11382:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11383:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11384:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11385:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11386:         $toplevel = $url;
1.984     raeburn  11387:         if ($rest ne '') {
1.987     raeburn  11388:             $url .= $rest;
                   11389:         }
                   11390:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11391:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11392:             $url = $args->{'docs_url'};
                   11393:             $toplevel = $url;
1.1084    raeburn  11394:             if ($args->{'context'} eq 'paste') {
                   11395:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11396:                 ($path) = 
                   11397:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11398:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11399:                 $fileloc =~ s{^/}{};
                   11400:             }
1.1071    raeburn  11401:         }
1.1084    raeburn  11402:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11403:         if ($env{'request.course.id'} ne '') {
                   11404:             if (ref($args) eq 'HASH') {
                   11405:                 $url = $args->{'docs_url'};
                   11406:                 $title = $args->{'docs_title'};
1.1126    raeburn  11407:                 $toplevel = $url; 
                   11408:                 unless ($toplevel =~ m{^/}) {
                   11409:                     $toplevel = "/$url";
                   11410:                 }
1.1085    raeburn  11411:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11412:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11413:                     $path = $1;
                   11414:                 } else {
                   11415:                     ($path) =
                   11416:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11417:                 }
1.1195    raeburn  11418:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11419:                     $fileloc = $toplevel;
                   11420:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11421:                     my ($udom,$uname,$fname) =
                   11422:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11423:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11424:                 } else {
                   11425:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11426:                 }
1.1071    raeburn  11427:                 $fileloc =~ s{^/}{};
                   11428:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11429:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11430:             }
1.987     raeburn  11431:         }
1.1123    raeburn  11432:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11433:         $udom = $cdom;
                   11434:         $uname = $cnum;
                   11435:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11436:         $toplevel = $url;
                   11437:         $path = $url;
                   11438:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11439:         $fileloc =~ s{^/}{};
1.987     raeburn  11440:     }
1.1249    damieng  11441:     
                   11442:     # parses the dependency paths to get some info
                   11443:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11444:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11445:     # (will be completed later)
                   11446:     # $mapping:
                   11447:     #   for external URLs: external URL -> external URL
                   11448:     #   for relative paths: clean path -> original path
                   11449:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11450:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11451:     foreach my $file (keys(%{$allfiles})) {
                   11452:         my $embed_file;
                   11453:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11454:             $embed_file = $1;
                   11455:         } else {
                   11456:             $embed_file = $file;
                   11457:         }
1.1158    raeburn  11458:         my ($absolutepath,$cleaned_file);
                   11459:         if ($embed_file =~ m{^\w+://}) {
                   11460:             $cleaned_file = $embed_file;
1.1147    raeburn  11461:             $newfiles{$cleaned_file} = 1;
                   11462:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11463:         } else {
1.1158    raeburn  11464:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11465:             if ($embed_file =~ m{^/}) {
                   11466:                 $absolutepath = $embed_file;
                   11467:             }
1.1147    raeburn  11468:             if ($cleaned_file =~ m{/}) {
                   11469:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11470:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11471:                 my $item = $fname;
                   11472:                 if ($path ne '') {
                   11473:                     $item = $path.'/'.$fname;
                   11474:                     $subdependencies{$path}{$fname} = 1;
                   11475:                 } else {
                   11476:                     $dependencies{$item} = 1;
                   11477:                 }
                   11478:                 if ($absolutepath) {
                   11479:                     $mapping{$item} = $absolutepath;
                   11480:                 } else {
                   11481:                     $mapping{$item} = $embed_file;
                   11482:                 }
                   11483:             } else {
                   11484:                 $dependencies{$embed_file} = 1;
                   11485:                 if ($absolutepath) {
1.1147    raeburn  11486:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11487:                 } else {
1.1147    raeburn  11488:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11489:                 }
                   11490:             }
1.984     raeburn  11491:         }
                   11492:     }
1.1249    damieng  11493:     
                   11494:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11495:     # and lists
                   11496:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11497:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11498:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11499:     #                                    the path had to be cleaned up
                   11500:     # $existing: hash clean path -> 1 if the file exists
                   11501:     # $numexisting: number of keys in $existing
                   11502:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11503:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11504:     #                                      dependency subdirectories that are
                   11505:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11506:     my $dirptr = 16384;
1.984     raeburn  11507:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11508:         $currsubfile{$path} = {};
1.1123    raeburn  11509:         if (($actionurl eq '/adm/portfolio') || 
                   11510:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11511:             my ($sublistref,$listerror) =
                   11512:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11513:             if (ref($sublistref) eq 'ARRAY') {
                   11514:                 foreach my $line (@{$sublistref}) {
                   11515:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11516:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11517:                 }
1.984     raeburn  11518:             }
1.987     raeburn  11519:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11520:             if (opendir(my $dir,$url.'/'.$path)) {
                   11521:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11522:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11523:             }
1.1084    raeburn  11524:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11525:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11526:                   ($args->{'context'} eq 'paste')) ||
                   11527:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11528:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11529:                 my $dir;
                   11530:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11531:                     $dir = $fileloc;
                   11532:                 } else {
                   11533:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11534:                 }
1.1071    raeburn  11535:                 if ($dir ne '') {
                   11536:                     my ($sublistref,$listerror) =
                   11537:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11538:                     if (ref($sublistref) eq 'ARRAY') {
                   11539:                         foreach my $line (@{$sublistref}) {
                   11540:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11541:                                 undef,$mtime)=split(/\&/,$line,12);
                   11542:                             unless (($testdir&$dirptr) ||
                   11543:                                     ($file_name =~ /^\.\.?$/)) {
                   11544:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11545:                             }
                   11546:                         }
                   11547:                     }
                   11548:                 }
1.984     raeburn  11549:             }
                   11550:         }
                   11551:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11552:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11553:                 my $item = $path.'/'.$file;
                   11554:                 unless ($mapping{$item} eq $item) {
                   11555:                     $pathchanges{$item} = 1;
                   11556:                 }
                   11557:                 $existing{$item} = 1;
                   11558:                 $numexisting ++;
                   11559:             } else {
                   11560:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11561:             }
                   11562:         }
1.1071    raeburn  11563:         if ($actionurl eq '/adm/dependencies') {
                   11564:             foreach my $path (keys(%currsubfile)) {
                   11565:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11566:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11567:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11568:                              next if (($rem ne '') &&
                   11569:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11570:                                        (ref($navmap) &&
                   11571:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11572:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11573:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11574:                              $unused{$path.'/'.$file} = 1; 
                   11575:                          }
                   11576:                     }
                   11577:                 }
                   11578:             }
                   11579:         }
1.984     raeburn  11580:     }
1.1249    damieng  11581:     
                   11582:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11583:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11584:     my %currfile;
1.1123    raeburn  11585:     if (($actionurl eq '/adm/portfolio') ||
                   11586:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11587:         my ($dirlistref,$listerror) =
                   11588:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11589:         if (ref($dirlistref) eq 'ARRAY') {
                   11590:             foreach my $line (@{$dirlistref}) {
                   11591:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11592:                 $currfile{$file_name} = 1;
                   11593:             }
1.984     raeburn  11594:         }
1.987     raeburn  11595:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11596:         if (opendir(my $dir,$url)) {
1.987     raeburn  11597:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11598:             map {$currfile{$_} = 1;} @dir_list;
                   11599:         }
1.1084    raeburn  11600:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11601:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11602:               ($args->{'context'} eq 'paste')) ||
                   11603:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11604:         if ($env{'request.course.id'} ne '') {
                   11605:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11606:             if ($dir ne '') {
                   11607:                 my ($dirlistref,$listerror) =
                   11608:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11609:                 if (ref($dirlistref) eq 'ARRAY') {
                   11610:                     foreach my $line (@{$dirlistref}) {
                   11611:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11612:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11613:                         unless (($testdir&$dirptr) ||
                   11614:                                 ($file_name =~ /^\.\.?$/)) {
                   11615:                             $currfile{$file_name} = [$size,$mtime];
                   11616:                         }
                   11617:                     }
                   11618:                 }
                   11619:             }
                   11620:         }
1.984     raeburn  11621:     }
1.1249    damieng  11622:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11623:     # are not in subdirectories, using $currfile
1.984     raeburn  11624:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11625:         if (exists($currfile{$file})) {
1.987     raeburn  11626:             unless ($mapping{$file} eq $file) {
                   11627:                 $pathchanges{$file} = 1;
                   11628:             }
                   11629:             $existing{$file} = 1;
                   11630:             $numexisting ++;
                   11631:         } else {
1.984     raeburn  11632:             $newfiles{$file} = 1;
                   11633:         }
                   11634:     }
1.1071    raeburn  11635:     foreach my $file (keys(%currfile)) {
                   11636:         unless (($file eq $filename) ||
                   11637:                 ($file eq $filename.'.bak') ||
                   11638:                 ($dependencies{$file})) {
1.1085    raeburn  11639:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11640:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11641:                     next if (($rem ne '') &&
                   11642:                              (($env{"httpref.$rem".$file} ne '') ||
                   11643:                               (ref($navmap) &&
                   11644:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11645:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11646:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11647:                 }
1.1085    raeburn  11648:             }
1.1071    raeburn  11649:             $unused{$file} = 1;
                   11650:         }
                   11651:     }
1.1249    damieng  11652:     
                   11653:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11654:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11655:         ($args->{'context'} eq 'paste')) {
                   11656:         $counter = scalar(keys(%existing));
                   11657:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11658:         return ($output,$counter,$numpathchg,\%existing);
                   11659:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11660:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11661:         $counter = scalar(keys(%existing));
                   11662:         $numpathchg = scalar(keys(%pathchanges));
                   11663:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11664:     }
1.1249    damieng  11665:     
                   11666:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11667:     
                   11668:     # $upload_output: missing dependencies (with upload form)
                   11669:     # $modify_output: uploaded dependencies (in use)
                   11670:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11671:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11672:         if ($actionurl eq '/adm/dependencies') {
                   11673:             next if ($embed_file =~ m{^\w+://});
                   11674:         }
1.660     raeburn  11675:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11676:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11677:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11678:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11679:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11680:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11681:         }
1.1123    raeburn  11682:         $upload_output .= '</td>';
1.1071    raeburn  11683:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11684:             $upload_output.='<td align="right">'.
                   11685:                             '<span class="LC_info LC_fontsize_medium">'.
                   11686:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11687:             $numremref++;
1.660     raeburn  11688:         } elsif ($args->{'error_on_invalid_names'}
                   11689:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11690:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11691:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11692:             $numinvalid++;
1.660     raeburn  11693:         } else {
1.1123    raeburn  11694:             $upload_output .= '<td>'.
                   11695:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11696:                                                      $embed_file,\%mapping,
1.1071    raeburn  11697:                                                      $allfiles,$codebase,'upload');
                   11698:             $counter ++;
                   11699:             $numnew ++;
1.987     raeburn  11700:         }
                   11701:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11702:     }
                   11703:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11704:         if ($actionurl eq '/adm/dependencies') {
                   11705:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11706:             $modify_output .= &start_data_table_row().
                   11707:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11708:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11709:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11710:                               '<td>'.$size.'</td>'.
                   11711:                               '<td>'.$mtime.'</td>'.
                   11712:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11713:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11714:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11715:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11716:                               &embedded_file_element('upload_embedded',$counter,
                   11717:                                                      $embed_file,\%mapping,
                   11718:                                                      $allfiles,$codebase,'modify').
                   11719:                               '</div></td>'.
                   11720:                               &end_data_table_row()."\n";
                   11721:             $counter ++;
                   11722:         } else {
                   11723:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11724:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11725:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11726:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11727:                               &Apache::loncommon::end_data_table_row()."\n";
                   11728:         }
                   11729:     }
                   11730:     my $delidx = $counter;
                   11731:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11732:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11733:         $delete_output .= &start_data_table_row().
                   11734:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11735:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11736:                           '<td>'.$size.'</td>'.
                   11737:                           '<td>'.$mtime.'</td>'.
                   11738:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11739:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11740:                           &embedded_file_element('upload_embedded',$delidx,
                   11741:                                                  $oldfile,\%mapping,$allfiles,
                   11742:                                                  $codebase,'delete').'</td>'.
                   11743:                           &end_data_table_row()."\n"; 
                   11744:         $numunused ++;
                   11745:         $delidx ++;
1.987     raeburn  11746:     }
                   11747:     if ($upload_output) {
                   11748:         $upload_output = &start_data_table().
                   11749:                          $upload_output.
                   11750:                          &end_data_table()."\n";
                   11751:     }
1.1071    raeburn  11752:     if ($modify_output) {
                   11753:         $modify_output = &start_data_table().
                   11754:                          &start_data_table_header_row().
                   11755:                          '<th>'.&mt('File').'</th>'.
                   11756:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11757:                          '<th>'.&mt('Modified').'</th>'.
                   11758:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11759:                          &end_data_table_header_row().
                   11760:                          $modify_output.
                   11761:                          &end_data_table()."\n";
                   11762:     }
                   11763:     if ($delete_output) {
                   11764:         $delete_output = &start_data_table().
                   11765:                          &start_data_table_header_row().
                   11766:                          '<th>'.&mt('File').'</th>'.
                   11767:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11768:                          '<th>'.&mt('Modified').'</th>'.
                   11769:                          '<th>'.&mt('Delete?').'</th>'.
                   11770:                          &end_data_table_header_row().
                   11771:                          $delete_output.
                   11772:                          &end_data_table()."\n";
                   11773:     }
1.987     raeburn  11774:     my $applies = 0;
                   11775:     if ($numremref) {
                   11776:         $applies ++;
                   11777:     }
                   11778:     if ($numinvalid) {
                   11779:         $applies ++;
                   11780:     }
                   11781:     if ($numexisting) {
                   11782:         $applies ++;
                   11783:     }
1.1071    raeburn  11784:     if ($counter || $numunused) {
1.987     raeburn  11785:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11786:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11787:                   $state.'<h3>'.$heading.'</h3>'; 
                   11788:         if ($actionurl eq '/adm/dependencies') {
                   11789:             if ($numnew) {
                   11790:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11791:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11792:                            $upload_output.'<br />'."\n";
                   11793:             }
                   11794:             if ($numexisting) {
                   11795:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11796:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11797:                            $modify_output.'<br />'."\n";
                   11798:                            $buttontext = &mt('Save changes');
                   11799:             }
                   11800:             if ($numunused) {
                   11801:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11802:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11803:                            $delete_output.'<br />'."\n";
                   11804:                            $buttontext = &mt('Save changes');
                   11805:             }
                   11806:         } else {
                   11807:             $output .= $upload_output.'<br />'."\n";
                   11808:         }
                   11809:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11810:                    $counter.'" />'."\n";
                   11811:         if ($actionurl eq '/adm/dependencies') { 
                   11812:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11813:                        $numnew.'" />'."\n";
                   11814:         } elsif ($actionurl eq '') {
1.987     raeburn  11815:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11816:         }
                   11817:     } elsif ($applies) {
                   11818:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11819:         if ($applies > 1) {
                   11820:             $output .=  
1.1123    raeburn  11821:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11822:             if ($numremref) {
                   11823:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11824:             }
                   11825:             if ($numinvalid) {
                   11826:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11827:             }
                   11828:             if ($numexisting) {
                   11829:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11830:             }
                   11831:             $output .= '</ul><br />';
                   11832:         } elsif ($numremref) {
                   11833:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11834:         } elsif ($numinvalid) {
                   11835:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11836:         } elsif ($numexisting) {
                   11837:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11838:         }
                   11839:         $output .= $upload_output.'<br />';
                   11840:     }
                   11841:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11842:     $chgcount = $counter;
1.987     raeburn  11843:     if (keys(%pathchanges) > 0) {
                   11844:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11845:             if ($counter) {
1.987     raeburn  11846:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11847:                                                   $embed_file,\%mapping,
1.1071    raeburn  11848:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11849:             } else {
                   11850:                 $pathchange_output .= 
                   11851:                     &start_data_table_row().
                   11852:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11853:                     $chgcount.'" checked="checked" /></td>'.
                   11854:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11855:                     '<td>'.$embed_file.
                   11856:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11857:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11858:                     '</td>'.&end_data_table_row();
1.660     raeburn  11859:             }
1.987     raeburn  11860:             $numpathchg ++;
                   11861:             $chgcount ++;
1.660     raeburn  11862:         }
                   11863:     }
1.1127    raeburn  11864:     if (($counter) || ($numunused)) {
1.987     raeburn  11865:         if ($numpathchg) {
                   11866:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11867:                        $numpathchg.'" />'."\n";
                   11868:         }
                   11869:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11870:             ($actionurl eq '/adm/imsimport')) {
                   11871:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11872:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11873:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11874:         } elsif ($actionurl eq '/adm/dependencies') {
                   11875:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11876:         }
1.1123    raeburn  11877:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11878:     } elsif ($numpathchg) {
                   11879:         my %pathchange = ();
                   11880:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11881:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11882:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11883:         }
1.987     raeburn  11884:     }
1.1071    raeburn  11885:     return ($output,$counter,$numpathchg);
1.987     raeburn  11886: }
                   11887: 
1.1147    raeburn  11888: =pod
                   11889: 
                   11890: =item * clean_path($name)
                   11891: 
                   11892: Performs clean-up of directories, subdirectories and filename in an
                   11893: embedded object, referenced in an HTML file which is being uploaded
                   11894: to a course or portfolio, where 
                   11895: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11896: checked.
                   11897: 
                   11898: Clean-up is similar to replacements in lonnet::clean_filename()
                   11899: except each / between sub-directory and next level is preserved.
                   11900: 
                   11901: =cut
                   11902: 
                   11903: sub clean_path {
                   11904:     my ($embed_file) = @_;
                   11905:     $embed_file =~s{^/+}{};
                   11906:     my @contents;
                   11907:     if ($embed_file =~ m{/}) {
                   11908:         @contents = split(/\//,$embed_file);
                   11909:     } else {
                   11910:         @contents = ($embed_file);
                   11911:     }
                   11912:     my $lastidx = scalar(@contents)-1;
                   11913:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11914:         $contents[$i]=~s{\\}{/}g;
                   11915:         $contents[$i]=~s/\s+/\_/g;
                   11916:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11917:         if ($i == $lastidx) {
                   11918:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11919:         }
                   11920:     }
                   11921:     if ($lastidx > 0) {
                   11922:         return join('/',@contents);
                   11923:     } else {
                   11924:         return $contents[0];
                   11925:     }
                   11926: }
                   11927: 
1.987     raeburn  11928: sub embedded_file_element {
1.1071    raeburn  11929:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11930:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11931:                    (ref($codebase) eq 'HASH'));
                   11932:     my $output;
1.1071    raeburn  11933:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11934:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11935:     }
                   11936:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11937:                &escape($embed_file).'" />';
                   11938:     unless (($context eq 'upload_embedded') && 
                   11939:             ($mapping->{$embed_file} eq $embed_file)) {
                   11940:         $output .='
                   11941:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11942:     }
                   11943:     my $attrib;
                   11944:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11945:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11946:     }
                   11947:     $output .=
                   11948:         "\n\t\t".
                   11949:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11950:         $attrib.'" />';
                   11951:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11952:         $output .=
                   11953:             "\n\t\t".
                   11954:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11955:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11956:     }
1.987     raeburn  11957:     return $output;
1.660     raeburn  11958: }
                   11959: 
1.1071    raeburn  11960: sub get_dependency_details {
                   11961:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11962:     my ($size,$mtime,$showsize,$showmtime);
                   11963:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11964:         if ($embed_file =~ m{/}) {
                   11965:             my ($path,$fname) = split(/\//,$embed_file);
                   11966:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11967:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11968:             }
                   11969:         } else {
                   11970:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11971:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11972:             }
                   11973:         }
                   11974:         $showsize = $size/1024.0;
                   11975:         $showsize = sprintf("%.1f",$showsize);
                   11976:         if ($mtime > 0) {
                   11977:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11978:         }
                   11979:     }
                   11980:     return ($showsize,$showmtime);
                   11981: }
                   11982: 
                   11983: sub ask_embedded_js {
                   11984:     return <<"END";
                   11985: <script type="text/javascript"">
                   11986: // <![CDATA[
                   11987: function toggleBrowse(counter) {
                   11988:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11989:     var fileid = document.getElementById('embedded_item_'+counter);
                   11990:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11991:     if (chkboxid.checked == true) {
                   11992:         uploaddivid.style.display='block';
                   11993:     } else {
                   11994:         uploaddivid.style.display='none';
                   11995:         fileid.value = '';
                   11996:     }
                   11997: }
                   11998: // ]]>
                   11999: </script>
                   12000: 
                   12001: END
                   12002: }
                   12003: 
1.661     raeburn  12004: sub upload_embedded {
                   12005:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12006:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12007:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12008:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12009:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12010:         my $orig_uploaded_filename =
                   12011:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12012:         foreach my $type ('orig','ref','attrib','codebase') {
                   12013:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12014:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12015:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12016:             }
                   12017:         }
1.661     raeburn  12018:         my ($path,$fname) =
                   12019:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12020:         # no path, whole string is fname
                   12021:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12022:         $fname = &Apache::lonnet::clean_filename($fname);
                   12023:         # See if there is anything left
                   12024:         next if ($fname eq '');
                   12025: 
                   12026:         # Check if file already exists as a file or directory.
                   12027:         my ($state,$msg);
                   12028:         if ($context eq 'portfolio') {
                   12029:             my $port_path = $dirpath;
                   12030:             if ($group ne '') {
                   12031:                 $port_path = "groups/$group/$port_path";
                   12032:             }
1.987     raeburn  12033:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12034:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12035:                                               $dir_root,$port_path,$disk_quota,
                   12036:                                               $current_disk_usage,$uname,$udom);
                   12037:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12038:                 || $state eq 'file_locked') {
1.661     raeburn  12039:                 $output .= $msg;
                   12040:                 next;
                   12041:             }
                   12042:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12043:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12044:             if ($state eq 'exists') {
                   12045:                 $output .= $msg;
                   12046:                 next;
                   12047:             }
                   12048:         }
                   12049:         # Check if extension is valid
                   12050:         if (($fname =~ /\.(\w+)$/) &&
                   12051:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12052:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12053:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12054:             next;
                   12055:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12056:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12057:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12058:             next;
                   12059:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12060:             $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  12061:             next;
                   12062:         }
                   12063:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12064:         my $subdir = $path;
                   12065:         $subdir =~ s{/+$}{};
1.661     raeburn  12066:         if ($context eq 'portfolio') {
1.984     raeburn  12067:             my $result;
                   12068:             if ($state eq 'existingfile') {
                   12069:                 $result=
                   12070:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12071:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12072:             } else {
1.984     raeburn  12073:                 $result=
                   12074:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12075:                                                     $dirpath.
1.1123    raeburn  12076:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12077:                 if ($result !~ m|^/uploaded/|) {
                   12078:                     $output .= '<span class="LC_error">'
                   12079:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12080:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12081:                                .'</span><br />';
                   12082:                     next;
                   12083:                 } else {
1.987     raeburn  12084:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12085:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12086:                 }
1.661     raeburn  12087:             }
1.1123    raeburn  12088:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12089:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12090:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12091:             my $result =
1.1126    raeburn  12092:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12093:             if ($result !~ m|^/uploaded/|) {
                   12094:                 $output .= '<span class="LC_error">'
                   12095:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12096:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12097:                            .'</span><br />';
                   12098:                     next;
                   12099:             } else {
                   12100:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12101:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12102:                 if ($context eq 'syllabus') {
                   12103:                     &Apache::lonnet::make_public_indefinitely($result);
                   12104:                 }
1.987     raeburn  12105:             }
1.661     raeburn  12106:         } else {
                   12107: # Save the file
                   12108:             my $target = $env{'form.embedded_item_'.$i};
                   12109:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12110:             my $dest = $fullpath.$fname;
                   12111:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12112:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12113:             my $count;
                   12114:             my $filepath = $dir_root;
1.1027    raeburn  12115:             foreach my $subdir (@parts) {
                   12116:                 $filepath .= "/$subdir";
                   12117:                 if (!-e $filepath) {
1.661     raeburn  12118:                     mkdir($filepath,0770);
                   12119:                 }
                   12120:             }
                   12121:             my $fh;
                   12122:             if (!open($fh,'>'.$dest)) {
                   12123:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12124:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12125:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12126:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12127:                            '</span><br />';
                   12128:             } else {
                   12129:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12130:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12131:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12132:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12133:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12134:                               '</span><br />';
                   12135:                 } else {
1.987     raeburn  12136:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12137:                                $url.'</span>').'<br />';
                   12138:                     unless ($context eq 'testbank') {
                   12139:                         $footer .= &mt('View embedded file: [_1]',
                   12140:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12141:                     }
                   12142:                 }
                   12143:                 close($fh);
                   12144:             }
                   12145:         }
                   12146:         if ($env{'form.embedded_ref_'.$i}) {
                   12147:             $pathchange{$i} = 1;
                   12148:         }
                   12149:     }
                   12150:     if ($output) {
                   12151:         $output = '<p>'.$output.'</p>';
                   12152:     }
                   12153:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12154:     $returnflag = 'ok';
1.1071    raeburn  12155:     my $numpathchgs = scalar(keys(%pathchange));
                   12156:     if ($numpathchgs > 0) {
1.987     raeburn  12157:         if ($context eq 'portfolio') {
                   12158:             $output .= '<p>'.&mt('or').'</p>';
                   12159:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12160:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12161:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12162:             $returnflag = 'modify_orightml';
                   12163:         }
                   12164:     }
1.1071    raeburn  12165:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12166: }
                   12167: 
                   12168: sub modify_html_form {
                   12169:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12170:     my $end = 0;
                   12171:     my $modifyform;
                   12172:     if ($context eq 'upload_embedded') {
                   12173:         return unless (ref($pathchange) eq 'HASH');
                   12174:         if ($env{'form.number_embedded_items'}) {
                   12175:             $end += $env{'form.number_embedded_items'};
                   12176:         }
                   12177:         if ($env{'form.number_pathchange_items'}) {
                   12178:             $end += $env{'form.number_pathchange_items'};
                   12179:         }
                   12180:         if ($end) {
                   12181:             for (my $i=0; $i<$end; $i++) {
                   12182:                 if ($i < $env{'form.number_embedded_items'}) {
                   12183:                     next unless($pathchange->{$i});
                   12184:                 }
                   12185:                 $modifyform .=
                   12186:                     &start_data_table_row().
                   12187:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12188:                     'checked="checked" /></td>'.
                   12189:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12190:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12191:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12192:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12193:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12194:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12195:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12196:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12197:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12198:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12199:                     &end_data_table_row();
1.1071    raeburn  12200:             }
1.987     raeburn  12201:         }
                   12202:     } else {
                   12203:         $modifyform = $pathchgtable;
                   12204:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12205:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12206:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12207:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12208:         }
                   12209:     }
                   12210:     if ($modifyform) {
1.1071    raeburn  12211:         if ($actionurl eq '/adm/dependencies') {
                   12212:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12213:         }
1.987     raeburn  12214:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12215:                '<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".
                   12216:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12217:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12218:                '</ol></p>'."\n".'<p>'.
                   12219:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12220:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12221:                &start_data_table()."\n".
                   12222:                &start_data_table_header_row().
                   12223:                '<th>'.&mt('Change?').'</th>'.
                   12224:                '<th>'.&mt('Current reference').'</th>'.
                   12225:                '<th>'.&mt('Required reference').'</th>'.
                   12226:                &end_data_table_header_row()."\n".
                   12227:                $modifyform.
                   12228:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12229:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12230:                '</form>'."\n";
                   12231:     }
                   12232:     return;
                   12233: }
                   12234: 
                   12235: sub modify_html_refs {
1.1123    raeburn  12236:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12237:     my $container;
                   12238:     if ($context eq 'portfolio') {
                   12239:         $container = $env{'form.container'};
                   12240:     } elsif ($context eq 'coursedoc') {
                   12241:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12242:     } elsif ($context eq 'manage_dependencies') {
                   12243:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12244:         $container = "/$container";
1.1123    raeburn  12245:     } elsif ($context eq 'syllabus') {
                   12246:         $container = $url;
1.987     raeburn  12247:     } else {
1.1027    raeburn  12248:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12249:     }
                   12250:     my (%allfiles,%codebase,$output,$content);
                   12251:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12252:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12253:         if (wantarray) {
                   12254:             return ('',0,0); 
                   12255:         } else {
                   12256:             return;
                   12257:         }
                   12258:     }
                   12259:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12260:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12261:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12262:             if (wantarray) {
                   12263:                 return ('',0,0);
                   12264:             } else {
                   12265:                 return;
                   12266:             }
                   12267:         } 
1.987     raeburn  12268:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12269:         if ($content eq '-1') {
                   12270:             if (wantarray) {
                   12271:                 return ('',0,0);
                   12272:             } else {
                   12273:                 return;
                   12274:             }
                   12275:         }
1.987     raeburn  12276:     } else {
1.1071    raeburn  12277:         unless ($container =~ /^\Q$dir_root\E/) {
                   12278:             if (wantarray) {
                   12279:                 return ('',0,0);
                   12280:             } else {
                   12281:                 return;
                   12282:             }
                   12283:         } 
1.1317    raeburn  12284:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12285:             $content = join('', <$fh>);
                   12286:             close($fh);
                   12287:         } else {
1.1071    raeburn  12288:             if (wantarray) {
                   12289:                 return ('',0,0);
                   12290:             } else {
                   12291:                 return;
                   12292:             }
1.987     raeburn  12293:         }
                   12294:     }
                   12295:     my ($count,$codebasecount) = (0,0);
                   12296:     my $mm = new File::MMagic;
                   12297:     my $mime_type = $mm->checktype_contents($content);
                   12298:     if ($mime_type eq 'text/html') {
                   12299:         my $parse_result = 
                   12300:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12301:                                                     \%codebase,\$content);
                   12302:         if ($parse_result eq 'ok') {
                   12303:             foreach my $i (@changes) {
                   12304:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12305:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12306:                 if ($allfiles{$ref}) {
                   12307:                     my $newname =  $orig;
                   12308:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12309:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12310:                     if ($attrib_regexp =~ /:/) {
                   12311:                         $attrib_regexp =~ s/\:/|/g;
                   12312:                     }
                   12313:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12314:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12315:                         $count += $numchg;
1.1123    raeburn  12316:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12317:                         delete($allfiles{$ref});
1.987     raeburn  12318:                     }
                   12319:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12320:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12321:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12322:                         $codebasecount ++;
                   12323:                     }
                   12324:                 }
                   12325:             }
1.1123    raeburn  12326:             my $skiprewrites;
1.987     raeburn  12327:             if ($count || $codebasecount) {
                   12328:                 my $saveresult;
1.1071    raeburn  12329:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12330:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12331:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12332:                     if ($url eq $container) {
                   12333:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12334:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12335:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12336:                                             $fname.'</span>').'</p>';
1.987     raeburn  12337:                     } else {
                   12338:                          $output = '<p class="LC_error">'.
                   12339:                                    &mt('Error: update failed for: [_1].',
                   12340:                                    '<span class="LC_filename">'.
                   12341:                                    $container.'</span>').'</p>';
                   12342:                     }
1.1123    raeburn  12343:                     if ($context eq 'syllabus') {
                   12344:                         unless ($saveresult eq 'ok') {
                   12345:                             $skiprewrites = 1;
                   12346:                         }
                   12347:                     }
1.987     raeburn  12348:                 } else {
1.1317    raeburn  12349:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12350:                         print $fh $content;
                   12351:                         close($fh);
                   12352:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12353:                                   $count,'<span class="LC_filename">'.
                   12354:                                   $container.'</span>').'</p>';
1.661     raeburn  12355:                     } else {
1.987     raeburn  12356:                          $output = '<p class="LC_error">'.
                   12357:                                    &mt('Error: could not update [_1].',
                   12358:                                    '<span class="LC_filename">'.
                   12359:                                    $container.'</span>').'</p>';
1.661     raeburn  12360:                     }
                   12361:                 }
                   12362:             }
1.1123    raeburn  12363:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12364:                 my ($actionurl,$state);
                   12365:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12366:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12367:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12368:                                               \%codebase,
                   12369:                                               {'context' => 'rewrites',
                   12370:                                                'ignore_remote_references' => 1,});
                   12371:                 if (ref($mapping) eq 'HASH') {
                   12372:                     my $rewrites = 0;
                   12373:                     foreach my $key (keys(%{$mapping})) {
                   12374:                         next if ($key =~ m{^https?://});
                   12375:                         my $ref = $mapping->{$key};
                   12376:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12377:                         my $attrib;
                   12378:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12379:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12380:                         }
                   12381:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12382:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12383:                             $rewrites += $numchg;
                   12384:                         }
                   12385:                     }
                   12386:                     if ($rewrites) {
                   12387:                         my $saveresult; 
                   12388:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12389:                         if ($url eq $container) {
                   12390:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12391:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12392:                                             $count,'<span class="LC_filename">'.
                   12393:                                             $fname.'</span>').'</p>';
                   12394:                         } else {
                   12395:                             $output .= '<p class="LC_error">'.
                   12396:                                        &mt('Error: could not update links in [_1].',
                   12397:                                        '<span class="LC_filename">'.
                   12398:                                        $container.'</span>').'</p>';
                   12399: 
                   12400:                         }
                   12401:                     }
                   12402:                 }
                   12403:             }
1.987     raeburn  12404:         } else {
                   12405:             &logthis('Failed to parse '.$container.
                   12406:                      ' to modify references: '.$parse_result);
1.661     raeburn  12407:         }
                   12408:     }
1.1071    raeburn  12409:     if (wantarray) {
                   12410:         return ($output,$count,$codebasecount);
                   12411:     } else {
                   12412:         return $output;
                   12413:     }
1.661     raeburn  12414: }
                   12415: 
                   12416: sub check_for_existing {
                   12417:     my ($path,$fname,$element) = @_;
                   12418:     my ($state,$msg);
                   12419:     if (-d $path.'/'.$fname) {
                   12420:         $state = 'exists';
                   12421:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12422:     } elsif (-e $path.'/'.$fname) {
                   12423:         $state = 'exists';
                   12424:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12425:     }
                   12426:     if ($state eq 'exists') {
                   12427:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12428:     }
                   12429:     return ($state,$msg);
                   12430: }
                   12431: 
                   12432: sub check_for_upload {
                   12433:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12434:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12435:     my $filesize = length($env{'form.'.$element});
                   12436:     if (!$filesize) {
                   12437:         my $msg = '<span class="LC_error">'.
                   12438:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12439:                       '<span class="LC_filename">'.$fname.'</span>',
                   12440:                       $filesize).'<br />'.
1.1007    raeburn  12441:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12442:                   '</span>';
                   12443:         return ('zero_bytes',$msg);
                   12444:     }
                   12445:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12446:     my $getpropath = 1;
1.1021    raeburn  12447:     my ($dirlistref,$listerror) =
                   12448:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12449:     my $found_file = 0;
                   12450:     my $locked_file = 0;
1.991     raeburn  12451:     my @lockers;
                   12452:     my $navmap;
                   12453:     if ($env{'request.course.id'}) {
                   12454:         $navmap = Apache::lonnavmaps::navmap->new();
                   12455:     }
1.1021    raeburn  12456:     if (ref($dirlistref) eq 'ARRAY') {
                   12457:         foreach my $line (@{$dirlistref}) {
                   12458:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12459:             if ($file_name eq $fname){
                   12460:                 $file_name = $path.$file_name;
                   12461:                 if ($group ne '') {
                   12462:                     $file_name = $group.$file_name;
                   12463:                 }
                   12464:                 $found_file = 1;
                   12465:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12466:                     foreach my $lock (@lockers) {
                   12467:                         if (ref($lock) eq 'ARRAY') {
                   12468:                             my ($symb,$crsid) = @{$lock};
                   12469:                             if ($crsid eq $env{'request.course.id'}) {
                   12470:                                 if (ref($navmap)) {
                   12471:                                     my $res = $navmap->getBySymb($symb);
                   12472:                                     foreach my $part (@{$res->parts()}) { 
                   12473:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12474:                                         unless (($slot_status == $res->RESERVED) ||
                   12475:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12476:                                             $locked_file = 1;
                   12477:                                         }
1.991     raeburn  12478:                                     }
1.1021    raeburn  12479:                                 } else {
                   12480:                                     $locked_file = 1;
1.991     raeburn  12481:                                 }
                   12482:                             } else {
                   12483:                                 $locked_file = 1;
                   12484:                             }
                   12485:                         }
1.1021    raeburn  12486:                    }
                   12487:                 } else {
                   12488:                     my @info = split(/\&/,$rest);
                   12489:                     my $currsize = $info[6]/1000;
                   12490:                     if ($currsize < $filesize) {
                   12491:                         my $extra = $filesize - $currsize;
                   12492:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12493:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12494:                                       &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   12495:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12496:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12497:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12498:                             return ('will_exceed_quota',$msg);
                   12499:                         }
1.984     raeburn  12500:                     }
                   12501:                 }
1.661     raeburn  12502:             }
                   12503:         }
                   12504:     }
                   12505:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12506:         my $msg = '<p class="LC_warning">'.
                   12507:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12508:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12509:         return ('will_exceed_quota',$msg);
                   12510:     } elsif ($found_file) {
                   12511:         if ($locked_file) {
1.1179    bisitz   12512:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12513:             $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   12514:             $msg .= '</p>';
1.661     raeburn  12515:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12516:             return ('file_locked',$msg);
                   12517:         } else {
1.1179    bisitz   12518:             my $msg = '<p class="LC_error">';
1.984     raeburn  12519:             $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   12520:             $msg .= '</p>';
1.984     raeburn  12521:             return ('existingfile',$msg);
1.661     raeburn  12522:         }
                   12523:     }
                   12524: }
                   12525: 
1.987     raeburn  12526: sub check_for_traversal {
                   12527:     my ($path,$url,$toplevel) = @_;
                   12528:     my @parts=split(/\//,$path);
                   12529:     my $cleanpath;
                   12530:     my $fullpath = $url;
                   12531:     for (my $i=0;$i<@parts;$i++) {
                   12532:         next if ($parts[$i] eq '.');
                   12533:         if ($parts[$i] eq '..') {
                   12534:             $fullpath =~ s{([^/]+/)$}{};
                   12535:         } else {
                   12536:             $fullpath .= $parts[$i].'/';
                   12537:         }
                   12538:     }
                   12539:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12540:         $cleanpath = $1;
                   12541:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12542:         my $curr_toprel = $1;
                   12543:         my @parts = split(/\//,$curr_toprel);
                   12544:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12545:         my @urlparts = split(/\//,$url_toprel);
                   12546:         my $doubledots;
                   12547:         my $startdiff = -1;
                   12548:         for (my $i=0; $i<@urlparts; $i++) {
                   12549:             if ($startdiff == -1) {
                   12550:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12551:                     $startdiff = $i;
                   12552:                     $doubledots .= '../';
                   12553:                 }
                   12554:             } else {
                   12555:                 $doubledots .= '../';
                   12556:             }
                   12557:         }
                   12558:         if ($startdiff > -1) {
                   12559:             $cleanpath = $doubledots;
                   12560:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12561:                 $cleanpath .= $parts[$i].'/';
                   12562:             }
                   12563:         }
                   12564:     }
                   12565:     $cleanpath =~ s{(/)$}{};
                   12566:     return $cleanpath;
                   12567: }
1.31      albertel 12568: 
1.1053    raeburn  12569: sub is_archive_file {
                   12570:     my ($mimetype) = @_;
                   12571:     if (($mimetype eq 'application/octet-stream') ||
                   12572:         ($mimetype eq 'application/x-stuffit') ||
                   12573:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12574:         return 1;
                   12575:     }
                   12576:     return;
                   12577: }
                   12578: 
                   12579: sub decompress_form {
1.1065    raeburn  12580:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12581:     my %lt = &Apache::lonlocal::texthash (
                   12582:         this => 'This file is an archive file.',
1.1067    raeburn  12583:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12584:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12585:         youm => 'You may wish to extract its contents.',
                   12586:         extr => 'Extract contents',
1.1067    raeburn  12587:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12588:         proa => 'Process automatically?',
1.1053    raeburn  12589:         yes  => 'Yes',
                   12590:         no   => 'No',
1.1067    raeburn  12591:         fold => 'Title for folder containing movie',
                   12592:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12593:     );
1.1065    raeburn  12594:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12595:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12596:     my $info = &list_archive_contents($fileloc,\@paths);
                   12597:     if (@paths) {
                   12598:         foreach my $path (@paths) {
                   12599:             $path =~ s{^/}{};
1.1067    raeburn  12600:             if ($path =~ m{^([^/]+)/$}) {
                   12601:                 $topdir = $1;
                   12602:             }
1.1065    raeburn  12603:             if ($path =~ m{^([^/]+)/}) {
                   12604:                 $toplevel{$1} = $path;
                   12605:             } else {
                   12606:                 $toplevel{$path} = $path;
                   12607:             }
                   12608:         }
                   12609:     }
1.1067    raeburn  12610:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12611:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12612:                         "$topdir/media/",
                   12613:                         "$topdir/media/$topdir.mp4",
                   12614:                         "$topdir/media/FirstFrame.png",
                   12615:                         "$topdir/media/player.swf",
                   12616:                         "$topdir/media/swfobject.js",
                   12617:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12618:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12619:                          "$topdir/$topdir.mp4",
                   12620:                          "$topdir/$topdir\_config.xml",
                   12621:                          "$topdir/$topdir\_controller.swf",
                   12622:                          "$topdir/$topdir\_embed.css",
                   12623:                          "$topdir/$topdir\_First_Frame.png",
                   12624:                          "$topdir/$topdir\_player.html",
                   12625:                          "$topdir/$topdir\_Thumbnails.png",
                   12626:                          "$topdir/playerProductInstall.swf",
                   12627:                          "$topdir/scripts/",
                   12628:                          "$topdir/scripts/config_xml.js",
                   12629:                          "$topdir/scripts/handlebars.js",
                   12630:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12631:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12632:                          "$topdir/scripts/modernizr.js",
                   12633:                          "$topdir/scripts/player-min.js",
                   12634:                          "$topdir/scripts/swfobject.js",
                   12635:                          "$topdir/skins/",
                   12636:                          "$topdir/skins/configuration_express.xml",
                   12637:                          "$topdir/skins/express_show/",
                   12638:                          "$topdir/skins/express_show/player-min.css",
                   12639:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12640:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12641:                          "$topdir/$topdir.mp4",
                   12642:                          "$topdir/$topdir\_config.xml",
                   12643:                          "$topdir/$topdir\_controller.swf",
                   12644:                          "$topdir/$topdir\_embed.css",
                   12645:                          "$topdir/$topdir\_First_Frame.png",
                   12646:                          "$topdir/$topdir\_player.html",
                   12647:                          "$topdir/$topdir\_Thumbnails.png",
                   12648:                          "$topdir/playerProductInstall.swf",
                   12649:                          "$topdir/scripts/",
                   12650:                          "$topdir/scripts/config_xml.js",
                   12651:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12652:                          "$topdir/skins/",
                   12653:                          "$topdir/skins/configuration_express.xml",
                   12654:                          "$topdir/skins/express_show/",
                   12655:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12656:                          "$topdir/skins/express_show/spritesheet.png",
                   12657:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12658:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12659:         if (@diffs == 0) {
1.1164    raeburn  12660:             $is_camtasia = 6;
                   12661:         } else {
1.1197    raeburn  12662:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12663:             if (@diffs == 0) {
                   12664:                 $is_camtasia = 8;
1.1197    raeburn  12665:             } else {
                   12666:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12667:                 if (@diffs == 0) {
                   12668:                     $is_camtasia = 8;
                   12669:                 }
1.1164    raeburn  12670:             }
1.1067    raeburn  12671:         }
                   12672:     }
                   12673:     my $output;
                   12674:     if ($is_camtasia) {
                   12675:         $output = <<"ENDCAM";
                   12676: <script type="text/javascript" language="Javascript">
                   12677: // <![CDATA[
                   12678: 
                   12679: function camtasiaToggle() {
                   12680:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12681:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12682:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12683:                 document.getElementById('camtasia_titles').style.display='block';
                   12684:             } else {
                   12685:                 document.getElementById('camtasia_titles').style.display='none';
                   12686:             }
                   12687:         }
                   12688:     }
                   12689:     return;
                   12690: }
                   12691: 
                   12692: // ]]>
                   12693: </script>
                   12694: <p>$lt{'camt'}</p>
                   12695: ENDCAM
1.1065    raeburn  12696:     } else {
1.1067    raeburn  12697:         $output = '<p>'.$lt{'this'};
                   12698:         if ($info eq '') {
                   12699:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12700:         } else {
                   12701:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12702:                        '<div><pre>'.$info.'</pre></div>';
                   12703:         }
1.1065    raeburn  12704:     }
1.1067    raeburn  12705:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12706:     my $duplicates;
                   12707:     my $num = 0;
                   12708:     if (ref($dirlist) eq 'ARRAY') {
                   12709:         foreach my $item (@{$dirlist}) {
                   12710:             if (ref($item) eq 'ARRAY') {
                   12711:                 if (exists($toplevel{$item->[0]})) {
                   12712:                     $duplicates .= 
                   12713:                         &start_data_table_row().
                   12714:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12715:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12716:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12717:                         'value="1" />'.&mt('Yes').'</label>'.
                   12718:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12719:                         '<td>'.$item->[0].'</td>';
                   12720:                     if ($item->[2]) {
                   12721:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12722:                     } else {
                   12723:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12724:                     }
                   12725:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12726:                                    '<td>'.
                   12727:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12728:                                    '</td>'.
                   12729:                                    &end_data_table_row();
                   12730:                     $num ++;
                   12731:                 }
                   12732:             }
                   12733:         }
                   12734:     }
                   12735:     my $itemcount;
                   12736:     if (@paths > 0) {
                   12737:         $itemcount = scalar(@paths);
                   12738:     } else {
                   12739:         $itemcount = 1;
                   12740:     }
1.1067    raeburn  12741:     if ($is_camtasia) {
                   12742:         $output .= $lt{'auto'}.'<br />'.
                   12743:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12744:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12745:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12746:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12747:                    $lt{'no'}.'</label></span><br />'.
                   12748:                    '<div id="camtasia_titles" style="display:block">'.
                   12749:                    &Apache::lonhtmlcommon::start_pick_box().
                   12750:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12751:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12752:                    &Apache::lonhtmlcommon::row_closure().
                   12753:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12754:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12755:                    &Apache::lonhtmlcommon::row_closure(1).
                   12756:                    &Apache::lonhtmlcommon::end_pick_box().
                   12757:                    '</div>';
                   12758:     }
1.1065    raeburn  12759:     $output .= 
                   12760:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12761:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12762:         "\n";
1.1065    raeburn  12763:     if ($duplicates ne '') {
                   12764:         $output .= '<p><span class="LC_warning">'.
                   12765:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12766:                    &start_data_table().
                   12767:                    &start_data_table_header_row().
                   12768:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12769:                    '<th>'.&mt('Name').'</th>'.
                   12770:                    '<th>'.&mt('Type').'</th>'.
                   12771:                    '<th>'.&mt('Size').'</th>'.
                   12772:                    '<th>'.&mt('Last modified').'</th>'.
                   12773:                    &end_data_table_header_row().
                   12774:                    $duplicates.
                   12775:                    &end_data_table().
                   12776:                    '</p>';
                   12777:     }
1.1067    raeburn  12778:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12779:     if (ref($hiddenelements) eq 'HASH') {
                   12780:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12781:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12782:         }
                   12783:     }
                   12784:     $output .= <<"END";
1.1067    raeburn  12785: <br />
1.1053    raeburn  12786: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12787: </form>
                   12788: $noextract
                   12789: END
                   12790:     return $output;
                   12791: }
                   12792: 
1.1065    raeburn  12793: sub decompression_utility {
                   12794:     my ($program) = @_;
                   12795:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12796:     my $location;
                   12797:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12798:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12799:                          '/usr/sbin/') {
                   12800:             if (-x $dir.$program) {
                   12801:                 $location = $dir.$program;
                   12802:                 last;
                   12803:             }
                   12804:         }
                   12805:     }
                   12806:     return $location;
                   12807: }
                   12808: 
                   12809: sub list_archive_contents {
                   12810:     my ($file,$pathsref) = @_;
                   12811:     my (@cmd,$output);
                   12812:     my $needsregexp;
                   12813:     if ($file =~ /\.zip$/) {
                   12814:         @cmd = (&decompression_utility('unzip'),"-l");
                   12815:         $needsregexp = 1;
                   12816:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12817:              ($file =~ /\.tgz$/)) {
                   12818:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12819:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12820:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12821:     } elsif ($file =~ m|\.tar$|) {
                   12822:         @cmd = (&decompression_utility('tar'),"-tf");
                   12823:     }
                   12824:     if (@cmd) {
                   12825:         undef($!);
                   12826:         undef($@);
                   12827:         if (open(my $fh,"-|", @cmd, $file)) {
                   12828:             while (my $line = <$fh>) {
                   12829:                 $output .= $line;
                   12830:                 chomp($line);
                   12831:                 my $item;
                   12832:                 if ($needsregexp) {
                   12833:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12834:                 } else {
                   12835:                     $item = $line;
                   12836:                 }
                   12837:                 if ($item ne '') {
                   12838:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12839:                         push(@{$pathsref},$item);
                   12840:                     } 
                   12841:                 }
                   12842:             }
                   12843:             close($fh);
                   12844:         }
                   12845:     }
                   12846:     return $output;
                   12847: }
                   12848: 
1.1053    raeburn  12849: sub decompress_uploaded_file {
                   12850:     my ($file,$dir) = @_;
                   12851:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12852:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12853:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12854:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12855:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12856:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12857:     my $decompressed = $env{'cgi.decompressed'};
                   12858:     &Apache::lonnet::delenv('cgi.file');
                   12859:     &Apache::lonnet::delenv('cgi.dir');
                   12860:     &Apache::lonnet::delenv('cgi.decompressed');
                   12861:     return ($decompressed,$result);
                   12862: }
                   12863: 
1.1055    raeburn  12864: sub process_decompression {
                   12865:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  12866:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12867:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12868:                &mt('Unexpected file path.').'</p>'."\n";
                   12869:     }
                   12870:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12871:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12872:                &mt('Unexpected course context.').'</p>'."\n";
                   12873:     }
1.1293    raeburn  12874:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  12875:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12876:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12877:     }
1.1055    raeburn  12878:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12879:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12880:         $error = &mt('Filename not a supported archive file type.').
                   12881:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12882:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12883:     } else {
                   12884:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12885:         if ($docuhome eq 'no_host') {
                   12886:             $error = &mt('Could not determine home server for course.');
                   12887:         } else {
                   12888:             my @ids=&Apache::lonnet::current_machine_ids();
                   12889:             my $currdir = "$dir_root/$destination";
                   12890:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12891:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12892:                        "$dir_root/$destination";
                   12893:             } else {
                   12894:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12895:                        "$dir_root/$docudom/$docuname/$destination";
                   12896:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12897:                     $error = &mt('Archive file not found.');
                   12898:                 }
                   12899:             }
1.1065    raeburn  12900:             my (@to_overwrite,@to_skip);
                   12901:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12902:                 my $total = $env{'form.archive_overwrite_total'};
                   12903:                 for (my $i=0; $i<$total; $i++) {
                   12904:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12905:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12906:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12907:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12908:                     }
                   12909:                 }
                   12910:             }
                   12911:             my $numskip = scalar(@to_skip);
1.1292    raeburn  12912:             my $numoverwrite = scalar(@to_overwrite);
                   12913:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  12914:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12915:             } elsif ($dir eq '') {
1.1055    raeburn  12916:                 $error = &mt('Directory containing archive file unavailable.');
                   12917:             } elsif (!$error) {
1.1065    raeburn  12918:                 my ($decompressed,$display);
1.1292    raeburn  12919:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12920:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12921:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  12922:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12923:                         ($decompressed,$display) = 
                   12924:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12925:                         foreach my $item (@to_skip) {
                   12926:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12927:                                 if (-f "$dir/$tempdir/$item") { 
                   12928:                                     unlink("$dir/$tempdir/$item");
                   12929:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  12930:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  12931:                                 }
                   12932:                             }
                   12933:                         }
                   12934:                         foreach my $item (@to_overwrite) {
                   12935:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12936:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12937:                                     if (-f "$dir/$item") {
                   12938:                                         unlink("$dir/$item");
                   12939:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  12940:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  12941:                                     }
                   12942:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12943:                                 }
1.1065    raeburn  12944:                             }
                   12945:                         }
1.1292    raeburn  12946:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  12947:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  12948:                         }
1.1065    raeburn  12949:                     }
                   12950:                 } else {
                   12951:                     ($decompressed,$display) = 
                   12952:                         &decompress_uploaded_file($file,$dir);
                   12953:                 }
1.1055    raeburn  12954:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12955:                     $output = '<p class="LC_info">'.
                   12956:                               &mt('Files extracted successfully from archive.').
                   12957:                               '</p>'."\n";
1.1055    raeburn  12958:                     my ($warning,$result,@contents);
                   12959:                     my ($newdirlistref,$newlisterror) =
                   12960:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12961:                                                  $docuname,1);
                   12962:                     my (%is_dir,%changes,@newitems);
                   12963:                     my $dirptr = 16384;
1.1065    raeburn  12964:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12965:                         foreach my $dir_line (@{$newdirlistref}) {
                   12966:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  12967:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  12968:                                 push(@newitems,$item);
                   12969:                                 if ($dirptr&$testdir) {
                   12970:                                     $is_dir{$item} = 1;
                   12971:                                 }
                   12972:                                 $changes{$item} = 1;
                   12973:                             }
                   12974:                         }
                   12975:                     }
                   12976:                     if (keys(%changes) > 0) {
                   12977:                         foreach my $item (sort(@newitems)) {
                   12978:                             if ($changes{$item}) {
                   12979:                                 push(@contents,$item);
                   12980:                             }
                   12981:                         }
                   12982:                     }
                   12983:                     if (@contents > 0) {
1.1067    raeburn  12984:                         my $wantform;
                   12985:                         unless ($env{'form.autoextract_camtasia'}) {
                   12986:                             $wantform = 1;
                   12987:                         }
1.1056    raeburn  12988:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12989:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12990:                                                                 $currdir,\%is_dir,
                   12991:                                                                 \%children,\%parent,
1.1056    raeburn  12992:                                                                 \@contents,\%dirorder,
                   12993:                                                                 \%titles,$wantform);
1.1055    raeburn  12994:                         if ($datatable ne '') {
                   12995:                             $output .= &archive_options_form('decompressed',$datatable,
                   12996:                                                              $count,$hiddenelem);
1.1065    raeburn  12997:                             my $startcount = 6;
1.1055    raeburn  12998:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12999:                                                            \%titles,\%children);
1.1055    raeburn  13000:                         }
1.1067    raeburn  13001:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13002:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13003:                             my %displayed;
                   13004:                             my $total = 1;
                   13005:                             $env{'form.archive_directory'} = [];
                   13006:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13007:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13008:                                 $path =~ s{/$}{};
                   13009:                                 my $item;
                   13010:                                 if ($path ne '') {
                   13011:                                     $item = "$path/$titles{$i}";
                   13012:                                 } else {
                   13013:                                     $item = $titles{$i};
                   13014:                                 }
                   13015:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13016:                                 if ($item eq $contents[0]) {
                   13017:                                     push(@{$env{'form.archive_directory'}},$i);
                   13018:                                     $env{'form.archive_'.$i} = 'display';
                   13019:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13020:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13021:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13022:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13023:                                     $env{'form.archive_'.$i} = 'display';
                   13024:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13025:                                     $displayed{'web'} = $i;
                   13026:                                 } else {
1.1164    raeburn  13027:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13028:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13029:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13030:                                         push(@{$env{'form.archive_directory'}},$i);
                   13031:                                     }
                   13032:                                     $env{'form.archive_'.$i} = 'dependency';
                   13033:                                 }
                   13034:                                 $total ++;
                   13035:                             }
                   13036:                             for (my $i=1; $i<$total; $i++) {
                   13037:                                 next if ($i == $displayed{'web'});
                   13038:                                 next if ($i == $displayed{'folder'});
                   13039:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13040:                             }
                   13041:                             $env{'form.phase'} = 'decompress_cleanup';
                   13042:                             $env{'form.archivedelete'} = 1;
                   13043:                             $env{'form.archive_count'} = $total-1;
                   13044:                             $output .=
                   13045:                                 &process_extracted_files('coursedocs',$docudom,
                   13046:                                                          $docuname,$destination,
                   13047:                                                          $dir_root,$hiddenelem);
                   13048:                         }
1.1055    raeburn  13049:                     } else {
                   13050:                         $warning = &mt('No new items extracted from archive file.');
                   13051:                     }
                   13052:                 } else {
                   13053:                     $output = $display;
                   13054:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13055:                 }
                   13056:             }
                   13057:         }
                   13058:     }
                   13059:     if ($error) {
                   13060:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13061:                    $error.'</p>'."\n";
                   13062:     }
                   13063:     if ($warning) {
                   13064:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13065:     }
                   13066:     return $output;
                   13067: }
                   13068: 
                   13069: sub get_extracted {
1.1056    raeburn  13070:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13071:         $titles,$wantform) = @_;
1.1055    raeburn  13072:     my $count = 0;
                   13073:     my $depth = 0;
                   13074:     my $datatable;
1.1056    raeburn  13075:     my @hierarchy;
1.1055    raeburn  13076:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13077:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13078:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13079:     foreach my $item (@{$contents}) {
                   13080:         $count ++;
1.1056    raeburn  13081:         @{$dirorder->{$count}} = @hierarchy;
                   13082:         $titles->{$count} = $item;
1.1055    raeburn  13083:         &archive_hierarchy($depth,$count,$parent,$children);
                   13084:         if ($wantform) {
                   13085:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13086:                                        $currdir,$depth,$count);
                   13087:         }
                   13088:         if ($is_dir->{$item}) {
                   13089:             $depth ++;
1.1056    raeburn  13090:             push(@hierarchy,$count);
                   13091:             $parent->{$depth} = $count;
1.1055    raeburn  13092:             $datatable .=
                   13093:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13094:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13095:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13096:             $depth --;
1.1056    raeburn  13097:             pop(@hierarchy);
1.1055    raeburn  13098:         }
                   13099:     }
                   13100:     return ($count,$datatable);
                   13101: }
                   13102: 
                   13103: sub recurse_extracted_archive {
1.1056    raeburn  13104:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13105:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13106:     my $result='';
1.1056    raeburn  13107:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13108:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13109:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13110:         return $result;
                   13111:     }
                   13112:     my $dirptr = 16384;
                   13113:     my ($newdirlistref,$newlisterror) =
                   13114:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13115:     if (ref($newdirlistref) eq 'ARRAY') {
                   13116:         foreach my $dir_line (@{$newdirlistref}) {
                   13117:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13118:             unless ($item =~ /^\.+$/) {
                   13119:                 $$count ++;
1.1056    raeburn  13120:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13121:                 $titles->{$$count} = $item;
1.1055    raeburn  13122:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13123: 
1.1055    raeburn  13124:                 my $is_dir;
                   13125:                 if ($dirptr&$testdir) {
                   13126:                     $is_dir = 1;
                   13127:                 }
                   13128:                 if ($wantform) {
                   13129:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13130:                 }
                   13131:                 if ($is_dir) {
                   13132:                     $$depth ++;
1.1056    raeburn  13133:                     push(@{$hierarchy},$$count);
                   13134:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13135:                     $result .=
                   13136:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13137:                                                    $docuname,$depth,$count,
1.1056    raeburn  13138:                                                    $hierarchy,$dirorder,$children,
                   13139:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13140:                     $$depth --;
1.1056    raeburn  13141:                     pop(@{$hierarchy});
1.1055    raeburn  13142:                 }
                   13143:             }
                   13144:         }
                   13145:     }
                   13146:     return $result;
                   13147: }
                   13148: 
                   13149: sub archive_hierarchy {
                   13150:     my ($depth,$count,$parent,$children) =@_;
                   13151:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13152:         if (exists($parent->{$depth})) {
                   13153:              $children->{$parent->{$depth}} .= $count.':';
                   13154:         }
                   13155:     }
                   13156:     return;
                   13157: }
                   13158: 
                   13159: sub archive_row {
                   13160:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13161:     my ($name) = ($item =~ m{([^/]+)$});
                   13162:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13163:                                        'display'    => 'Add as file',
1.1055    raeburn  13164:                                        'dependency' => 'Include as dependency',
                   13165:                                        'discard'    => 'Discard',
                   13166:                                       );
                   13167:     if ($is_dir) {
1.1059    raeburn  13168:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13169:     }
1.1056    raeburn  13170:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13171:     my $offset = 0;
1.1055    raeburn  13172:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13173:         $offset ++;
1.1065    raeburn  13174:         if ($action ne 'display') {
                   13175:             $offset ++;
                   13176:         }  
1.1055    raeburn  13177:         $output .= '<td><span class="LC_nobreak">'.
                   13178:                    '<label><input type="radio" name="archive_'.$count.
                   13179:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13180:         my $text = $choices{$action};
                   13181:         if ($is_dir) {
                   13182:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13183:             if ($action eq 'display') {
1.1059    raeburn  13184:                 $text = &mt('Add as folder');
1.1055    raeburn  13185:             }
1.1056    raeburn  13186:         } else {
                   13187:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13188: 
                   13189:         }
                   13190:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13191:         if ($action eq 'dependency') {
                   13192:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13193:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13194:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13195:                        '<option value=""></option>'."\n".
                   13196:                        '</select>'."\n".
                   13197:                        '</div>';
1.1059    raeburn  13198:         } elsif ($action eq 'display') {
                   13199:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13200:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13201:                        '</div>';
1.1055    raeburn  13202:         }
1.1056    raeburn  13203:         $output .= '</td>';
1.1055    raeburn  13204:     }
                   13205:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13206:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13207:     for (my $i=0; $i<$depth; $i++) {
                   13208:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13209:     }
                   13210:     if ($is_dir) {
                   13211:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13212:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13213:     } else {
                   13214:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13215:     }
                   13216:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13217:                &end_data_table_row();
                   13218:     return $output;
                   13219: }
                   13220: 
                   13221: sub archive_options_form {
1.1065    raeburn  13222:     my ($form,$display,$count,$hiddenelem) = @_;
                   13223:     my %lt = &Apache::lonlocal::texthash(
                   13224:                perm => 'Permanently remove archive file?',
                   13225:                hows => 'How should each extracted item be incorporated in the course?',
                   13226:                cont => 'Content actions for all',
                   13227:                addf => 'Add as folder/file',
                   13228:                incd => 'Include as dependency for a displayed file',
                   13229:                disc => 'Discard',
                   13230:                no   => 'No',
                   13231:                yes  => 'Yes',
                   13232:                save => 'Save',
                   13233:     );
                   13234:     my $output = <<"END";
                   13235: <form name="$form" method="post" action="">
                   13236: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13237: <label>
                   13238:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13239: </label>
                   13240: &nbsp;
                   13241: <label>
                   13242:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13243: </span>
                   13244: </p>
                   13245: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13246: <br />$lt{'hows'}
                   13247: <div class="LC_columnSection">
                   13248:   <fieldset>
                   13249:     <legend>$lt{'cont'}</legend>
                   13250:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13251:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13252:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13253:   </fieldset>
                   13254: </div>
                   13255: END
                   13256:     return $output.
1.1055    raeburn  13257:            &start_data_table()."\n".
1.1065    raeburn  13258:            $display."\n".
1.1055    raeburn  13259:            &end_data_table()."\n".
                   13260:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13261:            $hiddenelem.
1.1065    raeburn  13262:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13263:            '</form>';
                   13264: }
                   13265: 
                   13266: sub archive_javascript {
1.1056    raeburn  13267:     my ($startcount,$numitems,$titles,$children) = @_;
                   13268:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13269:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13270:     my $scripttag = <<START;
                   13271: <script type="text/javascript">
                   13272: // <![CDATA[
                   13273: 
                   13274: function checkAll(form,prefix) {
                   13275:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13276:     for (var i=0; i < form.elements.length; i++) {
                   13277:         var id = form.elements[i].id;
                   13278:         if ((id != '') && (id != undefined)) {
                   13279:             if (idstr.test(id)) {
                   13280:                 if (form.elements[i].type == 'radio') {
                   13281:                     form.elements[i].checked = true;
1.1056    raeburn  13282:                     var nostart = i-$startcount;
1.1059    raeburn  13283:                     var offset = nostart%7;
                   13284:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13285:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13286:                 }
                   13287:             }
                   13288:         }
                   13289:     }
                   13290: }
                   13291: 
                   13292: function propagateCheck(form,count) {
                   13293:     if (count > 0) {
1.1059    raeburn  13294:         var startelement = $startcount + ((count-1) * 7);
                   13295:         for (var j=1; j<6; j++) {
                   13296:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13297:                 var item = startelement + j; 
                   13298:                 if (form.elements[item].type == 'radio') {
                   13299:                     if (form.elements[item].checked) {
                   13300:                         containerCheck(form,count,j);
                   13301:                         break;
                   13302:                     }
1.1055    raeburn  13303:                 }
                   13304:             }
                   13305:         }
                   13306:     }
                   13307: }
                   13308: 
                   13309: numitems = $numitems
1.1056    raeburn  13310: var titles = new Array(numitems);
                   13311: var parents = new Array(numitems);
1.1055    raeburn  13312: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13313:     parents[i] = new Array;
1.1055    raeburn  13314: }
1.1059    raeburn  13315: var maintitle = '$maintitle';
1.1055    raeburn  13316: 
                   13317: START
                   13318: 
1.1056    raeburn  13319:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13320:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13321:         for (my $i=0; $i<@contents; $i ++) {
                   13322:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13323:         }
                   13324:     }
                   13325: 
1.1056    raeburn  13326:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13327:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13328:     }
                   13329: 
1.1055    raeburn  13330:     $scripttag .= <<END;
                   13331: 
                   13332: function containerCheck(form,count,offset) {
                   13333:     if (count > 0) {
1.1056    raeburn  13334:         dependencyCheck(form,count,offset);
1.1059    raeburn  13335:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13336:         form.elements[item].checked = true;
                   13337:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13338:             if (parents[count].length > 0) {
                   13339:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13340:                     containerCheck(form,parents[count][j],offset);
                   13341:                 }
                   13342:             }
                   13343:         }
                   13344:     }
                   13345: }
                   13346: 
                   13347: function dependencyCheck(form,count,offset) {
                   13348:     if (count > 0) {
1.1059    raeburn  13349:         var chosen = (offset+$startcount)+7*(count-1);
                   13350:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13351:         var currtype = form.elements[depitem].type;
                   13352:         if (form.elements[chosen].value == 'dependency') {
                   13353:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13354:             form.elements[depitem].options.length = 0;
                   13355:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13356:             for (var i=1; i<=numitems; i++) {
                   13357:                 if (i == count) {
                   13358:                     continue;
                   13359:                 }
1.1059    raeburn  13360:                 var startelement = $startcount + (i-1) * 7;
                   13361:                 for (var j=1; j<6; j++) {
                   13362:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13363:                         var item = startelement + j;
                   13364:                         if (form.elements[item].type == 'radio') {
                   13365:                             if (form.elements[item].checked) {
                   13366:                                 if (form.elements[item].value == 'display') {
                   13367:                                     var n = form.elements[depitem].options.length;
                   13368:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13369:                                 }
                   13370:                             }
                   13371:                         }
                   13372:                     }
                   13373:                 }
                   13374:             }
                   13375:         } else {
                   13376:             document.getElementById('arc_depon_'+count).style.display='none';
                   13377:             form.elements[depitem].options.length = 0;
                   13378:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13379:         }
1.1059    raeburn  13380:         titleCheck(form,count,offset);
1.1056    raeburn  13381:     }
                   13382: }
                   13383: 
                   13384: function propagateSelect(form,count,offset) {
                   13385:     if (count > 0) {
1.1065    raeburn  13386:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13387:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13388:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13389:             if (parents[count].length > 0) {
                   13390:                 for (var j=0; j<parents[count].length; j++) {
                   13391:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13392:                 }
                   13393:             }
                   13394:         }
                   13395:     }
                   13396: }
1.1056    raeburn  13397: 
                   13398: function containerSelect(form,count,offset,picked) {
                   13399:     if (count > 0) {
1.1065    raeburn  13400:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13401:         if (form.elements[item].type == 'radio') {
                   13402:             if (form.elements[item].value == 'dependency') {
                   13403:                 if (form.elements[item+1].type == 'select-one') {
                   13404:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13405:                         if (form.elements[item+1].options[i].value == picked) {
                   13406:                             form.elements[item+1].selectedIndex = i;
                   13407:                             break;
                   13408:                         }
                   13409:                     }
                   13410:                 }
                   13411:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13412:                     if (parents[count].length > 0) {
                   13413:                         for (var j=0; j<parents[count].length; j++) {
                   13414:                             containerSelect(form,parents[count][j],offset,picked);
                   13415:                         }
                   13416:                     }
                   13417:                 }
                   13418:             }
                   13419:         }
                   13420:     }
                   13421: }
                   13422: 
1.1059    raeburn  13423: function titleCheck(form,count,offset) {
                   13424:     if (count > 0) {
                   13425:         var chosen = (offset+$startcount)+7*(count-1);
                   13426:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13427:         var currtype = form.elements[depitem].type;
                   13428:         if (form.elements[chosen].value == 'display') {
                   13429:             document.getElementById('arc_title_'+count).style.display='block';
                   13430:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13431:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13432:             }
                   13433:         } else {
                   13434:             document.getElementById('arc_title_'+count).style.display='none';
                   13435:             if (currtype == 'text') { 
                   13436:                 document.getElementById('archive_title_'+count).value='';
                   13437:             }
                   13438:         }
                   13439:     }
                   13440:     return;
                   13441: }
                   13442: 
1.1055    raeburn  13443: // ]]>
                   13444: </script>
                   13445: END
                   13446:     return $scripttag;
                   13447: }
                   13448: 
                   13449: sub process_extracted_files {
1.1067    raeburn  13450:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13451:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  13452:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13453:     my @ids=&Apache::lonnet::current_machine_ids();
                   13454:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13455:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13456:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13457:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13458:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13459:         $pathtocheck = "$dir_root/$destination";
                   13460:         $dir = $dir_root;
                   13461:         $ishome = 1;
                   13462:     } else {
                   13463:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13464:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  13465:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13466:     }
                   13467:     my $currdir = "$dir_root/$destination";
                   13468:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13469:     if ($env{'form.folderpath'}) {
                   13470:         my @items = split('&',$env{'form.folderpath'});
                   13471:         $folders{'0'} = $items[-2];
1.1099    raeburn  13472:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13473:             $containers{'0'}='page';
                   13474:         } else {  
                   13475:             $containers{'0'}='sequence';
                   13476:         }
1.1055    raeburn  13477:     }
                   13478:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13479:     if ($numitems) {
                   13480:         for (my $i=1; $i<=$numitems; $i++) {
                   13481:             my $path = $env{'form.archive_content_'.$i};
                   13482:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13483:                 my $item = $1;
                   13484:                 $toplevelitems{$item} = $i;
                   13485:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13486:                     $is_dir{$item} = 1;
                   13487:                 }
                   13488:             }
                   13489:         }
                   13490:     }
1.1067    raeburn  13491:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13492:     if (keys(%toplevelitems) > 0) {
                   13493:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13494:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13495:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13496:     }
1.1066    raeburn  13497:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13498:     if ($numitems) {
                   13499:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13500:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13501:             my $path = $env{'form.archive_content_'.$i};
                   13502:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13503:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13504:                     if ($prefix ne '' && $path ne '') {
                   13505:                         if (-e $prefix.$path) {
1.1066    raeburn  13506:                             if ((@archdirs > 0) && 
                   13507:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13508:                                 $todeletedir{$prefix.$path} = 1;
                   13509:                             } else {
                   13510:                                 $todelete{$prefix.$path} = 1;
                   13511:                             }
1.1055    raeburn  13512:                         }
                   13513:                     }
                   13514:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13515:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13516:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13517:                     $docstitle = $env{'form.archive_title_'.$i};
                   13518:                     if ($docstitle eq '') {
                   13519:                         $docstitle = $title;
                   13520:                     }
1.1055    raeburn  13521:                     $outer = 0;
1.1056    raeburn  13522:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13523:                         if (@{$dirorder{$i}} > 0) {
                   13524:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13525:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13526:                                     $outer = $item;
                   13527:                                     last;
                   13528:                                 }
                   13529:                             }
                   13530:                         }
                   13531:                     }
                   13532:                     my ($errtext,$fatal) = 
                   13533:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13534:                                                '/'.$folders{$outer}.'.'.
                   13535:                                                $containers{$outer});
                   13536:                     next if ($fatal);
                   13537:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13538:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13539:                             $mapinner{$i} = time;
1.1055    raeburn  13540:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13541:                             $containers{$i} = 'sequence';
                   13542:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13543:                                       $folders{$i}.'.'.$containers{$i};
                   13544:                             my $newidx = &LONCAPA::map::getresidx();
                   13545:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13546:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13547:                             push(@LONCAPA::map::order,$newidx);
                   13548:                             my ($outtext,$errtext) =
                   13549:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13550:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13551:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13552:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13553:                             unless ($errtext) {
1.1294    raeburn  13554:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13555:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   13556:                                             '</li>'."\n";
1.1067    raeburn  13557:                             }
1.1055    raeburn  13558:                         }
                   13559:                     } else {
                   13560:                         if ($context eq 'coursedocs') {
                   13561:                             my $newidx=&LONCAPA::map::getresidx();
                   13562:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13563:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13564:                                       $title;
1.1294    raeburn  13565:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   13566:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13567:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13568:                                 }
                   13569:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13570:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13571:                                 }
                   13572:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13573:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13574:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13575:                                         unless ($ishome) {
                   13576:                                             my $fetch = "$newdest{$i}/$title";
                   13577:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13578:                                             $prompttofetch{$fetch} = 1;
                   13579:                                         }
1.1292    raeburn  13580:                                     }
1.1067    raeburn  13581:                                 }
1.1294    raeburn  13582:                                 $LONCAPA::map::resources[$newidx]=
                   13583:                                     $docstitle.':'.$url.':false:normal:res';
                   13584:                                 push(@LONCAPA::map::order, $newidx);
                   13585:                                 my ($outtext,$errtext)=
                   13586:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13587:                                                             $docuname.'/'.$folders{$outer}.
                   13588:                                                             '.'.$containers{$outer},1,1);
                   13589:                                 unless ($errtext) {
                   13590:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13591:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13592:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13593:                                                    '</li>'."\n";
                   13594:                                     }
1.1067    raeburn  13595:                                 }
1.1294    raeburn  13596:                             } else {
                   13597:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13598:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  13599:                             }
1.1055    raeburn  13600:                         }
                   13601:                     }
1.1086    raeburn  13602:                 }
                   13603:             } else {
1.1294    raeburn  13604:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13605:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  13606:             }
                   13607:         }
                   13608:         for (my $i=1; $i<=$numitems; $i++) {
                   13609:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13610:             my $path = $env{'form.archive_content_'.$i};
                   13611:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13612:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13613:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13614:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13615:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13616:                         my ($itemidx,$fullpath,$relpath);
                   13617:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13618:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13619:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13620:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13621:                                     $itemidx = $j;
1.1056    raeburn  13622:                                 }
                   13623:                             }
1.1086    raeburn  13624:                         }
                   13625:                         if ($itemidx eq '') {
                   13626:                             $itemidx =  0;
                   13627:                         } 
                   13628:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13629:                             if ($mapinner{$referrer{$i}}) {
                   13630:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13631:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13632:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13633:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13634:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13635:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13636:                                             if (!-e $fullpath) {
                   13637:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13638:                                             }
                   13639:                                         }
1.1086    raeburn  13640:                                     } else {
                   13641:                                         last;
1.1056    raeburn  13642:                                     }
1.1086    raeburn  13643:                                 }
                   13644:                             }
                   13645:                         } elsif ($newdest{$referrer{$i}}) {
                   13646:                             $fullpath = $newdest{$referrer{$i}};
                   13647:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13648:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13649:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13650:                                     last;
                   13651:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13652:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13653:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13654:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13655:                                         if (!-e $fullpath) {
                   13656:                                             mkdir($fullpath,0755);
1.1056    raeburn  13657:                                         }
                   13658:                                     }
1.1086    raeburn  13659:                                 } else {
                   13660:                                     last;
1.1056    raeburn  13661:                                 }
1.1055    raeburn  13662:                             }
                   13663:                         }
1.1086    raeburn  13664:                         if ($fullpath ne '') {
                   13665:                             if (-e "$prefix$path") {
1.1292    raeburn  13666:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13667:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13668:                                 }
1.1086    raeburn  13669:                             }
                   13670:                             if (-e "$fullpath/$title") {
                   13671:                                 my $showpath;
                   13672:                                 if ($relpath ne '') {
                   13673:                                     $showpath = "$relpath/$title";
                   13674:                                 } else {
                   13675:                                     $showpath = "/$title";
                   13676:                                 } 
1.1294    raeburn  13677:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13678:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13679:                                            '</li>'."\n";
1.1292    raeburn  13680:                                 unless ($ishome) {
                   13681:                                     my $fetch = "$fullpath/$title";
                   13682:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   13683:                                     $prompttofetch{$fetch} = 1;
                   13684:                                 }
1.1086    raeburn  13685:                             }
                   13686:                         }
1.1055    raeburn  13687:                     }
1.1086    raeburn  13688:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13689:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  13690:                                     &HTML::Entities::encode($path,'<>&"'),
                   13691:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13692:                                 '<br />';
1.1055    raeburn  13693:                 }
                   13694:             } else {
1.1294    raeburn  13695:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  13696:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13697:             }
                   13698:         }
                   13699:         if (keys(%todelete)) {
                   13700:             foreach my $key (keys(%todelete)) {
                   13701:                 unlink($key);
1.1066    raeburn  13702:             }
                   13703:         }
                   13704:         if (keys(%todeletedir)) {
                   13705:             foreach my $key (keys(%todeletedir)) {
                   13706:                 rmdir($key);
                   13707:             }
                   13708:         }
                   13709:         foreach my $dir (sort(keys(%is_dir))) {
                   13710:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13711:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13712:             }
                   13713:         }
1.1067    raeburn  13714:         if ($result ne '') {
                   13715:             $output .= '<ul>'."\n".
                   13716:                        $result."\n".
                   13717:                        '</ul>';
                   13718:         }
                   13719:         unless ($ishome) {
                   13720:             my $replicationfail;
                   13721:             foreach my $item (keys(%prompttofetch)) {
                   13722:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13723:                 unless ($fetchresult eq 'ok') {
                   13724:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13725:                 }
                   13726:             }
                   13727:             if ($replicationfail) {
                   13728:                 $output .= '<p class="LC_error">'.
                   13729:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13730:                            $replicationfail.
                   13731:                            '</ul></p>';
                   13732:             }
                   13733:         }
1.1055    raeburn  13734:     } else {
                   13735:         $warning = &mt('No items found in archive.');
                   13736:     }
                   13737:     if ($error) {
                   13738:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13739:                    $error.'</p>'."\n";
                   13740:     }
                   13741:     if ($warning) {
                   13742:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13743:     }
                   13744:     return $output;
                   13745: }
                   13746: 
1.1066    raeburn  13747: sub cleanup_empty_dirs {
                   13748:     my ($path) = @_;
                   13749:     if (($path ne '') && (-d $path)) {
                   13750:         if (opendir(my $dirh,$path)) {
                   13751:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13752:             my $numitems = 0;
                   13753:             foreach my $item (@dircontents) {
                   13754:                 if (-d "$path/$item") {
1.1111    raeburn  13755:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13756:                     if (-e "$path/$item") {
                   13757:                         $numitems ++;
                   13758:                     }
                   13759:                 } else {
                   13760:                     $numitems ++;
                   13761:                 }
                   13762:             }
                   13763:             if ($numitems == 0) {
                   13764:                 rmdir($path);
                   13765:             }
                   13766:             closedir($dirh);
                   13767:         }
                   13768:     }
                   13769:     return;
                   13770: }
                   13771: 
1.41      ng       13772: =pod
1.45      matthew  13773: 
1.1162    raeburn  13774: =item * &get_folder_hierarchy()
1.1068    raeburn  13775: 
                   13776: Provides hierarchy of names of folders/sub-folders containing the current
                   13777: item,
                   13778: 
                   13779: Inputs: 3
                   13780:      - $navmap - navmaps object
                   13781: 
                   13782:      - $map - url for map (either the trigger itself, or map containing
                   13783:                            the resource, which is the trigger).
                   13784: 
                   13785:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13786: 
                   13787: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13788: 
                   13789: =cut
                   13790: 
                   13791: sub get_folder_hierarchy {
                   13792:     my ($navmap,$map,$showitem) = @_;
                   13793:     my @pathitems;
                   13794:     if (ref($navmap)) {
                   13795:         my $mapres = $navmap->getResourceByUrl($map);
                   13796:         if (ref($mapres)) {
                   13797:             my $pcslist = $mapres->map_hierarchy();
                   13798:             if ($pcslist ne '') {
                   13799:                 my @pcs = split(/,/,$pcslist);
                   13800:                 foreach my $pc (@pcs) {
                   13801:                     if ($pc == 1) {
1.1129    raeburn  13802:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13803:                     } else {
                   13804:                         my $res = $navmap->getByMapPc($pc);
                   13805:                         if (ref($res)) {
                   13806:                             my $title = $res->compTitle();
                   13807:                             $title =~ s/\W+/_/g;
                   13808:                             if ($title ne '') {
                   13809:                                 push(@pathitems,$title);
                   13810:                             }
                   13811:                         }
                   13812:                     }
                   13813:                 }
                   13814:             }
1.1071    raeburn  13815:             if ($showitem) {
                   13816:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13817:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13818:                 } else {
                   13819:                     my $maptitle = $mapres->compTitle();
                   13820:                     $maptitle =~ s/\W+/_/g;
                   13821:                     if ($maptitle ne '') {
                   13822:                         push(@pathitems,$maptitle);
                   13823:                     }
1.1068    raeburn  13824:                 }
                   13825:             }
                   13826:         }
                   13827:     }
                   13828:     return @pathitems;
                   13829: }
                   13830: 
                   13831: =pod
                   13832: 
1.1015    raeburn  13833: =item * &get_turnedin_filepath()
                   13834: 
                   13835: Determines path in a user's portfolio file for storage of files uploaded
                   13836: to a specific essayresponse or dropbox item.
                   13837: 
                   13838: Inputs: 3 required + 1 optional.
                   13839: $symb is symb for resource, $uname and $udom are for current user (required).
                   13840: $caller is optional (can be "submission", if routine is called when storing
                   13841: an upoaded file when "Submit Answer" button was pressed).
                   13842: 
                   13843: Returns array containing $path and $multiresp. 
                   13844: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13845: than one file upload item.  Callers of routine should append partid as a 
                   13846: subdirectory to $path in cases where $multiresp is 1.
                   13847: 
                   13848: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13849: 
                   13850: =cut
                   13851: 
                   13852: sub get_turnedin_filepath {
                   13853:     my ($symb,$uname,$udom,$caller) = @_;
                   13854:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13855:     my $turnindir;
                   13856:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13857:     $turnindir = $userhash{'turnindir'};
                   13858:     my ($path,$multiresp);
                   13859:     if ($turnindir eq '') {
                   13860:         if ($caller eq 'submission') {
                   13861:             $turnindir = &mt('turned in');
                   13862:             $turnindir =~ s/\W+/_/g;
                   13863:             my %newhash = (
                   13864:                             'turnindir' => $turnindir,
                   13865:                           );
                   13866:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13867:         }
                   13868:     }
                   13869:     if ($turnindir ne '') {
                   13870:         $path = '/'.$turnindir.'/';
                   13871:         my ($multipart,$turnin,@pathitems);
                   13872:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13873:         if (defined($navmap)) {
                   13874:             my $mapres = $navmap->getResourceByUrl($map);
                   13875:             if (ref($mapres)) {
                   13876:                 my $pcslist = $mapres->map_hierarchy();
                   13877:                 if ($pcslist ne '') {
                   13878:                     foreach my $pc (split(/,/,$pcslist)) {
                   13879:                         my $res = $navmap->getByMapPc($pc);
                   13880:                         if (ref($res)) {
                   13881:                             my $title = $res->compTitle();
                   13882:                             $title =~ s/\W+/_/g;
                   13883:                             if ($title ne '') {
1.1149    raeburn  13884:                                 if (($pc > 1) && (length($title) > 12)) {
                   13885:                                     $title = substr($title,0,12);
                   13886:                                 }
1.1015    raeburn  13887:                                 push(@pathitems,$title);
                   13888:                             }
                   13889:                         }
                   13890:                     }
                   13891:                 }
                   13892:                 my $maptitle = $mapres->compTitle();
                   13893:                 $maptitle =~ s/\W+/_/g;
                   13894:                 if ($maptitle ne '') {
1.1149    raeburn  13895:                     if (length($maptitle) > 12) {
                   13896:                         $maptitle = substr($maptitle,0,12);
                   13897:                     }
1.1015    raeburn  13898:                     push(@pathitems,$maptitle);
                   13899:                 }
                   13900:                 unless ($env{'request.state'} eq 'construct') {
                   13901:                     my $res = $navmap->getBySymb($symb);
                   13902:                     if (ref($res)) {
                   13903:                         my $partlist = $res->parts();
                   13904:                         my $totaluploads = 0;
                   13905:                         if (ref($partlist) eq 'ARRAY') {
                   13906:                             foreach my $part (@{$partlist}) {
                   13907:                                 my @types = $res->responseType($part);
                   13908:                                 my @ids = $res->responseIds($part);
                   13909:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13910:                                     if ($types[$i] eq 'essay') {
                   13911:                                         my $partid = $part.'_'.$ids[$i];
                   13912:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13913:                                             $totaluploads ++;
                   13914:                                         }
                   13915:                                     }
                   13916:                                 }
                   13917:                             }
                   13918:                             if ($totaluploads > 1) {
                   13919:                                 $multiresp = 1;
                   13920:                             }
                   13921:                         }
                   13922:                     }
                   13923:                 }
                   13924:             } else {
                   13925:                 return;
                   13926:             }
                   13927:         } else {
                   13928:             return;
                   13929:         }
                   13930:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13931:         $restitle =~ s/\W+/_/g;
                   13932:         if ($restitle eq '') {
                   13933:             $restitle = ($resurl =~ m{/[^/]+$});
                   13934:             if ($restitle eq '') {
                   13935:                 $restitle = time;
                   13936:             }
                   13937:         }
1.1149    raeburn  13938:         if (length($restitle) > 12) {
                   13939:             $restitle = substr($restitle,0,12);
                   13940:         }
1.1015    raeburn  13941:         push(@pathitems,$restitle);
                   13942:         $path .= join('/',@pathitems);
                   13943:     }
                   13944:     return ($path,$multiresp);
                   13945: }
                   13946: 
                   13947: =pod
                   13948: 
1.464     albertel 13949: =back
1.41      ng       13950: 
1.112     bowersj2 13951: =head1 CSV Upload/Handling functions
1.38      albertel 13952: 
1.41      ng       13953: =over 4
                   13954: 
1.648     raeburn  13955: =item * &upfile_store($r)
1.41      ng       13956: 
                   13957: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13958: needs $env{'form.upfile'}
1.41      ng       13959: returns $datatoken to be put into hidden field
                   13960: 
                   13961: =cut
1.31      albertel 13962: 
                   13963: sub upfile_store {
                   13964:     my $r=shift;
1.258     albertel 13965:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13966:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13967:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13968:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13969: 
1.1299    raeburn  13970:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13971:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13972:                                      time.'_'.$$);
                   13973:     return if ($datatoken eq '');
                   13974: 
1.31      albertel 13975:     {
1.158     raeburn  13976:         my $datafile = $r->dir_config('lonDaemons').
                   13977:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  13978:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13979:             print $fh $env{'form.upfile'};
1.158     raeburn  13980:             close($fh);
                   13981:         }
1.31      albertel 13982:     }
                   13983:     return $datatoken;
                   13984: }
                   13985: 
1.56      matthew  13986: =pod
                   13987: 
1.1290    raeburn  13988: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13989: 
                   13990: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  13991: $datatoken is the name to assign to the temporary file.
1.258     albertel 13992: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13993: 
                   13994: =cut
1.31      albertel 13995: 
                   13996: sub load_tmp_file {
1.1290    raeburn  13997:     my ($r,$datatoken) = @_;
                   13998:     return if ($datatoken eq '');
1.31      albertel 13999:     my @studentdata=();
                   14000:     {
1.158     raeburn  14001:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14002:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14003:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14004:             @studentdata=<$fh>;
                   14005:             close($fh);
                   14006:         }
1.31      albertel 14007:     }
1.258     albertel 14008:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14009: }
                   14010: 
1.1290    raeburn  14011: sub valid_datatoken {
                   14012:     my ($datatoken) = @_;
1.1325    raeburn  14013:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14014:         return $datatoken;
                   14015:     }
                   14016:     return;
                   14017: }
                   14018: 
1.56      matthew  14019: =pod
                   14020: 
1.648     raeburn  14021: =item * &upfile_record_sep()
1.41      ng       14022: 
                   14023: Separate uploaded file into records
                   14024: returns array of records,
1.258     albertel 14025: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14026: 
                   14027: =cut
1.31      albertel 14028: 
                   14029: sub upfile_record_sep {
1.258     albertel 14030:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14031:     } else {
1.248     albertel 14032: 	my @records;
1.258     albertel 14033: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14034: 	    if ($line=~/^\s*$/) { next; }
                   14035: 	    push(@records,$line);
                   14036: 	}
                   14037: 	return @records;
1.31      albertel 14038:     }
                   14039: }
                   14040: 
1.56      matthew  14041: =pod
                   14042: 
1.648     raeburn  14043: =item * &record_sep($record)
1.41      ng       14044: 
1.258     albertel 14045: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14046: 
                   14047: =cut
                   14048: 
1.263     www      14049: sub takeleft {
                   14050:     my $index=shift;
                   14051:     return substr('0000'.$index,-4,4);
                   14052: }
                   14053: 
1.31      albertel 14054: sub record_sep {
                   14055:     my $record=shift;
                   14056:     my %components=();
1.258     albertel 14057:     if ($env{'form.upfiletype'} eq 'xml') {
                   14058:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14059:         my $i=0;
1.356     albertel 14060:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14061:             $field=~s/^(\"|\')//;
                   14062:             $field=~s/(\"|\')$//;
1.263     www      14063:             $components{&takeleft($i)}=$field;
1.31      albertel 14064:             $i++;
                   14065:         }
1.258     albertel 14066:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14067:         my $i=0;
1.356     albertel 14068:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14069:             $field=~s/^(\"|\')//;
                   14070:             $field=~s/(\"|\')$//;
1.263     www      14071:             $components{&takeleft($i)}=$field;
1.31      albertel 14072:             $i++;
                   14073:         }
                   14074:     } else {
1.561     www      14075:         my $separator=',';
1.480     banghart 14076:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14077:             $separator=';';
1.480     banghart 14078:         }
1.31      albertel 14079:         my $i=0;
1.561     www      14080: # the character we are looking for to indicate the end of a quote or a record 
                   14081:         my $looking_for=$separator;
                   14082: # do not add the characters to the fields
                   14083:         my $ignore=0;
                   14084: # we just encountered a separator (or the beginning of the record)
                   14085:         my $just_found_separator=1;
                   14086: # store the field we are working on here
                   14087:         my $field='';
                   14088: # work our way through all characters in record
                   14089:         foreach my $character ($record=~/(.)/g) {
                   14090:             if ($character eq $looking_for) {
                   14091:                if ($character ne $separator) {
                   14092: # Found the end of a quote, again looking for separator
                   14093:                   $looking_for=$separator;
                   14094:                   $ignore=1;
                   14095:                } else {
                   14096: # Found a separator, store away what we got
                   14097:                   $components{&takeleft($i)}=$field;
                   14098: 	          $i++;
                   14099:                   $just_found_separator=1;
                   14100:                   $ignore=0;
                   14101:                   $field='';
                   14102:                }
                   14103:                next;
                   14104:             }
                   14105: # single or double quotation marks after a separator indicate beginning of a quote
                   14106: # we are now looking for the end of the quote and need to ignore separators
                   14107:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14108:                $looking_for=$character;
                   14109:                next;
                   14110:             }
                   14111: # ignore would be true after we reached the end of a quote
                   14112:             if ($ignore) { next; }
                   14113:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14114:             $field.=$character;
                   14115:             $just_found_separator=0; 
1.31      albertel 14116:         }
1.561     www      14117: # catch the very last entry, since we never encountered the separator
                   14118:         $components{&takeleft($i)}=$field;
1.31      albertel 14119:     }
                   14120:     return %components;
                   14121: }
                   14122: 
1.144     matthew  14123: ######################################################
                   14124: ######################################################
                   14125: 
1.56      matthew  14126: =pod
                   14127: 
1.648     raeburn  14128: =item * &upfile_select_html()
1.41      ng       14129: 
1.144     matthew  14130: Return HTML code to select a file from the users machine and specify 
                   14131: the file type.
1.41      ng       14132: 
                   14133: =cut
                   14134: 
1.144     matthew  14135: ######################################################
                   14136: ######################################################
1.31      albertel 14137: sub upfile_select_html {
1.144     matthew  14138:     my %Types = (
                   14139:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14140:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14141:                  space => &mt('Space separated'),
                   14142:                  tab   => &mt('Tabulator separated'),
                   14143: #                 xml   => &mt('HTML/XML'),
                   14144:                  );
                   14145:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14146:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14147:     foreach my $type (sort(keys(%Types))) {
                   14148:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14149:     }
                   14150:     $Str .= "</select>\n";
                   14151:     return $Str;
1.31      albertel 14152: }
                   14153: 
1.301     albertel 14154: sub get_samples {
                   14155:     my ($records,$toget) = @_;
                   14156:     my @samples=({});
                   14157:     my $got=0;
                   14158:     foreach my $rec (@$records) {
                   14159: 	my %temp = &record_sep($rec);
                   14160: 	if (! grep(/\S/, values(%temp))) { next; }
                   14161: 	if (%temp) {
                   14162: 	    $samples[$got]=\%temp;
                   14163: 	    $got++;
                   14164: 	    if ($got == $toget) { last; }
                   14165: 	}
                   14166:     }
                   14167:     return \@samples;
                   14168: }
                   14169: 
1.144     matthew  14170: ######################################################
                   14171: ######################################################
                   14172: 
1.56      matthew  14173: =pod
                   14174: 
1.648     raeburn  14175: =item * &csv_print_samples($r,$records)
1.41      ng       14176: 
                   14177: Prints a table of sample values from each column uploaded $r is an
                   14178: Apache Request ref, $records is an arrayref from
                   14179: &Apache::loncommon::upfile_record_sep
                   14180: 
                   14181: =cut
                   14182: 
1.144     matthew  14183: ######################################################
                   14184: ######################################################
1.31      albertel 14185: sub csv_print_samples {
                   14186:     my ($r,$records) = @_;
1.662     bisitz   14187:     my $samples = &get_samples($records,5);
1.301     albertel 14188: 
1.594     raeburn  14189:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14190:               &start_data_table_header_row());
1.356     albertel 14191:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14192:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14193:     $r->print(&end_data_table_header_row());
1.301     albertel 14194:     foreach my $hash (@$samples) {
1.594     raeburn  14195: 	$r->print(&start_data_table_row());
1.356     albertel 14196: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14197: 	    $r->print('<td>');
1.356     albertel 14198: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14199: 	    $r->print('</td>');
                   14200: 	}
1.594     raeburn  14201: 	$r->print(&end_data_table_row());
1.31      albertel 14202:     }
1.594     raeburn  14203:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14204: }
                   14205: 
1.144     matthew  14206: ######################################################
                   14207: ######################################################
                   14208: 
1.56      matthew  14209: =pod
                   14210: 
1.648     raeburn  14211: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14212: 
                   14213: Prints a table to create associations between values and table columns.
1.144     matthew  14214: 
1.41      ng       14215: $r is an Apache Request ref,
                   14216: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14217: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14218: 
                   14219: =cut
                   14220: 
1.144     matthew  14221: ######################################################
                   14222: ######################################################
1.31      albertel 14223: sub csv_print_select_table {
                   14224:     my ($r,$records,$d) = @_;
1.301     albertel 14225:     my $i=0;
                   14226:     my $samples = &get_samples($records,1);
1.144     matthew  14227:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14228: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14229:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14230:               '<th>'.&mt('Column').'</th>'.
                   14231:               &end_data_table_header_row()."\n");
1.356     albertel 14232:     foreach my $array_ref (@$d) {
                   14233: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14234: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14235: 
1.875     bisitz   14236: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14237: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14238: 	$r->print('<option value="none"></option>');
1.356     albertel 14239: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14240: 	    $r->print('<option value="'.$sample.'"'.
                   14241:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14242:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14243: 	}
1.594     raeburn  14244: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14245: 	$i++;
                   14246:     }
1.594     raeburn  14247:     $r->print(&end_data_table());
1.31      albertel 14248:     $i--;
                   14249:     return $i;
                   14250: }
1.56      matthew  14251: 
1.144     matthew  14252: ######################################################
                   14253: ######################################################
                   14254: 
1.56      matthew  14255: =pod
1.31      albertel 14256: 
1.648     raeburn  14257: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14258: 
                   14259: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14260: 
                   14261: $r is an Apache Request ref,
                   14262: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14263: $d is an array of 2 element arrays (internal name, displayed name)
                   14264: 
                   14265: =cut
                   14266: 
1.144     matthew  14267: ######################################################
                   14268: ######################################################
1.31      albertel 14269: sub csv_samples_select_table {
                   14270:     my ($r,$records,$d) = @_;
                   14271:     my $i=0;
1.144     matthew  14272:     #
1.662     bisitz   14273:     my $max_samples = 5;
                   14274:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14275:     $r->print(&start_data_table().
                   14276:               &start_data_table_header_row().'<th>'.
                   14277:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14278:               &end_data_table_header_row());
1.301     albertel 14279: 
                   14280:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14281: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14282: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14283: 	foreach my $option (@$d) {
                   14284: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14285: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14286:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14287:                       $display.'</option>');
1.31      albertel 14288: 	}
                   14289: 	$r->print('</select></td><td>');
1.662     bisitz   14290: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14291: 	    if (defined($samples->[$line]{$key})) { 
                   14292: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14293: 	    }
                   14294: 	}
1.594     raeburn  14295: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14296: 	$i++;
                   14297:     }
1.594     raeburn  14298:     $r->print(&end_data_table());
1.31      albertel 14299:     $i--;
                   14300:     return($i);
1.115     matthew  14301: }
                   14302: 
1.144     matthew  14303: ######################################################
                   14304: ######################################################
                   14305: 
1.115     matthew  14306: =pod
                   14307: 
1.648     raeburn  14308: =item * &clean_excel_name($name)
1.115     matthew  14309: 
                   14310: Returns a replacement for $name which does not contain any illegal characters.
                   14311: 
                   14312: =cut
                   14313: 
1.144     matthew  14314: ######################################################
                   14315: ######################################################
1.115     matthew  14316: sub clean_excel_name {
                   14317:     my ($name) = @_;
                   14318:     $name =~ s/[:\*\?\/\\]//g;
                   14319:     if (length($name) > 31) {
                   14320:         $name = substr($name,0,31);
                   14321:     }
                   14322:     return $name;
1.25      albertel 14323: }
1.84      albertel 14324: 
1.85      albertel 14325: =pod
                   14326: 
1.648     raeburn  14327: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14328: 
                   14329: Returns either 1 or undef
                   14330: 
                   14331: 1 if the part is to be hidden, undef if it is to be shown
                   14332: 
                   14333: Arguments are:
                   14334: 
                   14335: $id the id of the part to be checked
                   14336: $symb, optional the symb of the resource to check
                   14337: $udom, optional the domain of the user to check for
                   14338: $uname, optional the username of the user to check for
                   14339: 
                   14340: =cut
1.84      albertel 14341: 
                   14342: sub check_if_partid_hidden {
                   14343:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14344:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14345: 					 $symb,$udom,$uname);
1.141     albertel 14346:     my $truth=1;
                   14347:     #if the string starts with !, then the list is the list to show not hide
                   14348:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14349:     my @hiddenlist=split(/,/,$hiddenparts);
                   14350:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14351: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14352:     }
1.141     albertel 14353:     return !$truth;
1.84      albertel 14354: }
1.127     matthew  14355: 
1.138     matthew  14356: 
                   14357: ############################################################
                   14358: ############################################################
                   14359: 
                   14360: =pod
                   14361: 
1.157     matthew  14362: =back 
                   14363: 
1.138     matthew  14364: =head1 cgi-bin script and graphing routines
                   14365: 
1.157     matthew  14366: =over 4
                   14367: 
1.648     raeburn  14368: =item * &get_cgi_id()
1.138     matthew  14369: 
                   14370: Inputs: none
                   14371: 
                   14372: Returns an id which can be used to pass environment variables
                   14373: to various cgi-bin scripts.  These environment variables will
                   14374: be removed from the users environment after a given time by
                   14375: the routine &Apache::lonnet::transfer_profile_to_env.
                   14376: 
                   14377: =cut
                   14378: 
                   14379: ############################################################
                   14380: ############################################################
1.152     albertel 14381: my $uniq=0;
1.136     matthew  14382: sub get_cgi_id {
1.154     albertel 14383:     $uniq=($uniq+1)%100000;
1.280     albertel 14384:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14385: }
                   14386: 
1.127     matthew  14387: ############################################################
                   14388: ############################################################
                   14389: 
                   14390: =pod
                   14391: 
1.648     raeburn  14392: =item * &DrawBarGraph()
1.127     matthew  14393: 
1.138     matthew  14394: Facilitates the plotting of data in a (stacked) bar graph.
                   14395: Puts plot definition data into the users environment in order for 
                   14396: graph.png to plot it.  Returns an <img> tag for the plot.
                   14397: The bars on the plot are labeled '1','2',...,'n'.
                   14398: 
                   14399: Inputs:
                   14400: 
                   14401: =over 4
                   14402: 
                   14403: =item $Title: string, the title of the plot
                   14404: 
                   14405: =item $xlabel: string, text describing the X-axis of the plot
                   14406: 
                   14407: =item $ylabel: string, text describing the Y-axis of the plot
                   14408: 
                   14409: =item $Max: scalar, the maximum Y value to use in the plot
                   14410: If $Max is < any data point, the graph will not be rendered.
                   14411: 
1.140     matthew  14412: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14413: they are plotted.  If undefined, default values will be used.
                   14414: 
1.178     matthew  14415: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14416: 
1.138     matthew  14417: =item @Values: An array of array references.  Each array reference holds data
                   14418: to be plotted in a stacked bar chart.
                   14419: 
1.239     matthew  14420: =item If the final element of @Values is a hash reference the key/value
                   14421: pairs will be added to the graph definition.
                   14422: 
1.138     matthew  14423: =back
                   14424: 
                   14425: Returns:
                   14426: 
                   14427: An <img> tag which references graph.png and the appropriate identifying
                   14428: information for the plot.
                   14429: 
1.127     matthew  14430: =cut
                   14431: 
                   14432: ############################################################
                   14433: ############################################################
1.134     matthew  14434: sub DrawBarGraph {
1.178     matthew  14435:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14436:     #
                   14437:     if (! defined($colors)) {
                   14438:         $colors = ['#33ff00', 
                   14439:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14440:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14441:                   ]; 
                   14442:     }
1.228     matthew  14443:     my $extra_settings = {};
                   14444:     if (ref($Values[-1]) eq 'HASH') {
                   14445:         $extra_settings = pop(@Values);
                   14446:     }
1.127     matthew  14447:     #
1.136     matthew  14448:     my $identifier = &get_cgi_id();
                   14449:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14450:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14451:         return '';
                   14452:     }
1.225     matthew  14453:     #
                   14454:     my @Labels;
                   14455:     if (defined($labels)) {
                   14456:         @Labels = @$labels;
                   14457:     } else {
                   14458:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14459:             push(@Labels,$i+1);
1.225     matthew  14460:         }
                   14461:     }
                   14462:     #
1.129     matthew  14463:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14464:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14465:     my %ValuesHash;
                   14466:     my $NumSets=1;
                   14467:     foreach my $array (@Values) {
                   14468:         next if (! ref($array));
1.136     matthew  14469:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14470:             join(',',@$array);
1.129     matthew  14471:     }
1.127     matthew  14472:     #
1.136     matthew  14473:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14474:     if ($NumBars < 3) {
                   14475:         $width = 120+$NumBars*32;
1.220     matthew  14476:         $xskip = 1;
1.225     matthew  14477:         $bar_width = 30;
                   14478:     } elsif ($NumBars < 5) {
                   14479:         $width = 120+$NumBars*20;
                   14480:         $xskip = 1;
                   14481:         $bar_width = 20;
1.220     matthew  14482:     } elsif ($NumBars < 10) {
1.136     matthew  14483:         $width = 120+$NumBars*15;
                   14484:         $xskip = 1;
                   14485:         $bar_width = 15;
                   14486:     } elsif ($NumBars <= 25) {
                   14487:         $width = 120+$NumBars*11;
                   14488:         $xskip = 5;
                   14489:         $bar_width = 8;
                   14490:     } elsif ($NumBars <= 50) {
                   14491:         $width = 120+$NumBars*8;
                   14492:         $xskip = 5;
                   14493:         $bar_width = 4;
                   14494:     } else {
                   14495:         $width = 120+$NumBars*8;
                   14496:         $xskip = 5;
                   14497:         $bar_width = 4;
                   14498:     }
                   14499:     #
1.137     matthew  14500:     $Max = 1 if ($Max < 1);
                   14501:     if ( int($Max) < $Max ) {
                   14502:         $Max++;
                   14503:         $Max = int($Max);
                   14504:     }
1.127     matthew  14505:     $Title  = '' if (! defined($Title));
                   14506:     $xlabel = '' if (! defined($xlabel));
                   14507:     $ylabel = '' if (! defined($ylabel));
1.369     www      14508:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14509:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14510:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14511:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14512:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14513:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14514:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14515:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14516:     $ValuesHash{$id.'.height'}   = $height;
                   14517:     $ValuesHash{$id.'.width'}    = $width;
                   14518:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14519:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14520:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14521:     #
1.228     matthew  14522:     # Deal with other parameters
                   14523:     while (my ($key,$value) = each(%$extra_settings)) {
                   14524:         $ValuesHash{$id.'.'.$key} = $value;
                   14525:     }
                   14526:     #
1.646     raeburn  14527:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14528:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14529: }
                   14530: 
                   14531: ############################################################
                   14532: ############################################################
                   14533: 
                   14534: =pod
                   14535: 
1.648     raeburn  14536: =item * &DrawXYGraph()
1.137     matthew  14537: 
1.138     matthew  14538: Facilitates the plotting of data in an XY graph.
                   14539: Puts plot definition data into the users environment in order for 
                   14540: graph.png to plot it.  Returns an <img> tag for the plot.
                   14541: 
                   14542: Inputs:
                   14543: 
                   14544: =over 4
                   14545: 
                   14546: =item $Title: string, the title of the plot
                   14547: 
                   14548: =item $xlabel: string, text describing the X-axis of the plot
                   14549: 
                   14550: =item $ylabel: string, text describing the Y-axis of the plot
                   14551: 
                   14552: =item $Max: scalar, the maximum Y value to use in the plot
                   14553: If $Max is < any data point, the graph will not be rendered.
                   14554: 
                   14555: =item $colors: Array ref containing the hex color codes for the data to be 
                   14556: plotted in.  If undefined, default values will be used.
                   14557: 
                   14558: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14559: 
                   14560: =item $Ydata: Array ref containing Array refs.  
1.185     www      14561: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14562: 
                   14563: =item %Values: hash indicating or overriding any default values which are 
                   14564: passed to graph.png.  
                   14565: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14566: 
                   14567: =back
                   14568: 
                   14569: Returns:
                   14570: 
                   14571: An <img> tag which references graph.png and the appropriate identifying
                   14572: information for the plot.
                   14573: 
1.137     matthew  14574: =cut
                   14575: 
                   14576: ############################################################
                   14577: ############################################################
                   14578: sub DrawXYGraph {
                   14579:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14580:     #
                   14581:     # Create the identifier for the graph
                   14582:     my $identifier = &get_cgi_id();
                   14583:     my $id = 'cgi.'.$identifier;
                   14584:     #
                   14585:     $Title  = '' if (! defined($Title));
                   14586:     $xlabel = '' if (! defined($xlabel));
                   14587:     $ylabel = '' if (! defined($ylabel));
                   14588:     my %ValuesHash = 
                   14589:         (
1.369     www      14590:          $id.'.title'  => &escape($Title),
                   14591:          $id.'.xlabel' => &escape($xlabel),
                   14592:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14593:          $id.'.y_max_value'=> $Max,
                   14594:          $id.'.labels'     => join(',',@$Xlabels),
                   14595:          $id.'.PlotType'   => 'XY',
                   14596:          );
                   14597:     #
                   14598:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14599:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14600:     }
                   14601:     #
                   14602:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14603:         return '';
                   14604:     }
                   14605:     my $NumSets=1;
1.138     matthew  14606:     foreach my $array (@{$Ydata}){
1.137     matthew  14607:         next if (! ref($array));
                   14608:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14609:     }
1.138     matthew  14610:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14611:     #
                   14612:     # Deal with other parameters
                   14613:     while (my ($key,$value) = each(%Values)) {
                   14614:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14615:     }
                   14616:     #
1.646     raeburn  14617:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14618:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14619: }
                   14620: 
                   14621: ############################################################
                   14622: ############################################################
                   14623: 
                   14624: =pod
                   14625: 
1.648     raeburn  14626: =item * &DrawXYYGraph()
1.138     matthew  14627: 
                   14628: Facilitates the plotting of data in an XY graph with two Y axes.
                   14629: Puts plot definition data into the users environment in order for 
                   14630: graph.png to plot it.  Returns an <img> tag for the plot.
                   14631: 
                   14632: Inputs:
                   14633: 
                   14634: =over 4
                   14635: 
                   14636: =item $Title: string, the title of the plot
                   14637: 
                   14638: =item $xlabel: string, text describing the X-axis of the plot
                   14639: 
                   14640: =item $ylabel: string, text describing the Y-axis of the plot
                   14641: 
                   14642: =item $colors: Array ref containing the hex color codes for the data to be 
                   14643: plotted in.  If undefined, default values will be used.
                   14644: 
                   14645: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14646: 
                   14647: =item $Ydata1: The first data set
                   14648: 
                   14649: =item $Min1: The minimum value of the left Y-axis
                   14650: 
                   14651: =item $Max1: The maximum value of the left Y-axis
                   14652: 
                   14653: =item $Ydata2: The second data set
                   14654: 
                   14655: =item $Min2: The minimum value of the right Y-axis
                   14656: 
                   14657: =item $Max2: The maximum value of the left Y-axis
                   14658: 
                   14659: =item %Values: hash indicating or overriding any default values which are 
                   14660: passed to graph.png.  
                   14661: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14662: 
                   14663: =back
                   14664: 
                   14665: Returns:
                   14666: 
                   14667: An <img> tag which references graph.png and the appropriate identifying
                   14668: information for the plot.
1.136     matthew  14669: 
                   14670: =cut
                   14671: 
                   14672: ############################################################
                   14673: ############################################################
1.137     matthew  14674: sub DrawXYYGraph {
                   14675:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14676:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14677:     #
                   14678:     # Create the identifier for the graph
                   14679:     my $identifier = &get_cgi_id();
                   14680:     my $id = 'cgi.'.$identifier;
                   14681:     #
                   14682:     $Title  = '' if (! defined($Title));
                   14683:     $xlabel = '' if (! defined($xlabel));
                   14684:     $ylabel = '' if (! defined($ylabel));
                   14685:     my %ValuesHash = 
                   14686:         (
1.369     www      14687:          $id.'.title'  => &escape($Title),
                   14688:          $id.'.xlabel' => &escape($xlabel),
                   14689:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14690:          $id.'.labels' => join(',',@$Xlabels),
                   14691:          $id.'.PlotType' => 'XY',
                   14692:          $id.'.NumSets' => 2,
1.137     matthew  14693:          $id.'.two_axes' => 1,
                   14694:          $id.'.y1_max_value' => $Max1,
                   14695:          $id.'.y1_min_value' => $Min1,
                   14696:          $id.'.y2_max_value' => $Max2,
                   14697:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14698:          );
                   14699:     #
1.137     matthew  14700:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14701:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14702:     }
                   14703:     #
                   14704:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14705:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14706:         return '';
                   14707:     }
                   14708:     my $NumSets=1;
1.137     matthew  14709:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14710:         next if (! ref($array));
                   14711:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14712:     }
                   14713:     #
                   14714:     # Deal with other parameters
                   14715:     while (my ($key,$value) = each(%Values)) {
                   14716:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14717:     }
                   14718:     #
1.646     raeburn  14719:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14720:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14721: }
                   14722: 
                   14723: ############################################################
                   14724: ############################################################
                   14725: 
                   14726: =pod
                   14727: 
1.157     matthew  14728: =back 
                   14729: 
1.139     matthew  14730: =head1 Statistics helper routines?  
                   14731: 
                   14732: Bad place for them but what the hell.
                   14733: 
1.157     matthew  14734: =over 4
                   14735: 
1.648     raeburn  14736: =item * &chartlink()
1.139     matthew  14737: 
                   14738: Returns a link to the chart for a specific student.  
                   14739: 
                   14740: Inputs:
                   14741: 
                   14742: =over 4
                   14743: 
                   14744: =item $linktext: The text of the link
                   14745: 
                   14746: =item $sname: The students username
                   14747: 
                   14748: =item $sdomain: The students domain
                   14749: 
                   14750: =back
                   14751: 
1.157     matthew  14752: =back
                   14753: 
1.139     matthew  14754: =cut
                   14755: 
                   14756: ############################################################
                   14757: ############################################################
                   14758: sub chartlink {
                   14759:     my ($linktext, $sname, $sdomain) = @_;
                   14760:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14761:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14762:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14763:        '">'.$linktext.'</a>';
1.153     matthew  14764: }
                   14765: 
                   14766: #######################################################
                   14767: #######################################################
                   14768: 
                   14769: =pod
                   14770: 
                   14771: =head1 Course Environment Routines
1.157     matthew  14772: 
                   14773: =over 4
1.153     matthew  14774: 
1.648     raeburn  14775: =item * &restore_course_settings()
1.153     matthew  14776: 
1.648     raeburn  14777: =item * &store_course_settings()
1.153     matthew  14778: 
                   14779: Restores/Store indicated form parameters from the course environment.
                   14780: Will not overwrite existing values of the form parameters.
                   14781: 
                   14782: Inputs: 
                   14783: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14784: 
                   14785: a hash ref describing the data to be stored.  For example:
                   14786:    
                   14787: %Save_Parameters = ('Status' => 'scalar',
                   14788:     'chartoutputmode' => 'scalar',
                   14789:     'chartoutputdata' => 'scalar',
                   14790:     'Section' => 'array',
1.373     raeburn  14791:     'Group' => 'array',
1.153     matthew  14792:     'StudentData' => 'array',
                   14793:     'Maps' => 'array');
                   14794: 
                   14795: Returns: both routines return nothing
                   14796: 
1.631     raeburn  14797: =back
                   14798: 
1.153     matthew  14799: =cut
                   14800: 
                   14801: #######################################################
                   14802: #######################################################
                   14803: sub store_course_settings {
1.496     albertel 14804:     return &store_settings($env{'request.course.id'},@_);
                   14805: }
                   14806: 
                   14807: sub store_settings {
1.153     matthew  14808:     # save to the environment
                   14809:     # appenv the same items, just to be safe
1.300     albertel 14810:     my $udom  = $env{'user.domain'};
                   14811:     my $uname = $env{'user.name'};
1.496     albertel 14812:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14813:     my %SaveHash;
                   14814:     my %AppHash;
                   14815:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14816:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14817:         my $envname = 'environment.'.$basename;
1.258     albertel 14818:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14819:             # Save this value away
                   14820:             if ($type eq 'scalar' &&
1.258     albertel 14821:                 (! exists($env{$envname}) || 
                   14822:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14823:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14824:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14825:             } elsif ($type eq 'array') {
                   14826:                 my $stored_form;
1.258     albertel 14827:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14828:                     $stored_form = join(',',
                   14829:                                         map {
1.369     www      14830:                                             &escape($_);
1.258     albertel 14831:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14832:                 } else {
                   14833:                     $stored_form = 
1.369     www      14834:                         &escape($env{'form.'.$setting});
1.153     matthew  14835:                 }
                   14836:                 # Determine if the array contents are the same.
1.258     albertel 14837:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14838:                     $SaveHash{$basename} = $stored_form;
                   14839:                     $AppHash{$envname}   = $stored_form;
                   14840:                 }
                   14841:             }
                   14842:         }
                   14843:     }
                   14844:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14845:                                           $udom,$uname);
1.153     matthew  14846:     if ($put_result !~ /^(ok|delayed)/) {
                   14847:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14848:                                  'got error:'.$put_result);
                   14849:     }
                   14850:     # Make sure these settings stick around in this session, too
1.646     raeburn  14851:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14852:     return;
                   14853: }
                   14854: 
                   14855: sub restore_course_settings {
1.499     albertel 14856:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14857: }
                   14858: 
                   14859: sub restore_settings {
                   14860:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14861:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14862:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14863:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14864:             '.'.$setting;
1.258     albertel 14865:         if (exists($env{$envname})) {
1.153     matthew  14866:             if ($type eq 'scalar') {
1.258     albertel 14867:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14868:             } elsif ($type eq 'array') {
1.258     albertel 14869:                 $env{'form.'.$setting} = [ 
1.153     matthew  14870:                                            map { 
1.369     www      14871:                                                &unescape($_); 
1.258     albertel 14872:                                            } split(',',$env{$envname})
1.153     matthew  14873:                                            ];
                   14874:             }
                   14875:         }
                   14876:     }
1.127     matthew  14877: }
                   14878: 
1.618     raeburn  14879: #######################################################
                   14880: #######################################################
                   14881: 
                   14882: =pod
                   14883: 
                   14884: =head1 Domain E-mail Routines  
                   14885: 
                   14886: =over 4
                   14887: 
1.648     raeburn  14888: =item * &build_recipient_list()
1.618     raeburn  14889: 
1.1144    raeburn  14890: Build recipient lists for following types of e-mail:
1.766     raeburn  14891: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14892: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14893: module change checking, student/employee ID conflict checks, as
                   14894: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14895: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14896: 
                   14897: Inputs:
1.619     raeburn  14898: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14899: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14900: requestsmail, updatesmail, or idconflictsmail).
                   14901: 
1.619     raeburn  14902: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14903: 
1.619     raeburn  14904: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  14905: i.e., predates configuration by DC via domainprefs.pm
                   14906: 
                   14907: $requname username of requester (if mailing type is helpdeskmail)
                   14908: 
                   14909: $requdom domain of requester (if mailing type is helpdeskmail)
                   14910: 
                   14911: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   14912: 
1.618     raeburn  14913: 
1.655     raeburn  14914: Returns: comma separated list of addresses to which to send e-mail.
                   14915: 
                   14916: =back
1.618     raeburn  14917: 
                   14918: =cut
                   14919: 
                   14920: ############################################################
                   14921: ############################################################
                   14922: sub build_recipient_list {
1.1297    raeburn  14923:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  14924:     my @recipients;
1.1270    raeburn  14925:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14926:     my %domconfig =
1.1270    raeburn  14927:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14928:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14929:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14930:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14931:                 my @contacts = ('adminemail','supportemail');
                   14932:                 foreach my $item (@contacts) {
                   14933:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14934:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14935:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14936:                             push(@recipients,$addr);
                   14937:                         }
1.619     raeburn  14938:                     }
1.1270    raeburn  14939:                 }
                   14940:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14941:                 if ($mailing eq 'helpdeskmail') {
                   14942:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14943:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14944:                         my @ok_bccs;
                   14945:                         foreach my $bcc (@bccs) {
                   14946:                             $bcc =~ s/^\s+//g;
                   14947:                             $bcc =~ s/\s+$//g;
                   14948:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14949:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14950:                                     push(@ok_bccs,$bcc);
                   14951:                                 }
                   14952:                             }
                   14953:                         }
                   14954:                         if (@ok_bccs > 0) {
                   14955:                             $allbcc = join(', ',@ok_bccs);
                   14956:                         }
                   14957:                     }
                   14958:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14959:                 }
                   14960:             }
1.766     raeburn  14961:         } elsif ($origmail ne '') {
1.1270    raeburn  14962:             $lastresort = $origmail;
1.618     raeburn  14963:         }
1.1297    raeburn  14964:         if ($mailing eq 'helpdeskmail') {
                   14965:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   14966:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   14967:                 my ($inststatus,$inststatus_checked);
                   14968:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   14969:                     ($env{'user.domain'} ne 'public')) {
                   14970:                     $inststatus_checked = 1;
                   14971:                     $inststatus = $env{'environment.inststatus'};
                   14972:                 }
                   14973:                 unless ($inststatus_checked) {
                   14974:                     if (($requname ne '') && ($requdom ne '')) {
                   14975:                         if (($requname =~ /^$match_username$/) &&
                   14976:                             ($requdom =~ /^$match_domain$/) &&
                   14977:                             (&Apache::lonnet::domain($requdom))) {
                   14978:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   14979:                                                                       $requdom);
                   14980:                             unless ($requhome eq 'no_host') {
                   14981:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   14982:                                 $inststatus = $userenv{'inststatus'};
                   14983:                                 $inststatus_checked = 1;
                   14984:                             }
                   14985:                         }
                   14986:                     }
                   14987:                 }
                   14988:                 unless ($inststatus_checked) {
                   14989:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   14990:                         my %srch = (srchby     => 'email',
                   14991:                                     srchdomain => $defdom,
                   14992:                                     srchterm   => $reqemail,
                   14993:                                     srchtype   => 'exact');
                   14994:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   14995:                         foreach my $uname (keys(%srch_results)) {
                   14996:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   14997:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   14998:                                 $inststatus_checked = 1;
                   14999:                                 last;
                   15000:                             }
                   15001:                         }
                   15002:                         unless ($inststatus_checked) {
                   15003:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15004:                             if ($dirsrchres eq 'ok') {
                   15005:                                 foreach my $uname (keys(%srch_results)) {
                   15006:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15007:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15008:                                         $inststatus_checked = 1;
                   15009:                                         last;
                   15010:                                     }
                   15011:                                 }
                   15012:                             }
                   15013:                         }
                   15014:                     }
                   15015:                 }
                   15016:                 if ($inststatus ne '') {
                   15017:                     foreach my $status (split(/\:/,$inststatus)) {
                   15018:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15019:                             my @contacts = ('adminemail','supportemail');
                   15020:                             foreach my $item (@contacts) {
                   15021:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15022:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15023:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15024:                                         push(@recipients,$addr);
                   15025:                                     }
                   15026:                                 }
                   15027:                             }
                   15028:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15029:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15030:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15031:                                 my @ok_bccs;
                   15032:                                 foreach my $bcc (@bccs) {
                   15033:                                     $bcc =~ s/^\s+//g;
                   15034:                                     $bcc =~ s/\s+$//g;
                   15035:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15036:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15037:                                             push(@ok_bccs,$bcc);
                   15038:                                         }
                   15039:                                     }
                   15040:                                 }
                   15041:                                 if (@ok_bccs > 0) {
                   15042:                                     $allbcc = join(', ',@ok_bccs);
                   15043:                                 }
                   15044:                             }
                   15045:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15046:                             last;
                   15047:                         }
                   15048:                     }
                   15049:                 }
                   15050:             }
                   15051:         }
1.619     raeburn  15052:     } elsif ($origmail ne '') {
1.1270    raeburn  15053:         $lastresort = $origmail;
                   15054:     }
1.1297    raeburn  15055:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15056:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15057:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15058:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15059:             my %what = (
                   15060:                           perlvar => 1,
                   15061:                        );
                   15062:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15063:             if ($primary) {
                   15064:                 my $gotaddr;
                   15065:                 my ($result,$returnhash) =
                   15066:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15067:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15068:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15069:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15070:                         $gotaddr = 1;
                   15071:                     }
                   15072:                 }
                   15073:                 unless ($gotaddr) {
                   15074:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15075:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15076:                     unless ($uintdom eq $intdom) {
                   15077:                         my %domconfig =
                   15078:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15079:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15080:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15081:                                 my @contacts = ('adminemail','supportemail');
                   15082:                                 foreach my $item (@contacts) {
                   15083:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15084:                                         my $addr = $domconfig{'contacts'}{$item};
                   15085:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15086:                                             push(@recipients,$addr);
                   15087:                                         }
                   15088:                                     }
                   15089:                                 }
                   15090:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15091:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15092:                                 }
                   15093:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15094:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15095:                                     my @ok_bccs;
                   15096:                                     foreach my $bcc (@bccs) {
                   15097:                                         $bcc =~ s/^\s+//g;
                   15098:                                         $bcc =~ s/\s+$//g;
                   15099:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15100:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15101:                                                 push(@ok_bccs,$bcc);
                   15102:                                             }
                   15103:                                         }
                   15104:                                     }
                   15105:                                     if (@ok_bccs > 0) {
                   15106:                                         $allbcc = join(', ',@ok_bccs);
                   15107:                                     }
                   15108:                                 }
                   15109:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15110:                             }
                   15111:                         }
                   15112:                     }
                   15113:                 }
                   15114:             }
                   15115:         }
1.618     raeburn  15116:     }
1.688     raeburn  15117:     if (defined($defmail)) {
                   15118:         if ($defmail ne '') {
                   15119:             push(@recipients,$defmail);
                   15120:         }
1.618     raeburn  15121:     }
                   15122:     if ($otheremails) {
1.619     raeburn  15123:         my @others;
                   15124:         if ($otheremails =~ /,/) {
                   15125:             @others = split(/,/,$otheremails);
1.618     raeburn  15126:         } else {
1.619     raeburn  15127:             push(@others,$otheremails);
                   15128:         }
                   15129:         foreach my $addr (@others) {
                   15130:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15131:                 push(@recipients,$addr);
                   15132:             }
1.618     raeburn  15133:         }
                   15134:     }
1.1298    raeburn  15135:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15136:         if ((!@recipients) && ($lastresort ne '')) {
                   15137:             push(@recipients,$lastresort);
                   15138:         }
                   15139:     } elsif ($lastresort ne '') {
                   15140:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15141:             push(@recipients,$lastresort);
                   15142:         }
                   15143:     }
1.1271    raeburn  15144:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15145:     if (wantarray) {
                   15146:         return ($recipientlist,$allbcc,$addtext);
                   15147:     } else {
                   15148:         return $recipientlist;
                   15149:     }
1.618     raeburn  15150: }
                   15151: 
1.127     matthew  15152: ############################################################
                   15153: ############################################################
1.154     albertel 15154: 
1.655     raeburn  15155: =pod
                   15156: 
1.1224    musolffc 15157: =over 4
                   15158: 
1.1223    musolffc 15159: =item * &mime_email()
                   15160: 
                   15161: Sends an email with a possible attachment
                   15162: 
                   15163: Inputs:
                   15164: 
                   15165: =over 4
                   15166: 
                   15167: from -              Sender's email address
                   15168: 
                   15169: to -                Email address of recipient
                   15170: 
                   15171: subject -           Subject of email
                   15172: 
                   15173: body -              Body of email
                   15174: 
                   15175: cc_string -         Carbon copy email address
                   15176: 
                   15177: bcc -               Blind carbon copy email address
                   15178: 
                   15179: type -              File type of attachment
                   15180: 
                   15181: attachment_path -   Path of file to be attached
                   15182: 
                   15183: file_name -         Name of file to be attached
                   15184: 
                   15185: attachment_text -   The body of an attachment of type "TEXT"
                   15186: 
                   15187: =back
                   15188: 
                   15189: =back
                   15190: 
                   15191: =cut
                   15192: 
                   15193: ############################################################
                   15194: ############################################################
                   15195: 
                   15196: sub mime_email {
                   15197:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   15198:         $file_name, $attachment_text) = @_;
                   15199:     my $msg = MIME::Lite->new(
                   15200:              From    => $from,
                   15201:              To      => $to,
                   15202:              Subject => $subject,
                   15203:              Type    =>'TEXT',
                   15204:              Data    => $body,
                   15205:              );
                   15206:     if ($cc_string ne '') {
                   15207:         $msg->add("Cc" => $cc_string);
                   15208:     }
                   15209:     if ($bcc ne '') {
                   15210:         $msg->add("Bcc" => $bcc);
                   15211:     }
                   15212:     $msg->attr("content-type"         => "text/plain");
                   15213:     $msg->attr("content-type.charset" => "UTF-8");
                   15214:     # Attach file if given
                   15215:     if ($attachment_path) {
                   15216:         unless ($file_name) {
                   15217:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15218:         }
                   15219:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15220:         $msg->attach(Type     => $type,
                   15221:                      Path     => $attachment_path,
                   15222:                      Filename => $file_name
                   15223:                      );
                   15224:     # Otherwise attach text if given
                   15225:     } elsif ($attachment_text) {
                   15226:         $msg->attach(Type => 'TEXT',
                   15227:                      Data => $attachment_text);
                   15228:     }
                   15229:     # Send it
                   15230:     $msg->send('sendmail');
                   15231: }
                   15232: 
                   15233: ############################################################
                   15234: ############################################################
                   15235: 
                   15236: =pod
                   15237: 
1.655     raeburn  15238: =head1 Course Catalog Routines
                   15239: 
                   15240: =over 4
                   15241: 
                   15242: =item * &gather_categories()
                   15243: 
                   15244: Converts category definitions - keys of categories hash stored in  
                   15245: coursecategories in configuration.db on the primary library server in a 
                   15246: domain - to an array.  Also generates javascript and idx hash used to 
                   15247: generate Domain Coordinator interface for editing Course Categories.
                   15248: 
                   15249: Inputs:
1.663     raeburn  15250: 
1.655     raeburn  15251: categories (reference to hash of category definitions).
1.663     raeburn  15252: 
1.655     raeburn  15253: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15254:       categories and subcategories).
1.663     raeburn  15255: 
1.655     raeburn  15256: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15257:       editing Course Categories).
1.663     raeburn  15258: 
1.655     raeburn  15259: jsarray (reference to array of categories used to create Javascript arrays for
                   15260:          Domain Coordinator interface for editing Course Categories).
                   15261: 
                   15262: Returns: nothing
                   15263: 
                   15264: Side effects: populates cats, idx and jsarray. 
                   15265: 
                   15266: =cut
                   15267: 
                   15268: sub gather_categories {
                   15269:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15270:     my %counters;
                   15271:     my $num = 0;
                   15272:     foreach my $item (keys(%{$categories})) {
                   15273:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15274:         if ($container eq '' && $depth == 0) {
                   15275:             $cats->[$depth][$categories->{$item}] = $cat;
                   15276:         } else {
                   15277:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15278:         }
                   15279:         my ($escitem,$tail) = split(/:/,$item,2);
                   15280:         if ($counters{$tail} eq '') {
                   15281:             $counters{$tail} = $num;
                   15282:             $num ++;
                   15283:         }
                   15284:         if (ref($idx) eq 'HASH') {
                   15285:             $idx->{$item} = $counters{$tail};
                   15286:         }
                   15287:         if (ref($jsarray) eq 'ARRAY') {
                   15288:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15289:         }
                   15290:     }
                   15291:     return;
                   15292: }
                   15293: 
                   15294: =pod
                   15295: 
                   15296: =item * &extract_categories()
                   15297: 
                   15298: Used to generate breadcrumb trails for course categories.
                   15299: 
                   15300: Inputs:
1.663     raeburn  15301: 
1.655     raeburn  15302: categories (reference to hash of category definitions).
1.663     raeburn  15303: 
1.655     raeburn  15304: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15305:       categories and subcategories).
1.663     raeburn  15306: 
1.655     raeburn  15307: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15308: 
1.655     raeburn  15309: allitems (reference to hash - key is category key 
                   15310:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15311: 
1.655     raeburn  15312: idx (reference to hash of counters used in Domain Coordinator interface for
                   15313:       editing Course Categories).
1.663     raeburn  15314: 
1.655     raeburn  15315: jsarray (reference to array of categories used to create Javascript arrays for
                   15316:          Domain Coordinator interface for editing Course Categories).
                   15317: 
1.665     raeburn  15318: subcats (reference to hash of arrays containing all subcategories within each 
                   15319:          category, -recursive)
                   15320: 
1.1321    raeburn  15321: maxd (reference to hash used to hold max depth for all top-level categories).
                   15322: 
1.655     raeburn  15323: Returns: nothing
                   15324: 
                   15325: Side effects: populates trails and allitems hash references.
                   15326: 
                   15327: =cut
                   15328: 
                   15329: sub extract_categories {
1.1321    raeburn  15330:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15331:     if (ref($categories) eq 'HASH') {
                   15332:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15333:         if (ref($cats->[0]) eq 'ARRAY') {
                   15334:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15335:                 my $name = $cats->[0][$i];
                   15336:                 my $item = &escape($name).'::0';
                   15337:                 my $trailstr;
                   15338:                 if ($name eq 'instcode') {
                   15339:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15340:                 } elsif ($name eq 'communities') {
                   15341:                     $trailstr = &mt('Communities');
1.1239    raeburn  15342:                 } elsif ($name eq 'placement') {
                   15343:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15344:                 } else {
                   15345:                     $trailstr = $name;
                   15346:                 }
                   15347:                 if ($allitems->{$item} eq '') {
                   15348:                     push(@{$trails},$trailstr);
                   15349:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15350:                 }
                   15351:                 my @parents = ($name);
                   15352:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15353:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15354:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15355:                         if (ref($subcats) eq 'HASH') {
                   15356:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15357:                         }
1.1321    raeburn  15358:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15359:                     }
                   15360:                 } else {
                   15361:                     if (ref($subcats) eq 'HASH') {
                   15362:                         $subcats->{$item} = [];
1.655     raeburn  15363:                     }
1.1321    raeburn  15364:                     if (ref($maxd) eq 'HASH') {
                   15365:                         $maxd->{$name} = 1;
                   15366:                     }
1.655     raeburn  15367:                 }
                   15368:             }
                   15369:         }
                   15370:     }
                   15371:     return;
                   15372: }
                   15373: 
                   15374: =pod
                   15375: 
1.1162    raeburn  15376: =item * &recurse_categories()
1.655     raeburn  15377: 
                   15378: Recursively used to generate breadcrumb trails for course categories.
                   15379: 
                   15380: Inputs:
1.663     raeburn  15381: 
1.655     raeburn  15382: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15383:       categories and subcategories).
1.663     raeburn  15384: 
1.655     raeburn  15385: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15386: 
                   15387: category (current course category, for which breadcrumb trail is being generated).
                   15388: 
                   15389: trails (reference to array of breadcrumb trails for each category).
                   15390: 
1.655     raeburn  15391: allitems (reference to hash - key is category key
                   15392:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15393: 
1.655     raeburn  15394: parents (array containing containers directories for current category, 
                   15395:          back to top level). 
                   15396: 
                   15397: Returns: nothing
                   15398: 
                   15399: Side effects: populates trails and allitems hash references
                   15400: 
                   15401: =cut
                   15402: 
                   15403: sub recurse_categories {
1.1321    raeburn  15404:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15405:     my $shallower = $depth - 1;
                   15406:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15407:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15408:             my $name = $cats->[$depth]{$category}[$k];
                   15409:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15410:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15411:             if ($allitems->{$item} eq '') {
                   15412:                 push(@{$trails},$trailstr);
                   15413:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15414:             }
                   15415:             my $deeper = $depth+1;
                   15416:             push(@{$parents},$category);
1.665     raeburn  15417:             if (ref($subcats) eq 'HASH') {
                   15418:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15419:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15420:                     my $higher;
                   15421:                     if ($j > 0) {
                   15422:                         $higher = &escape($parents->[$j]).':'.
                   15423:                                   &escape($parents->[$j-1]).':'.$j;
                   15424:                     } else {
                   15425:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15426:                     }
                   15427:                     push(@{$subcats->{$higher}},$subcat);
                   15428:                 }
                   15429:             }
                   15430:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  15431:                                 $subcats,$maxd);
1.655     raeburn  15432:             pop(@{$parents});
                   15433:         }
                   15434:     } else {
                   15435:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  15436:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15437:         if ($allitems->{$item} eq '') {
                   15438:             push(@{$trails},$trailstr);
                   15439:             $allitems->{$item} = scalar(@{$trails})-1;
                   15440:         }
1.1321    raeburn  15441:         if (ref($maxd) eq 'HASH') {
                   15442:             if ($depth > $maxd->{$parents->[0]}) {
                   15443:                 $maxd->{$parents->[0]} = $depth;
                   15444:             }
                   15445:         }
1.655     raeburn  15446:     }
                   15447:     return;
                   15448: }
                   15449: 
1.663     raeburn  15450: =pod
                   15451: 
1.1162    raeburn  15452: =item * &assign_categories_table()
1.663     raeburn  15453: 
                   15454: Create a datatable for display of hierarchical categories in a domain,
                   15455: with checkboxes to allow a course to be categorized. 
                   15456: 
                   15457: Inputs:
                   15458: 
                   15459: cathash - reference to hash of categories defined for the domain (from
                   15460:           configuration.db)
                   15461: 
                   15462: currcat - scalar with an & separated list of categories assigned to a course. 
                   15463: 
1.919     raeburn  15464: type    - scalar contains course type (Course or Community).
                   15465: 
1.1260    raeburn  15466: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15467:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15468: 
1.663     raeburn  15469: Returns: $output (markup to be displayed) 
                   15470: 
                   15471: =cut
                   15472: 
                   15473: sub assign_categories_table {
1.1259    raeburn  15474:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15475:     my $output;
                   15476:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  15477:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15478:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15479:         $maxdepth = scalar(@cats);
                   15480:         if (@cats > 0) {
                   15481:             my $itemcount = 0;
                   15482:             if (ref($cats[0]) eq 'ARRAY') {
                   15483:                 my @currcategories;
                   15484:                 if ($currcat ne '') {
                   15485:                     @currcategories = split('&',$currcat);
                   15486:                 }
1.919     raeburn  15487:                 my $table;
1.663     raeburn  15488:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15489:                     my $parent = $cats[0][$i];
1.919     raeburn  15490:                     next if ($parent eq 'instcode');
                   15491:                     if ($type eq 'Community') {
                   15492:                         next unless ($parent eq 'communities');
1.1239    raeburn  15493:                     } elsif ($type eq 'Placement') {
                   15494:                         next unless ($parent eq 'placement');
1.919     raeburn  15495:                     } else {
1.1239    raeburn  15496:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15497:                     }
1.663     raeburn  15498:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15499:                     my $item = &escape($parent).'::0';
                   15500:                     my $checked = '';
                   15501:                     if (@currcategories > 0) {
                   15502:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15503:                             $checked = ' checked="checked"';
1.663     raeburn  15504:                         }
                   15505:                     }
1.919     raeburn  15506:                     my $parent_title = $parent;
                   15507:                     if ($parent eq 'communities') {
                   15508:                         $parent_title = &mt('Communities');
1.1239    raeburn  15509:                     } elsif ($parent eq 'placement') {
                   15510:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15511:                     }
                   15512:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15513:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15514:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15515:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15516:                     my $depth = 1;
                   15517:                     push(@path,$parent);
1.1259    raeburn  15518:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15519:                     pop(@path);
1.919     raeburn  15520:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15521:                     $itemcount ++;
                   15522:                 }
1.919     raeburn  15523:                 if ($itemcount) {
                   15524:                     $output = &Apache::loncommon::start_data_table().
                   15525:                               $table.
                   15526:                               &Apache::loncommon::end_data_table();
                   15527:                 }
1.663     raeburn  15528:             }
                   15529:         }
                   15530:     }
                   15531:     return $output;
                   15532: }
                   15533: 
                   15534: =pod
                   15535: 
1.1162    raeburn  15536: =item * &assign_category_rows()
1.663     raeburn  15537: 
                   15538: Create a datatable row for display of nested categories in a domain,
                   15539: with checkboxes to allow a course to be categorized,called recursively.
                   15540: 
                   15541: Inputs:
                   15542: 
                   15543: itemcount - track row number for alternating colors
                   15544: 
                   15545: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15546:       categories and subcategories.
                   15547: 
                   15548: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15549: 
                   15550: parent - parent of current category item
                   15551: 
                   15552: path - Array containing all categories back up through the hierarchy from the
                   15553:        current category to the top level.
                   15554: 
                   15555: currcategories - reference to array of current categories assigned to the course
                   15556: 
1.1260    raeburn  15557: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15558:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15559: 
1.663     raeburn  15560: Returns: $output (markup to be displayed).
                   15561: 
                   15562: =cut
                   15563: 
                   15564: sub assign_category_rows {
1.1259    raeburn  15565:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15566:     my ($text,$name,$item,$chgstr);
                   15567:     if (ref($cats) eq 'ARRAY') {
                   15568:         my $maxdepth = scalar(@{$cats});
                   15569:         if (ref($cats->[$depth]) eq 'HASH') {
                   15570:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15571:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15572:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15573:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15574:                 for (my $j=0; $j<$numchildren; $j++) {
                   15575:                     $name = $cats->[$depth]{$parent}[$j];
                   15576:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15577:                     my $deeper = $depth+1;
                   15578:                     my $checked = '';
                   15579:                     if (ref($currcategories) eq 'ARRAY') {
                   15580:                         if (@{$currcategories} > 0) {
                   15581:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15582:                                 $checked = ' checked="checked"';
1.663     raeburn  15583:                             }
                   15584:                         }
                   15585:                     }
1.664     raeburn  15586:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15587:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15588:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15589:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15590:                              '</td><td>';
1.663     raeburn  15591:                     if (ref($path) eq 'ARRAY') {
                   15592:                         push(@{$path},$name);
1.1259    raeburn  15593:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15594:                         pop(@{$path});
                   15595:                     }
                   15596:                     $text .= '</td></tr>';
                   15597:                 }
                   15598:                 $text .= '</table></td>';
                   15599:             }
                   15600:         }
                   15601:     }
                   15602:     return $text;
                   15603: }
                   15604: 
1.1181    raeburn  15605: =pod
                   15606: 
                   15607: =back
                   15608: 
                   15609: =cut
                   15610: 
1.655     raeburn  15611: ############################################################
                   15612: ############################################################
                   15613: 
                   15614: 
1.443     albertel 15615: sub commit_customrole {
1.664     raeburn  15616:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15617:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15618:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15619:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15620:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15621:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15622:                  '</b><br />';
                   15623:     return $output;
                   15624: }
                   15625: 
                   15626: sub commit_standardrole {
1.1116    raeburn  15627:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15628:     my ($output,$logmsg,$linefeed);
                   15629:     if ($context eq 'auto') {
                   15630:         $linefeed = "\n";
                   15631:     } else {
                   15632:         $linefeed = "<br />\n";
                   15633:     }  
1.443     albertel 15634:     if ($three eq 'st') {
1.541     raeburn  15635:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15636:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15637:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15638:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15639:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15640:         } else {
1.541     raeburn  15641:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15642:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15643:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15644:             if ($context eq 'auto') {
                   15645:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15646:             } else {
                   15647:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15648:                &mt('Add to classlist').': <b>ok</b>';
                   15649:             }
                   15650:             $output .= $linefeed;
1.443     albertel 15651:         }
                   15652:     } else {
                   15653:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15654:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15655:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15656:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15657:         if ($context eq 'auto') {
                   15658:             $output .= $result.$linefeed;
                   15659:         } else {
                   15660:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15661:         }
1.443     albertel 15662:     }
                   15663:     return $output;
                   15664: }
                   15665: 
                   15666: sub commit_studentrole {
1.1116    raeburn  15667:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15668:         $credits) = @_;
1.626     raeburn  15669:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15670:     if ($context eq 'auto') {
                   15671:         $linefeed = "\n";
                   15672:     } else {
                   15673:         $linefeed = '<br />'."\n";
                   15674:     }
1.443     albertel 15675:     if (defined($one) && defined($two)) {
                   15676:         my $cid=$one.'_'.$two;
                   15677:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15678:         my $secchange = 0;
                   15679:         my $expire_role_result;
                   15680:         my $modify_section_result;
1.628     raeburn  15681:         if ($oldsec ne '-1') { 
                   15682:             if ($oldsec ne $sec) {
1.443     albertel 15683:                 $secchange = 1;
1.628     raeburn  15684:                 my $now = time;
1.443     albertel 15685:                 my $uurl='/'.$cid;
                   15686:                 $uurl=~s/\_/\//g;
                   15687:                 if ($oldsec) {
                   15688:                     $uurl.='/'.$oldsec;
                   15689:                 }
1.626     raeburn  15690:                 $oldsecurl = $uurl;
1.628     raeburn  15691:                 $expire_role_result = 
1.652     raeburn  15692:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15693:                 if ($env{'request.course.sec'} ne '') { 
                   15694:                     if ($expire_role_result eq 'refused') {
                   15695:                         my @roles = ('st');
                   15696:                         my @statuses = ('previous');
                   15697:                         my @roledoms = ($one);
                   15698:                         my $withsec = 1;
                   15699:                         my %roleshash = 
                   15700:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15701:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15702:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15703:                             my ($oldstart,$oldend) = 
                   15704:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15705:                             if ($oldend > 0 && $oldend <= $now) {
                   15706:                                 $expire_role_result = 'ok';
                   15707:                             }
                   15708:                         }
                   15709:                     }
                   15710:                 }
1.443     albertel 15711:                 $result = $expire_role_result;
                   15712:             }
                   15713:         }
                   15714:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15715:             $modify_section_result = 
                   15716:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15717:                                                            undef,undef,undef,$sec,
                   15718:                                                            $end,$start,'','',$cid,
                   15719:                                                            '',$context,$credits);
1.443     albertel 15720:             if ($modify_section_result =~ /^ok/) {
                   15721:                 if ($secchange == 1) {
1.628     raeburn  15722:                     if ($sec eq '') {
                   15723:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15724:                     } else {
                   15725:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15726:                     }
1.443     albertel 15727:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15728:                     if ($sec eq '') {
                   15729:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15730:                     } else {
                   15731:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15732:                     }
1.443     albertel 15733:                 } else {
1.628     raeburn  15734:                     if ($sec eq '') {
                   15735:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15736:                     } else {
                   15737:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15738:                     }
1.443     albertel 15739:                 }
                   15740:             } else {
1.1115    raeburn  15741:                 if ($secchange) { 
1.628     raeburn  15742:                     $$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;
                   15743:                 } else {
                   15744:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15745:                 }
1.443     albertel 15746:             }
                   15747:             $result = $modify_section_result;
                   15748:         } elsif ($secchange == 1) {
1.628     raeburn  15749:             if ($oldsec eq '') {
1.1103    raeburn  15750:                 $$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  15751:             } else {
                   15752:                 $$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;
                   15753:             }
1.626     raeburn  15754:             if ($expire_role_result eq 'refused') {
                   15755:                 my $newsecurl = '/'.$cid;
                   15756:                 $newsecurl =~ s/\_/\//g;
                   15757:                 if ($sec ne '') {
                   15758:                     $newsecurl.='/'.$sec;
                   15759:                 }
                   15760:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15761:                     if ($sec eq '') {
                   15762:                         $$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;
                   15763:                     } else {
                   15764:                         $$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;
                   15765:                     }
                   15766:                 }
                   15767:             }
1.443     albertel 15768:         }
                   15769:     } else {
1.626     raeburn  15770:         $$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 15771:         $result = "error: incomplete course id\n";
                   15772:     }
                   15773:     return $result;
                   15774: }
                   15775: 
1.1108    raeburn  15776: sub show_role_extent {
                   15777:     my ($scope,$context,$role) = @_;
                   15778:     $scope =~ s{^/}{};
                   15779:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15780:     push(@courseroles,'co');
                   15781:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15782:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15783:         $scope =~ s{/}{_};
                   15784:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15785:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15786:         my ($audom,$auname) = split(/\//,$scope);
                   15787:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15788:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15789:     } else {
                   15790:         $scope =~ s{/$}{};
                   15791:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15792:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15793:     }
                   15794: }
                   15795: 
1.443     albertel 15796: ############################################################
                   15797: ############################################################
                   15798: 
1.566     albertel 15799: sub check_clone {
1.578     raeburn  15800:     my ($args,$linefeed) = @_;
1.566     albertel 15801:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15802:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15803:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15804:     my $clonemsg;
                   15805:     my $can_clone = 0;
1.944     raeburn  15806:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15807:     if ($lctype ne 'community') {
                   15808:         $lctype = 'course';
                   15809:     }
1.566     albertel 15810:     if ($clonehome eq 'no_host') {
1.944     raeburn  15811:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15812:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15813:         } else {
                   15814:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   15815:         }     
1.566     albertel 15816:     } else {
                   15817: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15818:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15819:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15820:                 $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
1.908     raeburn  15821:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15822:             }
                   15823:         }
1.1262    raeburn  15824: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15825:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15826: 	    $can_clone = 1;
                   15827: 	} else {
1.1221    raeburn  15828: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15829: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15830:             if ($clonehash{'cloners'} eq '') {
                   15831:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15832:                 if ($domdefs{'canclone'}) {
                   15833:                     unless ($domdefs{'canclone'} eq 'none') {
                   15834:                         if ($domdefs{'canclone'} eq 'domain') {
                   15835:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15836:                                 $can_clone = 1;
                   15837:                             }
                   15838:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15839:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15840:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15841:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15842:                                 $can_clone = 1;
                   15843:                             }
                   15844:                         }
                   15845:                     }
                   15846:                 }
1.578     raeburn  15847:             } else {
1.1221    raeburn  15848: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15849:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15850:                     $can_clone = 1;
1.1221    raeburn  15851:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15852:                     $can_clone = 1;
1.1225    raeburn  15853:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15854:                     $can_clone = 1;
1.1221    raeburn  15855:                 }
                   15856:                 unless ($can_clone) {
1.1225    raeburn  15857:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15858:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15859:                         my (%gotdomdefaults,%gotcodedefaults);
                   15860:                         foreach my $cloner (@cloners) {
                   15861:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15862:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15863:                                 my (%codedefaults,@code_order);
                   15864:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15865:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15866:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15867:                                     }
                   15868:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15869:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15870:                                     }
                   15871:                                 } else {
                   15872:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15873:                                                                             \%codedefaults,
                   15874:                                                                             \@code_order);
                   15875:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15876:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15877:                                 }
                   15878:                                 if (@code_order > 0) {
                   15879:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15880:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15881:                                                                                 $args->{'crscode'})) {
                   15882:                                         $can_clone = 1;
                   15883:                                         last;
                   15884:                                     }
                   15885:                                 }
                   15886:                             }
                   15887:                         }
                   15888:                     }
1.1225    raeburn  15889:                 }
                   15890:             }
                   15891:             unless ($can_clone) {
                   15892:                 my $ccrole = 'cc';
                   15893:                 if ($args->{'crstype'} eq 'Community') {
                   15894:                     $ccrole = 'co';
                   15895:                 }
                   15896: 	        my %roleshash =
                   15897: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15898: 					          $args->{'ccdomain'},
                   15899:                                                   'userroles',['active'],[$ccrole],
                   15900: 					          [$args->{'clonedomain'}]);
                   15901: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15902:                     $can_clone = 1;
                   15903:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15904:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15905:                     $can_clone = 1;
1.1221    raeburn  15906:                 }
                   15907:             }
                   15908:             unless ($can_clone) {
                   15909:                 if ($args->{'crstype'} eq 'Community') {
                   15910:                     $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
1.942     raeburn  15911:                 } else {
1.1221    raeburn  15912:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   15913:                 }
1.566     albertel 15914: 	    }
1.578     raeburn  15915:         }
1.566     albertel 15916:     }
                   15917:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15918: }
                   15919: 
1.444     albertel 15920: sub construct_course {
1.1262    raeburn  15921:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15922:         $cnum,$category,$coderef) = @_;
1.444     albertel 15923:     my $outcome;
1.541     raeburn  15924:     my $linefeed =  '<br />'."\n";
                   15925:     if ($context eq 'auto') {
                   15926:         $linefeed = "\n";
                   15927:     }
1.566     albertel 15928: 
                   15929: #
                   15930: # Are we cloning?
                   15931: #
                   15932:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15933:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15934: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15935: 	if ($context ne 'auto') {
1.578     raeburn  15936:             if ($clonemsg ne '') {
                   15937: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15938:             }
1.566     albertel 15939: 	}
                   15940: 	$outcome .= $clonemsg.$linefeed;
                   15941: 
                   15942:         if (!$can_clone) {
                   15943: 	    return (0,$outcome);
                   15944: 	}
                   15945:     }
                   15946: 
1.444     albertel 15947: #
                   15948: # Open course
                   15949: #
1.1239    raeburn  15950:     my $showncrstype;
                   15951:     if ($args->{'crstype'} eq 'Placement') {
                   15952:         $showncrstype = 'placement test'; 
                   15953:     } else {  
                   15954:         $showncrstype = lc($args->{'crstype'});
                   15955:     }
1.444     albertel 15956:     my %cenv=();
                   15957:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15958:                                              $args->{'cdescr'},
                   15959:                                              $args->{'curl'},
                   15960:                                              $args->{'course_home'},
                   15961:                                              $args->{'nonstandard'},
                   15962:                                              $args->{'crscode'},
                   15963:                                              $args->{'ccuname'}.':'.
                   15964:                                              $args->{'ccdomain'},
1.882     raeburn  15965:                                              $args->{'crstype'},
1.885     raeburn  15966:                                              $cnum,$context,$category);
1.444     albertel 15967: 
                   15968:     # Note: The testing routines depend on this being output; see 
                   15969:     # Utils::Course. This needs to at least be output as a comment
                   15970:     # if anyone ever decides to not show this, and Utils::Course::new
                   15971:     # will need to be suitably modified.
1.1239    raeburn  15972:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15973:     if ($$courseid =~ /^error:/) {
                   15974:         return (0,$outcome);
                   15975:     }
                   15976: 
1.444     albertel 15977: #
                   15978: # Check if created correctly
                   15979: #
1.479     albertel 15980:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15981:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15982:     if ($crsuhome eq 'no_host') {
                   15983:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15984:         return (0,$outcome);
                   15985:     }
1.541     raeburn  15986:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15987: 
1.444     albertel 15988: #
1.566     albertel 15989: # Do the cloning
                   15990: #   
                   15991:     if ($can_clone && $cloneid) {
1.1239    raeburn  15992: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15993: 	if ($context ne 'auto') {
                   15994: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15995: 	}
                   15996: 	$outcome .= $clonemsg.$linefeed;
                   15997: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15998: # Copy all files
1.637     www      15999: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 16000: # Restore URL
1.566     albertel 16001: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16002: # Restore title
1.566     albertel 16003: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16004: # Restore creation date, creator and creation context.
                   16005:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16006:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16007:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16008: # Mark as cloned
1.566     albertel 16009: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16010: # Need to clone grading mode
                   16011:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16012:         $cenv{'grading'}=$newenv{'grading'};
                   16013: # Do not clone these environment entries
                   16014:         &Apache::lonnet::del('environment',
                   16015:                   ['default_enrollment_start_date',
                   16016:                    'default_enrollment_end_date',
                   16017:                    'question.email',
                   16018:                    'policy.email',
                   16019:                    'comment.email',
                   16020:                    'pch.users.denied',
1.725     raeburn  16021:                    'plc.users.denied',
                   16022:                    'hidefromcat',
1.1121    raeburn  16023:                    'checkforpriv',
1.1166    raeburn  16024:                    'categories',
                   16025:                    'internal.uniquecode'],
1.638     www      16026:                    $$crsudom,$$crsunum);
1.1170    raeburn  16027:         if ($args->{'textbook'}) {
                   16028:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16029:         }
1.444     albertel 16030:     }
1.566     albertel 16031: 
1.444     albertel 16032: #
                   16033: # Set environment (will override cloned, if existing)
                   16034: #
                   16035:     my @sections = ();
                   16036:     my @xlists = ();
                   16037:     if ($args->{'crstype'}) {
                   16038:         $cenv{'type'}=$args->{'crstype'};
                   16039:     }
                   16040:     if ($args->{'crsid'}) {
                   16041:         $cenv{'courseid'}=$args->{'crsid'};
                   16042:     }
                   16043:     if ($args->{'crscode'}) {
                   16044:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16045:     }
                   16046:     if ($args->{'crsquota'} ne '') {
                   16047:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16048:     } else {
                   16049:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16050:     }
                   16051:     if ($args->{'ccuname'}) {
                   16052:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16053:                                         ':'.$args->{'ccdomain'};
                   16054:     } else {
                   16055:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16056:     }
1.1116    raeburn  16057:     if ($args->{'defaultcredits'}) {
                   16058:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16059:     }
1.444     albertel 16060:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16061:     if ($args->{'crssections'}) {
                   16062:         $cenv{'internal.sectionnums'} = '';
                   16063:         if ($args->{'crssections'} =~ m/,/) {
                   16064:             @sections = split/,/,$args->{'crssections'};
                   16065:         } else {
                   16066:             $sections[0] = $args->{'crssections'};
                   16067:         }
                   16068:         if (@sections > 0) {
                   16069:             foreach my $item (@sections) {
                   16070:                 my ($sec,$gp) = split/:/,$item;
                   16071:                 my $class = $args->{'crscode'}.$sec;
                   16072:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16073:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16074:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16075:                     push(@badclasses,$class);
1.444     albertel 16076:                 }
                   16077:             }
                   16078:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16079:         }
                   16080:     }
                   16081: # do not hide course coordinator from staff listing, 
                   16082: # even if privileged
                   16083:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16084: # add course coordinator's domain to domains to check for privileged users
                   16085: # if different to course domain
                   16086:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16087:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16088:     }
1.444     albertel 16089: # add crosslistings
                   16090:     if ($args->{'crsxlist'}) {
                   16091:         $cenv{'internal.crosslistings'}='';
                   16092:         if ($args->{'crsxlist'} =~ m/,/) {
                   16093:             @xlists = split/,/,$args->{'crsxlist'};
                   16094:         } else {
                   16095:             $xlists[0] = $args->{'crsxlist'};
                   16096:         }
                   16097:         if (@xlists > 0) {
                   16098:             foreach my $item (@xlists) {
                   16099:                 my ($xl,$gp) = split/:/,$item;
                   16100:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16101:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16102:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16103:                     push(@badclasses,$xl);
1.444     albertel 16104:                 }
                   16105:             }
                   16106:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16107:         }
                   16108:     }
                   16109:     if ($args->{'autoadds'}) {
                   16110:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16111:     }
                   16112:     if ($args->{'autodrops'}) {
                   16113:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16114:     }
                   16115: # check for notification of enrollment changes
                   16116:     my @notified = ();
                   16117:     if ($args->{'notify_owner'}) {
                   16118:         if ($args->{'ccuname'} ne '') {
                   16119:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16120:         }
                   16121:     }
                   16122:     if ($args->{'notify_dc'}) {
                   16123:         if ($uname ne '') { 
1.630     raeburn  16124:             push(@notified,$uname.':'.$udom);
1.444     albertel 16125:         }
                   16126:     }
                   16127:     if (@notified > 0) {
                   16128:         my $notifylist;
                   16129:         if (@notified > 1) {
                   16130:             $notifylist = join(',',@notified);
                   16131:         } else {
                   16132:             $notifylist = $notified[0];
                   16133:         }
                   16134:         $cenv{'internal.notifylist'} = $notifylist;
                   16135:     }
                   16136:     if (@badclasses > 0) {
                   16137:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16138:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16139:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16140:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16141:         );
1.1264    raeburn  16142:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16143:                            &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  16144:         if ($context eq 'auto') {
                   16145:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16146:         } else {
1.566     albertel 16147:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16148:         }
                   16149:         foreach my $item (@badclasses) {
1.541     raeburn  16150:             if ($context eq 'auto') {
1.1261    raeburn  16151:                 $outcome .= " - $item\n";
1.541     raeburn  16152:             } else {
1.1261    raeburn  16153:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16154:             }
1.1261    raeburn  16155:         }
                   16156:         if ($context eq 'auto') {
                   16157:             $outcome .= $linefeed;
                   16158:         } else {
                   16159:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16160:         } 
1.444     albertel 16161:     }
                   16162:     if ($args->{'no_end_date'}) {
                   16163:         $args->{'endaccess'} = 0;
                   16164:     }
                   16165:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16166:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16167:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16168:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16169:     if ($args->{'showphotos'}) {
                   16170:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16171:     }
                   16172:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16173:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16174:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16175:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16176:             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'); 
                   16177:             if ($context eq 'auto') {
                   16178:                 $outcome .= $krb_msg;
                   16179:             } else {
1.566     albertel 16180:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16181:             }
                   16182:             $outcome .= $linefeed;
1.444     albertel 16183:         }
                   16184:     }
                   16185:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16186:        if ($args->{'setpolicy'}) {
                   16187:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16188:        }
                   16189:        if ($args->{'setcontent'}) {
                   16190:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16191:        }
1.1251    raeburn  16192:        if ($args->{'setcomment'}) {
                   16193:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16194:        }
1.444     albertel 16195:     }
                   16196:     if ($args->{'reshome'}) {
                   16197: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16198: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16199:     }
                   16200: #
                   16201: # course has keyed access
                   16202: #
                   16203:     if ($args->{'setkeys'}) {
                   16204:        $cenv{'keyaccess'}='yes';
                   16205:     }
                   16206: # if specified, key authority is not course, but user
                   16207: # only active if keyaccess is yes
                   16208:     if ($args->{'keyauth'}) {
1.487     albertel 16209: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16210: 	$user = &LONCAPA::clean_username($user);
                   16211: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16212: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16213: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16214: 	}
                   16215:     }
                   16216: 
1.1166    raeburn  16217: #
1.1167    raeburn  16218: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16219: #
                   16220:     if ($args->{'uniquecode'}) {
                   16221:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16222:         if ($code) {
                   16223:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16224:             my %crsinfo =
                   16225:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16226:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16227:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16228:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16229:             } 
1.1166    raeburn  16230:             if (ref($coderef)) {
                   16231:                 $$coderef = $code;
                   16232:             }
                   16233:         }
                   16234:     }
                   16235: 
1.444     albertel 16236:     if ($args->{'disresdis'}) {
                   16237:         $cenv{'pch.roles.denied'}='st';
                   16238:     }
                   16239:     if ($args->{'disablechat'}) {
                   16240:         $cenv{'plc.roles.denied'}='st';
                   16241:     }
                   16242: 
                   16243:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16244:     # course
                   16245:     $cenv{'course.helper.not.run'} = 1;
                   16246:     #
                   16247:     # Use new Randomseed
                   16248:     #
                   16249:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16250:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16251:     #
                   16252:     # The encryption code and receipt prefix for this course
                   16253:     #
                   16254:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16255:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16256:     #
                   16257:     # By default, use standard grading
                   16258:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16259: 
1.541     raeburn  16260:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16261:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16262: #
                   16263: # Open all assignments
                   16264: #
                   16265:     if ($args->{'openall'}) {
                   16266:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   16267:        my %storecontent = ($storeunder         => time,
                   16268:                            $storeunder.'.type' => 'date_start');
                   16269:        
                   16270:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  16271:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16272:    }
                   16273: #
                   16274: # Set first page
                   16275: #
                   16276:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16277: 	    || ($cloneid)) {
1.445     albertel 16278: 	use LONCAPA::map;
1.444     albertel 16279: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16280: 
                   16281: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16282:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16283: 
1.444     albertel 16284:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16285:         my $title; my $url;
                   16286:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16287: 	    $title=&mt('Syllabus');
1.444     albertel 16288:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16289:         } else {
1.963     raeburn  16290:             $title=&mt('Table of Contents');
1.444     albertel 16291:             $url='/adm/navmaps';
                   16292:         }
1.445     albertel 16293: 
                   16294:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16295: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16296: 
                   16297: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16298:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16299:     }
1.566     albertel 16300: 
1.1237    raeburn  16301: # 
                   16302: # Set params for Placement Tests
                   16303: #
1.1239    raeburn  16304:     if ($args->{'crstype'} eq 'Placement') {
                   16305:        my %storecontent; 
                   16306:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16307:        my %defaults = (
                   16308:                         buttonshide   => { value => 'yes',
                   16309:                                            type => 'string_yesno',},
                   16310:                         type          => { value => 'randomizetry',
                   16311:                                            type  => 'string_questiontype',},
                   16312:                         maxtries      => { value => 1,
                   16313:                                            type => 'int_pos',},
                   16314:                         problemstatus => { value => 'no',
                   16315:                                            type  => 'string_problemstatus',},
                   16316:                       );
                   16317:        foreach my $key (keys(%defaults)) {
                   16318:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   16319:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   16320:        }
1.1237    raeburn  16321:        &Apache::lonnet::cput
                   16322:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   16323:     }
                   16324: 
1.566     albertel 16325:     return (1,$outcome);
1.444     albertel 16326: }
                   16327: 
1.1166    raeburn  16328: sub make_unique_code {
                   16329:     my ($cdom,$cnum) = @_;
                   16330:     # get lock on uniquecodes db
                   16331:     my $lockhash = {
                   16332:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16333:                                                   ':'.$env{'user.domain'},
                   16334:                    };
                   16335:     my $tries = 0;
                   16336:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16337:     my ($code,$error);
                   16338:   
                   16339:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16340:         $tries ++;
                   16341:         sleep 1;
                   16342:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16343:     }
                   16344:     if ($gotlock eq 'ok') {
                   16345:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16346:         my $gotcode;
                   16347:         my $attempts = 0;
                   16348:         while ((!$gotcode) && ($attempts < 100)) {
                   16349:             $code = &generate_code();
                   16350:             if (!exists($currcodes{$code})) {
                   16351:                 $gotcode = 1;
                   16352:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16353:                     $error = 'nostore';
                   16354:                 }
                   16355:             }
                   16356:             $attempts ++;
                   16357:         }
                   16358:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16359:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16360:     } else {
                   16361:         $error = 'nolock';
                   16362:     }
                   16363:     return ($code,$error);
                   16364: }
                   16365: 
                   16366: sub generate_code {
                   16367:     my $code;
                   16368:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16369:     for (my $i=0; $i<6; $i++) {
                   16370:         my $lettnum = int (rand 2);
                   16371:         my $item = '';
                   16372:         if ($lettnum) {
                   16373:             $item = $letts[int( rand(18) )];
                   16374:         } else {
                   16375:             $item = 1+int( rand(8) );
                   16376:         }
                   16377:         $code .= $item;
                   16378:     }
                   16379:     return $code;
                   16380: }
                   16381: 
1.444     albertel 16382: ############################################################
                   16383: ############################################################
                   16384: 
1.1237    raeburn  16385: # Community, Course and Placement Test
1.378     raeburn  16386: sub course_type {
                   16387:     my ($cid) = @_;
                   16388:     if (!defined($cid)) {
                   16389:         $cid = $env{'request.course.id'};
                   16390:     }
1.404     albertel 16391:     if (defined($env{'course.'.$cid.'.type'})) {
                   16392:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16393:     } else {
                   16394:         return 'Course';
1.377     raeburn  16395:     }
                   16396: }
1.156     albertel 16397: 
1.406     raeburn  16398: sub group_term {
                   16399:     my $crstype = &course_type();
                   16400:     my %names = (
                   16401:                   'Course' => 'group',
1.865     raeburn  16402:                   'Community' => 'group',
1.1237    raeburn  16403:                   'Placement' => 'group',
1.406     raeburn  16404:                 );
                   16405:     return $names{$crstype};
                   16406: }
                   16407: 
1.902     raeburn  16408: sub course_types {
1.1310    raeburn  16409:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  16410:     my %typename = (
                   16411:                          official   => 'Official course',
                   16412:                          unofficial => 'Unofficial course',
                   16413:                          community  => 'Community',
1.1165    raeburn  16414:                          textbook   => 'Textbook course',
1.1237    raeburn  16415:                          placement  => 'Placement test',
1.1310    raeburn  16416:                          lti        => 'LTI provider',
1.902     raeburn  16417:                    );
                   16418:     return (\@types,\%typename);
                   16419: }
                   16420: 
1.156     albertel 16421: sub icon {
                   16422:     my ($file)=@_;
1.505     albertel 16423:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16424:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16425:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16426:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16427: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16428: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16429: 	            $curfext.".gif") {
                   16430: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16431: 		$curfext.".gif";
                   16432: 	}
                   16433:     }
1.249     albertel 16434:     return &lonhttpdurl($iconname);
1.154     albertel 16435: } 
1.84      albertel 16436: 
1.575     albertel 16437: sub lonhttpdurl {
1.692     www      16438: #
                   16439: # Had been used for "small fry" static images on separate port 8080.
                   16440: # Modify here if lightweight http functionality desired again.
                   16441: # Currently eliminated due to increasing firewall issues.
                   16442: #
1.575     albertel 16443:     my ($url)=@_;
1.692     www      16444:     return $url;
1.215     albertel 16445: }
                   16446: 
1.213     albertel 16447: sub connection_aborted {
                   16448:     my ($r)=@_;
                   16449:     $r->print(" ");$r->rflush();
                   16450:     my $c = $r->connection;
                   16451:     return $c->aborted();
                   16452: }
                   16453: 
1.221     foxr     16454: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16455: #    strings as 'strings'.
                   16456: sub escape_single {
1.221     foxr     16457:     my ($input) = @_;
1.223     albertel 16458:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16459:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16460:     return $input;
                   16461: }
1.223     albertel 16462: 
1.222     foxr     16463: #  Same as escape_single, but escape's "'s  This 
                   16464: #  can be used for  "strings"
                   16465: sub escape_double {
                   16466:     my ($input) = @_;
                   16467:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16468:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16469:     return $input;
                   16470: }
1.223     albertel 16471:  
1.222     foxr     16472: #   Escapes the last element of a full URL.
                   16473: sub escape_url {
                   16474:     my ($url)   = @_;
1.238     raeburn  16475:     my @urlslices = split(/\//, $url,-1);
1.369     www      16476:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16477:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16478: }
1.462     albertel 16479: 
1.820     raeburn  16480: sub compare_arrays {
                   16481:     my ($arrayref1,$arrayref2) = @_;
                   16482:     my (@difference,%count);
                   16483:     @difference = ();
                   16484:     %count = ();
                   16485:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16486:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16487:         foreach my $element (keys(%count)) {
                   16488:             if ($count{$element} == 1) {
                   16489:                 push(@difference,$element);
                   16490:             }
                   16491:         }
                   16492:     }
                   16493:     return @difference;
                   16494: }
                   16495: 
1.1322    raeburn  16496: sub lon_status_items {
                   16497:     my %defaults = (
                   16498:                      E         => 100,
                   16499:                      W         => 4,
                   16500:                      N         => 1,
1.1324    raeburn  16501:                      U         => 5,
1.1322    raeburn  16502:                      threshold => 200,
                   16503:                      sysmail   => 2500,
                   16504:                    );
                   16505:     my %names = (
                   16506:                    E => 'Errors',
                   16507:                    W => 'Warnings',
                   16508:                    N => 'Notices',
1.1324    raeburn  16509:                    U => 'Unsent',
1.1322    raeburn  16510:                 );
                   16511:     return (\%defaults,\%names);
                   16512: }
                   16513: 
1.817     bisitz   16514: # -------------------------------------------------------- Initialize user login
1.462     albertel 16515: sub init_user_environment {
1.463     albertel 16516:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16517:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16518: 
                   16519:     my $public=($username eq 'public' && $domain eq 'public');
                   16520: 
1.1062    raeburn  16521:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16522:     my $now=time;
                   16523: 
                   16524:     if ($public) {
                   16525: 	my $max_public=100;
                   16526: 	my $oldest;
                   16527: 	my $oldest_time=0;
                   16528: 	for(my $next=1;$next<=$max_public;$next++) {
                   16529: 	    if (-e $lonids."/publicuser_$next.id") {
                   16530: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16531: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16532: 		    $oldest_time=$mtime;
                   16533: 		    $oldest=$next;
                   16534: 		}
                   16535: 	    } else {
                   16536: 		$cookie="publicuser_$next";
                   16537: 		last;
                   16538: 	    }
                   16539: 	}
                   16540: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16541:     } else {
1.1275    raeburn  16542: 	# See if old ID present, if so, remove if this isn't a robot,
                   16543: 	# killing any existing non-robot sessions
1.463     albertel 16544: 	if (!$args->{'robot'}) {
                   16545: 	    opendir(DIR,$lonids);
                   16546: 	    while ($filename=readdir(DIR)) {
                   16547: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  16548:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16549:                             &GDBM_READER(),0640)) {
1.1295    raeburn  16550:                         my $linkedfile;
1.1320    raeburn  16551:                         if (exists($oldenv{'user.linkedenv'})) {
                   16552:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  16553:                         }
1.1320    raeburn  16554:                         untie(%oldenv);
                   16555:                         if (unlink("$lonids/$filename")) {
                   16556:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16557:                                 if (-l "$lonids/$linkedfile.id") {
                   16558:                                     unlink("$lonids/$linkedfile.id");
                   16559:                                 }
1.1295    raeburn  16560:                             }
                   16561:                         }
                   16562:                     } else {
                   16563:                         unlink($lonids.'/'.$filename);
                   16564:                     }
1.463     albertel 16565: 		}
1.462     albertel 16566: 	    }
1.463     albertel 16567: 	    closedir(DIR);
1.1204    raeburn  16568: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16569:             my $namespace = 'nohist_courseeditor';
                   16570:             my $lockingkey = 'paste'."\0".'locked_num';
                   16571:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16572:                                                 $domain,$username);
                   16573:             if (exists($lockhash{$lockingkey})) {
                   16574:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16575:                 unless ($delresult eq 'ok') {
                   16576:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16577:                 }
                   16578:             }
1.462     albertel 16579: 	}
                   16580: # Give them a new cookie
1.463     albertel 16581: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16582: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16583: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16584:     
                   16585: # Initialize roles
                   16586: 
1.1062    raeburn  16587: 	($userroles,$firstaccenv,$timerintenv) = 
                   16588:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16589:     }
                   16590: # ------------------------------------ Check browser type and MathML capability
                   16591: 
1.1194    raeburn  16592:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16593:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16594: 
                   16595: # ------------------------------------------------------------- Get environment
                   16596: 
                   16597:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16598:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16599:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16600: 	undef(%userenv);
                   16601:     }
                   16602:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16603: 	$form->{'interface'}=$userenv{'interface'};
                   16604:     }
                   16605:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16606: 
                   16607: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16608:     foreach my $option ('interface','localpath','localres') {
                   16609:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16610:     }
                   16611: # --------------------------------------------------------- Write first profile
                   16612: 
                   16613:     {
                   16614: 	my %initial_env = 
                   16615: 	    ("user.name"          => $username,
                   16616: 	     "user.domain"        => $domain,
                   16617: 	     "user.home"          => $authhost,
                   16618: 	     "browser.type"       => $clientbrowser,
                   16619: 	     "browser.version"    => $clientversion,
                   16620: 	     "browser.mathml"     => $clientmathml,
                   16621: 	     "browser.unicode"    => $clientunicode,
                   16622: 	     "browser.os"         => $clientos,
1.1137    raeburn  16623:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16624:              "browser.info"       => $clientinfo,
1.1194    raeburn  16625:              "browser.osversion"  => $clientosversion,
1.462     albertel 16626: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16627: 	     "request.course.fn"  => '',
                   16628: 	     "request.course.uri" => '',
                   16629: 	     "request.course.sec" => '',
                   16630: 	     "request.role"       => 'cm',
                   16631: 	     "request.role.adv"   => $env{'user.adv'},
                   16632: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16633: 
                   16634:         if ($form->{'localpath'}) {
                   16635: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16636: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16637:         }
                   16638: 	
                   16639: 	if ($form->{'interface'}) {
                   16640: 	    $form->{'interface'}=~s/\W//gs;
                   16641: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16642: 	    $env{'browser.interface'}=$form->{'interface'};
                   16643: 	}
                   16644: 
1.1157    raeburn  16645:         if ($form->{'iptoken'}) {
                   16646:             my $lonhost = $r->dir_config('lonHostID');
                   16647:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16648:             $env{'user.noloadbalance'} = $lonhost;
                   16649:         }
                   16650: 
1.1268    raeburn  16651:         if ($form->{'noloadbalance'}) {
                   16652:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16653:             my $hosthere = $form->{'noloadbalance'};
                   16654:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16655:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16656:                 $env{'user.noloadbalance'} = $hosthere;
                   16657:             }
                   16658:         }
                   16659: 
1.1016    raeburn  16660:         unless ($domain eq 'public') {
1.1273    raeburn  16661:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16662:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16663: 
                   16664:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16665:                 $userenv{'availabletools.'.$tool} = 
                   16666:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16667:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16668:             }
1.980     raeburn  16669: 
1.1311    raeburn  16670:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  16671:                 $userenv{'canrequest.'.$crstype} =
                   16672:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16673:                                                       'reload','requestcourses',
                   16674:                                                       \%userenv,\%domdef,\%is_adv);
                   16675:             }
1.724     raeburn  16676: 
1.1273    raeburn  16677:             $userenv{'canrequest.author'} =
                   16678:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16679:                                                   'reload','requestauthor',
1.980     raeburn  16680:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16681:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16682:                                                  $domain,$username);
                   16683:             my $reqstatus = $reqauthor{'author_status'};
                   16684:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16685:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16686:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16687:                                                       $reqauthor{'author'}{'timestamp'};
                   16688:                 }
1.1092    raeburn  16689:             }
1.1287    raeburn  16690:             my ($types,$typename) = &course_types();
                   16691:             if (ref($types) eq 'ARRAY') {
                   16692:                 my @options = ('approval','validate','autolimit');
                   16693:                 my $optregex = join('|',@options);
                   16694:                 my (%willtrust,%trustchecked);
                   16695:                 foreach my $type (@{$types}) {
                   16696:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   16697:                     if ($dom_str ne '') {
                   16698:                         my $updatedstr = '';
                   16699:                         my @possdomains = split(',',$dom_str);
                   16700:                         foreach my $entry (@possdomains) {
                   16701:                             my ($extdom,$extopt) = split(':',$entry);
                   16702:                             unless ($trustchecked{$extdom}) {
                   16703:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   16704:                                 $trustchecked{$extdom} = 1;
                   16705:                             }
                   16706:                             if ($willtrust{$extdom}) {
                   16707:                                 $updatedstr .= $entry.',';
                   16708:                             }
                   16709:                         }
                   16710:                         $updatedstr =~ s/,$//;
                   16711:                         if ($updatedstr) {
                   16712:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   16713:                         } else {
                   16714:                             delete($userenv{'reqcrsotherdom.'.$type});
                   16715:                         }
                   16716:                     }
                   16717:                 }
                   16718:             }
1.1092    raeburn  16719:         }
1.462     albertel 16720: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16721: 
1.462     albertel 16722: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16723: 		 &GDBM_WRCREAT(),0640)) {
                   16724: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16725: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16726: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16727:             if (ref($firstaccenv) eq 'HASH') {
                   16728:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16729:             }
                   16730:             if (ref($timerintenv) eq 'HASH') {
                   16731:                 &_add_to_env(\%disk_env,$timerintenv);
                   16732:             }
1.463     albertel 16733: 	    if (ref($args->{'extra_env'})) {
                   16734: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16735: 	    }
1.462     albertel 16736: 	    untie(%disk_env);
                   16737: 	} else {
1.705     tempelho 16738: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16739: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16740: 	    return 'error: '.$!;
                   16741: 	}
                   16742:     }
                   16743:     $env{'request.role'}='cm';
                   16744:     $env{'request.role.adv'}=$env{'user.adv'};
                   16745:     $env{'browser.type'}=$clientbrowser;
                   16746: 
                   16747:     return $cookie;
                   16748: 
                   16749: }
                   16750: 
                   16751: sub _add_to_env {
                   16752:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16753:     if (ref($env_data) eq 'HASH') {
                   16754:         while (my ($key,$value) = each(%$env_data)) {
                   16755: 	    $idf->{$prefix.$key} = $value;
                   16756: 	    $env{$prefix.$key}   = $value;
                   16757:         }
1.462     albertel 16758:     }
                   16759: }
                   16760: 
1.685     tempelho 16761: # --- Get the symbolic name of a problem and the url
                   16762: sub get_symb {
                   16763:     my ($request,$silent) = @_;
1.726     raeburn  16764:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16765:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16766:     if ($symb eq '') {
                   16767:         if (!$silent) {
1.1071    raeburn  16768:             if (ref($request)) { 
                   16769:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16770:             }
1.685     tempelho 16771:             return ();
                   16772:         }
                   16773:     }
                   16774:     &Apache::lonenc::check_decrypt(\$symb);
                   16775:     return ($symb);
                   16776: }
                   16777: 
                   16778: # --------------------------------------------------------------Get annotation
                   16779: 
                   16780: sub get_annotation {
                   16781:     my ($symb,$enc) = @_;
                   16782: 
                   16783:     my $key = $symb;
                   16784:     if (!$enc) {
                   16785:         $key =
                   16786:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16787:     }
                   16788:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16789:     return $annotation{$key};
                   16790: }
                   16791: 
                   16792: sub clean_symb {
1.731     raeburn  16793:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16794: 
                   16795:     &Apache::lonenc::check_decrypt(\$symb);
                   16796:     my $enc = $env{'request.enc'};
1.731     raeburn  16797:     if ($delete_enc) {
1.730     raeburn  16798:         delete($env{'request.enc'});
                   16799:     }
1.685     tempelho 16800: 
                   16801:     return ($symb,$enc);
                   16802: }
1.462     albertel 16803: 
1.1181    raeburn  16804: ############################################################
                   16805: ############################################################
                   16806: 
                   16807: =pod
                   16808: 
                   16809: =head1 Routines for building display used to search for courses
                   16810: 
                   16811: 
                   16812: =over 4
                   16813: 
                   16814: =item * &build_filters()
                   16815: 
                   16816: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16817: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16818: and quotacheck.pl
                   16819: 
1.1181    raeburn  16820: 
                   16821: Inputs:
                   16822: 
                   16823: filterlist - anonymous array of fields to include as potential filters 
                   16824: 
                   16825: crstype - course type
                   16826: 
                   16827: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16828:               to pop-open a course selector (will contain "extra element"). 
                   16829: 
                   16830: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16831: 
                   16832: filter - anonymous hash of criteria and their values
                   16833: 
                   16834: action - form action
                   16835: 
                   16836: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16837: 
1.1182    raeburn  16838: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16839: 
                   16840: cloneruname - username of owner of new course who wants to clone
                   16841: 
                   16842: clonerudom - domain of owner of new course who wants to clone
                   16843: 
                   16844: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16845: 
                   16846: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16847: 
                   16848: codedom - domain
                   16849: 
                   16850: formname - value of form element named "form". 
                   16851: 
                   16852: fixeddom - domain, if fixed.
                   16853: 
                   16854: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16855: 
                   16856: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16857: 
                   16858: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16859: 
                   16860: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16861: 
                   16862: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16863: 
                   16864: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16865: 
                   16866: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16867: 
1.1182    raeburn  16868: 
1.1181    raeburn  16869: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16870: 
1.1182    raeburn  16871: 
1.1181    raeburn  16872: Side Effects: None
                   16873: 
                   16874: =cut
                   16875: 
                   16876: # ---------------------------------------------- search for courses based on last activity etc.
                   16877: 
                   16878: sub build_filters {
                   16879:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16880:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16881:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16882:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16883:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16884:     my ($list,$jscript);
1.1181    raeburn  16885:     my $onchange = 'javascript:updateFilters(this)';
                   16886:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16887:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16888:         $typeselectform,$instcodetitle);
                   16889:     if ($formname eq '') {
                   16890:         $formname = $caller;
                   16891:     }
                   16892:     foreach my $item (@{$filterlist}) {
                   16893:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16894:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16895:             if ($item eq 'domainfilter') {
                   16896:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16897:             } elsif ($item eq 'coursefilter') {
                   16898:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16899:             } elsif ($item eq 'ownerfilter') {
                   16900:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16901:             } elsif ($item eq 'ownerdomfilter') {
                   16902:                 $filter->{'ownerdomfilter'} =
                   16903:                     &LONCAPA::clean_domain($filter->{$item});
                   16904:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16905:                                                        'ownerdomfilter',1);
                   16906:             } elsif ($item eq 'personfilter') {
                   16907:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16908:             } elsif ($item eq 'persondomfilter') {
                   16909:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16910:                                                         'persondomfilter',1);
                   16911:             } else {
                   16912:                 $filter->{$item} =~ s/\W//g;
                   16913:             }
                   16914:             if (!$filter->{$item}) {
                   16915:                 $filter->{$item} = '';
                   16916:             }
                   16917:         }
                   16918:         if ($item eq 'domainfilter') {
                   16919:             my $allow_blank = 1;
                   16920:             if ($formname eq 'portform') {
                   16921:                 $allow_blank=0;
                   16922:             } elsif ($formname eq 'studentform') {
                   16923:                 $allow_blank=0;
                   16924:             }
                   16925:             if ($fixeddom) {
                   16926:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16927:                                     ' value="'.$codedom.'" />'.
                   16928:                                     &Apache::lonnet::domain($codedom,'description');
                   16929:             } else {
                   16930:                 $domainselectform = &select_dom_form($filter->{$item},
                   16931:                                                      'domainfilter',
                   16932:                                                       $allow_blank,'',$onchange);
                   16933:             }
                   16934:         } else {
                   16935:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16936:         }
                   16937:     }
                   16938: 
                   16939:     # last course activity filter and selection
                   16940:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16941: 
                   16942:     # course created filter and selection
                   16943:     if (exists($filter->{'createdfilter'})) {
                   16944:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16945:     }
                   16946: 
1.1239    raeburn  16947:     my $prefix = $crstype;
                   16948:     if ($crstype eq 'Placement') {
                   16949:         $prefix = 'Placement Test'
                   16950:     }
1.1181    raeburn  16951:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16952:                 'cac' => "$prefix Activity",
                   16953:                 'ccr' => "$prefix Created",
                   16954:                 'cde' => "$prefix Title",
                   16955:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16956:                 'ins' => 'Institutional Code',
                   16957:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16958:                 'cow' => "$prefix Owner/Co-owner",
                   16959:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16960:                 'cog' => 'Type',
                   16961:              );
                   16962: 
                   16963:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16964:         my $typeval = 'Course';
                   16965:         if ($crstype eq 'Community') {
                   16966:             $typeval = 'Community';
1.1239    raeburn  16967:         } elsif ($crstype eq 'Placement') {
                   16968:             $typeval = 'Placement';
1.1181    raeburn  16969:         }
                   16970:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16971:     } else {
                   16972:         $typeselectform =  '<select name="type" size="1"';
                   16973:         if ($onchange) {
                   16974:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16975:         }
                   16976:         $typeselectform .= '>'."\n";
1.1237    raeburn  16977:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16978:             my $shown;
                   16979:             if ($posstype eq 'Placement') {
                   16980:                 $shown = &mt('Placement Test');
                   16981:             } else {
                   16982:                 $shown = &mt($posstype);
                   16983:             }
1.1181    raeburn  16984:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16985:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16986:         }
                   16987:         $typeselectform.="</select>";
                   16988:     }
                   16989: 
                   16990:     my ($cloneableonlyform,$cloneabletitle);
                   16991:     if (exists($filter->{'cloneableonly'})) {
                   16992:         my $cloneableon = '';
                   16993:         my $cloneableoff = ' checked="checked"';
                   16994:         if ($filter->{'cloneableonly'}) {
                   16995:             $cloneableon = $cloneableoff;
                   16996:             $cloneableoff = '';
                   16997:         }
                   16998:         $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>';
                   16999:         if ($formname eq 'ccrs') {
1.1187    bisitz   17000:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17001:         } else {
                   17002:             $cloneabletitle = &mt('Cloneable by you');
                   17003:         }
                   17004:     }
                   17005:     my $officialjs;
                   17006:     if ($crstype eq 'Course') {
                   17007:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17008: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17009: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17010:             if ($codedom) { 
1.1181    raeburn  17011:                 $officialjs = 1;
                   17012:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17013:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17014:                                                                   $officialjs,$codetitlesref);
                   17015:                 if ($jscript) {
1.1182    raeburn  17016:                     $jscript = '<script type="text/javascript">'."\n".
                   17017:                                '// <![CDATA['."\n".
                   17018:                                $jscript."\n".
                   17019:                                '// ]]>'."\n".
                   17020:                                '</script>'."\n";
1.1181    raeburn  17021:                 }
                   17022:             }
                   17023:             if ($instcodeform eq '') {
                   17024:                 $instcodeform =
                   17025:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17026:                     $list->{'instcodefilter'}.'" />';
                   17027:                 $instcodetitle = $lt{'ins'};
                   17028:             } else {
                   17029:                 $instcodetitle = $lt{'inc'};
                   17030:             }
                   17031:             if ($fixeddom) {
                   17032:                 $instcodetitle .= '<br />('.$codedom.')';
                   17033:             }
                   17034:         }
                   17035:     }
                   17036:     my $output = qq|
                   17037: <form method="post" name="filterpicker" action="$action">
                   17038: <input type="hidden" name="form" value="$formname" />
                   17039: |;
                   17040:     if ($formname eq 'modifycourse') {
                   17041:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17042:                    '<input type="hidden" name="prevphase" value="'.
                   17043:                    $prevphase.'" />'."\n";
1.1198    musolffc 17044:     } elsif ($formname eq 'quotacheck') {
                   17045:         $output .= qq|
                   17046: <input type="hidden" name="sortby" value="" />
                   17047: <input type="hidden" name="sortorder" value="" />
                   17048: |;
                   17049:     } else {
1.1181    raeburn  17050:         my $name_input;
                   17051:         if ($cnameelement ne '') {
                   17052:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17053:                           $cnameelement.'" />';
                   17054:         }
                   17055:         $output .= qq|
1.1182    raeburn  17056: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17057: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17058: $name_input
                   17059: $roleelement
                   17060: $multelement
                   17061: $typeelement
                   17062: |;
                   17063:         if ($formname eq 'portform') {
                   17064:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17065:         }
                   17066:     }
                   17067:     if ($fixeddom) {
                   17068:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17069:     }
                   17070:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17071:     if ($sincefilterform) {
                   17072:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17073:                   .$sincefilterform
                   17074:                   .&Apache::lonhtmlcommon::row_closure();
                   17075:     }
                   17076:     if ($createdfilterform) {
                   17077:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17078:                   .$createdfilterform
                   17079:                   .&Apache::lonhtmlcommon::row_closure();
                   17080:     }
                   17081:     if ($domainselectform) {
                   17082:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17083:                   .$domainselectform
                   17084:                   .&Apache::lonhtmlcommon::row_closure();
                   17085:     }
                   17086:     if ($typeselectform) {
                   17087:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17088:             $output .= $typeselectform;
                   17089:         } else {
                   17090:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17091:                       .$typeselectform
                   17092:                       .&Apache::lonhtmlcommon::row_closure();
                   17093:         }
                   17094:     }
                   17095:     if ($instcodeform) {
                   17096:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17097:                   .$instcodeform
                   17098:                   .&Apache::lonhtmlcommon::row_closure();
                   17099:     }
                   17100:     if (exists($filter->{'ownerfilter'})) {
                   17101:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17102:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17103:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17104:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17105:                    $ownerdomselectform.'</td></tr></table>'.
                   17106:                    &Apache::lonhtmlcommon::row_closure();
                   17107:     }
                   17108:     if (exists($filter->{'personfilter'})) {
                   17109:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17110:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17111:                    '<input type="text" name="personfilter" size="20" value="'.
                   17112:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17113:                    $persondomselectform.'</td></tr></table>'.
                   17114:                    &Apache::lonhtmlcommon::row_closure();
                   17115:     }
                   17116:     if (exists($filter->{'coursefilter'})) {
                   17117:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17118:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17119:                   .$list->{'coursefilter'}.'" />'
                   17120:                   .&Apache::lonhtmlcommon::row_closure();
                   17121:     }
                   17122:     if ($cloneableonlyform) {
                   17123:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17124:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17125:     }
                   17126:     if (exists($filter->{'descriptfilter'})) {
                   17127:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17128:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17129:                   .$list->{'descriptfilter'}.'" />'
                   17130:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17131:     }
                   17132:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17133:                '<input type="hidden" name="updater" value="" />'."\n".
                   17134:                '<input type="submit" name="gosearch" value="'.
                   17135:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17136:     return $jscript.$clonewarning.$output;
                   17137: }
                   17138: 
                   17139: =pod 
                   17140: 
                   17141: =item * &timebased_select_form()
                   17142: 
1.1182    raeburn  17143: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17144: filter e.g., Course Activity, Course Created, when searching for courses
                   17145: or communities
                   17146: 
                   17147: Inputs:
                   17148: 
                   17149: item - name of form element (sincefilter or createdfilter)
                   17150: 
                   17151: filter - anonymous hash of criteria and their values
                   17152: 
                   17153: Returns: HTML for a select box contained a blank, then six time selections,
                   17154:          with value set in incoming form variables currently selected. 
                   17155: 
                   17156: Side Effects: None
                   17157: 
                   17158: =cut
                   17159: 
                   17160: sub timebased_select_form {
                   17161:     my ($item,$filter) = @_;
                   17162:     if (ref($filter) eq 'HASH') {
                   17163:         $filter->{$item} =~ s/[^\d-]//g;
                   17164:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17165:         return &select_form(
                   17166:                             $filter->{$item},
                   17167:                             $item,
                   17168:                             {      '-1' => '',
                   17169:                                 '86400' => &mt('today'),
                   17170:                                '604800' => &mt('last week'),
                   17171:                               '2592000' => &mt('last month'),
                   17172:                               '7776000' => &mt('last three months'),
                   17173:                              '15552000' => &mt('last six months'),
                   17174:                              '31104000' => &mt('last year'),
                   17175:                     'select_form_order' =>
                   17176:                            ['-1','86400','604800','2592000','7776000',
                   17177:                             '15552000','31104000']});
                   17178:     }
                   17179: }
                   17180: 
                   17181: =pod
                   17182: 
                   17183: =item * &js_changer()
                   17184: 
                   17185: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17186: when course type or domain is changed, and also to hide 'Searching ...' on
                   17187: page load completion for page showing search result.
1.1181    raeburn  17188: 
                   17189: Inputs: None
                   17190: 
1.1183    raeburn  17191: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17192: 
                   17193: Side Effects: None
                   17194: 
                   17195: =cut
                   17196: 
                   17197: sub js_changer {
                   17198:     return <<ENDJS;
                   17199: <script type="text/javascript">
                   17200: // <![CDATA[
                   17201: function updateFilters(caller) {
                   17202:     if (typeof(caller) != "undefined") {
                   17203:         document.filterpicker.updater.value = caller.name;
                   17204:     }
                   17205:     document.filterpicker.submit();
                   17206: }
1.1183    raeburn  17207: 
                   17208: function hideSearching() {
                   17209:     if (document.getElementById('searching')) {
                   17210:         document.getElementById('searching').style.display = 'none';
                   17211:     }
                   17212:     return;
                   17213: }
                   17214: 
1.1181    raeburn  17215: // ]]>
                   17216: </script>
                   17217: 
                   17218: ENDJS
                   17219: }
                   17220: 
                   17221: =pod
                   17222: 
1.1182    raeburn  17223: =item * &search_courses()
                   17224: 
                   17225: Process selected filters form course search form and pass to lonnet::courseiddump
                   17226: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17227: 
                   17228: Inputs:
                   17229: 
                   17230: dom - domain being searched 
                   17231: 
                   17232: type - course type ('Course' or 'Community' or '.' if any).
                   17233: 
                   17234: filter - anonymous hash of criteria and their values
                   17235: 
                   17236: numtitles - for institutional codes - number of categories
                   17237: 
                   17238: cloneruname - optional username of new course owner
                   17239: 
                   17240: clonerudom - optional domain of new course owner
                   17241: 
1.1221    raeburn  17242: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17243:             (used when DC is using course creation form)
                   17244: 
                   17245: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17246: 
1.1221    raeburn  17247: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17248:            (and so can clone automatically)
                   17249: 
                   17250: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17251: 
                   17252: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17253:               courses to clone 
1.1182    raeburn  17254: 
                   17255: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17256: 
                   17257: 
                   17258: Side Effects: None
                   17259: 
                   17260: =cut
                   17261: 
                   17262: 
                   17263: sub search_courses {
1.1221    raeburn  17264:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17265:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17266:     my (%courses,%showcourses,$cloner);
                   17267:     if (($filter->{'ownerfilter'} ne '') ||
                   17268:         ($filter->{'ownerdomfilter'} ne '')) {
                   17269:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17270:                                        $filter->{'ownerdomfilter'};
                   17271:     }
                   17272:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17273:         if (!$filter->{$item}) {
                   17274:             $filter->{$item}='.';
                   17275:         }
                   17276:     }
                   17277:     my $now = time;
                   17278:     my $timefilter =
                   17279:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17280:     my ($createdbefore,$createdafter);
                   17281:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17282:         $createdbefore = $now;
                   17283:         $createdafter = $now-$filter->{'createdfilter'};
                   17284:     }
                   17285:     my ($instcodefilter,$regexpok);
                   17286:     if ($numtitles) {
                   17287:         if ($env{'form.official'} eq 'on') {
                   17288:             $instcodefilter =
                   17289:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17290:             $regexpok = 1;
                   17291:         } elsif ($env{'form.official'} eq 'off') {
                   17292:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17293:             unless ($instcodefilter eq '') {
                   17294:                 $regexpok = -1;
                   17295:             }
                   17296:         }
                   17297:     } else {
                   17298:         $instcodefilter = $filter->{'instcodefilter'};
                   17299:     }
                   17300:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17301:     if ($type eq '') { $type = '.'; }
                   17302: 
                   17303:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17304:         $cloner = $cloneruname.':'.$clonerudom;
                   17305:     }
                   17306:     %courses = &Apache::lonnet::courseiddump($dom,
                   17307:                                              $filter->{'descriptfilter'},
                   17308:                                              $timefilter,
                   17309:                                              $instcodefilter,
                   17310:                                              $filter->{'combownerfilter'},
                   17311:                                              $filter->{'coursefilter'},
                   17312:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  17313:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  17314:                                              $filter->{'cloneableonly'},
                   17315:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  17316:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  17317:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17318:         my $ccrole;
                   17319:         if ($type eq 'Community') {
                   17320:             $ccrole = 'co';
                   17321:         } else {
                   17322:             $ccrole = 'cc';
                   17323:         }
                   17324:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17325:                                                      $filter->{'persondomfilter'},
                   17326:                                                      'userroles',undef,
                   17327:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17328:                                                      $dom);
                   17329:         foreach my $role (keys(%rolehash)) {
                   17330:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17331:             my $cid = $cdom.'_'.$cnum;
                   17332:             if (exists($courses{$cid})) {
                   17333:                 if (ref($courses{$cid}) eq 'HASH') {
                   17334:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17335:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  17336:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  17337:                         }
                   17338:                     } else {
                   17339:                         $courses{$cid}{roles} = [$courserole];
                   17340:                     }
                   17341:                     $showcourses{$cid} = $courses{$cid};
                   17342:                 }
                   17343:             }
                   17344:         }
                   17345:         %courses = %showcourses;
                   17346:     }
                   17347:     return %courses;
                   17348: }
                   17349: 
                   17350: =pod
                   17351: 
1.1181    raeburn  17352: =back
                   17353: 
1.1207    raeburn  17354: =head1 Routines for version requirements for current course.
                   17355: 
                   17356: =over 4
                   17357: 
                   17358: =item * &check_release_required()
                   17359: 
                   17360: Compares required LON-CAPA version with version on server, and
                   17361: if required version is newer looks for a server with the required version.
                   17362: 
                   17363: Looks first at servers in user's owen domain; if none suitable, looks at
                   17364: servers in course's domain are permitted to host sessions for user's domain.
                   17365: 
                   17366: Inputs:
                   17367: 
                   17368: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17369: 
                   17370: $courseid - Course ID of current course
                   17371: 
                   17372: $rolecode - User's current role in course (for switchserver query string).
                   17373: 
                   17374: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17375: 
                   17376: 
                   17377: Returns:
                   17378: 
                   17379: $switchserver - query string tp append to /adm/switchserver call (if 
                   17380:                 current server's LON-CAPA version is too old. 
                   17381: 
                   17382: $warning - Message is displayed if no suitable server could be found.
                   17383: 
                   17384: =cut
                   17385: 
                   17386: sub check_release_required {
                   17387:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17388:     my ($switchserver,$warning);
                   17389:     if ($required ne '') {
                   17390:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17391:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17392:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17393:             my $otherserver;
                   17394:             if (($major eq '' && $minor eq '') ||
                   17395:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17396:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17397:                 my $switchlcrev =
                   17398:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17399:                                                            $userdomserver);
                   17400:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17401:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17402:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17403:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17404:                     if ($cdom ne $env{'user.domain'}) {
                   17405:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17406:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17407:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17408:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17409:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17410:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17411:                         my $canhost =
                   17412:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17413:                                                               $coursedomserver,
                   17414:                                                               $remoterev,
                   17415:                                                               $udomdefaults{'remotesessions'},
                   17416:                                                               $defdomdefaults{'hostedsessions'});
                   17417: 
                   17418:                         if ($canhost) {
                   17419:                             $otherserver = $coursedomserver;
                   17420:                         } else {
                   17421:                             $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.");
                   17422:                         }
                   17423:                     } else {
                   17424:                         $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).");
                   17425:                     }
                   17426:                 } else {
                   17427:                     $otherserver = $userdomserver;
                   17428:                 }
                   17429:             }
                   17430:             if ($otherserver ne '') {
                   17431:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17432:             }
                   17433:         }
                   17434:     }
                   17435:     return ($switchserver,$warning);
                   17436: }
                   17437: 
                   17438: =pod
                   17439: 
                   17440: =item * &check_release_result()
                   17441: 
                   17442: Inputs:
                   17443: 
                   17444: $switchwarning - Warning message if no suitable server found to host session.
                   17445: 
                   17446: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17447:                 and current role.
                   17448: 
                   17449: Returns: HTML to display with information about requirement to switch server.
                   17450:          Either displaying warning with link to Roles/Courses screen or
                   17451:          display link to switchserver.
                   17452: 
1.1181    raeburn  17453: =cut
                   17454: 
1.1207    raeburn  17455: sub check_release_result {
                   17456:     my ($switchwarning,$switchserver) = @_;
                   17457:     my $output = &start_page('Selected course unavailable on this server').
                   17458:                  '<p class="LC_warning">';
                   17459:     if ($switchwarning) {
                   17460:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17461:         if (&show_course()) {
                   17462:             $output .= &mt('Display courses');
                   17463:         } else {
                   17464:             $output .= &mt('Display roles');
                   17465:         }
                   17466:         $output .= '</a>';
                   17467:     } elsif ($switchserver) {
                   17468:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17469:                    '<br />'.
                   17470:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17471:                    &mt('Switch Server').
                   17472:                    '</a>';
                   17473:     }
                   17474:     $output .= '</p>'.&end_page();
                   17475:     return $output;
                   17476: }
                   17477: 
                   17478: =pod
                   17479: 
                   17480: =item * &needs_coursereinit()
                   17481: 
                   17482: Determine if course contents stored for user's session needs to be
                   17483: refreshed, because content has changed since "Big Hash" last tied.
                   17484: 
                   17485: Check for change is made if time last checked is more than 10 minutes ago
                   17486: (by default).
                   17487: 
                   17488: Inputs:
                   17489: 
                   17490: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17491: 
                   17492: $interval (optional) - Time which may elapse (in s) between last check for content
                   17493:                        change in current course. (default: 600 s).  
                   17494: 
                   17495: Returns: an array; first element is:
                   17496: 
                   17497: =over 4
                   17498: 
                   17499: 'switch' - if content updates mean user's session
                   17500:            needs to be switched to a server running a newer LON-CAPA version
                   17501:  
                   17502: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17503:            on current server hosting user's session                
                   17504: 
                   17505: ''       - if no action required.
                   17506: 
                   17507: =back
                   17508: 
                   17509: If first item element is 'switch':
                   17510: 
                   17511: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17512: 
                   17513: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17514:                               and current role. 
                   17515: 
                   17516: otherwise: no other elements returned.
                   17517: 
                   17518: =back
                   17519: 
                   17520: =cut
                   17521: 
                   17522: sub needs_coursereinit {
                   17523:     my ($loncaparev,$interval) = @_;
                   17524:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17525:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17526:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17527:     my $now = time;
                   17528:     if ($interval eq '') {
                   17529:         $interval = 600;
                   17530:     }
                   17531:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17532:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17533:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17534:         if ($blocked) {
                   17535:             return ();
                   17536:         }
1.1207    raeburn  17537:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17538:         if ($lastchange > $env{'request.course.tied'}) {
                   17539:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17540:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17541:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17542:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17543:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17544:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17545:                     my ($switchserver,$switchwarning) =
                   17546:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17547:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17548:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17549:                         return ('switch',$switchwarning,$switchserver);
                   17550:                     }
                   17551:                 }
                   17552:             }
                   17553:             return ('update');
                   17554:         }
                   17555:     }
                   17556:     return ();
                   17557: }
1.1181    raeburn  17558: 
1.1083    raeburn  17559: sub update_content_constraints {
1.1326    raeburn  17560:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  17561:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17562:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  17563:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  17564:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17565:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17566:         if ($item eq 'resourcetag') {
                   17567:             if ($name eq 'responsetype') {
                   17568:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17569:             }
1.1307    raeburn  17570:         } elsif ($item eq 'course') {
                   17571:             if ($name eq 'courserestype') {
                   17572:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   17573:             }
1.1083    raeburn  17574:         }
                   17575:     }
                   17576:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17577:     if (defined($navmap)) {
1.1307    raeburn  17578:         my (%allresponses,%allcrsrestypes);
                   17579:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   17580:             if ($res->is_tool()) {
                   17581:                 if ($allcrsrestypes{'exttool'}) {
                   17582:                     $allcrsrestypes{'exttool'} ++;
                   17583:                 } else {
                   17584:                     $allcrsrestypes{'exttool'} = 1;
                   17585:                 }
                   17586:                 next;
                   17587:             }
1.1083    raeburn  17588:             my %responses = $res->responseTypes();
                   17589:             foreach my $key (keys(%responses)) {
                   17590:                 next unless(exists($checkresponsetypes{$key}));
                   17591:                 $allresponses{$key} += $responses{$key};
                   17592:             }
                   17593:         }
                   17594:         foreach my $key (keys(%allresponses)) {
                   17595:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17596:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17597:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17598:             }
                   17599:         }
1.1307    raeburn  17600:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  17601:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  17602:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17603:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17604:             }
                   17605:         }
1.1083    raeburn  17606:         undef($navmap);
                   17607:     }
1.1326    raeburn  17608:     my (@resources,@order,@resparms,@zombies);
                   17609:     if ($keeporder) {
                   17610:         use LONCAPA::map;
                   17611:         @resources = @LONCAPA::map::resources;
                   17612:         @order = @LONCAPA::map::order;
                   17613:         @resparms = @LONCAPA::map::resparms;
                   17614:         @zombies = @LONCAPA::map::zombies;
                   17615:     }
1.1308    raeburn  17616:     my $suppmap = 'supplemental.sequence';
                   17617:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   17618:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   17619:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  17620:     if ($keeporder) {
                   17621:         @LONCAPA::map::resources = @resources;
                   17622:         @LONCAPA::map::order = @order;
                   17623:         @LONCAPA::map::resparms = @resparms;
                   17624:         @LONCAPA::map::zombies = @zombies;
                   17625:     }
1.1308    raeburn  17626:     if ($supptools) {
                   17627:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   17628:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17629:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   17630:         }
                   17631:     }
1.1083    raeburn  17632:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17633:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17634:     }
                   17635:     return;
                   17636: }
                   17637: 
1.1110    raeburn  17638: sub allmaps_incourse {
                   17639:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17640:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17641:         $cid = $env{'request.course.id'};
                   17642:         $cdom = $env{'course.'.$cid.'.domain'};
                   17643:         $cnum = $env{'course.'.$cid.'.num'};
                   17644:         $chome = $env{'course.'.$cid.'.home'};
                   17645:     }
                   17646:     my %allmaps = ();
                   17647:     my $lastchange =
                   17648:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17649:     if ($lastchange > $env{'request.course.tied'}) {
                   17650:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17651:         unless ($ferr) {
1.1326    raeburn  17652:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  17653:         }
                   17654:     }
                   17655:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17656:     if (defined($navmap)) {
                   17657:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17658:             $allmaps{$res->src()} = 1;
                   17659:         }
                   17660:     }
                   17661:     return \%allmaps;
                   17662: }
                   17663: 
1.1083    raeburn  17664: sub parse_supplemental_title {
                   17665:     my ($title) = @_;
                   17666: 
                   17667:     my ($foldertitle,$renametitle);
                   17668:     if ($title =~ /&amp;&amp;&amp;/) {
                   17669:         $title = &HTML::Entites::decode($title);
                   17670:     }
                   17671:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17672:         $renametitle=$4;
                   17673:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17674:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17675:         my $name =  &plainname($uname,$udom);
                   17676:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17677:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17678:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17679:             $name.': <br />'.$foldertitle;
                   17680:     }
                   17681:     if (wantarray) {
                   17682:         return ($title,$foldertitle,$renametitle);
                   17683:     }
                   17684:     return $title;
                   17685: }
                   17686: 
1.1143    raeburn  17687: sub recurse_supplemental {
1.1308    raeburn  17688:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  17689:     if ($suppmap) {
                   17690:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17691:         if ($fatal) {
                   17692:             $errors ++;
                   17693:         } else {
                   17694:             if ($#LONCAPA::map::resources > 0) {
                   17695:                 foreach my $res (@LONCAPA::map::resources) {
                   17696:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17697:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17698:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  17699:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   17700:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  17701:                         } else {
1.1308    raeburn  17702:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   17703:                                 $numexttools ++;
                   17704:                             }
1.1143    raeburn  17705:                             $numfiles ++;
                   17706:                         }
                   17707:                     }
                   17708:                 }
                   17709:             }
                   17710:         }
                   17711:     }
1.1308    raeburn  17712:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  17713: }
                   17714: 
1.1101    raeburn  17715: sub symb_to_docspath {
1.1267    raeburn  17716:     my ($symb,$navmapref) = @_;
                   17717:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17718:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17719:     if ($resurl=~/\.(sequence|page)$/) {
                   17720:         $mapurl=$resurl;
                   17721:     } elsif ($resurl eq 'adm/navmaps') {
                   17722:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17723:     }
                   17724:     my $mapresobj;
1.1267    raeburn  17725:     unless (ref($$navmapref)) {
                   17726:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17727:     }
                   17728:     if (ref($$navmapref)) {
                   17729:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17730:     }
                   17731:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17732:     my $type=$2;
                   17733:     my $path;
                   17734:     if (ref($mapresobj)) {
                   17735:         my $pcslist = $mapresobj->map_hierarchy();
                   17736:         if ($pcslist ne '') {
                   17737:             foreach my $pc (split(/,/,$pcslist)) {
                   17738:                 next if ($pc <= 1);
1.1267    raeburn  17739:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17740:                 if (ref($res)) {
                   17741:                     my $thisurl = $res->src();
                   17742:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17743:                     my $thistitle = $res->title();
                   17744:                     $path .= '&'.
                   17745:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17746:                              &escape($thistitle).
1.1101    raeburn  17747:                              ':'.$res->randompick().
                   17748:                              ':'.$res->randomout().
                   17749:                              ':'.$res->encrypted().
                   17750:                              ':'.$res->randomorder().
                   17751:                              ':'.$res->is_page();
                   17752:                 }
                   17753:             }
                   17754:         }
                   17755:         $path =~ s/^\&//;
                   17756:         my $maptitle = $mapresobj->title();
                   17757:         if ($mapurl eq 'default') {
1.1129    raeburn  17758:             $maptitle = 'Main Content';
1.1101    raeburn  17759:         }
                   17760:         $path .= (($path ne '')? '&' : '').
                   17761:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17762:                  &escape($maptitle).
1.1101    raeburn  17763:                  ':'.$mapresobj->randompick().
                   17764:                  ':'.$mapresobj->randomout().
                   17765:                  ':'.$mapresobj->encrypted().
                   17766:                  ':'.$mapresobj->randomorder().
                   17767:                  ':'.$mapresobj->is_page();
                   17768:     } else {
                   17769:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17770:         my $ispage = (($type eq 'page')? 1 : '');
                   17771:         if ($mapurl eq 'default') {
1.1129    raeburn  17772:             $maptitle = 'Main Content';
1.1101    raeburn  17773:         }
                   17774:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17775:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17776:     }
                   17777:     unless ($mapurl eq 'default') {
                   17778:         $path = 'default&'.
1.1146    raeburn  17779:                 &escape('Main Content').
1.1101    raeburn  17780:                 ':::::&'.$path;
                   17781:     }
                   17782:     return $path;
                   17783: }
                   17784: 
1.1094    raeburn  17785: sub captcha_display {
1.1327    raeburn  17786:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  17787:     my ($output,$error);
1.1234    raeburn  17788:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  17789:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  17790:     if ($captcha eq 'original') {
1.1094    raeburn  17791:         $output = &create_captcha();
                   17792:         unless ($output) {
1.1172    raeburn  17793:             $error = 'captcha';
1.1094    raeburn  17794:         }
                   17795:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17796:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17797:         unless ($output) {
1.1172    raeburn  17798:             $error = 'recaptcha';
1.1094    raeburn  17799:         }
                   17800:     }
1.1234    raeburn  17801:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17802: }
                   17803: 
                   17804: sub captcha_response {
1.1327    raeburn  17805:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  17806:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  17807:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  17808:     if ($captcha eq 'original') {
1.1094    raeburn  17809:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17810:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17811:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17812:     } else {
                   17813:         $captcha_chk = 1;
                   17814:     }
                   17815:     return ($captcha_chk,$captcha_error);
                   17816: }
                   17817: 
                   17818: sub get_captcha_config {
1.1327    raeburn  17819:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  17820:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17821:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17822:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17823:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17824:     if ($context eq 'usercreation') {
                   17825:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17826:         if (ref($domconfig{$context}) eq 'HASH') {
                   17827:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17828:             if (ref($hashtocheck) eq 'HASH') {
                   17829:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17830:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17831:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17832:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17833:                     }
                   17834:                     if ($privkey && $pubkey) {
                   17835:                         $captcha = 'recaptcha';
1.1234    raeburn  17836:                         $version = $hashtocheck->{'recaptchaversion'};
                   17837:                         if ($version ne '2') {
                   17838:                             $version = 1;
                   17839:                         }
1.1095    raeburn  17840:                     } else {
                   17841:                         $captcha = 'original';
                   17842:                     }
                   17843:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17844:                     $captcha = 'original';
                   17845:                 }
1.1094    raeburn  17846:             }
1.1095    raeburn  17847:         } else {
                   17848:             $captcha = 'captcha';
                   17849:         }
                   17850:     } elsif ($context eq 'login') {
                   17851:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17852:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17853:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17854:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17855:             if ($privkey && $pubkey) {
                   17856:                 $captcha = 'recaptcha';
1.1234    raeburn  17857:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17858:                 if ($version ne '2') {
                   17859:                     $version = 1; 
                   17860:                 }
1.1095    raeburn  17861:             } else {
                   17862:                 $captcha = 'original';
1.1094    raeburn  17863:             }
1.1095    raeburn  17864:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17865:             $captcha = 'original';
1.1094    raeburn  17866:         }
1.1327    raeburn  17867:     } elsif ($context eq 'passwords') {
                   17868:         if ($dom_in_effect) {
                   17869:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   17870:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   17871:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   17872:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   17873:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   17874:                 }
                   17875:                 if ($privkey && $pubkey) {
                   17876:                     $captcha = 'recaptcha';
                   17877:                     $version = $passwdconf{'recaptchaversion'};
                   17878:                     if ($version ne '2') {
                   17879:                         $version = 1;
                   17880:                     }
                   17881:                 } else {
                   17882:                     $captcha = 'original';
                   17883:                 }
                   17884:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   17885:                 $captcha = 'original';
                   17886:             }
                   17887:         }
                   17888:     } 
1.1234    raeburn  17889:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17890: }
                   17891: 
                   17892: sub create_captcha {
                   17893:     my %captcha_params = &captcha_settings();
                   17894:     my ($output,$maxtries,$tries) = ('',10,0);
                   17895:     while ($tries < $maxtries) {
                   17896:         $tries ++;
                   17897:         my $captcha = Authen::Captcha->new (
                   17898:                                            output_folder => $captcha_params{'output_dir'},
                   17899:                                            data_folder   => $captcha_params{'db_dir'},
                   17900:                                           );
                   17901:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17902: 
                   17903:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17904:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17905:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17906:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17907:                       '<br />'.
                   17908:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17909:             last;
                   17910:         }
                   17911:     }
1.1323    raeburn  17912:     if ($output eq '') {
                   17913:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   17914:     }
1.1094    raeburn  17915:     return $output;
                   17916: }
                   17917: 
                   17918: sub captcha_settings {
                   17919:     my %captcha_params = (
                   17920:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17921:                            www_output_dir => "/captchaspool",
                   17922:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17923:                            numchars       => '5',
                   17924:                          );
                   17925:     return %captcha_params;
                   17926: }
                   17927: 
                   17928: sub check_captcha {
                   17929:     my ($captcha_chk,$captcha_error);
                   17930:     my $code = $env{'form.code'};
                   17931:     my $md5sum = $env{'form.crypt'};
                   17932:     my %captcha_params = &captcha_settings();
                   17933:     my $captcha = Authen::Captcha->new(
                   17934:                       output_folder => $captcha_params{'output_dir'},
                   17935:                       data_folder   => $captcha_params{'db_dir'},
                   17936:                   );
1.1109    raeburn  17937:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17938:     my %captcha_hash = (
                   17939:                         0       => 'Code not checked (file error)',
                   17940:                        -1      => 'Failed: code expired',
                   17941:                        -2      => 'Failed: invalid code (not in database)',
                   17942:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17943:     );
                   17944:     if ($captcha_chk != 1) {
                   17945:         $captcha_error = $captcha_hash{$captcha_chk}
                   17946:     }
                   17947:     return ($captcha_chk,$captcha_error);
                   17948: }
                   17949: 
                   17950: sub create_recaptcha {
1.1234    raeburn  17951:     my ($pubkey,$version) = @_;
                   17952:     if ($version >= 2) {
                   17953:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17954:     } else {
                   17955:         my $use_ssl;
                   17956:         if ($ENV{'SERVER_PORT'} == 443) {
                   17957:             $use_ssl = 1;
                   17958:         }
                   17959:         my $captcha = Captcha::reCAPTCHA->new;
                   17960:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17961:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17962:                &mt('If the text is hard to read, [_1] will replace them.',
                   17963:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17964:                '<br /><br />';
                   17965:     }
1.1094    raeburn  17966: }
                   17967: 
                   17968: sub check_recaptcha {
1.1234    raeburn  17969:     my ($privkey,$version) = @_;
1.1094    raeburn  17970:     my $captcha_chk;
1.1234    raeburn  17971:     if ($version >= 2) {
                   17972:         my %info = (
                   17973:                      secret   => $privkey, 
                   17974:                      response => $env{'form.g-recaptcha-response'},
                   17975:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17976:                    );
1.1280    raeburn  17977:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   17978:         $request->content(join('&',map {
                   17979:                          my $name = escape($_);
                   17980:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   17981:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   17982:                          : &escape($info{$_}) );
                   17983:         } keys(%info)));
                   17984:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  17985:         if ($response->is_success)  {
                   17986:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17987:             if (ref($data) eq 'HASH') {
                   17988:                 if ($data->{'success'}) {
                   17989:                     $captcha_chk = 1;
                   17990:                 }
                   17991:             }
                   17992:         }
                   17993:     } else {
                   17994:         my $captcha = Captcha::reCAPTCHA->new;
                   17995:         my $captcha_result =
                   17996:             $captcha->check_answer(
                   17997:                                     $privkey,
                   17998:                                     $ENV{'REMOTE_ADDR'},
                   17999:                                     $env{'form.recaptcha_challenge_field'},
                   18000:                                     $env{'form.recaptcha_response_field'},
                   18001:                                   );
                   18002:         if ($captcha_result->{is_valid}) {
                   18003:             $captcha_chk = 1;
                   18004:         }
1.1094    raeburn  18005:     }
                   18006:     return $captcha_chk;
                   18007: }
                   18008: 
1.1174    raeburn  18009: sub emailusername_info {
1.1244    raeburn  18010:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18011:     my %titles = &Apache::lonlocal::texthash (
                   18012:                      lastname      => 'Last Name',
                   18013:                      firstname     => 'First Name',
                   18014:                      institution   => 'School/college/university',
                   18015:                      location      => "School's city, state/province, country",
                   18016:                      web           => "School's web address",
                   18017:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18018:                      id            => 'Student/Employee ID',
1.1174    raeburn  18019:                  );
                   18020:     return (\@fields,\%titles);
                   18021: }
                   18022: 
1.1161    raeburn  18023: sub cleanup_html {
                   18024:     my ($incoming) = @_;
                   18025:     my $outgoing;
                   18026:     if ($incoming ne '') {
                   18027:         $outgoing = $incoming;
                   18028:         $outgoing =~ s/;/&#059;/g;
                   18029:         $outgoing =~ s/\#/&#035;/g;
                   18030:         $outgoing =~ s/\&/&#038;/g;
                   18031:         $outgoing =~ s/</&#060;/g;
                   18032:         $outgoing =~ s/>/&#062;/g;
                   18033:         $outgoing =~ s/\(/&#040/g;
                   18034:         $outgoing =~ s/\)/&#041;/g;
                   18035:         $outgoing =~ s/"/&#034;/g;
                   18036:         $outgoing =~ s/'/&#039;/g;
                   18037:         $outgoing =~ s/\$/&#036;/g;
                   18038:         $outgoing =~ s{/}{&#047;}g;
                   18039:         $outgoing =~ s/=/&#061;/g;
                   18040:         $outgoing =~ s/\\/&#092;/g
                   18041:     }
                   18042:     return $outgoing;
                   18043: }
                   18044: 
1.1190    musolffc 18045: # Checks for critical messages and returns a redirect url if one exists.
                   18046: # $interval indicates how often to check for messages.
1.1282    raeburn  18047: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18048: sub critical_redirect {
1.1282    raeburn  18049:     my ($interval,$context) = @_;
1.1190    musolffc 18050:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18051:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18052:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18053:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18054:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   18055:             if ($blocked) {
                   18056:                 my $checkrole = "cm./$cdom/$cnum";
                   18057:                 if ($env{'request.course.sec'} ne '') {
                   18058:                     $checkrole .= "/$env{'request.course.sec'}";
                   18059:                 }
                   18060:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18061:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18062:                     return;
                   18063:                 }
                   18064:             }
                   18065:         }
1.1190    musolffc 18066:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18067:                                         $env{'user.name'});
                   18068:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18069:         my $redirecturl;
1.1190    musolffc 18070:         if ($what[0]) {
                   18071: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   18072: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18073: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18074:                 return (1, $url);
1.1190    musolffc 18075:             }
1.1191    raeburn  18076:         }
                   18077:     } 
                   18078:     return ();
1.1190    musolffc 18079: }
                   18080: 
1.1174    raeburn  18081: # Use:
                   18082: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18083: #
                   18084: ##################################################
                   18085: #          password associated functions         #
                   18086: ##################################################
                   18087: sub des_keys {
                   18088:     # Make a new key for DES encryption.
                   18089:     # Each key has two parts which are returned separately.
                   18090:     # Please note:  Each key must be passed through the &hex function
                   18091:     # before it is output to the web browser.  The hex versions cannot
                   18092:     # be used to decrypt.
                   18093:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18094:                 '8','9','a','b','c','d','e','f');
                   18095:     my $lkey='';
                   18096:     for (0..7) {
                   18097:         $lkey.=$hexstr[rand(15)];
                   18098:     }
                   18099:     my $ukey='';
                   18100:     for (0..7) {
                   18101:         $ukey.=$hexstr[rand(15)];
                   18102:     }
                   18103:     return ($lkey,$ukey);
                   18104: }
                   18105: 
                   18106: sub des_decrypt {
                   18107:     my ($key,$cyphertext) = @_;
                   18108:     my $keybin=pack("H16",$key);
                   18109:     my $cypher;
                   18110:     if ($Crypt::DES::VERSION>=2.03) {
                   18111:         $cypher=new Crypt::DES $keybin;
                   18112:     } else {
                   18113:         $cypher=new DES $keybin;
                   18114:     }
1.1233    raeburn  18115:     my $plaintext='';
                   18116:     my $cypherlength = length($cyphertext);
                   18117:     my $numchunks = int($cypherlength/32);
                   18118:     for (my $j=0; $j<$numchunks; $j++) {
                   18119:         my $start = $j*32;
                   18120:         my $cypherblock = substr($cyphertext,$start,32);
                   18121:         my $chunk =
                   18122:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18123:         $chunk .=
                   18124:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18125:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18126:         $plaintext .= $chunk;
                   18127:     }
1.1174    raeburn  18128:     return $plaintext;
                   18129: }
                   18130: 
1.1309    raeburn  18131: sub make_short_symbs {
                   18132:     my ($cdom,$cnum,$navmap) = @_;
                   18133:     return unless (ref($navmap));
                   18134:     my ($numnew,@errors);
                   18135:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18136:     if (@toshorten) {
                   18137:         my (%maps,%resources,%titles);
                   18138:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18139:                                                                'shorturls',$cdom,$cnum);
                   18140:         my %tocreate;
                   18141:         if (keys(%resources)) {
                   18142:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18143:                 my $symb = $resources{$item};
                   18144:                 if ($symb) {
                   18145:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18146:                 }
                   18147:             }
                   18148:         }
                   18149:         if (keys(%tocreate)) {
                   18150:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18151:             my $su = Short::URL->new(no_vowels => 1);
                   18152:             my $init = '';
                   18153:             my (%newunique,%addcourse,%courseonly,%failed);
                   18154:             # get lock on tiny db
                   18155:             my $now = time;
                   18156:             my $lockhash = {
                   18157:                                 "lock\0$now" => $env{'user.name'}.
                   18158:                                                 ':'.$env{'user.domain'},
                   18159:                             };
                   18160:             my $tries = 0;
                   18161:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18162:             my ($code,$error);
                   18163:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18164:                 $tries ++;
                   18165:                 sleep 1;
1.1319    raeburn  18166:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18167:             }
                   18168:             if ($gotlock eq 'ok') {
                   18169:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18170:                                        \%addcourse,\%courseonly,\%failed);
                   18171:                 if (keys(%failed)) {
                   18172:                     my $numfailed = scalar(keys(%failed));
                   18173:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18174:                 }
                   18175:                 if (keys(%newunique)) {
                   18176:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18177:                     if ($putres eq 'ok') {
                   18178:                         $numnew = scalar(keys(%newunique));
                   18179:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18180:                         unless ($newputres eq 'ok') {
                   18181:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18182:                         }
                   18183:                     } else {
                   18184:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18185:                     }
                   18186:                 }
                   18187:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18188:                 unless ($dellockres eq 'ok') {
                   18189:                     push(@errors,&mt('error: could not release lockfile'));
                   18190:                 }
                   18191:             } else {
                   18192:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18193:             }
                   18194:             if (keys(%courseonly)) {
                   18195:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18196:                 if ($result ne 'ok') {
                   18197:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18198:                 }
                   18199:             }
                   18200:         }
                   18201:     }
                   18202:     return ($numnew,\@errors);
                   18203: }
                   18204: 
                   18205: sub shorten_symbs {
                   18206:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18207:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18208:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18209:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18210:     my (%possibles,%collisions);
                   18211:     foreach my $key (keys(%{$tocreate})) {
                   18212:         my $num = String::CRC32::crc32($key);
                   18213:         my $tiny = $su->encode($num,$init);
                   18214:         if ($tiny) {
                   18215:             $possibles{$tiny} = $key;
                   18216:         }
                   18217:     }
                   18218:     if (!$init) {
                   18219:         $init = 1;
                   18220:     } else {
                   18221:         $init ++;
                   18222:     }
                   18223:     if (keys(%possibles)) {
                   18224:         my @posstiny = keys(%possibles);
                   18225:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18226:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18227:         if (keys(%currtiny)) {
                   18228:             foreach my $key (keys(%currtiny)) {
                   18229:                 next if ($currtiny{$key} eq '');
                   18230:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18231:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18232:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18233:                         $courseonly->{$tsymb} = $key;
                   18234:                     }
                   18235:                 } else {
                   18236:                     $collisions{$possibles{$key}} = 1;
                   18237:                 }
                   18238:                 delete($possibles{$key});
                   18239:             }
                   18240:         }
                   18241:         foreach my $key (keys(%possibles)) {
                   18242:             $newunique->{$key} = $possibles{$key};
                   18243:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18244:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18245:                 $addcourse->{$tsymb} = $key;
                   18246:             }
                   18247:         }
                   18248:     }
                   18249:     if (keys(%collisions)) {
                   18250:         if ($init <5) {
                   18251:             if (!$init) {
                   18252:                 $init = 1;
                   18253:             } else {
                   18254:                 $init ++;
                   18255:             }
                   18256:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18257:                                    $newunique,$addcourse,$courseonly,$failed);
                   18258:         } else {
                   18259:             foreach my $key (keys(%collisions)) {
                   18260:                 $failed->{$key} = 1;
                   18261:             }
                   18262:         }
                   18263:     }
                   18264:     return $init;
                   18265: }
                   18266: 
1.1328    raeburn  18267: sub is_nonframeable {
1.1329    raeburn  18268:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18269:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18270:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18271: 
                   18272:     $remprotocol = lc($remprotocol);
                   18273:     $remhost = lc($remhost);
                   18274:     my $remport = 80;
                   18275:     if ($remprotocol eq 'https') {
                   18276:         $remport = 443;
                   18277:     }
1.1330    raeburn  18278:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18279:     if ($cached) {
                   18280:         unless ($nocache) {
                   18281:             if ($result) {
                   18282:                 return 1;
                   18283:             } else {
                   18284:                 return 0;
                   18285:             }
                   18286:         }
                   18287:     }
1.1328    raeburn  18288:     my $uselink;
                   18289:     my $request = new HTTP::Request('HEAD',$url);
                   18290:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   18291:     if ($response->is_success()) {
                   18292:         my $secpolicy = lc($response->header('content-security-policy'));
                   18293:         my $xframeop = lc($response->header('x-frame-options'));
                   18294:         $secpolicy =~ s/^\s+|\s+$//g;
                   18295:         $xframeop =~ s/^\s+|\s+$//g;
                   18296:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  18297:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  18298:             my ($origin,$protocol,$port);
                   18299:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18300:                 $port = $ENV{'SERVER_PORT'};
                   18301:             } else {
                   18302:                 $port = 80;
                   18303:             }
                   18304:             if ($absolute eq '') {
                   18305:                 $protocol = 'http:';
                   18306:                 if ($port == 443) {
                   18307:                     $protocol = 'https:';
                   18308:                 }
                   18309:                 $origin = $protocol.'//'.lc($hostname);
                   18310:             } else {
                   18311:                 $origin = lc($absolute);
                   18312:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18313:             }
                   18314:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18315:                 my $framepolicy = $1;
                   18316:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18317:                 my @policies = split(/\s+/,$framepolicy);
                   18318:                 if (@policies) {
                   18319:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18320:                         $uselink = 1;
                   18321:                     } else {
                   18322:                         $uselink = 1;
                   18323:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18324:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18325:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18326:                             undef($uselink);
                   18327:                         }
                   18328:                         if ($uselink) {
                   18329:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18330:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18331:                                     undef($uselink);
                   18332:                                 }
                   18333:                             }
                   18334:                         }
                   18335:                         if ($uselink) {
                   18336:                             my @possok;
                   18337:                             if ($ip ne '') {
                   18338:                                 push(@possok,$ip);
                   18339:                             }
                   18340:                             my $hoststr = '';
                   18341:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18342:                                 if ($hoststr eq '') {
                   18343:                                     $hoststr = $part;
                   18344:                                 } else {
                   18345:                                     $hoststr = "$part.$hoststr";
                   18346:                                 }
                   18347:                                 if ($hoststr eq $hostname) {
                   18348:                                     push(@possok,$hostname);
                   18349:                                 } else {
                   18350:                                     push(@possok,"*.$hoststr");
                   18351:                                 }
                   18352:                             }
                   18353:                             if (@possok) {
                   18354:                                 foreach my $poss (@possok) {
                   18355:                                     last if (!$uselink);
                   18356:                                     foreach my $policy (@policies) {
                   18357:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18358:                                             undef($uselink);
                   18359:                                             last;
                   18360:                                         }
                   18361:                                     }
                   18362:                                 }
                   18363:                             }
                   18364:                         }
                   18365:                     }
                   18366:                 }
                   18367:             } elsif ($xframeop ne '') {
                   18368:                 $uselink = 1;
                   18369:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18370:                 if (@policies) {
                   18371:                     unless (grep(/^deny$/,@policies)) {
                   18372:                         if ($origin ne '') {
                   18373:                             if (grep(/^sameorigin$/,@policies)) {
                   18374:                                 if ($remotehost eq $origin) {
                   18375:                                     undef($uselink);
                   18376:                                 }
                   18377:                             }
                   18378:                             if ($uselink) {
                   18379:                                 foreach my $policy (@policies) {
                   18380:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18381:                                         my $allowfrom = $1;
                   18382:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18383:                                             undef($uselink);
                   18384:                                             last;
                   18385:                                         }
                   18386:                                     }
                   18387:                                 }
                   18388:                             }
                   18389:                         }
                   18390:                     }
                   18391:                 }
                   18392:             }
                   18393:         }
                   18394:     }
1.1329    raeburn  18395:     if ($nocache) {
                   18396:         if ($cached) {
                   18397:             my $devalidate;
                   18398:             if ($uselink && !$result) {
                   18399:                 $devalidate = 1;
                   18400:             } elsif (!$uselink && $result) {
                   18401:                 $devalidate = 1;
                   18402:             }
                   18403:             if ($devalidate) {
                   18404:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18405:             }
                   18406:         }
                   18407:     } else {
                   18408:         if ($uselink) {
                   18409:             $result = 1;
                   18410:         } else {
                   18411:             $result = 0;
                   18412:         }
                   18413:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18414:     }
1.1328    raeburn  18415:     return $uselink;
                   18416: }
                   18417: 
1.112     bowersj2 18418: 1;
                   18419: __END__;
1.41      ng       18420: 

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