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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1287  ! raeburn     4: # $Id: loncommon.pm,v 1.1286 2017/08/03 16:22:09 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.657     raeburn    75: use DateTime::TimeZone;
1.1241    raeburn    76: use DateTime::Locale;
1.1220    raeburn    77: use Encode();
1.1091    foxr       78: use Text::Aspell;
1.1094    raeburn    79: use Authen::Captcha;
                     80: use Captcha::reCAPTCHA;
1.1234    raeburn    81: use JSON::DWIW;
                     82: use LWP::UserAgent;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.117     www        87: 
1.517     raeburn    88: # ---------------------------------------------- Designs
                     89: use vars qw(%defaultdesign);
                     90: 
1.22      www        91: my $readit;
                     92: 
1.517     raeburn    93: 
1.157     matthew    94: ##
                     95: ## Global Variables
                     96: ##
1.46      matthew    97: 
1.643     foxr       98: 
                     99: # ----------------------------------------------- SSI with retries:
                    100: #
                    101: 
                    102: =pod
                    103: 
1.648     raeburn   104: =head1 Server Side include with retries:
1.643     foxr      105: 
                    106: =over 4
                    107: 
1.648     raeburn   108: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      109: 
                    110: Performs an ssi with some number of retries.  Retries continue either
                    111: until the result is ok or until the retry count supplied by the
                    112: caller is exhausted.  
                    113: 
                    114: Inputs:
1.648     raeburn   115: 
                    116: =over 4
                    117: 
1.643     foxr      118: resource   - Identifies the resource to insert.
1.648     raeburn   119: 
1.643     foxr      120: retries    - Count of the number of retries allowed.
1.648     raeburn   121: 
1.643     foxr      122: form       - Hash that identifies the rendering options.
                    123: 
1.648     raeburn   124: =back
                    125: 
                    126: Returns:
                    127: 
                    128: =over 4
                    129: 
1.643     foxr      130: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   131: 
1.643     foxr      132: response   - The response from the last attempt (which may or may not have been successful.
                    133: 
1.648     raeburn   134: =back
                    135: 
                    136: =back
                    137: 
1.643     foxr      138: =cut
                    139: 
                    140: sub ssi_with_retries {
                    141:     my ($resource, $retries, %form) = @_;
                    142: 
                    143: 
                    144:     my $ok = 0;			# True if we got a good response.
                    145:     my $content;
                    146:     my $response;
                    147: 
                    148:     # Try to get the ssi done. within the retries count:
                    149: 
                    150:     do {
                    151: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    152: 	$ok      = $response->is_success;
1.650     www       153:         if (!$ok) {
                    154:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    155:         }
1.643     foxr      156: 	$retries--;
                    157:     } while (!$ok && ($retries > 0));
                    158: 
                    159:     if (!$ok) {
                    160: 	$content = '';		# On error return an empty content.
                    161:     }
                    162:     return ($content, $response);
                    163: 
                    164: }
                    165: 
                    166: 
                    167: 
1.20      www       168: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  169: my %language;
1.124     www       170: my %supported_language;
1.1088    foxr      171: my %supported_codes;
1.1048    foxr      172: my %latex_language;		# For choosing hyphenation in <transl..>
                    173: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  174: my %cprtag;
1.192     taceyjo1  175: my %scprtag;
1.351     www       176: my %fe; my %fd; my %fm;
1.41      ng        177: my %category_extensions;
1.12      harris41  178: 
1.46      matthew   179: # ---------------------------------------------- Thesaurus variables
1.144     matthew   180: #
                    181: # %Keywords:
                    182: #      A hash used by &keyword to determine if a word is considered a keyword.
                    183: # $thesaurus_db_file 
                    184: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   185: 
                    186: my %Keywords;
                    187: my $thesaurus_db_file;
                    188: 
1.144     matthew   189: #
                    190: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    191: # thesaurus.tab, and filecategories.tab.
                    192: #
1.18      www       193: BEGIN {
1.46      matthew   194:     # Variable initialization
                    195:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    196:     #
1.22      www       197:     unless ($readit) {
1.12      harris41  198: # ------------------------------------------------------------------- languages
                    199:     {
1.158     raeburn   200:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    201:                                    '/language.tab';
                    202:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  203:             while (my $line = <$fh>) {
                    204:                 next if ($line=~/^\#/);
                    205:                 chomp($line);
1.1088    foxr      206:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   207:                 $language{$key}=$val.' - '.$enc;
                    208:                 if ($sup) {
                    209:                     $supported_language{$key}=$sup;
1.1088    foxr      210: 		    $supported_codes{$key}   = $code;
1.158     raeburn   211:                 }
1.1048    foxr      212: 		if ($latex) {
                    213: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      214: 		    $latex_language{$code} = $latex;
1.1048    foxr      215: 		}
1.158     raeburn   216:             }
                    217:             close($fh);
                    218:         }
1.12      harris41  219:     }
                    220: # ------------------------------------------------------------------ copyrights
                    221:     {
1.158     raeburn   222:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    223:                                   '/copyright.tab';
                    224:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  225:             while (my $line = <$fh>) {
                    226:                 next if ($line=~/^\#/);
                    227:                 chomp($line);
                    228:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   229:                 $cprtag{$key}=$val;
                    230:             }
                    231:             close($fh);
                    232:         }
1.12      harris41  233:     }
1.351     www       234: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  235:     {
                    236:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    237:                                   '/source_copyright.tab';
                    238:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  239:             while (my $line = <$fh>) {
                    240:                 next if ($line =~ /^\#/);
                    241:                 chomp($line);
                    242:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  243:                 $scprtag{$key}=$val;
                    244:             }
                    245:             close($fh);
                    246:         }
                    247:     }
1.63      www       248: 
1.517     raeburn   249: # -------------------------------------------------------------- default domain designs
1.63      www       250:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   251:     my $designfile = $designdir.'/default.tab';
                    252:     if ( open (my $fh,"<$designfile") ) {
                    253:         while (my $line = <$fh>) {
                    254:             next if ($line =~ /^\#/);
                    255:             chomp($line);
                    256:             my ($key,$val)=(split(/\=/,$line));
                    257:             if ($val) { $defaultdesign{$key}=$val; }
                    258:         }
                    259:         close($fh);
1.63      www       260:     }
                    261: 
1.15      harris41  262: # ------------------------------------------------------------- file categories
                    263:     {
1.158     raeburn   264:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    265:                                   '/filecategories.tab';
                    266:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  267: 	    while (my $line = <$fh>) {
                    268: 		next if ($line =~ /^\#/);
                    269: 		chomp($line);
                    270:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   271:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   272:             }
                    273:             close($fh);
                    274:         }
                    275: 
1.15      harris41  276:     }
1.12      harris41  277: # ------------------------------------------------------------------ file types
                    278:     {
1.158     raeburn   279:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    280:                '/filetypes.tab';
                    281:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  282:             while (my $line = <$fh>) {
                    283: 		next if ($line =~ /^\#/);
                    284: 		chomp($line);
                    285:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   286:                 if ($descr ne '') {
                    287:                     $fe{$ending}=lc($emb);
                    288:                     $fd{$ending}=$descr;
1.351     www       289:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   290:                 }
                    291:             }
                    292:             close($fh);
                    293:         }
1.12      harris41  294:     }
1.22      www       295:     &Apache::lonnet::logthis(
1.705     tempelho  296:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       297:     $readit=1;
1.46      matthew   298:     }  # end of unless($readit) 
1.32      matthew   299:     
                    300: }
1.112     bowersj2  301: 
1.42      matthew   302: ###############################################################
                    303: ##           HTML and Javascript Helper Functions            ##
                    304: ###############################################################
                    305: 
                    306: =pod 
                    307: 
1.112     bowersj2  308: =head1 HTML and Javascript Functions
1.42      matthew   309: 
1.112     bowersj2  310: =over 4
                    311: 
1.648     raeburn   312: =item * &browser_and_searcher_javascript()
1.112     bowersj2  313: 
                    314: X<browsing, javascript>X<searching, javascript>Returns a string
                    315: containing javascript with two functions, C<openbrowser> and
                    316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    317: tags.
1.42      matthew   318: 
1.648     raeburn   319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   320: 
                    321: inputs: formname, elementname, only, omit
                    322: 
                    323: formname and elementname indicate the name of the html form and name of
                    324: the element that the results of the browsing selection are to be placed in. 
                    325: 
                    326: Specifying 'only' will restrict the browser to displaying only files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
                    329: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       330: with the given extension.  Can be a comma separated list.
1.42      matthew   331: 
1.648     raeburn   332: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   333: 
                    334: Inputs: formname, elementname
                    335: 
                    336: formname and elementname specify the name of the html form and the name
                    337: of the element the selection from the search results will be placed in.
1.542     raeburn   338: 
1.42      matthew   339: =cut
                    340: 
                    341: sub browser_and_searcher_javascript {
1.199     albertel  342:     my ($mode)=@_;
                    343:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  344:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   345:     return <<END;
1.219     albertel  346: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   347:     var editbrowser = null;
1.135     albertel  348:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       349:         var url = '$resurl/?';
1.42      matthew   350:         if (editbrowser == null) {
                    351:             url += 'launch=1&';
                    352:         }
                    353:         url += 'catalogmode=interactive&';
1.199     albertel  354:         url += 'mode=$mode&';
1.611     albertel  355:         url += 'inhibitmenu=yes&';
1.42      matthew   356:         url += 'form=' + formname + '&';
                    357:         if (only != null) {
                    358:             url += 'only=' + only + '&';
1.217     albertel  359:         } else {
                    360:             url += 'only=&';
                    361: 	}
1.42      matthew   362:         if (omit != null) {
                    363:             url += 'omit=' + omit + '&';
1.217     albertel  364:         } else {
                    365:             url += 'omit=&';
                    366: 	}
1.135     albertel  367:         if (titleelement != null) {
                    368:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  369:         } else {
                    370: 	    url += 'titleelement=&';
                    371: 	}
1.42      matthew   372:         url += 'element=' + elementname + '';
                    373:         var title = 'Browser';
1.435     albertel  374:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   375:         options += ',width=700,height=600';
                    376:         editbrowser = open(url,title,options,'1');
                    377:         editbrowser.focus();
                    378:     }
                    379:     var editsearcher;
1.135     albertel  380:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   381:         var url = '/adm/searchcat?';
                    382:         if (editsearcher == null) {
                    383:             url += 'launch=1&';
                    384:         }
                    385:         url += 'catalogmode=interactive&';
1.199     albertel  386:         url += 'mode=$mode&';
1.42      matthew   387:         url += 'form=' + formname + '&';
1.135     albertel  388:         if (titleelement != null) {
                    389:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  390:         } else {
                    391: 	    url += 'titleelement=&';
                    392: 	}
1.42      matthew   393:         url += 'element=' + elementname + '';
                    394:         var title = 'Search';
1.435     albertel  395:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   396:         options += ',width=700,height=600';
                    397:         editsearcher = open(url,title,options,'1');
                    398:         editsearcher.focus();
                    399:     }
1.219     albertel  400: // END LON-CAPA Internal -->
1.42      matthew   401: END
1.170     www       402: }
                    403: 
                    404: sub lastresurl {
1.258     albertel  405:     if ($env{'environment.lastresurl'}) {
                    406: 	return $env{'environment.lastresurl'}
1.170     www       407:     } else {
                    408: 	return '/res';
                    409:     }
                    410: }
                    411: 
                    412: sub storeresurl {
                    413:     my $resurl=&Apache::lonnet::clutter(shift);
                    414:     unless ($resurl=~/^\/res/) { return 0; }
                    415:     $resurl=~s/\/$//;
                    416:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   417:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       418:     return 1;
1.42      matthew   419: }
                    420: 
1.74      www       421: sub studentbrowser_javascript {
1.111     www       422:    unless (
1.258     albertel  423:             (($env{'request.course.id'}) && 
1.302     albertel  424:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    425: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    426: 					  '/'.$env{'request.course.sec'})
                    427: 	      ))
1.258     albertel  428:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       429:           ) { return ''; }  
1.74      www       430:    return (<<'ENDSTDBRW');
1.776     bisitz    431: <script type="text/javascript" language="Javascript">
1.824     bisitz    432: // <![CDATA[
1.74      www       433:     var stdeditbrowser;
1.999     www       434:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       435:         var url = '/adm/pickstudent?';
                    436:         var filter;
1.558     albertel  437: 	if (!ignorefilter) {
                    438: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    439: 	}
1.74      www       440:         if (filter != null) {
                    441:            if (filter != '') {
                    442:                url += 'filter='+filter+'&';
                    443: 	   }
                    444:         }
                    445:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       446:                                     '&udomelement='+udom+
                    447:                                     '&clicker='+clicker;
1.111     www       448: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   449:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       450:         var title = 'Student_Browser';
1.74      www       451:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    452:         options += ',width=700,height=600';
                    453:         stdeditbrowser = open(url,title,options,'1');
                    454:         stdeditbrowser.focus();
                    455:     }
1.824     bisitz    456: // ]]>
1.74      www       457: </script>
                    458: ENDSTDBRW
                    459: }
1.42      matthew   460: 
1.1003    www       461: sub resourcebrowser_javascript {
                    462:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       463:    return (<<'ENDRESBRW');
1.1003    www       464: <script type="text/javascript" language="Javascript">
                    465: // <![CDATA[
                    466:     var reseditbrowser;
1.1004    www       467:     function openresbrowser(formname,reslink) {
1.1005    www       468:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       469:         var title = 'Resource_Browser';
                    470:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       471:         options += ',width=700,height=500';
1.1004    www       472:         reseditbrowser = open(url,title,options,'1');
                    473:         reseditbrowser.focus();
1.1003    www       474:     }
                    475: // ]]>
                    476: </script>
1.1004    www       477: ENDRESBRW
1.1003    www       478: }
                    479: 
1.74      www       480: sub selectstudent_link {
1.999     www       481:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    482:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    483:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    484:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  485:    if ($env{'request.course.id'}) {  
1.302     albertel  486:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    487: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    488: 					'/'.$env{'request.course.sec'})) {
1.111     www       489: 	   return '';
                    490:        }
1.999     www       491:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   492:        if ($courseadvonly)  {
                    493:            $callargs .= ",'',1,1";
                    494:        }
                    495:        return '<span class="LC_nobreak">'.
                    496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    497:               &mt('Select User').'</a></span>';
1.74      www       498:    }
1.258     albertel  499:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       500:        $callargs .= ",'',1"; 
1.793     raeburn   501:        return '<span class="LC_nobreak">'.
                    502:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    503:               &mt('Select User').'</a></span>';
1.111     www       504:    }
                    505:    return '';
1.91      www       506: }
                    507: 
1.1004    www       508: sub selectresource_link {
                    509:    my ($form,$reslink,$arg)=@_;
                    510:    
                    511:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    512:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    513:    unless ($env{'request.course.id'}) { return $arg; }
                    514:    return '<span class="LC_nobreak">'.
                    515:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    516:               $arg.'</a></span>';
                    517: }
                    518: 
                    519: 
                    520: 
1.653     raeburn   521: sub authorbrowser_javascript {
                    522:     return <<"ENDAUTHORBRW";
1.776     bisitz    523: <script type="text/javascript" language="JavaScript">
1.824     bisitz    524: // <![CDATA[
1.653     raeburn   525: var stdeditbrowser;
                    526: 
                    527: function openauthorbrowser(formname,udom) {
                    528:     var url = '/adm/pickauthor?';
                    529:     url += 'form='+formname+'&roledom='+udom;
                    530:     var title = 'Author_Browser';
                    531:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    532:     options += ',width=700,height=600';
                    533:     stdeditbrowser = open(url,title,options,'1');
                    534:     stdeditbrowser.focus();
                    535: }
                    536: 
1.824     bisitz    537: // ]]>
1.653     raeburn   538: </script>
                    539: ENDAUTHORBRW
                    540: }
                    541: 
1.91      www       542: sub coursebrowser_javascript {
1.1116    raeburn   543:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   544:         $credits_element,$instcode) = @_;
1.932     raeburn   545:     my $wintitle = 'Course_Browser';
1.931     raeburn   546:     if ($crstype eq 'Community') {
1.932     raeburn   547:         $wintitle = 'Community_Browser';
1.909     raeburn   548:     }
1.876     raeburn   549:     my $id_functions = &javascript_index_functions();
                    550:     my $output = '
1.776     bisitz    551: <script type="text/javascript" language="JavaScript">
1.824     bisitz    552: // <![CDATA[
1.468     raeburn   553:     var stdeditbrowser;'."\n";
1.876     raeburn   554: 
                    555:     $output .= <<"ENDSTDBRW";
1.909     raeburn   556:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       557:         var url = '/adm/pickcourse?';
1.895     raeburn   558:         var formid = getFormIdByName(formname);
1.876     raeburn   559:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  560:         if (domainfilter != null) {
                    561:            if (domainfilter != '') {
                    562:                url += 'domainfilter='+domainfilter+'&';
                    563: 	   }
                    564:         }
1.91      www       565:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  566: 	                            '&cdomelement='+udom+
                    567:                                     '&cnameelement='+desc;
1.468     raeburn   568:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   569:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   570:                 url += '&roleelement='+extra_element;
                    571:                 if (domainfilter == null || domainfilter == '') {
                    572:                     url += '&domainfilter='+extra_element;
                    573:                 }
1.234     raeburn   574:             }
1.468     raeburn   575:             else {
                    576:                 if (formname == 'portform') {
                    577:                     url += '&setroles='+extra_element;
1.800     raeburn   578:                 } else {
                    579:                     if (formname == 'rules') {
                    580:                         url += '&fixeddom='+extra_element; 
                    581:                     }
1.468     raeburn   582:                 }
                    583:             }     
1.230     raeburn   584:         }
1.909     raeburn   585:         if (type != null && type != '') {
                    586:             url += '&type='+type;
                    587:         }
                    588:         if (type_elem != null && type_elem != '') {
                    589:             url += '&typeelement='+type_elem;
                    590:         }
1.872     raeburn   591:         if (formname == 'ccrs') {
                    592:             var ownername = document.forms[formid].ccuname.value;
                    593:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   594:             url += '&cloner='+ownername+':'+ownerdom;
                    595:             if (type == 'Course') {
                    596:                 url += '&crscode='+document.forms[formid].crscode.value;
                    597:             }
1.1221    raeburn   598:         }
                    599:         if (formname == 'requestcrs') {
                    600:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   601:         }
1.293     raeburn   602:         if (multflag !=null && multflag != '') {
                    603:             url += '&multiple='+multflag;
                    604:         }
1.909     raeburn   605:         var title = '$wintitle';
1.91      www       606:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    607:         options += ',width=700,height=600';
                    608:         stdeditbrowser = open(url,title,options,'1');
                    609:         stdeditbrowser.focus();
                    610:     }
1.876     raeburn   611: $id_functions
                    612: ENDSTDBRW
1.1116    raeburn   613:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    614:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    615:                                       $credits_element);
1.876     raeburn   616:     }
                    617:     $output .= '
                    618: // ]]>
                    619: </script>';
                    620:     return $output;
                    621: }
                    622: 
                    623: sub javascript_index_functions {
                    624:     return <<"ENDJS";
                    625: 
                    626: function getFormIdByName(formname) {
                    627:     for (var i=0;i<document.forms.length;i++) {
                    628:         if (document.forms[i].name == formname) {
                    629:             return i;
                    630:         }
                    631:     }
                    632:     return -1;
                    633: }
                    634: 
                    635: function getIndexByName(formid,item) {
                    636:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    637:         if (document.forms[formid].elements[i].name == item) {
                    638:             return i;
                    639:         }
                    640:     }
                    641:     return -1;
                    642: }
1.468     raeburn   643: 
1.876     raeburn   644: function getDomainFromSelectbox(formname,udom) {
                    645:     var userdom;
                    646:     var formid = getFormIdByName(formname);
                    647:     if (formid > -1) {
                    648:         var domid = getIndexByName(formid,udom);
                    649:         if (domid > -1) {
                    650:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    651:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    652:             }
                    653:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    654:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   655:             }
                    656:         }
                    657:     }
1.876     raeburn   658:     return userdom;
                    659: }
                    660: 
                    661: ENDJS
1.468     raeburn   662: 
1.876     raeburn   663: }
                    664: 
1.1017    raeburn   665: sub javascript_array_indexof {
1.1018    raeburn   666:     return <<ENDJS;
1.1017    raeburn   667: <script type="text/javascript" language="JavaScript">
                    668: // <![CDATA[
                    669: 
                    670: if (!Array.prototype.indexOf) {
                    671:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    672:         "use strict";
                    673:         if (this === void 0 || this === null) {
                    674:             throw new TypeError();
                    675:         }
                    676:         var t = Object(this);
                    677:         var len = t.length >>> 0;
                    678:         if (len === 0) {
                    679:             return -1;
                    680:         }
                    681:         var n = 0;
                    682:         if (arguments.length > 0) {
                    683:             n = Number(arguments[1]);
1.1088    foxr      684:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   685:                 n = 0;
                    686:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    687:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    688:             }
                    689:         }
                    690:         if (n >= len) {
                    691:             return -1;
                    692:         }
                    693:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    694:         for (; k < len; k++) {
                    695:             if (k in t && t[k] === searchElement) {
                    696:                 return k;
                    697:             }
                    698:         }
                    699:         return -1;
                    700:     }
                    701: }
                    702: 
                    703: // ]]>
                    704: </script>
                    705: 
                    706: ENDJS
                    707: 
                    708: }
                    709: 
1.876     raeburn   710: sub userbrowser_javascript {
                    711:     my $id_functions = &javascript_index_functions();
                    712:     return <<"ENDUSERBRW";
                    713: 
1.888     raeburn   714: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   715:     var url = '/adm/pickuser?';
                    716:     var userdom = getDomainFromSelectbox(formname,udom);
                    717:     if (userdom != null) {
                    718:        if (userdom != '') {
                    719:            url += 'srchdom='+userdom+'&';
                    720:        }
                    721:     }
                    722:     url += 'form=' + formname + '&unameelement='+uname+
                    723:                                 '&udomelement='+udom+
                    724:                                 '&ulastelement='+ulast+
                    725:                                 '&ufirstelement='+ufirst+
                    726:                                 '&uemailelement='+uemail+
1.881     raeburn   727:                                 '&hideudomelement='+hideudom+
                    728:                                 '&coursedom='+crsdom;
1.888     raeburn   729:     if ((caller != null) && (caller != undefined)) {
                    730:         url += '&caller='+caller;
                    731:     }
1.876     raeburn   732:     var title = 'User_Browser';
                    733:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    734:     options += ',width=700,height=600';
                    735:     var stdeditbrowser = open(url,title,options,'1');
                    736:     stdeditbrowser.focus();
                    737: }
                    738: 
1.888     raeburn   739: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   740:     var formid = getFormIdByName(formname);
                    741:     if (formid > -1) {
1.888     raeburn   742:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   743:         var domid = getIndexByName(formid,udom);
                    744:         var hidedomid = getIndexByName(formid,origdom);
                    745:         if (hidedomid > -1) {
                    746:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   747:             var unameval = document.forms[formid].elements[unameid].value;
                    748:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    749:                 if (domid > -1) {
                    750:                     var slct = document.forms[formid].elements[domid];
                    751:                     if (slct.type == 'select-one') {
                    752:                         var i;
                    753:                         for (i=0;i<slct.length;i++) {
                    754:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    755:                         }
                    756:                     }
                    757:                     if (slct.type == 'hidden') {
                    758:                         slct.value = fixeddom;
1.876     raeburn   759:                     }
                    760:                 }
1.468     raeburn   761:             }
                    762:         }
                    763:     }
1.876     raeburn   764:     return;
                    765: }
                    766: 
                    767: $id_functions
                    768: ENDUSERBRW
1.468     raeburn   769: }
                    770: 
                    771: sub setsec_javascript {
1.1116    raeburn   772:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   773:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    774:         $communityrolestr);
                    775:     if ($role_element ne '') {
                    776:         my @allroles = ('st','ta','ep','in','ad');
                    777:         foreach my $crstype ('Course','Community') {
                    778:             if ($crstype eq 'Community') {
                    779:                 foreach my $role (@allroles) {
                    780:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    781:                 }
                    782:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    783:             } else {
                    784:                 foreach my $role (@allroles) {
                    785:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    786:                 }
                    787:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    788:             }
                    789:         }
                    790:         $rolestr = '"'.join('","',@allroles).'"';
                    791:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    792:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    793:     }
1.468     raeburn   794:     my $setsections = qq|
                    795: function setSect(sectionlist) {
1.629     raeburn   796:     var sectionsArray = new Array();
                    797:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    798:         sectionsArray = sectionlist.split(",");
                    799:     }
1.468     raeburn   800:     var numSections = sectionsArray.length;
                    801:     document.$formname.$sec_element.length = 0;
                    802:     if (numSections == 0) {
                    803:         document.$formname.$sec_element.multiple=false;
                    804:         document.$formname.$sec_element.size=1;
                    805:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    806:     } else {
                    807:         if (numSections == 1) {
                    808:             document.$formname.$sec_element.multiple=false;
                    809:             document.$formname.$sec_element.size=1;
                    810:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    811:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    812:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    813:         } else {
                    814:             for (var i=0; i<numSections; i++) {
                    815:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    816:             }
                    817:             document.$formname.$sec_element.multiple=true
                    818:             if (numSections < 3) {
                    819:                 document.$formname.$sec_element.size=numSections;
                    820:             } else {
                    821:                 document.$formname.$sec_element.size=3;
                    822:             }
                    823:             document.$formname.$sec_element.options[0].selected = false
                    824:         }
                    825:     }
1.91      www       826: }
1.905     raeburn   827: 
                    828: function setRole(crstype) {
1.468     raeburn   829: |;
1.905     raeburn   830:     if ($role_element eq '') {
                    831:         $setsections .= '    return;
                    832: }
                    833: ';
                    834:     } else {
                    835:         $setsections .= qq|
                    836:     var elementLength = document.$formname.$role_element.length;
                    837:     var allroles = Array($rolestr);
                    838:     var courserolenames = Array($courserolestr);
                    839:     var communityrolenames = Array($communityrolestr);
                    840:     if (elementLength != undefined) {
                    841:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    842:             if (crstype == 'Course') {
                    843:                 return;
                    844:             } else {
                    845:                 allroles[5] = 'co';
                    846:                 for (var i=0; i<6; i++) {
                    847:                     document.$formname.$role_element.options[i].value = allroles[i];
                    848:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    849:                 }
                    850:             }
                    851:         } else {
                    852:             if (crstype == 'Community') {
                    853:                 return;
                    854:             } else {
                    855:                 allroles[5] = 'cc';
                    856:                 for (var i=0; i<6; i++) {
                    857:                     document.$formname.$role_element.options[i].value = allroles[i];
                    858:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    859:                 }
                    860:             }
                    861:         }
                    862:     }
                    863:     return;
                    864: }
                    865: |;
                    866:     }
1.1116    raeburn   867:     if ($credits_element) {
                    868:         $setsections .= qq|
                    869: function setCredits(defaultcredits) {
                    870:     document.$formname.$credits_element.value = defaultcredits;
                    871:     return;
                    872: }
                    873: |;
                    874:     }
1.468     raeburn   875:     return $setsections;
                    876: }
                    877: 
1.91      www       878: sub selectcourse_link {
1.909     raeburn   879:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    880:        $typeelement) = @_;
                    881:    my $type = $selecttype;
1.871     raeburn   882:    my $linktext = &mt('Select Course');
                    883:    if ($selecttype eq 'Community') {
1.909     raeburn   884:        $linktext = &mt('Select Community');
1.1239    raeburn   885:    } elsif ($selecttype eq 'Placement') {
                    886:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   887:    } elsif ($selecttype eq 'Course/Community') {
                    888:        $linktext = &mt('Select Course/Community');
1.909     raeburn   889:        $type = '';
1.1019    raeburn   890:    } elsif ($selecttype eq 'Select') {
                    891:        $linktext = &mt('Select');
                    892:        $type = '';
1.871     raeburn   893:    }
1.787     bisitz    894:    return '<span class="LC_nobreak">'
                    895:          ."<a href='"
                    896:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    897:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   898:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   899:          ."'>".$linktext.'</a>'
1.787     bisitz    900:          .'</span>';
1.74      www       901: }
1.42      matthew   902: 
1.653     raeburn   903: sub selectauthor_link {
                    904:    my ($form,$udom)=@_;
                    905:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    906:           &mt('Select Author').'</a>';
                    907: }
                    908: 
1.876     raeburn   909: sub selectuser_link {
1.881     raeburn   910:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   911:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   912:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   913:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   914:            ');">'.$linktext.'</a>';
1.876     raeburn   915: }
                    916: 
1.273     raeburn   917: sub check_uncheck_jscript {
                    918:     my $jscript = <<"ENDSCRT";
                    919: function checkAll(field) {
                    920:     if (field.length > 0) {
                    921:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   922:             if (!field[i].disabled) { 
                    923:                 field[i].checked = true;
                    924:             }
1.273     raeburn   925:         }
                    926:     } else {
1.1093    raeburn   927:         if (!field.disabled) { 
                    928:             field.checked = true;
                    929:         }
1.273     raeburn   930:     }
                    931: }
                    932:  
                    933: function uncheckAll(field) {
                    934:     if (field.length > 0) {
                    935:         for (i = 0; i < field.length; i++) {
                    936:             field[i].checked = false ;
1.543     albertel  937:         }
                    938:     } else {
1.273     raeburn   939:         field.checked = false ;
                    940:     }
                    941: }
                    942: ENDSCRT
                    943:     return $jscript;
                    944: }
                    945: 
1.656     www       946: sub select_timezone {
1.1256    raeburn   947:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    948:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   949:    if ($includeempty) {
                    950:        $output .= '<option value=""';
                    951:        if (($selected eq '') || ($selected eq 'local')) {
                    952:            $output .= ' selected="selected" ';
                    953:        }
                    954:        $output .= '> </option>';
                    955:    }
1.657     raeburn   956:    my @timezones = DateTime::TimeZone->all_names;
                    957:    foreach my $tzone (@timezones) {
                    958:        $output.= '<option value="'.$tzone.'"';
                    959:        if ($tzone eq $selected) {
                    960:            $output.=' selected="selected"';
                    961:        }
                    962:        $output.=">$tzone</option>\n";
1.656     www       963:    }
                    964:    $output.="</select>";
                    965:    return $output;
                    966: }
1.273     raeburn   967: 
1.687     raeburn   968: sub select_datelocale {
1.1256    raeburn   969:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    970:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   971:     if ($includeempty) {
                    972:         $output .= '<option value=""';
                    973:         if ($selected eq '') {
                    974:             $output .= ' selected="selected" ';
                    975:         }
                    976:         $output .= '> </option>';
                    977:     }
1.1241    raeburn   978:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   979:     my (@possibles,%locale_names);
1.1241    raeburn   980:     my @locales = DateTime::Locale->ids();
                    981:     foreach my $id (@locales) {
                    982:         if ($id ne '') {
                    983:             my ($en_terr,$native_terr);
                    984:             my $loc = DateTime::Locale->load($id);
                    985:             if (ref($loc)) {
                    986:                 $en_terr = $loc->name();
                    987:                 $native_terr = $loc->native_name();
1.687     raeburn   988:                 if (grep(/^en$/,@languages) || !@languages) {
                    989:                     if ($en_terr ne '') {
                    990:                         $locale_names{$id} = '('.$en_terr.')';
                    991:                     } elsif ($native_terr ne '') {
                    992:                         $locale_names{$id} = $native_terr;
                    993:                     }
                    994:                 } else {
                    995:                     if ($native_terr ne '') {
                    996:                         $locale_names{$id} = $native_terr.' ';
                    997:                     } elsif ($en_terr ne '') {
                    998:                         $locale_names{$id} = '('.$en_terr.')';
                    999:                     }
                   1000:                 }
1.1220    raeburn  1001:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1002:                 push(@possibles,$id);
                   1003:             } 
1.687     raeburn  1004:         }
                   1005:     }
                   1006:     foreach my $item (sort(@possibles)) {
                   1007:         $output.= '<option value="'.$item.'"';
                   1008:         if ($item eq $selected) {
                   1009:             $output.=' selected="selected"';
                   1010:         }
                   1011:         $output.=">$item";
                   1012:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1013:             $output.='  '.$locale_names{$item};
1.687     raeburn  1014:         }
                   1015:         $output.="</option>\n";
                   1016:     }
                   1017:     $output.="</select>";
                   1018:     return $output;
                   1019: }
                   1020: 
1.792     raeburn  1021: sub select_language {
1.1256    raeburn  1022:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1023:     my %langchoices;
                   1024:     if ($includeempty) {
1.1117    raeburn  1025:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1026:     }
                   1027:     foreach my $id (&languageids()) {
                   1028:         my $code = &supportedlanguagecode($id);
                   1029:         if ($code) {
                   1030:             $langchoices{$code} = &plainlanguagedescription($id);
                   1031:         }
                   1032:     }
1.1117    raeburn  1033:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1034:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1035: }
                   1036: 
1.42      matthew  1037: =pod
1.36      matthew  1038: 
1.1088    foxr     1039: 
                   1040: =item * &list_languages()
                   1041: 
                   1042: Returns an array reference that is suitable for use in language prompters.
                   1043: Each array element is itself a two element array.  The first element
                   1044: is the language code.  The second element a descsriptiuon of the 
                   1045: language itself.  This is suitable for use in e.g.
                   1046: &Apache::edit::select_arg (once dereferenced that is).
                   1047: 
                   1048: =cut 
                   1049: 
                   1050: sub list_languages {
                   1051:     my @lang_choices;
                   1052: 
                   1053:     foreach my $id (&languageids()) {
                   1054: 	my $code = &supportedlanguagecode($id);
                   1055: 	if ($code) {
                   1056: 	    my $selector    = $supported_codes{$id};
                   1057: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1058: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1059: 	}
                   1060:     }
                   1061:     return \@lang_choices;
                   1062: }
                   1063: 
                   1064: =pod
                   1065: 
1.648     raeburn  1066: =item * &linked_select_forms(...)
1.36      matthew  1067: 
                   1068: linked_select_forms returns a string containing a <script></script> block
                   1069: and html for two <select> menus.  The select menus will be linked in that
                   1070: changing the value of the first menu will result in new values being placed
                   1071: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1072: order unless a defined order is provided.
1.36      matthew  1073: 
                   1074: linked_select_forms takes the following ordered inputs:
                   1075: 
                   1076: =over 4
                   1077: 
1.112     bowersj2 1078: =item * $formname, the name of the <form> tag
1.36      matthew  1079: 
1.112     bowersj2 1080: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1081: 
1.112     bowersj2 1082: =item * $firstdefault, the default value for the first menu
1.36      matthew  1083: 
1.112     bowersj2 1084: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1085: 
1.112     bowersj2 1086: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1087: 
1.112     bowersj2 1088: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1089: 
1.609     raeburn  1090: =item * $menuorder, the order of values in the first menu
                   1091: 
1.1115    raeburn  1092: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1093:         event for the first <select> tag
                   1094: 
                   1095: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1096:         event for the second <select> tag
                   1097: 
1.1245    raeburn  1098: =item * $suffix, to differentiate separate uses of select2data javascript
                   1099:         objects in a page.
                   1100: 
1.41      ng       1101: =back 
                   1102: 
1.36      matthew  1103: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1104: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1105: values for the first select menu.  The text that coincides with the 
1.41      ng       1106: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1107: and text for the second menu are given in the hash pointed to by 
                   1108: $menu{$choice1}->{'select2'}.  
                   1109: 
1.112     bowersj2 1110:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1111:                        default => "B3",
                   1112:                        select2 => { 
                   1113:                            B1 => "Choice B1",
                   1114:                            B2 => "Choice B2",
                   1115:                            B3 => "Choice B3",
                   1116:                            B4 => "Choice B4"
1.609     raeburn  1117:                            },
                   1118:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1119:                    },
                   1120:                A2 => { text =>"Choice A2" ,
                   1121:                        default => "C2",
                   1122:                        select2 => { 
                   1123:                            C1 => "Choice C1",
                   1124:                            C2 => "Choice C2",
                   1125:                            C3 => "Choice C3"
1.609     raeburn  1126:                            },
                   1127:                        order => ['C2','C1','C3'],
1.112     bowersj2 1128:                    },
                   1129:                A3 => { text =>"Choice A3" ,
                   1130:                        default => "D6",
                   1131:                        select2 => { 
                   1132:                            D1 => "Choice D1",
                   1133:                            D2 => "Choice D2",
                   1134:                            D3 => "Choice D3",
                   1135:                            D4 => "Choice D4",
                   1136:                            D5 => "Choice D5",
                   1137:                            D6 => "Choice D6",
                   1138:                            D7 => "Choice D7"
1.609     raeburn  1139:                            },
                   1140:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1141:                    }
                   1142:                );
1.36      matthew  1143: 
                   1144: =cut
                   1145: 
                   1146: sub linked_select_forms {
                   1147:     my ($formname,
                   1148:         $middletext,
                   1149:         $firstdefault,
                   1150:         $firstselectname,
                   1151:         $secondselectname, 
1.609     raeburn  1152:         $hashref,
                   1153:         $menuorder,
1.1115    raeburn  1154:         $onchangefirst,
1.1245    raeburn  1155:         $onchangesecond,
                   1156:         $suffix
1.36      matthew  1157:         ) = @_;
                   1158:     my $second = "document.$formname.$secondselectname";
                   1159:     my $first = "document.$formname.$firstselectname";
                   1160:     # output the javascript to do the changing
                   1161:     my $result = '';
1.776     bisitz   1162:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1163:     $result.="// <![CDATA[\n";
1.1245    raeburn  1164:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1165:     $" = '","';
                   1166:     my $debug = '';
                   1167:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1168:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1169:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1170:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1171:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1172:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1173:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1174:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1175:         }
1.36      matthew  1176:         $result.="\"@s2values\");\n";
1.1245    raeburn  1177:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1178:         my @s2texts;
                   1179:         foreach my $value (@s2values) {
1.1263    raeburn  1180:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1181:         }
                   1182:         $result.="\"@s2texts\");\n";
                   1183:     }
                   1184:     $"=' ';
                   1185:     $result.= <<"END";
                   1186: 
1.1245    raeburn  1187: function select1${suffix}_changed() {
1.36      matthew  1188:     // Determine new choice
1.1245    raeburn  1189:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1190:     // update select2
1.1245    raeburn  1191:     var values     = select2data${suffix}[newvalue].values;
                   1192:     var texts      = select2data${suffix}[newvalue].texts;
                   1193:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1194:     var i;
                   1195:     // out with the old
1.1245    raeburn  1196:     $second.options.length = 0;
                   1197:     // in with the new
1.36      matthew  1198:     for (i=0;i<values.length; i++) {
                   1199:         $second.options[i] = new Option(values[i]);
1.143     matthew  1200:         $second.options[i].value = values[i];
1.36      matthew  1201:         $second.options[i].text = texts[i];
                   1202:         if (values[i] == select2def) {
                   1203:             $second.options[i].selected = true;
                   1204:         }
                   1205:     }
                   1206: }
1.824     bisitz   1207: // ]]>
1.36      matthew  1208: </script>
                   1209: END
                   1210:     # output the initial values for the selection lists
1.1245    raeburn  1211:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1212:     my @order = sort(keys(%{$hashref}));
                   1213:     if (ref($menuorder) eq 'ARRAY') {
                   1214:         @order = @{$menuorder};
                   1215:     }
                   1216:     foreach my $value (@order) {
1.36      matthew  1217:         $result.="    <option value=\"$value\" ";
1.253     albertel 1218:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1219:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1220:     }
                   1221:     $result .= "</select>\n";
                   1222:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1223:     $result .= $middletext;
1.1115    raeburn  1224:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1225:     if ($onchangesecond) {
                   1226:         $result .= ' onchange="'.$onchangesecond.'"';
                   1227:     }
                   1228:     $result .= ">\n";
1.36      matthew  1229:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1230:     
                   1231:     my @secondorder = sort(keys(%select2));
                   1232:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1233:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1234:     }
                   1235:     foreach my $value (@secondorder) {
1.36      matthew  1236:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1237:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1238:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1239:     }
                   1240:     $result .= "</select>\n";
                   1241:     #    return $debug;
                   1242:     return $result;
                   1243: }   #  end of sub linked_select_forms {
                   1244: 
1.45      matthew  1245: =pod
1.44      bowersj2 1246: 
1.973     raeburn  1247: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1248: 
1.112     bowersj2 1249: Returns a string corresponding to an HTML link to the given help
                   1250: $topic, where $topic corresponds to the name of a .tex file in
                   1251: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1252: spaces. 
                   1253: 
                   1254: $text will optionally be linked to the same topic, allowing you to
                   1255: link text in addition to the graphic. If you do not want to link
                   1256: text, but wish to specify one of the later parameters, pass an
                   1257: empty string. 
                   1258: 
                   1259: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1260: the link will not open a new window. If false, the link will open
                   1261: a new window using Javascript. (Default is false.) 
                   1262: 
                   1263: $width and $height are optional numerical parameters that will
                   1264: override the width and height of the popped up window, which may
1.973     raeburn  1265: be useful for certain help topics with big pictures included.
                   1266: 
                   1267: $imgid is the id of the img tag used for the help icon. This may be
                   1268: used in a javascript call to switch the image src.  See 
                   1269: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1270: 
                   1271: =cut
                   1272: 
                   1273: sub help_open_topic {
1.973     raeburn  1274:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1275:     $text = "" if (not defined $text);
1.44      bowersj2 1276:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1277:     $width = 500 if (not defined $width);
1.44      bowersj2 1278:     $height = 400 if (not defined $height);
                   1279:     my $filename = $topic;
                   1280:     $filename =~ s/ /_/g;
                   1281: 
1.48      bowersj2 1282:     my $template = "";
                   1283:     my $link;
1.572     banghart 1284:     
1.159     www      1285:     $topic=~s/\W/\_/g;
1.44      bowersj2 1286: 
1.572     banghart 1287:     if (!$stayOnPage) {
1.1033    www      1288: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1289:     } elsif ($stayOnPage eq 'popup') {
                   1290:         $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 1291:     } else {
1.48      bowersj2 1292: 	$link = "/adm/help/${filename}.hlp";
                   1293:     }
                   1294: 
                   1295:     # Add the text
1.755     neumanie 1296:     if ($text ne "") {	
1.763     bisitz   1297: 	$template.='<span class="LC_help_open_topic">'
                   1298:                   .'<a target="_top" href="'.$link.'">'
                   1299:                   .$text.'</a>';
1.48      bowersj2 1300:     }
                   1301: 
1.763     bisitz   1302:     # (Always) Add the graphic
1.179     matthew  1303:     my $title = &mt('Online Help');
1.667     raeburn  1304:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1305:     if ($imgid ne '') {
                   1306:         $imgid = ' id="'.$imgid.'"';
                   1307:     }
1.763     bisitz   1308:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1309:               .'<img src="'.$helpicon.'" border="0"'
                   1310:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1311:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1312:               .' /></a>';
                   1313:     if ($text ne "") {	
                   1314:         $template.='</span>';
                   1315:     }
1.44      bowersj2 1316:     return $template;
                   1317: 
1.106     bowersj2 1318: }
                   1319: 
                   1320: # This is a quicky function for Latex cheatsheet editing, since it 
                   1321: # appears in at least four places
                   1322: sub helpLatexCheatsheet {
1.1037    www      1323:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1324:     my $out;
1.106     bowersj2 1325:     my $addOther = '';
1.732     raeburn  1326:     if ($topic) {
1.1037    www      1327: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1328:     }
                   1329:     $out = '<span>' # Start cheatsheet
                   1330: 	  .$addOther
                   1331:           .'<span>'
1.1037    www      1332: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1333: 	  .'</span> <span>'
1.1037    www      1334: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1335: 	  .'</span>';
1.732     raeburn  1336:     unless ($not_author) {
1.1186    kruse    1337:         $out .= '<span>'
                   1338:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1339:                .'</span> <span>'
                   1340:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1341: 	       .'</span>';
1.732     raeburn  1342:     }
1.763     bisitz   1343:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1344:     return $out;
1.172     www      1345: }
                   1346: 
1.430     albertel 1347: sub general_help {
                   1348:     my $helptopic='Student_Intro';
                   1349:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1350: 	$helptopic='Authoring_Intro';
1.907     raeburn  1351:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1352: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1353:     } elsif ($env{'request.role'}=~/^dc/) {
                   1354:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1355:     }
                   1356:     return $helptopic;
                   1357: }
                   1358: 
                   1359: sub update_help_link {
                   1360:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1361:     my $origurl = $ENV{'REQUEST_URI'};
                   1362:     $origurl=~s|^/~|/priv/|;
                   1363:     my $timestamp = time;
                   1364:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1365:         $$datum = &escape($$datum);
                   1366:     }
                   1367: 
                   1368:     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";
                   1369:     my $output .= <<"ENDOUTPUT";
                   1370: <script type="text/javascript">
1.824     bisitz   1371: // <![CDATA[
1.430     albertel 1372: banner_link = '$banner_link';
1.824     bisitz   1373: // ]]>
1.430     albertel 1374: </script>
                   1375: ENDOUTPUT
                   1376:     return $output;
                   1377: }
                   1378: 
                   1379: # now just updates the help link and generates a blue icon
1.193     raeburn  1380: sub help_open_menu {
1.430     albertel 1381:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1382: 	= @_;    
1.949     droeschl 1383:     $stayOnPage = 1;
1.430     albertel 1384:     my $output;
                   1385:     if ($component_help) {
                   1386: 	if (!$text) {
                   1387: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1388: 				       $width,$height);
                   1389: 	} else {
                   1390: 	    my $help_text;
                   1391: 	    $help_text=&unescape($topic);
                   1392: 	    $output='<table><tr><td>'.
                   1393: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1394: 				 $width,$height).'</td></tr></table>';
                   1395: 	}
                   1396:     }
                   1397:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1398:     return $output.$banner_link;
                   1399: }
                   1400: 
                   1401: sub top_nav_help {
                   1402:     my ($text) = @_;
1.436     albertel 1403:     $text = &mt($text);
1.949     droeschl 1404:     my $stay_on_page = 1;
                   1405: 
1.1168    raeburn  1406:     my ($link,$banner_link);
                   1407:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1408:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1409: 	                         : "javascript:helpMenu('open')";
                   1410:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1411:     }
1.201     raeburn  1412:     my $title = &mt('Get help');
1.1168    raeburn  1413:     if ($link) {
                   1414:         return <<"END";
1.436     albertel 1415: $banner_link
1.1159    raeburn  1416: <a href="$link" title="$title">$text</a>
1.436     albertel 1417: END
1.1168    raeburn  1418:     } else {
                   1419:         return '&nbsp;'.$text.'&nbsp;';
                   1420:     }
1.436     albertel 1421: }
                   1422: 
                   1423: sub help_menu_js {
1.1154    raeburn  1424:     my ($httphost) = @_;
1.949     droeschl 1425:     my $stayOnPage = 1;
1.436     albertel 1426:     my $width = 620;
                   1427:     my $height = 600;
1.430     albertel 1428:     my $helptopic=&general_help();
1.1154    raeburn  1429:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1430:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1431:     my $start_page =
                   1432:         &Apache::loncommon::start_page('Help Menu', undef,
                   1433: 				       {'frameset'    => 1,
                   1434: 					'js_ready'    => 1,
1.1154    raeburn  1435:                                         'use_absolute' => $httphost,
1.331     albertel 1436: 					'add_entries' => {
1.1168    raeburn  1437: 					    'border' => '0', 
1.579     raeburn  1438: 					    'rows'   => "110,*",},});
1.331     albertel 1439:     my $end_page =
                   1440:         &Apache::loncommon::end_page({'frameset' => 1,
                   1441: 				      'js_ready' => 1,});
                   1442: 
1.436     albertel 1443:     my $template .= <<"ENDTEMPLATE";
                   1444: <script type="text/javascript">
1.877     bisitz   1445: // <![CDATA[
1.253     albertel 1446: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1447: var banner_link = '';
1.243     raeburn  1448: function helpMenu(target) {
                   1449:     var caller = this;
                   1450:     if (target == 'open') {
                   1451:         var newWindow = null;
                   1452:         try {
1.262     albertel 1453:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1454:         }
                   1455:         catch(error) {
                   1456:             writeHelp(caller);
                   1457:             return;
                   1458:         }
                   1459:         if (newWindow) {
                   1460:             caller = newWindow;
                   1461:         }
1.193     raeburn  1462:     }
1.243     raeburn  1463:     writeHelp(caller);
                   1464:     return;
                   1465: }
                   1466: function writeHelp(caller) {
1.1168    raeburn  1467:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1468:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1469:     caller.document.close();
                   1470:     caller.focus();
1.193     raeburn  1471: }
1.877     bisitz   1472: // END LON-CAPA Internal -->
1.253     albertel 1473: // ]]>
1.436     albertel 1474: </script>
1.193     raeburn  1475: ENDTEMPLATE
                   1476:     return $template;
                   1477: }
                   1478: 
1.172     www      1479: sub help_open_bug {
                   1480:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1481:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1482:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1483:     $text = "" if (not defined $text);
                   1484: 	$stayOnPage=1;
1.184     albertel 1485:     $width = 600 if (not defined $width);
                   1486:     $height = 600 if (not defined $height);
1.172     www      1487: 
                   1488:     $topic=~s/\W+/\+/g;
                   1489:     my $link='';
                   1490:     my $template='';
1.379     albertel 1491:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1492: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1493:     if (!$stayOnPage)
                   1494:     {
                   1495: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1496:     }
                   1497:     else
                   1498:     {
                   1499: 	$link = $url;
                   1500:     }
                   1501:     # Add the text
                   1502:     if ($text ne "")
                   1503:     {
                   1504: 	$template .= 
                   1505:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1506:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1507:     }
                   1508: 
                   1509:     # Add the graphic
1.179     matthew  1510:     my $title = &mt('Report a Bug');
1.215     albertel 1511:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1512:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1513:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1514: ENDTEMPLATE
                   1515:     if ($text ne '') { $template.='</td></tr></table>' };
                   1516:     return $template;
                   1517: 
                   1518: }
                   1519: 
                   1520: sub help_open_faq {
                   1521:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1522:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1523:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1524:     $text = "" if (not defined $text);
                   1525: 	$stayOnPage=1;
                   1526:     $width = 350 if (not defined $width);
                   1527:     $height = 400 if (not defined $height);
                   1528: 
                   1529:     $topic=~s/\W+/\+/g;
                   1530:     my $link='';
                   1531:     my $template='';
                   1532:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1533:     if (!$stayOnPage)
                   1534:     {
                   1535: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1536:     }
                   1537:     else
                   1538:     {
                   1539: 	$link = $url;
                   1540:     }
                   1541: 
                   1542:     # Add the text
                   1543:     if ($text ne "")
                   1544:     {
                   1545: 	$template .= 
1.173     www      1546:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1547:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1548:     }
                   1549: 
                   1550:     # Add the graphic
1.179     matthew  1551:     my $title = &mt('View the FAQ');
1.215     albertel 1552:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1553:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1554:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1555: ENDTEMPLATE
                   1556:     if ($text ne '') { $template.='</td></tr></table>' };
                   1557:     return $template;
                   1558: 
1.44      bowersj2 1559: }
1.37      matthew  1560: 
1.180     matthew  1561: ###############################################################
                   1562: ###############################################################
                   1563: 
1.45      matthew  1564: =pod
                   1565: 
1.648     raeburn  1566: =item * &change_content_javascript():
1.256     matthew  1567: 
                   1568: This and the next function allow you to create small sections of an
                   1569: otherwise static HTML page that you can update on the fly with
                   1570: Javascript, even in Netscape 4.
                   1571: 
                   1572: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1573: must be written to the HTML page once. It will prove the Javascript
                   1574: function "change(name, content)". Calling the change function with the
                   1575: name of the section 
                   1576: you want to update, matching the name passed to C<changable_area>, and
                   1577: the new content you want to put in there, will put the content into
                   1578: that area.
                   1579: 
                   1580: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1581: to contain room for the original contents. You need to "make space"
                   1582: for whatever changes you wish to make, and be B<sure> to check your
                   1583: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1584: it's adequate for updating a one-line status display, but little more.
                   1585: This script will set the space to 100% width, so you only need to
                   1586: worry about height in Netscape 4.
                   1587: 
                   1588: Modern browsers are much less limiting, and if you can commit to the
                   1589: user not using Netscape 4, this feature may be used freely with
                   1590: pretty much any HTML.
                   1591: 
                   1592: =cut
                   1593: 
                   1594: sub change_content_javascript {
                   1595:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1596:     if ($env{'browser.type'} eq 'netscape' &&
                   1597: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1598: 	return (<<NETSCAPE4);
                   1599: 	function change(name, content) {
                   1600: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1601: 	    doc.open();
                   1602: 	    doc.write(content);
                   1603: 	    doc.close();
                   1604: 	}
                   1605: NETSCAPE4
                   1606:     } else {
                   1607: 	# Otherwise, we need to use semi-standards-compliant code
                   1608: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1609: 	# is really scary, and every useful browser supports it
                   1610: 	return (<<DOMBASED);
                   1611: 	function change(name, content) {
                   1612: 	    element = document.getElementById(name);
                   1613: 	    element.innerHTML = content;
                   1614: 	}
                   1615: DOMBASED
                   1616:     }
                   1617: }
                   1618: 
                   1619: =pod
                   1620: 
1.648     raeburn  1621: =item * &changable_area($name,$origContent):
1.256     matthew  1622: 
                   1623: This provides a "changable area" that can be modified on the fly via
                   1624: the Javascript code provided in C<change_content_javascript>. $name is
                   1625: the name you will use to reference the area later; do not repeat the
                   1626: same name on a given HTML page more then once. $origContent is what
                   1627: the area will originally contain, which can be left blank.
                   1628: 
                   1629: =cut
                   1630: 
                   1631: sub changable_area {
                   1632:     my ($name, $origContent) = @_;
                   1633: 
1.258     albertel 1634:     if ($env{'browser.type'} eq 'netscape' &&
                   1635: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1636: 	# If this is netscape 4, we need to use the Layer tag
                   1637: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1638:     } else {
                   1639: 	return "<span id='$name'>$origContent</span>";
                   1640:     }
                   1641: }
                   1642: 
                   1643: =pod
                   1644: 
1.648     raeburn  1645: =item * &viewport_geometry_js 
1.590     raeburn  1646: 
                   1647: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1648: 
                   1649: =cut
                   1650: 
                   1651: 
                   1652: sub viewport_geometry_js { 
                   1653:     return <<"GEOMETRY";
                   1654: var Geometry = {};
                   1655: function init_geometry() {
                   1656:     if (Geometry.init) { return };
                   1657:     Geometry.init=1;
                   1658:     if (window.innerHeight) {
                   1659:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1660:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1661:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1662:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1663:     }
                   1664:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1665:         Geometry.getViewportHeight =
                   1666:             function() { return document.documentElement.clientHeight; };
                   1667:         Geometry.getViewportWidth =
                   1668:             function() { return document.documentElement.clientWidth; };
                   1669: 
                   1670:         Geometry.getHorizontalScroll =
                   1671:             function() { return document.documentElement.scrollLeft; };
                   1672:         Geometry.getVerticalScroll =
                   1673:             function() { return document.documentElement.scrollTop; };
                   1674:     }
                   1675:     else if (document.body.clientHeight) {
                   1676:         Geometry.getViewportHeight =
                   1677:             function() { return document.body.clientHeight; };
                   1678:         Geometry.getViewportWidth =
                   1679:             function() { return document.body.clientWidth; };
                   1680:         Geometry.getHorizontalScroll =
                   1681:             function() { return document.body.scrollLeft; };
                   1682:         Geometry.getVerticalScroll =
                   1683:             function() { return document.body.scrollTop; };
                   1684:     }
                   1685: }
                   1686: 
                   1687: GEOMETRY
                   1688: }
                   1689: 
                   1690: =pod
                   1691: 
1.648     raeburn  1692: =item * &viewport_size_js()
1.590     raeburn  1693: 
                   1694: 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. 
                   1695: 
                   1696: =cut
                   1697: 
                   1698: sub viewport_size_js {
                   1699:     my $geometry = &viewport_geometry_js();
                   1700:     return <<"DIMS";
                   1701: 
                   1702: $geometry
                   1703: 
                   1704: function getViewportDims(width,height) {
                   1705:     init_geometry();
                   1706:     width.value = Geometry.getViewportWidth();
                   1707:     height.value = Geometry.getViewportHeight();
                   1708:     return;
                   1709: }
                   1710: 
                   1711: DIMS
                   1712: }
                   1713: 
                   1714: =pod
                   1715: 
1.648     raeburn  1716: =item * &resize_textarea_js()
1.565     albertel 1717: 
                   1718: emits the needed javascript to resize a textarea to be as big as possible
                   1719: 
                   1720: creates a function resize_textrea that takes two IDs first should be
                   1721: the id of the element to resize, second should be the id of a div that
                   1722: surrounds everything that comes after the textarea, this routine needs
                   1723: to be attached to the <body> for the onload and onresize events.
                   1724: 
1.648     raeburn  1725: =back
1.565     albertel 1726: 
                   1727: =cut
                   1728: 
                   1729: sub resize_textarea_js {
1.590     raeburn  1730:     my $geometry = &viewport_geometry_js();
1.565     albertel 1731:     return <<"RESIZE";
                   1732:     <script type="text/javascript">
1.824     bisitz   1733: // <![CDATA[
1.590     raeburn  1734: $geometry
1.565     albertel 1735: 
1.588     albertel 1736: function getX(element) {
                   1737:     var x = 0;
                   1738:     while (element) {
                   1739: 	x += element.offsetLeft;
                   1740: 	element = element.offsetParent;
                   1741:     }
                   1742:     return x;
                   1743: }
                   1744: function getY(element) {
                   1745:     var y = 0;
                   1746:     while (element) {
                   1747: 	y += element.offsetTop;
                   1748: 	element = element.offsetParent;
                   1749:     }
                   1750:     return y;
                   1751: }
                   1752: 
                   1753: 
1.565     albertel 1754: function resize_textarea(textarea_id,bottom_id) {
                   1755:     init_geometry();
                   1756:     var textarea        = document.getElementById(textarea_id);
                   1757:     //alert(textarea);
                   1758: 
1.588     albertel 1759:     var textarea_top    = getY(textarea);
1.565     albertel 1760:     var textarea_height = textarea.offsetHeight;
                   1761:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1762:     var bottom_top      = getY(bottom);
1.565     albertel 1763:     var bottom_height   = bottom.offsetHeight;
                   1764:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1765:     var fudge           = 23;
1.565     albertel 1766:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1767:     if (new_height < 300) {
                   1768: 	new_height = 300;
                   1769:     }
                   1770:     textarea.style.height=new_height+'px';
                   1771: }
1.824     bisitz   1772: // ]]>
1.565     albertel 1773: </script>
                   1774: RESIZE
                   1775: 
                   1776: }
                   1777: 
1.1205    golterma 1778: sub colorfuleditor_js {
1.1248    raeburn  1779:     my $browse_or_search;
                   1780:     my $respath;
                   1781:     my ($cnum,$cdom) = &crsauthor_url();
                   1782:     if ($cnum) {
                   1783:         $respath = "/res/$cdom/$cnum/";
                   1784:         my %js_lt = &Apache::lonlocal::texthash(
                   1785:             sunm => 'Sub-directory name',
                   1786:             save => 'Save page to make this permanent',
                   1787:         );
                   1788:         &js_escape(\%js_lt);
                   1789:         $browse_or_search = <<"END";
                   1790: 
                   1791:     function toggleChooser(form,element,titleid,only,search) {
                   1792:         var disp = 'none';
                   1793:         if (document.getElementById('chooser_'+element)) {
                   1794:             var curr = document.getElementById('chooser_'+element).style.display;
                   1795:             if (curr == 'none') {
                   1796:                 disp='inline';
                   1797:                 if (form.elements['chooser_'+element].length) {
                   1798:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1799:                         form.elements['chooser_'+element][i].checked = false;
                   1800:                     }
                   1801:                 }
                   1802:                 toggleResImport(form,element);
                   1803:             }
                   1804:             document.getElementById('chooser_'+element).style.display = disp;
                   1805:         }
                   1806:     }
                   1807: 
                   1808:     function toggleCrsFile(form,element,numdirs) {
                   1809:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1810:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1811:             if (curr == 'none') {
                   1812:                 if (numdirs) {
                   1813:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1814:                     if (numdirs > 1) {
                   1815:                         window['select1'+element+'_changed']();
                   1816:                     }
                   1817:                 }
                   1818:             } 
                   1819:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1820:             
                   1821:         }
                   1822:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1823:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1824:             if (document.getElementById('uploadcrsres_'+element)) {
                   1825:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1826:             }
                   1827:         }
                   1828:         return;
                   1829:     }
                   1830: 
                   1831:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1832:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1833:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1834:         }
                   1835:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1836:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1837:             if (curr == 'none') {
                   1838:                 if (numcrsdirs) {
                   1839:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1840:                    form.elements['newsubdir_'+element][0].checked = true;
                   1841:                    toggleNewsubdir(form,element);
                   1842:                 }
                   1843:             }
                   1844:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1845:         }
                   1846:         return;
                   1847:     }
                   1848: 
                   1849:     function toggleResImport(form,element) {
                   1850:         var choices = new Array('crsres','upload');
                   1851:         for (var i=0; i<choices.length; i++) {
                   1852:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1853:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1854:             }
                   1855:         }
                   1856:     }
                   1857: 
                   1858:     function toggleNewsubdir(form,element) {
                   1859:         var newsub = form.elements['newsubdir_'+element];
                   1860:         if (newsub) {
                   1861:             if (newsub.length) {
                   1862:                 for (var j=0; j<newsub.length; j++) {
                   1863:                     if (newsub[j].checked) {
                   1864:                         if (document.getElementById('newsubdirname_'+element)) {
                   1865:                             if (newsub[j].value == '1') {
                   1866:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1867:                                 if (document.getElementById('newsubdir_'+element)) {
                   1868:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1869:                                 }
                   1870:                             } else {
                   1871:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1872:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1873:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1874:                             }
                   1875:                         }
                   1876:                         break; 
                   1877:                     }
                   1878:                 }
                   1879:             }
                   1880:         }
                   1881:     }
                   1882: 
                   1883:     function updateCrsFile(form,element) {
                   1884:         var directory = form.elements['coursepath_'+element];
                   1885:         var filename = form.elements['coursefile_'+element];
                   1886:         var path = directory.options[directory.selectedIndex].value;
                   1887:         var file = filename.options[filename.selectedIndex].value;
                   1888:         form.elements[element].value = '$respath';
                   1889:         if (path == '/') {
                   1890:             form.elements[element].value += file;
                   1891:         } else {
                   1892:             form.elements[element].value += path+'/'+file;
                   1893:         }
                   1894:         unClean();
                   1895:         if (document.getElementById('previewimg_'+element)) {
                   1896:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1897:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1898:         }
                   1899:         if (document.getElementById('showimg_'+element)) {
                   1900:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1901:         }
                   1902:         toggleChooser(form,element);
                   1903:         return;
                   1904:     }
                   1905: 
                   1906:     function uploadDone(suffix,name) {
                   1907:         if (name) {
                   1908: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1909:             unClean();
                   1910:             toggleChooser(document.forms["lonhomework"],suffix);
                   1911:         }
                   1912:     }
                   1913: 
                   1914: \$(document).ready(function(){
                   1915: 
                   1916:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1917:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1918:             var buttonId = this.id;
                   1919:             var suffix = buttonId.toString();
                   1920:             suffix = suffix.replace(/^crsupload_/,'');
                   1921:             event.preventDefault();
                   1922:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1923:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1924:             \$(this.form).submit();
                   1925:             document.lonhomework.target = '';
                   1926:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1927:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1928:             }
                   1929:             return false;
                   1930:         }
                   1931:     });
                   1932: });
                   1933: END
                   1934:     }
1.1205    golterma 1935:     return <<"COLORFULEDIT"
                   1936: <script type="text/javascript">
                   1937: // <![CDATA[>
                   1938:     function fold_box(curDepth, lastresource){
                   1939: 
                   1940:     // we need a list because there can be several blocks you need to fold in one tag
                   1941:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1942:     // but there is only one folding button per tag
                   1943:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1944: 
                   1945:         if(block.item(0).style.display == 'none'){
                   1946: 
                   1947:             foldbutton.value = '@{[&mt("Hide")]}';
                   1948:             for (i = 0; i < block.length; i++){
                   1949:                 block.item(i).style.display = '';
                   1950:             }
                   1951:         }else{
                   1952: 
                   1953:             foldbutton.value = '@{[&mt("Show")]}';
                   1954:             for (i = 0; i < block.length; i++){
                   1955:                 // block.item(i).style.visibility = 'collapse';
                   1956:                 block.item(i).style.display = 'none';
                   1957:             }
                   1958:         };
                   1959:         saveState(lastresource);
                   1960:     }
                   1961: 
                   1962:     function saveState (lastresource) {
                   1963: 
                   1964:         var tag_list = getTagList();
                   1965:         if(tag_list != null){
                   1966:             var timestamp = new Date().getTime();
                   1967:             var key = lastresource;
                   1968: 
                   1969:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1970:             // starting with timestamp
                   1971:             var value = timestamp+';';
                   1972: 
                   1973:             // building the list of key-value pairs
                   1974:             for(var i = 0; i < tag_list.length; i++){
                   1975:                 value += tag_list[i]+',';
                   1976:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1977:             }
                   1978: 
                   1979:             // only iterate whole storage if nothing to override
                   1980:             if(localStorage.getItem(key) == null){        
                   1981: 
                   1982:                 // prevent storage from growing large
                   1983:                 if(localStorage.length > 50){
                   1984:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1985:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1986:                     var oldest_key;
                   1987:                     
                   1988:                     for(var i = 1; i < localStorage.length; i++){
                   1989:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1990:                             oldest_key = localStorage.key(i);
                   1991:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1992:                         }
                   1993:                     }
                   1994:                     localStorage.removeItem(oldest_key);
                   1995:                 }
                   1996:             }
                   1997:             localStorage.setItem(key,value);
                   1998:         }
                   1999:     }
                   2000: 
                   2001:     // restore folding status of blocks (on page load)
                   2002:     function restoreState (lastresource) {
                   2003:         if(localStorage.getItem(lastresource) != null){
                   2004:             var key = lastresource;
                   2005:             var value = localStorage.getItem(key);
                   2006:             var regex_delTimestamp = /^\d+;/;
                   2007: 
                   2008:             value.replace(regex_delTimestamp, '');
                   2009: 
                   2010:             var valueArr = value.split(';');
                   2011:             var pairs;
                   2012:             var elements;
                   2013:             for (var i = 0; i < valueArr.length; i++){
                   2014:                 pairs = valueArr[i].split(',');
                   2015:                 elements = document.getElementsByName(pairs[0]);
                   2016: 
                   2017:                 for (var j = 0; j < elements.length; j++){  
                   2018:                     elements[j].style.display = pairs[1];
                   2019:                     if (pairs[1] == "none"){
                   2020:                         var regex_id = /([_\\d]+)\$/;
                   2021:                         regex_id.exec(pairs[0]);
                   2022:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2023:                     }
                   2024:                 }
                   2025:             }
                   2026:         }
                   2027:     }
                   2028: 
                   2029:     function getTagList () {
                   2030:         
                   2031:         var stringToSearch = document.lonhomework.innerHTML;
                   2032: 
                   2033:         var ret = new Array();
                   2034:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2035:         var tag_list = stringToSearch.match(regex_findBlock);
                   2036: 
                   2037:         if(tag_list != null){
                   2038:             for(var i = 0; i < tag_list.length; i++){            
                   2039:                 ret.push(tag_list[i].replace(/"/, ''));
                   2040:             }
                   2041:         }
                   2042:         return ret;
                   2043:     }
                   2044: 
                   2045:     function saveScrollPosition (resource) {
                   2046:         var tag_list = getTagList();
                   2047: 
                   2048:         // we dont always want to jump to the first block
                   2049:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2050:         if(\$(window).scrollTop() > 170){
                   2051:             if(tag_list != null){
                   2052:                 var result;
                   2053:                 for(var i = 0; i < tag_list.length; i++){
                   2054:                     if(isElementInViewport(tag_list[i])){
                   2055:                         result += tag_list[i]+';';
                   2056:                     }
                   2057:                 }
                   2058:                 sessionStorage.setItem('anchor_'+resource, result);
                   2059:             }
                   2060:         } else {
                   2061:             // we dont need to save zero, just delete the item to leave everything tidy
                   2062:             sessionStorage.removeItem('anchor_'+resource);
                   2063:         }
                   2064:     }
                   2065: 
                   2066:     function restoreScrollPosition(resource){
                   2067: 
                   2068:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2069:         if(elem != null){
                   2070:             var tag_list = elem.split(';');
                   2071:             var elem_list;
                   2072: 
                   2073:             for(var i = 0; i < tag_list.length; i++){
                   2074:                 elem_list = document.getElementsByName(tag_list[i]);
                   2075:                 
                   2076:                 if(elem_list.length > 0){
                   2077:                     elem = elem_list[0];
                   2078:                     break;
                   2079:                 }
                   2080:             }
                   2081:             elem.scrollIntoView();
                   2082:         }
                   2083:     }
                   2084: 
                   2085:     function isElementInViewport(el) {
                   2086: 
                   2087:         // change to last element instead of first
                   2088:         var elem = document.getElementsByName(el);
                   2089:         var rect = elem[0].getBoundingClientRect();
                   2090: 
                   2091:         return (
                   2092:             rect.top >= 0 &&
                   2093:             rect.left >= 0 &&
                   2094:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2095:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2096:         );
                   2097:     }
                   2098:     
                   2099:     function autosize(depth){
                   2100:         var cmInst = window['cm'+depth];
                   2101:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2102: 
                   2103:         // is fixed size, switching to dynamic
                   2104:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2105:             cmInst.setSize("","auto");
                   2106:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2107:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2108: 
                   2109:         // is dynamic size, switching to fixed
                   2110:         } else {
                   2111:             cmInst.setSize("","300px");
                   2112:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2113:             sessionStorage.removeItem("autosized_"+depth);
                   2114:         }
                   2115:     }
                   2116: 
1.1248    raeburn  2117: $browse_or_search
1.1205    golterma 2118: 
                   2119: // ]]>
                   2120: </script>
                   2121: COLORFULEDIT
                   2122: }
                   2123: 
                   2124: sub xmleditor_js {
                   2125:     return <<XMLEDIT
                   2126: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2127: <script type="text/javascript">
                   2128: // <![CDATA[>
                   2129: 
                   2130:     function saveScrollPosition (resource) {
                   2131: 
                   2132:         var scrollPos = \$(window).scrollTop();
                   2133:         sessionStorage.setItem(resource,scrollPos);
                   2134:     }
                   2135: 
                   2136:     function restoreScrollPosition(resource){
                   2137: 
                   2138:         var scrollPos = sessionStorage.getItem(resource);
                   2139:         \$(window).scrollTop(scrollPos);
                   2140:     }
                   2141: 
                   2142:     // unless internet explorer
                   2143:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2144: 
                   2145:         \$(document).ready(function() {
                   2146:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2147:         });
                   2148:     }
                   2149: 
                   2150:     // inserts text at cursor position into codemirror (xml editor only)
                   2151:     function insertText(text){
                   2152:         cm.focus();
                   2153:         var curPos = cm.getCursor();
                   2154:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2155:     }
                   2156: // ]]>
                   2157: </script>
                   2158: XMLEDIT
                   2159: }
                   2160: 
                   2161: sub insert_folding_button {
                   2162:     my $curDepth = $Apache::lonxml::curdepth;
                   2163:     my $lastresource = $env{'request.ambiguous'};
                   2164: 
                   2165:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2166:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2167: }
                   2168: 
1.1248    raeburn  2169: sub crsauthor_url {
                   2170:     my ($url) = @_;
                   2171:     if ($url eq '') {
                   2172:         $url = $ENV{'REQUEST_URI'};
                   2173:     }
                   2174:     my ($cnum,$cdom);
                   2175:     if ($env{'request.course.id'}) {
                   2176:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2177:         if ($audom ne '' && $auname ne '') {
                   2178:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2179:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2180:                 $cnum = $auname;
                   2181:                 $cdom = $audom;
                   2182:             }
                   2183:         }
                   2184:     }
                   2185:     return ($cnum,$cdom);
                   2186: }
                   2187: 
                   2188: sub import_crsauthor_form {
1.1265    raeburn  2189:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2190:     return (0) unless ($env{'request.course.id'});
                   2191:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2192:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2193:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2194:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2195:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2196:     my @ids=&Apache::lonnet::current_machine_ids();
                   2197:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2198:     
                   2199:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2200:         $is_home = 1;
                   2201:     }
                   2202:     $relpath = "/priv/$cdom/$cnum";
                   2203:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2204:     my %lt = &Apache::lonlocal::texthash (
                   2205:         fnam => 'Filename',
                   2206:         dire => 'Directory',
                   2207:     );
                   2208:     my $numdirs = scalar(keys(%files));
                   2209:     my (%possexts,$singledir,@singledirfiles);
                   2210:     if ($only) {
                   2211:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2212:     }
                   2213:     my (%nonemptydirs,$possdirs);
                   2214:     if ($numdirs > 1) {
                   2215:         my @order;
                   2216:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2217:             if (ref($files{$key}) eq 'HASH') {
                   2218:                 my $shown = $key;
                   2219:                 if ($key eq '') {
                   2220:                     $shown = '/';
                   2221:                 }
                   2222:                 my @ordered = ();
                   2223:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
                   2224:                     if ($only) {
                   2225:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2226:                         unless ($possexts{lc($ext)}) {
                   2227:                             next;
                   2228:                         }
                   2229:                     }
                   2230:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2231:                     push(@ordered,$file);
                   2232:                 }
                   2233:                 if (@ordered) {
                   2234:                     push(@order,$key);
                   2235:                     $nonemptydirs{$key} = 1;
                   2236:                     $selimport_menus{$key}->{'text'} = $shown;
                   2237:                     $selimport_menus{$key}->{'default'} = '';
                   2238:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2239:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2240:                 }
                   2241:             }
                   2242:         }
                   2243:         $possdirs = scalar(keys(%nonemptydirs));
                   2244:         if ($possdirs > 1) {
                   2245:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2246:             $output = $lt{'dire'}.
                   2247:                       &linked_select_forms($form,'<br />'.
                   2248:                                            $lt{'fnam'},'',
                   2249:                                            $firstselectname,$secondselectname,
                   2250:                                            \%selimport_menus,\@order,
                   2251:                                            $onchangefirst,'',$suffix).'<br />';
                   2252:         } elsif ($possdirs == 1) {
                   2253:             $singledir = (keys(%nonemptydirs))[0];
                   2254:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2255:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2256:             }
                   2257:             delete($selimport_menus{$singledir});
                   2258:         }
                   2259:     } elsif ($numdirs == 1) {
                   2260:         $singledir = (keys(%files))[0];
                   2261:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2262:             if ($only) {
                   2263:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2264:                 unless ($possexts{lc($ext)}) {
                   2265:                     next;
                   2266:                 }
                   2267:             }
                   2268:             push(@singledirfiles,$file);
                   2269:         }
                   2270:         if (@singledirfiles) {
                   2271:             $possdirs == 1;
                   2272:         }
                   2273:     }
                   2274:     if (($possdirs == 1) && (@singledirfiles)) {
                   2275:         my $showdir = $singledir;
                   2276:         if ($singledir eq '') {
                   2277:             $showdir = '/';
                   2278:         }
                   2279:         $output = $lt{'dire'}.
                   2280:                   '<select name="'.$firstselectname.'">'.
                   2281:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2282:                   '</select><br />'.
                   2283:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2284:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2285:         foreach my $file (@singledirfiles) {
                   2286:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2287:         }
                   2288:         $output .= '</select><br />'."\n";
                   2289:     }
                   2290:     return ($possdirs,$output);
                   2291: }
                   2292: 
1.565     albertel 2293: =pod
                   2294: 
1.256     matthew  2295: =head1 Excel and CSV file utility routines
                   2296: 
                   2297: =cut
                   2298: 
                   2299: ###############################################################
                   2300: ###############################################################
                   2301: 
                   2302: =pod
                   2303: 
1.1162    raeburn  2304: =over 4
                   2305: 
1.648     raeburn  2306: =item * &csv_translate($text) 
1.37      matthew  2307: 
1.185     www      2308: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2309: format.
                   2310: 
                   2311: =cut
                   2312: 
1.180     matthew  2313: ###############################################################
                   2314: ###############################################################
1.37      matthew  2315: sub csv_translate {
                   2316:     my $text = shift;
                   2317:     $text =~ s/\"/\"\"/g;
1.209     albertel 2318:     $text =~ s/\n/ /g;
1.37      matthew  2319:     return $text;
                   2320: }
1.180     matthew  2321: 
                   2322: ###############################################################
                   2323: ###############################################################
                   2324: 
                   2325: =pod
                   2326: 
1.648     raeburn  2327: =item * &define_excel_formats()
1.180     matthew  2328: 
                   2329: Define some commonly used Excel cell formats.
                   2330: 
                   2331: Currently supported formats:
                   2332: 
                   2333: =over 4
                   2334: 
                   2335: =item header
                   2336: 
                   2337: =item bold
                   2338: 
                   2339: =item h1
                   2340: 
                   2341: =item h2
                   2342: 
                   2343: =item h3
                   2344: 
1.256     matthew  2345: =item h4
                   2346: 
                   2347: =item i
                   2348: 
1.180     matthew  2349: =item date
                   2350: 
                   2351: =back
                   2352: 
                   2353: Inputs: $workbook
                   2354: 
                   2355: Returns: $format, a hash reference.
                   2356: 
1.1057    foxr     2357: 
1.180     matthew  2358: =cut
                   2359: 
                   2360: ###############################################################
                   2361: ###############################################################
                   2362: sub define_excel_formats {
                   2363:     my ($workbook) = @_;
                   2364:     my $format;
                   2365:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2366:                                                 bottom    => 1,
                   2367:                                                 align     => 'center');
                   2368:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2369:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2370:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2371:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2372:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2373:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2374:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2375:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2376:     return $format;
                   2377: }
                   2378: 
                   2379: ###############################################################
                   2380: ###############################################################
1.113     bowersj2 2381: 
                   2382: =pod
                   2383: 
1.648     raeburn  2384: =item * &create_workbook()
1.255     matthew  2385: 
                   2386: Create an Excel worksheet.  If it fails, output message on the
                   2387: request object and return undefs.
                   2388: 
                   2389: Inputs: Apache request object
                   2390: 
                   2391: Returns (undef) on failure, 
                   2392:     Excel worksheet object, scalar with filename, and formats 
                   2393:     from &Apache::loncommon::define_excel_formats on success
                   2394: 
                   2395: =cut
                   2396: 
                   2397: ###############################################################
                   2398: ###############################################################
                   2399: sub create_workbook {
                   2400:     my ($r) = @_;
                   2401:         #
                   2402:     # Create the excel spreadsheet
                   2403:     my $filename = '/prtspool/'.
1.258     albertel 2404:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2405:         time.'_'.rand(1000000000).'.xls';
                   2406:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2407:     if (! defined($workbook)) {
                   2408:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2409:         $r->print(
                   2410:             '<p class="LC_error">'
                   2411:            .&mt('Problems occurred in creating the new Excel file.')
                   2412:            .' '.&mt('This error has been logged.')
                   2413:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2414:            .'</p>'
                   2415:         );
1.255     matthew  2416:         return (undef);
                   2417:     }
                   2418:     #
1.1014    foxr     2419:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2420:     #
                   2421:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2422:     return ($workbook,$filename,$format);
                   2423: }
                   2424: 
                   2425: ###############################################################
                   2426: ###############################################################
                   2427: 
                   2428: =pod
                   2429: 
1.648     raeburn  2430: =item * &create_text_file()
1.113     bowersj2 2431: 
1.542     raeburn  2432: Create a file to write to and eventually make available to the user.
1.256     matthew  2433: If file creation fails, outputs an error message on the request object and 
                   2434: return undefs.
1.113     bowersj2 2435: 
1.256     matthew  2436: Inputs: Apache request object, and file suffix
1.113     bowersj2 2437: 
1.256     matthew  2438: Returns (undef) on failure, 
                   2439:     Filehandle and filename on success.
1.113     bowersj2 2440: 
                   2441: =cut
                   2442: 
1.256     matthew  2443: ###############################################################
                   2444: ###############################################################
                   2445: sub create_text_file {
                   2446:     my ($r,$suffix) = @_;
                   2447:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2448:     my $fh;
                   2449:     my $filename = '/prtspool/'.
1.258     albertel 2450:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2451:         time.'_'.rand(1000000000).'.'.$suffix;
                   2452:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2453:     if (! defined($fh)) {
                   2454:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2455:         $r->print(
                   2456:             '<p class="LC_error">'
                   2457:            .&mt('Problems occurred in creating the output file.')
                   2458:            .' '.&mt('This error has been logged.')
                   2459:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2460:            .'</p>'
                   2461:         );
1.113     bowersj2 2462:     }
1.256     matthew  2463:     return ($fh,$filename)
1.113     bowersj2 2464: }
                   2465: 
                   2466: 
1.256     matthew  2467: =pod 
1.113     bowersj2 2468: 
                   2469: =back
                   2470: 
                   2471: =cut
1.37      matthew  2472: 
                   2473: ###############################################################
1.33      matthew  2474: ##        Home server <option> list generating code          ##
                   2475: ###############################################################
1.35      matthew  2476: 
1.169     www      2477: # ------------------------------------------
                   2478: 
                   2479: sub domain_select {
                   2480:     my ($name,$value,$multiple)=@_;
                   2481:     my %domains=map { 
1.514     albertel 2482: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2483:     } &Apache::lonnet::all_domains();
1.169     www      2484:     if ($multiple) {
                   2485: 	$domains{''}=&mt('Any domain');
1.550     albertel 2486: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2487: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2488:     } else {
1.550     albertel 2489: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2490: 	return &select_form($name,$value,\%domains);
1.169     www      2491:     }
                   2492: }
                   2493: 
1.282     albertel 2494: #-------------------------------------------
                   2495: 
                   2496: =pod
                   2497: 
1.519     raeburn  2498: =head1 Routines for form select boxes
                   2499: 
                   2500: =over 4
                   2501: 
1.648     raeburn  2502: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2503: 
                   2504: Returns a string containing a <select> element int multiple mode
                   2505: 
                   2506: 
                   2507: Args:
                   2508:   $name - name of the <select> element
1.506     raeburn  2509:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2510:   $size - number of rows long the select element is
1.283     albertel 2511:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2512:           (shown text should already have been &mt())
1.506     raeburn  2513:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2514: 
1.282     albertel 2515: =cut
                   2516: 
                   2517: #-------------------------------------------
1.169     www      2518: sub multiple_select_form {
1.284     albertel 2519:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2520:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2521:     my $output='';
1.191     matthew  2522:     if (! defined($size)) {
                   2523:         $size = 4;
1.283     albertel 2524:         if (scalar(keys(%$hash))<4) {
                   2525:             $size = scalar(keys(%$hash));
1.191     matthew  2526:         }
                   2527:     }
1.734     bisitz   2528:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2529:     my @order;
1.506     raeburn  2530:     if (ref($order) eq 'ARRAY')  {
                   2531:         @order = @{$order};
                   2532:     } else {
                   2533:         @order = sort(keys(%$hash));
1.501     banghart 2534:     }
                   2535:     if (exists($$hash{'select_form_order'})) {
                   2536:         @order = @{$$hash{'select_form_order'}};
                   2537:     }
                   2538:         
1.284     albertel 2539:     foreach my $key (@order) {
1.356     albertel 2540:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2541:         $output.='selected="selected" ' if ($selected{$key});
                   2542:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2543:     }
                   2544:     $output.="</select>\n";
                   2545:     return $output;
                   2546: }
                   2547: 
1.88      www      2548: #-------------------------------------------
                   2549: 
                   2550: =pod
                   2551: 
1.1254    raeburn  2552: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2553: 
                   2554: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2555: allow a user to select options from a ref to a hash containing:
                   2556: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2557: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2558: An optional arg -- $readonly -- if true will cause the select form
                   2559: to be disabled, e.g., for the case where an instructor has a section-
                   2560: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2561: 
1.88      www      2562: See lonrights.pm for an example invocation and use.
                   2563: 
                   2564: =cut
                   2565: 
                   2566: #-------------------------------------------
                   2567: sub select_form {
1.1228    raeburn  2568:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2569:     return unless (ref($hashref) eq 'HASH');
                   2570:     if ($onchange) {
                   2571:         $onchange = ' onchange="'.$onchange.'"';
                   2572:     }
1.1228    raeburn  2573:     my $disabled;
                   2574:     if ($readonly) {
                   2575:         $disabled = ' disabled="disabled"';
                   2576:     }
                   2577:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2578:     my @keys;
1.970     raeburn  2579:     if (exists($hashref->{'select_form_order'})) {
                   2580: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2581:     } else {
1.970     raeburn  2582: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2583:     }
1.356     albertel 2584:     foreach my $key (@keys) {
                   2585:         $selectform.=
                   2586: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2587:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2588:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2589:     }
                   2590:     $selectform.="</select>";
                   2591:     return $selectform;
                   2592: }
                   2593: 
1.475     www      2594: # For display filters
                   2595: 
                   2596: sub display_filter {
1.1074    raeburn  2597:     my ($context) = @_;
1.475     www      2598:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2599:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2600:     my $phraseinput = 'hidden';
                   2601:     my $includeinput = 'hidden';
                   2602:     my ($checked,$includetypestext);
                   2603:     if ($env{'form.displayfilter'} eq 'containing') {
                   2604:         $phraseinput = 'text'; 
                   2605:         if ($context eq 'parmslog') {
                   2606:             $includeinput = 'checkbox';
                   2607:             if ($env{'form.includetypes'}) {
                   2608:                 $checked = ' checked="checked"';
                   2609:             }
                   2610:             $includetypestext = &mt('Include parameter types');
                   2611:         }
                   2612:     } else {
                   2613:         $includetypestext = '&nbsp;';
                   2614:     }
                   2615:     my ($additional,$secondid,$thirdid);
                   2616:     if ($context eq 'parmslog') {
                   2617:         $additional = 
                   2618:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2619:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2620:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2621:             '</label>';
                   2622:         $secondid = 'includetypes';
                   2623:         $thirdid = 'includetypestext';
                   2624:     }
                   2625:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2626:                                                     '$secondid','$thirdid')";
                   2627:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2628: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2629: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2630: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2631:            &mt('Filter: [_1]',
1.477     www      2632: 	   &select_form($env{'form.displayfilter'},
                   2633: 			'displayfilter',
1.970     raeburn  2634: 			{'currentfolder' => 'Current folder/page',
1.477     www      2635: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2636: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2637: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2638:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2639:                          '" />'.$additional;
                   2640: }
                   2641: 
                   2642: sub display_filter_js {
                   2643:     my $includetext = &mt('Include parameter types');
                   2644:     return <<"ENDJS";
                   2645:   
                   2646: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2647:     var firstType = 'hidden';
                   2648:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2649:         firstType = 'text';
                   2650:     }
                   2651:     firstObject = document.getElementById(firstid);
                   2652:     if (typeof(firstObject) == 'object') {
                   2653:         if (firstObject.type != firstType) {
                   2654:             changeInputType(firstObject,firstType);
                   2655:         }
                   2656:     }
                   2657:     if (context == 'parmslog') {
                   2658:         var secondType = 'hidden';
                   2659:         if (firstType == 'text') {
                   2660:             secondType = 'checkbox';
                   2661:         }
                   2662:         secondObject = document.getElementById(secondid);  
                   2663:         if (typeof(secondObject) == 'object') {
                   2664:             if (secondObject.type != secondType) {
                   2665:                 changeInputType(secondObject,secondType);
                   2666:             }
                   2667:         }
                   2668:         var textItem = document.getElementById(thirdid);
                   2669:         var currtext = textItem.innerHTML;
                   2670:         var newtext;
                   2671:         if (firstType == 'text') {
                   2672:             newtext = '$includetext';
                   2673:         } else {
                   2674:             newtext = '&nbsp;';
                   2675:         }
                   2676:         if (currtext != newtext) {
                   2677:             textItem.innerHTML = newtext;
                   2678:         }
                   2679:     }
                   2680:     return;
                   2681: }
                   2682: 
                   2683: function changeInputType(oldObject,newType) {
                   2684:     var newObject = document.createElement('input');
                   2685:     newObject.type = newType;
                   2686:     if (oldObject.size) {
                   2687:         newObject.size = oldObject.size;
                   2688:     }
                   2689:     if (oldObject.value) {
                   2690:         newObject.value = oldObject.value;
                   2691:     }
                   2692:     if (oldObject.name) {
                   2693:         newObject.name = oldObject.name;
                   2694:     }
                   2695:     if (oldObject.id) {
                   2696:         newObject.id = oldObject.id;
                   2697:     }
                   2698:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2699:     return;
                   2700: }
                   2701: 
                   2702: ENDJS
1.475     www      2703: }
                   2704: 
1.167     www      2705: sub gradeleveldescription {
                   2706:     my $gradelevel=shift;
                   2707:     my %gradelevels=(0 => 'Not specified',
                   2708: 		     1 => 'Grade 1',
                   2709: 		     2 => 'Grade 2',
                   2710: 		     3 => 'Grade 3',
                   2711: 		     4 => 'Grade 4',
                   2712: 		     5 => 'Grade 5',
                   2713: 		     6 => 'Grade 6',
                   2714: 		     7 => 'Grade 7',
                   2715: 		     8 => 'Grade 8',
                   2716: 		     9 => 'Grade 9',
                   2717: 		     10 => 'Grade 10',
                   2718: 		     11 => 'Grade 11',
                   2719: 		     12 => 'Grade 12',
                   2720: 		     13 => 'Grade 13',
                   2721: 		     14 => '100 Level',
                   2722: 		     15 => '200 Level',
                   2723: 		     16 => '300 Level',
                   2724: 		     17 => '400 Level',
                   2725: 		     18 => 'Graduate Level');
                   2726:     return &mt($gradelevels{$gradelevel});
                   2727: }
                   2728: 
1.163     www      2729: sub select_level_form {
                   2730:     my ($deflevel,$name)=@_;
                   2731:     unless ($deflevel) { $deflevel=0; }
1.167     www      2732:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2733:     for (my $i=0; $i<=18; $i++) {
                   2734:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2735:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2736:                 ">".&gradeleveldescription($i)."</option>\n";
                   2737:     }
                   2738:     $selectform.="</select>";
                   2739:     return $selectform;
1.163     www      2740: }
1.167     www      2741: 
1.35      matthew  2742: #-------------------------------------------
                   2743: 
1.45      matthew  2744: =pod
                   2745: 
1.1256    raeburn  2746: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2747: 
                   2748: Returns a string containing a <select name='$name' size='1'> form to 
                   2749: allow a user to select the domain to preform an operation in.  
                   2750: See loncreateuser.pm for an example invocation and use.
                   2751: 
1.90      www      2752: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2753: selected");
                   2754: 
1.743     raeburn  2755: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2756: 
1.910     raeburn  2757: 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.
                   2758: 
1.1121    raeburn  2759: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2760: 
                   2761: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2762: 
1.1256    raeburn  2763: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2764: 
1.35      matthew  2765: =cut
                   2766: 
                   2767: #-------------------------------------------
1.34      matthew  2768: sub select_dom_form {
1.1256    raeburn  2769:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2770:     if ($onchange) {
1.874     raeburn  2771:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2772:     }
1.1256    raeburn  2773:     if ($disabled) {
                   2774:         $disabled = ' disabled="disabled"';
                   2775:     }
1.1121    raeburn  2776:     my (@domains,%exclude);
1.910     raeburn  2777:     if (ref($incdoms) eq 'ARRAY') {
                   2778:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2779:     } else {
                   2780:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2781:     }
1.90      www      2782:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2783:     if (ref($excdoms) eq 'ARRAY') {
                   2784:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2785:     }
1.1256    raeburn  2786:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2787:     foreach my $dom (@domains) {
1.1121    raeburn  2788:         next if ($exclude{$dom});
1.356     albertel 2789:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2790:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2791:         if ($showdomdesc) {
                   2792:             if ($dom ne '') {
                   2793:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2794:                 if ($domdesc ne '') {
                   2795:                     $selectdomain .= ' ('.$domdesc.')';
                   2796:                 }
                   2797:             } 
                   2798:         }
                   2799:         $selectdomain .= "</option>\n";
1.34      matthew  2800:     }
                   2801:     $selectdomain.="</select>";
                   2802:     return $selectdomain;
                   2803: }
                   2804: 
1.35      matthew  2805: #-------------------------------------------
                   2806: 
1.45      matthew  2807: =pod
                   2808: 
1.648     raeburn  2809: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2810: 
1.586     raeburn  2811: input: 4 arguments (two required, two optional) - 
                   2812:     $domain - domain of new user
                   2813:     $name - name of form element
                   2814:     $default - Value of 'default' causes a default item to be first 
                   2815:                             option, and selected by default. 
                   2816:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2817:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2818: output: returns 2 items: 
1.586     raeburn  2819: (a) form element which contains either:
                   2820:    (i) <select name="$name">
                   2821:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2822:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2823:        </select>
                   2824:        form item if there are multiple library servers in $domain, or
                   2825:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2826:        if there is only one library server in $domain.
                   2827: 
                   2828: (b) number of library servers found.
                   2829: 
                   2830: See loncreateuser.pm for example of use.
1.35      matthew  2831: 
                   2832: =cut
                   2833: 
                   2834: #-------------------------------------------
1.586     raeburn  2835: sub home_server_form_item {
                   2836:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2837:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2838:     my $result;
                   2839:     my $numlib = keys(%servers);
                   2840:     if ($numlib > 1) {
                   2841:         $result .= '<select name="'.$name.'" />'."\n";
                   2842:         if ($default) {
1.804     bisitz   2843:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2844:                        '</option>'."\n";
                   2845:         }
                   2846:         foreach my $hostid (sort(keys(%servers))) {
                   2847:             $result.= '<option value="'.$hostid.'">'.
                   2848: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2849:         }
                   2850:         $result .= '</select>'."\n";
                   2851:     } elsif ($numlib == 1) {
                   2852:         my $hostid;
                   2853:         foreach my $item (keys(%servers)) {
                   2854:             $hostid = $item;
                   2855:         }
                   2856:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2857:                    $hostid.'" />';
                   2858:                    if (!$hide) {
                   2859:                        $result .= $hostid.' '.$servers{$hostid};
                   2860:                    }
                   2861:                    $result .= "\n";
                   2862:     } elsif ($default) {
                   2863:         $result .= '<input type="hidden" name="'.$name.
                   2864:                    '" value="default" />';
                   2865:                    if (!$hide) {
                   2866:                        $result .= &mt('default');
                   2867:                    }
                   2868:                    $result .= "\n";
1.33      matthew  2869:     }
1.586     raeburn  2870:     return ($result,$numlib);
1.33      matthew  2871: }
1.112     bowersj2 2872: 
                   2873: =pod
                   2874: 
1.534     albertel 2875: =back 
                   2876: 
1.112     bowersj2 2877: =cut
1.87      matthew  2878: 
                   2879: ###############################################################
1.112     bowersj2 2880: ##                  Decoding User Agent                      ##
1.87      matthew  2881: ###############################################################
                   2882: 
                   2883: =pod
                   2884: 
1.112     bowersj2 2885: =head1 Decoding the User Agent
                   2886: 
                   2887: =over 4
                   2888: 
                   2889: =item * &decode_user_agent()
1.87      matthew  2890: 
                   2891: Inputs: $r
                   2892: 
                   2893: Outputs:
                   2894: 
                   2895: =over 4
                   2896: 
1.112     bowersj2 2897: =item * $httpbrowser
1.87      matthew  2898: 
1.112     bowersj2 2899: =item * $clientbrowser
1.87      matthew  2900: 
1.112     bowersj2 2901: =item * $clientversion
1.87      matthew  2902: 
1.112     bowersj2 2903: =item * $clientmathml
1.87      matthew  2904: 
1.112     bowersj2 2905: =item * $clientunicode
1.87      matthew  2906: 
1.112     bowersj2 2907: =item * $clientos
1.87      matthew  2908: 
1.1137    raeburn  2909: =item * $clientmobile
                   2910: 
1.1141    raeburn  2911: =item * $clientinfo
                   2912: 
1.1194    raeburn  2913: =item * $clientosversion
                   2914: 
1.87      matthew  2915: =back
                   2916: 
1.157     matthew  2917: =back 
                   2918: 
1.87      matthew  2919: =cut
                   2920: 
                   2921: ###############################################################
                   2922: ###############################################################
                   2923: sub decode_user_agent {
1.247     albertel 2924:     my ($r)=@_;
1.87      matthew  2925:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2926:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2927:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2928:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2929:     my $clientbrowser='unknown';
                   2930:     my $clientversion='0';
                   2931:     my $clientmathml='';
                   2932:     my $clientunicode='0';
1.1137    raeburn  2933:     my $clientmobile=0;
1.1194    raeburn  2934:     my $clientosversion='';
1.87      matthew  2935:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2936:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2937: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2938: 	    $clientbrowser=$bname;
                   2939:             $httpbrowser=~/$vreg/i;
                   2940: 	    $clientversion=$1;
                   2941:             $clientmathml=($clientversion>=$minv);
                   2942:             $clientunicode=($clientversion>=$univ);
                   2943: 	}
                   2944:     }
                   2945:     my $clientos='unknown';
1.1141    raeburn  2946:     my $clientinfo;
1.87      matthew  2947:     if (($httpbrowser=~/linux/i) ||
                   2948:         ($httpbrowser=~/unix/i) ||
                   2949:         ($httpbrowser=~/ux/i) ||
                   2950:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2951:     if (($httpbrowser=~/vax/i) ||
                   2952:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2953:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2954:     if (($httpbrowser=~/mac/i) ||
                   2955:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2956:     if ($httpbrowser=~/win/i) {
                   2957:         $clientos='win';
                   2958:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2959:             $clientosversion = $1;
                   2960:         }
                   2961:     }
1.87      matthew  2962:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2963:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2964:         $clientmobile=lc($1);
                   2965:     }
1.1141    raeburn  2966:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2967:         $clientinfo = 'firefox-'.$1;
                   2968:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2969:         $clientinfo = 'chromeframe-'.$1;
                   2970:     }
1.87      matthew  2971:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2972:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2973:             $clientosversion);
1.87      matthew  2974: }
                   2975: 
1.32      matthew  2976: ###############################################################
                   2977: ##    Authentication changing form generation subroutines    ##
                   2978: ###############################################################
                   2979: ##
                   2980: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2981: ## hash, and have reasonable default values.
                   2982: ##
                   2983: ##    formname = the name given in the <form> tag.
1.35      matthew  2984: #-------------------------------------------
                   2985: 
1.45      matthew  2986: =pod
                   2987: 
1.112     bowersj2 2988: =head1 Authentication Routines
                   2989: 
                   2990: =over 4
                   2991: 
1.648     raeburn  2992: =item * &authform_xxxxxx()
1.35      matthew  2993: 
                   2994: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2995: handle some of the conveniences required for authentication forms.  
                   2996: This is not an optimal method, but it works.  
                   2997: 
                   2998: =over 4
                   2999: 
1.112     bowersj2 3000: =item * authform_header
1.35      matthew  3001: 
1.112     bowersj2 3002: =item * authform_authorwarning
1.35      matthew  3003: 
1.112     bowersj2 3004: =item * authform_nochange
1.35      matthew  3005: 
1.112     bowersj2 3006: =item * authform_kerberos
1.35      matthew  3007: 
1.112     bowersj2 3008: =item * authform_internal
1.35      matthew  3009: 
1.112     bowersj2 3010: =item * authform_filesystem
1.35      matthew  3011: 
                   3012: =back
                   3013: 
1.648     raeburn  3014: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3015: 
1.35      matthew  3016: =cut
                   3017: 
                   3018: #-------------------------------------------
1.32      matthew  3019: sub authform_header{  
                   3020:     my %in = (
                   3021:         formname => 'cu',
1.80      albertel 3022:         kerb_def_dom => '',
1.32      matthew  3023:         @_,
                   3024:     );
                   3025:     $in{'formname'} = 'document.' . $in{'formname'};
                   3026:     my $result='';
1.80      albertel 3027: 
                   3028: #---------------------------------------------- Code for upper case translation
                   3029:     my $Javascript_toUpperCase;
                   3030:     unless ($in{kerb_def_dom}) {
                   3031:         $Javascript_toUpperCase =<<"END";
                   3032:         switch (choice) {
                   3033:            case 'krb': currentform.elements[choicearg].value =
                   3034:                currentform.elements[choicearg].value.toUpperCase();
                   3035:                break;
                   3036:            default:
                   3037:         }
                   3038: END
                   3039:     } else {
                   3040:         $Javascript_toUpperCase = "";
                   3041:     }
                   3042: 
1.165     raeburn  3043:     my $radioval = "'nochange'";
1.591     raeburn  3044:     if (defined($in{'curr_authtype'})) {
                   3045:         if ($in{'curr_authtype'} ne '') {
                   3046:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3047:         }
1.174     matthew  3048:     }
1.165     raeburn  3049:     my $argfield = 'null';
1.591     raeburn  3050:     if (defined($in{'mode'})) {
1.165     raeburn  3051:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3052:             if (defined($in{'curr_autharg'})) {
                   3053:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3054:                     $argfield = "'$in{'curr_autharg'}'";
                   3055:                 }
                   3056:             }
                   3057:         }
                   3058:     }
                   3059: 
1.32      matthew  3060:     $result.=<<"END";
                   3061: var current = new Object();
1.165     raeburn  3062: current.radiovalue = $radioval;
                   3063: current.argfield = $argfield;
1.32      matthew  3064: 
                   3065: function changed_radio(choice,currentform) {
                   3066:     var choicearg = choice + 'arg';
                   3067:     // If a radio button in changed, we need to change the argfield
                   3068:     if (current.radiovalue != choice) {
                   3069:         current.radiovalue = choice;
                   3070:         if (current.argfield != null) {
                   3071:             currentform.elements[current.argfield].value = '';
                   3072:         }
                   3073:         if (choice == 'nochange') {
                   3074:             current.argfield = null;
                   3075:         } else {
                   3076:             current.argfield = choicearg;
                   3077:             switch(choice) {
                   3078:                 case 'krb': 
                   3079:                     currentform.elements[current.argfield].value = 
                   3080:                         "$in{'kerb_def_dom'}";
                   3081:                 break;
                   3082:               default:
                   3083:                 break;
                   3084:             }
                   3085:         }
                   3086:     }
                   3087:     return;
                   3088: }
1.22      www      3089: 
1.32      matthew  3090: function changed_text(choice,currentform) {
                   3091:     var choicearg = choice + 'arg';
                   3092:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3093:         $Javascript_toUpperCase
1.32      matthew  3094:         // clear old field
                   3095:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3096:             currentform.elements[current.argfield].value = '';
                   3097:         }
                   3098:         current.argfield = choicearg;
                   3099:     }
                   3100:     set_auth_radio_buttons(choice,currentform);
                   3101:     return;
1.20      www      3102: }
1.32      matthew  3103: 
                   3104: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3105:     var numauthchoices = currentform.login.length;
                   3106:     if (typeof numauthchoices  == "undefined") {
                   3107:         return;
                   3108:     } 
1.32      matthew  3109:     var i=0;
1.986     raeburn  3110:     while (i < numauthchoices) {
1.32      matthew  3111:         if (currentform.login[i].value == newvalue) { break; }
                   3112:         i++;
                   3113:     }
1.986     raeburn  3114:     if (i == numauthchoices) {
1.32      matthew  3115:         return;
                   3116:     }
                   3117:     current.radiovalue = newvalue;
                   3118:     currentform.login[i].checked = true;
                   3119:     return;
                   3120: }
                   3121: END
                   3122:     return $result;
                   3123: }
                   3124: 
1.1106    raeburn  3125: sub authform_authorwarning {
1.32      matthew  3126:     my $result='';
1.144     matthew  3127:     $result='<i>'.
                   3128:         &mt('As a general rule, only authors or co-authors should be '.
                   3129:             'filesystem authenticated '.
                   3130:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3131:     return $result;
                   3132: }
                   3133: 
1.1106    raeburn  3134: sub authform_nochange {
1.32      matthew  3135:     my %in = (
                   3136:               formname => 'document.cu',
                   3137:               kerb_def_dom => 'MSU.EDU',
                   3138:               @_,
                   3139:           );
1.1106    raeburn  3140:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3141:     my $result;
1.1104    raeburn  3142:     if (!$authnum) {
1.1105    raeburn  3143:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3144:     } else {
                   3145:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3146:                   '<input type="radio" name="login" value="nochange" '.
                   3147:                   'checked="checked" onclick="'.
1.281     albertel 3148:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3149: 	    '</label>';
1.586     raeburn  3150:     }
1.32      matthew  3151:     return $result;
                   3152: }
                   3153: 
1.591     raeburn  3154: sub authform_kerberos {
1.32      matthew  3155:     my %in = (
                   3156:               formname => 'document.cu',
                   3157:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3158:               kerb_def_auth => 'krb4',
1.32      matthew  3159:               @_,
                   3160:               );
1.586     raeburn  3161:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3162:         $autharg,$jscall,$disabled);
1.1106    raeburn  3163:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3164:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3165:        $check5 = ' checked="checked"';
1.80      albertel 3166:     } else {
1.772     bisitz   3167:        $check4 = ' checked="checked"';
1.80      albertel 3168:     }
1.1259    raeburn  3169:     if ($in{'readonly'}) {
                   3170:         $disabled = ' disabled="disabled"';
                   3171:     }
1.165     raeburn  3172:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3173:     if (defined($in{'curr_authtype'})) {
                   3174:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3175:             $krbcheck = ' checked="checked"';
1.623     raeburn  3176:             if (defined($in{'mode'})) {
                   3177:                 if ($in{'mode'} eq 'modifyuser') {
                   3178:                     $krbcheck = '';
                   3179:                 }
                   3180:             }
1.591     raeburn  3181:             if (defined($in{'curr_kerb_ver'})) {
                   3182:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3183:                     $check5 = ' checked="checked"';
1.591     raeburn  3184:                     $check4 = '';
                   3185:                 } else {
1.772     bisitz   3186:                     $check4 = ' checked="checked"';
1.591     raeburn  3187:                     $check5 = '';
                   3188:                 }
1.586     raeburn  3189:             }
1.591     raeburn  3190:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3191:                 $krbarg = $in{'curr_autharg'};
                   3192:             }
1.586     raeburn  3193:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3194:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3195:                     $result = 
                   3196:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3197:         $in{'curr_autharg'},$krbver);
                   3198:                 } else {
                   3199:                     $result =
                   3200:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3201:                 }
                   3202:                 return $result; 
                   3203:             }
                   3204:         }
                   3205:     } else {
                   3206:         if ($authnum == 1) {
1.784     bisitz   3207:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3208:         }
                   3209:     }
1.586     raeburn  3210:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3211:         return;
1.587     raeburn  3212:     } elsif ($authtype eq '') {
1.591     raeburn  3213:         if (defined($in{'mode'})) {
1.587     raeburn  3214:             if ($in{'mode'} eq 'modifycourse') {
                   3215:                 if ($authnum == 1) {
1.1259    raeburn  3216:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3217:                 }
                   3218:             }
                   3219:         }
1.586     raeburn  3220:     }
                   3221:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3222:     if ($authtype eq '') {
                   3223:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3224:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3225:                     $krbcheck.$disabled.' />';
1.586     raeburn  3226:     }
                   3227:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3228:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3229:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3230:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3231:          $in{'curr_authtype'} eq 'krb4')) {
                   3232:         $result .= &mt
1.144     matthew  3233:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3234:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3235:          '<label>'.$authtype,
1.281     albertel 3236:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3237:              'value="'.$krbarg.'" '.
1.1259    raeburn  3238:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3239:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3240:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3241: 	 '</label>');
1.586     raeburn  3242:     } elsif ($can_assign{'krb4'}) {
                   3243:         $result .= &mt
                   3244:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3245:          '[_3] Version 4 [_4]',
                   3246:          '<label>'.$authtype,
                   3247:          '</label><input type="text" size="10" name="krbarg" '.
                   3248:              'value="'.$krbarg.'" '.
1.1259    raeburn  3249:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3250:          '<label><input type="hidden" name="krbver" value="4" />',
                   3251:          '</label>');
                   3252:     } elsif ($can_assign{'krb5'}) {
                   3253:         $result .= &mt
                   3254:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3255:          '[_3] Version 5 [_4]',
                   3256:          '<label>'.$authtype,
                   3257:          '</label><input type="text" size="10" name="krbarg" '.
                   3258:              'value="'.$krbarg.'" '.
1.1259    raeburn  3259:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3260:          '<label><input type="hidden" name="krbver" value="5" />',
                   3261:          '</label>');
                   3262:     }
1.32      matthew  3263:     return $result;
                   3264: }
                   3265: 
1.1106    raeburn  3266: sub authform_internal {
1.586     raeburn  3267:     my %in = (
1.32      matthew  3268:                 formname => 'document.cu',
                   3269:                 kerb_def_dom => 'MSU.EDU',
                   3270:                 @_,
                   3271:                 );
1.1259    raeburn  3272:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3273:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3274:     if ($in{'readonly'}) {
                   3275:         $disabled = ' disabled="disabled"';
                   3276:     }
1.591     raeburn  3277:     if (defined($in{'curr_authtype'})) {
                   3278:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3279:             if ($can_assign{'int'}) {
1.772     bisitz   3280:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3281:                 if (defined($in{'mode'})) {
                   3282:                     if ($in{'mode'} eq 'modifyuser') {
                   3283:                         $intcheck = '';
                   3284:                     }
                   3285:                 }
1.591     raeburn  3286:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3287:                     $intarg = $in{'curr_autharg'};
                   3288:                 }
                   3289:             } else {
                   3290:                 $result = &mt('Currently internally authenticated.');
                   3291:                 return $result;
1.165     raeburn  3292:             }
                   3293:         }
1.586     raeburn  3294:     } else {
                   3295:         if ($authnum == 1) {
1.784     bisitz   3296:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3297:         }
                   3298:     }
                   3299:     if (!$can_assign{'int'}) {
                   3300:         return;
1.587     raeburn  3301:     } elsif ($authtype eq '') {
1.591     raeburn  3302:         if (defined($in{'mode'})) {
1.587     raeburn  3303:             if ($in{'mode'} eq 'modifycourse') {
                   3304:                 if ($authnum == 1) {
1.1259    raeburn  3305:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3306:                 }
                   3307:             }
                   3308:         }
1.165     raeburn  3309:     }
1.586     raeburn  3310:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3311:     if ($authtype eq '') {
                   3312:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3313:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3314:     }
1.605     bisitz   3315:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3316:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3317:     $result = &mt
1.144     matthew  3318:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3319:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3320:     $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  3321:     return $result;
                   3322: }
                   3323: 
1.1104    raeburn  3324: sub authform_local {
1.32      matthew  3325:     my %in = (
                   3326:               formname => 'document.cu',
                   3327:               kerb_def_dom => 'MSU.EDU',
                   3328:               @_,
                   3329:               );
1.1259    raeburn  3330:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3331:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3332:     if ($in{'readonly'}) {
                   3333:         $disabled = ' disabled="disabled"';
                   3334:     } 
1.591     raeburn  3335:     if (defined($in{'curr_authtype'})) {
                   3336:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3337:             if ($can_assign{'loc'}) {
1.772     bisitz   3338:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3339:                 if (defined($in{'mode'})) {
                   3340:                     if ($in{'mode'} eq 'modifyuser') {
                   3341:                         $loccheck = '';
                   3342:                     }
                   3343:                 }
1.591     raeburn  3344:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3345:                     $locarg = $in{'curr_autharg'};
                   3346:                 }
                   3347:             } else {
                   3348:                 $result = &mt('Currently using local (institutional) authentication.');
                   3349:                 return $result;
1.165     raeburn  3350:             }
                   3351:         }
1.586     raeburn  3352:     } else {
                   3353:         if ($authnum == 1) {
1.784     bisitz   3354:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3355:         }
                   3356:     }
                   3357:     if (!$can_assign{'loc'}) {
                   3358:         return;
1.587     raeburn  3359:     } elsif ($authtype eq '') {
1.591     raeburn  3360:         if (defined($in{'mode'})) {
1.587     raeburn  3361:             if ($in{'mode'} eq 'modifycourse') {
                   3362:                 if ($authnum == 1) {
1.1259    raeburn  3363:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3364:                 }
                   3365:             }
                   3366:         }
1.165     raeburn  3367:     }
1.586     raeburn  3368:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3369:     if ($authtype eq '') {
                   3370:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3371:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3372:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3373:     }
                   3374:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3375:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3376:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3377:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3378:     return $result;
                   3379: }
                   3380: 
1.1106    raeburn  3381: sub authform_filesystem {
1.32      matthew  3382:     my %in = (
                   3383:               formname => 'document.cu',
                   3384:               kerb_def_dom => 'MSU.EDU',
                   3385:               @_,
                   3386:               );
1.1259    raeburn  3387:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3388:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3389:     if ($in{'readonly'}) {
                   3390:         $disabled = ' disabled="disabled"';
                   3391:     }
1.591     raeburn  3392:     if (defined($in{'curr_authtype'})) {
                   3393:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3394:             if ($can_assign{'fsys'}) {
1.772     bisitz   3395:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3396:                 if (defined($in{'mode'})) {
                   3397:                     if ($in{'mode'} eq 'modifyuser') {
                   3398:                         $fsyscheck = '';
                   3399:                     }
                   3400:                 }
1.586     raeburn  3401:             } else {
                   3402:                 $result = &mt('Currently Filesystem Authenticated.');
                   3403:                 return $result;
1.1259    raeburn  3404:             }
1.586     raeburn  3405:         }
                   3406:     } else {
                   3407:         if ($authnum == 1) {
1.784     bisitz   3408:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3409:         }
                   3410:     }
                   3411:     if (!$can_assign{'fsys'}) {
                   3412:         return;
1.587     raeburn  3413:     } elsif ($authtype eq '') {
1.591     raeburn  3414:         if (defined($in{'mode'})) {
1.587     raeburn  3415:             if ($in{'mode'} eq 'modifycourse') {
                   3416:                 if ($authnum == 1) {
1.1259    raeburn  3417:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3418:                 }
                   3419:             }
                   3420:         }
1.586     raeburn  3421:     }
                   3422:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3423:     if ($authtype eq '') {
                   3424:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3425:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3426:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3427:     }
                   3428:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3429:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3430:     $result = &mt
1.144     matthew  3431:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3432:          '<label><input type="radio" name="login" value="fsys" '.
1.1259    raeburn  3433:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3434:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1259    raeburn  3435:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3436:     return $result;
                   3437: }
                   3438: 
1.586     raeburn  3439: sub get_assignable_auth {
                   3440:     my ($dom) = @_;
                   3441:     if ($dom eq '') {
                   3442:         $dom = $env{'request.role.domain'};
                   3443:     }
                   3444:     my %can_assign = (
                   3445:                           krb4 => 1,
                   3446:                           krb5 => 1,
                   3447:                           int  => 1,
                   3448:                           loc  => 1,
                   3449:                      );
                   3450:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3451:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3452:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3453:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3454:             my $context;
                   3455:             if ($env{'request.role'} =~ /^au/) {
                   3456:                 $context = 'author';
1.1259    raeburn  3457:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3458:                 $context = 'domain';
                   3459:             } elsif ($env{'request.course.id'}) {
                   3460:                 $context = 'course';
                   3461:             }
                   3462:             if ($context) {
                   3463:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3464:                    %can_assign = %{$authhash->{$context}}; 
                   3465:                 }
                   3466:             }
                   3467:         }
                   3468:     }
                   3469:     my $authnum = 0;
                   3470:     foreach my $key (keys(%can_assign)) {
                   3471:         if ($can_assign{$key}) {
                   3472:             $authnum ++;
                   3473:         }
                   3474:     }
                   3475:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3476:         $authnum --;
                   3477:     }
                   3478:     return ($authnum,%can_assign);
                   3479: }
                   3480: 
1.80      albertel 3481: ###############################################################
                   3482: ##    Get Kerberos Defaults for Domain                 ##
                   3483: ###############################################################
                   3484: ##
                   3485: ## Returns default kerberos version and an associated argument
                   3486: ## as listed in file domain.tab. If not listed, provides
                   3487: ## appropriate default domain and kerberos version.
                   3488: ##
                   3489: #-------------------------------------------
                   3490: 
                   3491: =pod
                   3492: 
1.648     raeburn  3493: =item * &get_kerberos_defaults()
1.80      albertel 3494: 
                   3495: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3496: version and domain. If not found, it defaults to version 4 and the 
                   3497: domain of the server.
1.80      albertel 3498: 
1.648     raeburn  3499: =over 4
                   3500: 
1.80      albertel 3501: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3502: 
1.648     raeburn  3503: =back
                   3504: 
                   3505: =back
                   3506: 
1.80      albertel 3507: =cut
                   3508: 
                   3509: #-------------------------------------------
                   3510: sub get_kerberos_defaults {
                   3511:     my $domain=shift;
1.641     raeburn  3512:     my ($krbdef,$krbdefdom);
                   3513:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3514:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3515:         $krbdef = $domdefaults{'auth_def'};
                   3516:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3517:     } else {
1.80      albertel 3518:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3519:         my $krbdefdom=$1;
                   3520:         $krbdefdom=~tr/a-z/A-Z/;
                   3521:         $krbdef = "krb4";
                   3522:     }
                   3523:     return ($krbdef,$krbdefdom);
                   3524: }
1.112     bowersj2 3525: 
1.32      matthew  3526: 
1.46      matthew  3527: ###############################################################
                   3528: ##                Thesaurus Functions                        ##
                   3529: ###############################################################
1.20      www      3530: 
1.46      matthew  3531: =pod
1.20      www      3532: 
1.112     bowersj2 3533: =head1 Thesaurus Functions
                   3534: 
                   3535: =over 4
                   3536: 
1.648     raeburn  3537: =item * &initialize_keywords()
1.46      matthew  3538: 
                   3539: Initializes the package variable %Keywords if it is empty.  Uses the
                   3540: package variable $thesaurus_db_file.
                   3541: 
                   3542: =cut
                   3543: 
                   3544: ###################################################
                   3545: 
                   3546: sub initialize_keywords {
                   3547:     return 1 if (scalar keys(%Keywords));
                   3548:     # If we are here, %Keywords is empty, so fill it up
                   3549:     #   Make sure the file we need exists...
                   3550:     if (! -e $thesaurus_db_file) {
                   3551:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3552:                                  " failed because it does not exist");
                   3553:         return 0;
                   3554:     }
                   3555:     #   Set up the hash as a database
                   3556:     my %thesaurus_db;
                   3557:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3558:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3559:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3560:                                  $thesaurus_db_file);
                   3561:         return 0;
                   3562:     } 
                   3563:     #  Get the average number of appearances of a word.
                   3564:     my $avecount = $thesaurus_db{'average.count'};
                   3565:     #  Put keywords (those that appear > average) into %Keywords
                   3566:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3567:         my ($count,undef) = split /:/,$data;
                   3568:         $Keywords{$word}++ if ($count > $avecount);
                   3569:     }
                   3570:     untie %thesaurus_db;
                   3571:     # Remove special values from %Keywords.
1.356     albertel 3572:     foreach my $value ('total.count','average.count') {
                   3573:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3574:   }
1.46      matthew  3575:     return 1;
                   3576: }
                   3577: 
                   3578: ###################################################
                   3579: 
                   3580: =pod
                   3581: 
1.648     raeburn  3582: =item * &keyword($word)
1.46      matthew  3583: 
                   3584: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3585: than the average number of times in the thesaurus database.  Calls 
                   3586: &initialize_keywords
                   3587: 
                   3588: =cut
                   3589: 
                   3590: ###################################################
1.20      www      3591: 
                   3592: sub keyword {
1.46      matthew  3593:     return if (!&initialize_keywords());
                   3594:     my $word=lc(shift());
                   3595:     $word=~s/\W//g;
                   3596:     return exists($Keywords{$word});
1.20      www      3597: }
1.46      matthew  3598: 
                   3599: ###############################################################
                   3600: 
                   3601: =pod 
1.20      www      3602: 
1.648     raeburn  3603: =item * &get_related_words()
1.46      matthew  3604: 
1.160     matthew  3605: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3606: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3607: will be returned.  The order of the words returned is determined by the
                   3608: database which holds them.
                   3609: 
                   3610: Uses global $thesaurus_db_file.
                   3611: 
1.1057    foxr     3612: 
1.46      matthew  3613: =cut
                   3614: 
                   3615: ###############################################################
                   3616: sub get_related_words {
                   3617:     my $keyword = shift;
                   3618:     my %thesaurus_db;
                   3619:     if (! -e $thesaurus_db_file) {
                   3620:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3621:                                  "failed because the file does not exist");
                   3622:         return ();
                   3623:     }
                   3624:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3625:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3626:         return ();
                   3627:     } 
                   3628:     my @Words=();
1.429     www      3629:     my $count=0;
1.46      matthew  3630:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3631: 	# The first element is the number of times
                   3632: 	# the word appears.  We do not need it now.
1.429     www      3633: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3634: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3635: 	my $threshold=$mostfrequentcount/10;
                   3636:         foreach my $possibleword (@RelatedWords) {
                   3637:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3638:             if ($wordcount>$threshold) {
                   3639: 		push(@Words,$word);
                   3640:                 $count++;
                   3641:                 if ($count>10) { last; }
                   3642: 	    }
1.20      www      3643:         }
                   3644:     }
1.46      matthew  3645:     untie %thesaurus_db;
                   3646:     return @Words;
1.14      harris41 3647: }
1.1090    foxr     3648: ###############################################################
                   3649: #
                   3650: #  Spell checking
                   3651: #
                   3652: 
                   3653: =pod
                   3654: 
1.1142    raeburn  3655: =back
                   3656: 
1.1090    foxr     3657: =head1 Spell checking
                   3658: 
                   3659: =over 4
                   3660: 
                   3661: =item * &check_spelling($wordlist $language)
                   3662: 
                   3663: Takes a string containing words and feeds it to an external
                   3664: spellcheck program via a pipeline. Returns a string containing
                   3665: them mis-spelled words.
                   3666: 
                   3667: Parameters:
                   3668: 
                   3669: =over 4
                   3670: 
                   3671: =item - $wordlist
                   3672: 
                   3673: String that will be fed into the spellcheck program.
                   3674: 
                   3675: =item - $language
                   3676: 
                   3677: Language string that specifies the language for which the spell
                   3678: check will be performed.
                   3679: 
                   3680: =back
                   3681: 
                   3682: =back
                   3683: 
                   3684: Note: This sub assumes that aspell is installed.
                   3685: 
                   3686: 
                   3687: =cut
                   3688: 
1.46      matthew  3689: 
1.1090    foxr     3690: sub check_spelling {
                   3691:     my ($wordlist, $language) = @_;
1.1091    foxr     3692:     my @misspellings;
                   3693:     
                   3694:     # Generate the speller and set the langauge.
                   3695:     # if explicitly selected:
1.1090    foxr     3696: 
1.1091    foxr     3697:     my $speller = Text::Aspell->new;
1.1090    foxr     3698:     if ($language) {
1.1091    foxr     3699: 	$speller->set_option('lang', $language);
1.1090    foxr     3700:     }
                   3701: 
1.1091    foxr     3702:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3703: 
1.1091    foxr     3704:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3705: 
1.1091    foxr     3706:     foreach my $word (@words) {
                   3707: 	if(! $speller->check($word)) {
                   3708: 	    push(@misspellings, $word);
1.1090    foxr     3709: 	}
                   3710:     }
1.1091    foxr     3711:     return join(' ', @misspellings);
                   3712:     
1.1090    foxr     3713: }
                   3714: 
1.61      www      3715: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3716: =pod
                   3717: 
1.112     bowersj2 3718: =head1 User Name Functions
                   3719: 
                   3720: =over 4
                   3721: 
1.648     raeburn  3722: =item * &plainname($uname,$udom,$first)
1.81      albertel 3723: 
1.112     bowersj2 3724: Takes a users logon name and returns it as a string in
1.226     albertel 3725: "first middle last generation" form 
                   3726: if $first is set to 'lastname' then it returns it as
                   3727: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3728: 
                   3729: =cut
1.61      www      3730: 
1.295     www      3731: 
1.81      albertel 3732: ###############################################################
1.61      www      3733: sub plainname {
1.226     albertel 3734:     my ($uname,$udom,$first)=@_;
1.537     albertel 3735:     return if (!defined($uname) || !defined($udom));
1.295     www      3736:     my %names=&getnames($uname,$udom);
1.226     albertel 3737:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3738: 					  $names{'middlename'},
                   3739: 					  $names{'lastname'},
                   3740: 					  $names{'generation'},$first);
                   3741:     $name=~s/^\s+//;
1.62      www      3742:     $name=~s/\s+$//;
                   3743:     $name=~s/\s+/ /g;
1.353     albertel 3744:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3745:     return $name;
1.61      www      3746: }
1.66      www      3747: 
                   3748: # -------------------------------------------------------------------- Nickname
1.81      albertel 3749: =pod
                   3750: 
1.648     raeburn  3751: =item * &nickname($uname,$udom)
1.81      albertel 3752: 
                   3753: Gets a users name and returns it as a string as
                   3754: 
                   3755: "&quot;nickname&quot;"
1.66      www      3756: 
1.81      albertel 3757: if the user has a nickname or
                   3758: 
                   3759: "first middle last generation"
                   3760: 
                   3761: if the user does not
                   3762: 
                   3763: =cut
1.66      www      3764: 
                   3765: sub nickname {
                   3766:     my ($uname,$udom)=@_;
1.537     albertel 3767:     return if (!defined($uname) || !defined($udom));
1.295     www      3768:     my %names=&getnames($uname,$udom);
1.68      albertel 3769:     my $name=$names{'nickname'};
1.66      www      3770:     if ($name) {
                   3771:        $name='&quot;'.$name.'&quot;'; 
                   3772:     } else {
                   3773:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3774: 	     $names{'lastname'}.' '.$names{'generation'};
                   3775:        $name=~s/\s+$//;
                   3776:        $name=~s/\s+/ /g;
                   3777:     }
                   3778:     return $name;
                   3779: }
                   3780: 
1.295     www      3781: sub getnames {
                   3782:     my ($uname,$udom)=@_;
1.537     albertel 3783:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3784:     if ($udom eq 'public' && $uname eq 'public') {
                   3785: 	return ('lastname' => &mt('Public'));
                   3786:     }
1.295     www      3787:     my $id=$uname.':'.$udom;
                   3788:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3789:     if ($cached) {
                   3790: 	return %{$names};
                   3791:     } else {
                   3792: 	my %loadnames=&Apache::lonnet::get('environment',
                   3793:                     ['firstname','middlename','lastname','generation','nickname'],
                   3794: 					 $udom,$uname);
                   3795: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3796: 	return %loadnames;
                   3797:     }
                   3798: }
1.61      www      3799: 
1.542     raeburn  3800: # -------------------------------------------------------------------- getemails
1.648     raeburn  3801: 
1.542     raeburn  3802: =pod
                   3803: 
1.648     raeburn  3804: =item * &getemails($uname,$udom)
1.542     raeburn  3805: 
                   3806: Gets a user's email information and returns it as a hash with keys:
                   3807: notification, critnotification, permanentemail
                   3808: 
                   3809: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3810: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3811:  
1.648     raeburn  3812: 
1.542     raeburn  3813: =cut
                   3814: 
1.648     raeburn  3815: 
1.466     albertel 3816: sub getemails {
                   3817:     my ($uname,$udom)=@_;
                   3818:     if ($udom eq 'public' && $uname eq 'public') {
                   3819: 	return;
                   3820:     }
1.467     www      3821:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3822:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3823:     my $id=$uname.':'.$udom;
                   3824:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3825:     if ($cached) {
                   3826: 	return %{$names};
                   3827:     } else {
                   3828: 	my %loadnames=&Apache::lonnet::get('environment',
                   3829:                     			   ['notification','critnotification',
                   3830: 					    'permanentemail'],
                   3831: 					   $udom,$uname);
                   3832: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3833: 	return %loadnames;
                   3834:     }
                   3835: }
                   3836: 
1.551     albertel 3837: sub flush_email_cache {
                   3838:     my ($uname,$udom)=@_;
                   3839:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3840:     if (!$uname) { $uname=$env{'user.name'};   }
                   3841:     return if ($udom eq 'public' && $uname eq 'public');
                   3842:     my $id=$uname.':'.$udom;
                   3843:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3844: }
                   3845: 
1.728     raeburn  3846: # -------------------------------------------------------------------- getlangs
                   3847: 
                   3848: =pod
                   3849: 
                   3850: =item * &getlangs($uname,$udom)
                   3851: 
                   3852: Gets a user's language preference and returns it as a hash with key:
                   3853: language.
                   3854: 
                   3855: =cut
                   3856: 
                   3857: 
                   3858: sub getlangs {
                   3859:     my ($uname,$udom) = @_;
                   3860:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3861:     if (!$uname) { $uname=$env{'user.name'};   }
                   3862:     my $id=$uname.':'.$udom;
                   3863:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3864:     if ($cached) {
                   3865:         return %{$langs};
                   3866:     } else {
                   3867:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3868:                                            $udom,$uname);
                   3869:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3870:         return %loadlangs;
                   3871:     }
                   3872: }
                   3873: 
                   3874: sub flush_langs_cache {
                   3875:     my ($uname,$udom)=@_;
                   3876:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3877:     if (!$uname) { $uname=$env{'user.name'};   }
                   3878:     return if ($udom eq 'public' && $uname eq 'public');
                   3879:     my $id=$uname.':'.$udom;
                   3880:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3881: }
                   3882: 
1.61      www      3883: # ------------------------------------------------------------------ Screenname
1.81      albertel 3884: 
                   3885: =pod
                   3886: 
1.648     raeburn  3887: =item * &screenname($uname,$udom)
1.81      albertel 3888: 
                   3889: Gets a users screenname and returns it as a string
                   3890: 
                   3891: =cut
1.61      www      3892: 
                   3893: sub screenname {
                   3894:     my ($uname,$udom)=@_;
1.258     albertel 3895:     if ($uname eq $env{'user.name'} &&
                   3896: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3897:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3898:     return $names{'screenname'};
1.62      www      3899: }
                   3900: 
1.212     albertel 3901: 
1.802     bisitz   3902: # ------------------------------------------------------------- Confirm Wrapper
                   3903: =pod
                   3904: 
1.1142    raeburn  3905: =item * &confirmwrapper($message)
1.802     bisitz   3906: 
                   3907: Wrap messages about completion of operation in box
                   3908: 
                   3909: =cut
                   3910: 
                   3911: sub confirmwrapper {
                   3912:     my ($message)=@_;
                   3913:     if ($message) {
                   3914:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3915:                .$message."\n"
                   3916:                .'</div>'."\n";
                   3917:     } else {
                   3918:         return $message;
                   3919:     }
                   3920: }
                   3921: 
1.62      www      3922: # ------------------------------------------------------------- Message Wrapper
                   3923: 
                   3924: sub messagewrapper {
1.369     www      3925:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3926:     return 
1.441     albertel 3927:         '<a href="/adm/email?compose=individual&amp;'.
                   3928:         'recname='.$username.'&amp;recdom='.$domain.
                   3929: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3930:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3931: }
1.802     bisitz   3932: 
1.74      www      3933: # --------------------------------------------------------------- Notes Wrapper
                   3934: 
                   3935: sub noteswrapper {
                   3936:     my ($link,$un,$do)=@_;
                   3937:     return 
1.896     amueller 3938: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3939: }
1.802     bisitz   3940: 
1.62      www      3941: # ------------------------------------------------------------- Aboutme Wrapper
                   3942: 
                   3943: sub aboutmewrapper {
1.1070    raeburn  3944:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3945:     if (!defined($username)  && !defined($domain)) {
                   3946:         return;
                   3947:     }
1.1096    raeburn  3948:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3949: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3950: }
                   3951: 
                   3952: # ------------------------------------------------------------ Syllabus Wrapper
                   3953: 
                   3954: sub syllabuswrapper {
1.707     bisitz   3955:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3956:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3957: }
1.14      harris41 3958: 
1.802     bisitz   3959: # -----------------------------------------------------------------------------
                   3960: 
1.208     matthew  3961: sub track_student_link {
1.887     raeburn  3962:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3963:     my $link ="/adm/trackstudent?";
1.208     matthew  3964:     my $title = 'View recent activity';
                   3965:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3966:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3967:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3968:         $title .= ' of this student';
1.268     albertel 3969:     } 
1.208     matthew  3970:     if (defined($target) && $target !~ /^\s*$/) {
                   3971:         $target = qq{target="$target"};
                   3972:     } else {
                   3973:         $target = '';
                   3974:     }
1.268     albertel 3975:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3976:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3977:     $title = &mt($title);
                   3978:     $linktext = &mt($linktext);
1.448     albertel 3979:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3980: 	&help_open_topic('View_recent_activity');
1.208     matthew  3981: }
                   3982: 
1.781     raeburn  3983: sub slot_reservations_link {
                   3984:     my ($linktext,$sname,$sdom,$target) = @_;
                   3985:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3986:     my $title = 'View slot reservation history';
                   3987:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3988:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3989:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3990:         $title .= ' of this student';
                   3991:     }
                   3992:     if (defined($target) && $target !~ /^\s*$/) {
                   3993:         $target = qq{target="$target"};
                   3994:     } else {
                   3995:         $target = '';
                   3996:     }
                   3997:     $title = &mt($title);
                   3998:     $linktext = &mt($linktext);
                   3999:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4000: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4001: 
                   4002: }
                   4003: 
1.508     www      4004: # ===================================================== Display a student photo
                   4005: 
                   4006: 
1.509     albertel 4007: sub student_image_tag {
1.508     www      4008:     my ($domain,$user)=@_;
                   4009:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4010:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4011: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4012:     } else {
                   4013: 	return '';
                   4014:     }
                   4015: }
                   4016: 
1.112     bowersj2 4017: =pod
                   4018: 
                   4019: =back
                   4020: 
                   4021: =head1 Access .tab File Data
                   4022: 
                   4023: =over 4
                   4024: 
1.648     raeburn  4025: =item * &languageids() 
1.112     bowersj2 4026: 
                   4027: returns list of all language ids
                   4028: 
                   4029: =cut
                   4030: 
1.14      harris41 4031: sub languageids {
1.16      harris41 4032:     return sort(keys(%language));
1.14      harris41 4033: }
                   4034: 
1.112     bowersj2 4035: =pod
                   4036: 
1.648     raeburn  4037: =item * &languagedescription() 
1.112     bowersj2 4038: 
                   4039: returns description of a specified language id
                   4040: 
                   4041: =cut
                   4042: 
1.14      harris41 4043: sub languagedescription {
1.125     www      4044:     my $code=shift;
                   4045:     return  ($supported_language{$code}?'* ':'').
                   4046:             $language{$code}.
1.126     www      4047: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4048: }
                   4049: 
1.1048    foxr     4050: =pod
                   4051: 
                   4052: =item * &plainlanguagedescription
                   4053: 
                   4054: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4055: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4056: 
                   4057: =cut
                   4058: 
1.145     www      4059: sub plainlanguagedescription {
                   4060:     my $code=shift;
                   4061:     return $language{$code};
                   4062: }
                   4063: 
1.1048    foxr     4064: =pod
                   4065: 
                   4066: =item * &supportedlanguagecode
                   4067: 
                   4068: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4069: code.
                   4070: 
                   4071: =cut
                   4072: 
1.145     www      4073: sub supportedlanguagecode {
                   4074:     my $code=shift;
                   4075:     return $supported_language{$code};
1.97      www      4076: }
                   4077: 
1.112     bowersj2 4078: =pod
                   4079: 
1.1048    foxr     4080: =item * &latexlanguage()
                   4081: 
                   4082: Given a language key code returns the correspondnig language to use
                   4083: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4084: is no supported hyphenation for the language code.
                   4085: 
                   4086: =cut
                   4087: 
                   4088: sub latexlanguage {
                   4089:     my $code = shift;
                   4090:     return $latex_language{$code};
                   4091: }
                   4092: 
                   4093: =pod
                   4094: 
                   4095: =item * &latexhyphenation()
                   4096: 
                   4097: Same as above but what's supplied is the language as it might be stored
                   4098: in the metadata.
                   4099: 
                   4100: =cut
                   4101: 
                   4102: sub latexhyphenation {
                   4103:     my $key = shift;
                   4104:     return $latex_language_bykey{$key};
                   4105: }
                   4106: 
                   4107: =pod
                   4108: 
1.648     raeburn  4109: =item * &copyrightids() 
1.112     bowersj2 4110: 
                   4111: returns list of all copyrights
                   4112: 
                   4113: =cut
                   4114: 
                   4115: sub copyrightids {
                   4116:     return sort(keys(%cprtag));
                   4117: }
                   4118: 
                   4119: =pod
                   4120: 
1.648     raeburn  4121: =item * &copyrightdescription() 
1.112     bowersj2 4122: 
                   4123: returns description of a specified copyright id
                   4124: 
                   4125: =cut
                   4126: 
                   4127: sub copyrightdescription {
1.166     www      4128:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4129: }
1.197     matthew  4130: 
                   4131: =pod
                   4132: 
1.648     raeburn  4133: =item * &source_copyrightids() 
1.192     taceyjo1 4134: 
                   4135: returns list of all source copyrights
                   4136: 
                   4137: =cut
                   4138: 
                   4139: sub source_copyrightids {
                   4140:     return sort(keys(%scprtag));
                   4141: }
                   4142: 
                   4143: =pod
                   4144: 
1.648     raeburn  4145: =item * &source_copyrightdescription() 
1.192     taceyjo1 4146: 
                   4147: returns description of a specified source copyright id
                   4148: 
                   4149: =cut
                   4150: 
                   4151: sub source_copyrightdescription {
                   4152:     return &mt($scprtag{shift(@_)});
                   4153: }
1.112     bowersj2 4154: 
                   4155: =pod
                   4156: 
1.648     raeburn  4157: =item * &filecategories() 
1.112     bowersj2 4158: 
                   4159: returns list of all file categories
                   4160: 
                   4161: =cut
                   4162: 
                   4163: sub filecategories {
                   4164:     return sort(keys(%category_extensions));
                   4165: }
                   4166: 
                   4167: =pod
                   4168: 
1.648     raeburn  4169: =item * &filecategorytypes() 
1.112     bowersj2 4170: 
                   4171: returns list of file types belonging to a given file
                   4172: category
                   4173: 
                   4174: =cut
                   4175: 
                   4176: sub filecategorytypes {
1.356     albertel 4177:     my ($cat) = @_;
1.1248    raeburn  4178:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4179:         return @{$category_extensions{lc($cat)}};
                   4180:     } else {
                   4181:         return ();
                   4182:     }
1.112     bowersj2 4183: }
                   4184: 
                   4185: =pod
                   4186: 
1.648     raeburn  4187: =item * &fileembstyle() 
1.112     bowersj2 4188: 
                   4189: returns embedding style for a specified file type
                   4190: 
                   4191: =cut
                   4192: 
                   4193: sub fileembstyle {
                   4194:     return $fe{lc(shift(@_))};
1.169     www      4195: }
                   4196: 
1.351     www      4197: sub filemimetype {
                   4198:     return $fm{lc(shift(@_))};
                   4199: }
                   4200: 
1.169     www      4201: 
                   4202: sub filecategoryselect {
                   4203:     my ($name,$value)=@_;
1.189     matthew  4204:     return &select_form($value,$name,
1.970     raeburn  4205:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4206: }
                   4207: 
                   4208: =pod
                   4209: 
1.648     raeburn  4210: =item * &filedescription() 
1.112     bowersj2 4211: 
                   4212: returns description for a specified file type
                   4213: 
                   4214: =cut
                   4215: 
                   4216: sub filedescription {
1.188     matthew  4217:     my $file_description = $fd{lc(shift())};
                   4218:     $file_description =~ s:([\[\]]):~$1:g;
                   4219:     return &mt($file_description);
1.112     bowersj2 4220: }
                   4221: 
                   4222: =pod
                   4223: 
1.648     raeburn  4224: =item * &filedescriptionex() 
1.112     bowersj2 4225: 
                   4226: returns description for a specified file type with
                   4227: extra formatting
                   4228: 
                   4229: =cut
                   4230: 
                   4231: sub filedescriptionex {
                   4232:     my $ex=shift;
1.188     matthew  4233:     my $file_description = $fd{lc($ex)};
                   4234:     $file_description =~ s:([\[\]]):~$1:g;
                   4235:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4236: }
                   4237: 
                   4238: # End of .tab access
                   4239: =pod
                   4240: 
                   4241: =back
                   4242: 
                   4243: =cut
                   4244: 
                   4245: # ------------------------------------------------------------------ File Types
                   4246: sub fileextensions {
                   4247:     return sort(keys(%fe));
                   4248: }
                   4249: 
1.97      www      4250: # ----------------------------------------------------------- Display Languages
                   4251: # returns a hash with all desired display languages
                   4252: #
                   4253: 
                   4254: sub display_languages {
                   4255:     my %languages=();
1.695     raeburn  4256:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4257: 	$languages{$lang}=1;
1.97      www      4258:     }
                   4259:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4260:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4261: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4262: 	    $languages{$lang}=1;
1.97      www      4263:         }
                   4264:     }
                   4265:     return %languages;
1.14      harris41 4266: }
                   4267: 
1.582     albertel 4268: sub languages {
                   4269:     my ($possible_langs) = @_;
1.695     raeburn  4270:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4271:     if (!ref($possible_langs)) {
                   4272: 	if( wantarray ) {
                   4273: 	    return @preferred_langs;
                   4274: 	} else {
                   4275: 	    return $preferred_langs[0];
                   4276: 	}
                   4277:     }
                   4278:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4279:     my @preferred_possibilities;
                   4280:     foreach my $preferred_lang (@preferred_langs) {
                   4281: 	if (exists($possibilities{$preferred_lang})) {
                   4282: 	    push(@preferred_possibilities, $preferred_lang);
                   4283: 	}
                   4284:     }
                   4285:     if( wantarray ) {
                   4286: 	return @preferred_possibilities;
                   4287:     }
                   4288:     return $preferred_possibilities[0];
                   4289: }
                   4290: 
1.742     raeburn  4291: sub user_lang {
                   4292:     my ($touname,$toudom,$fromcid) = @_;
                   4293:     my @userlangs;
                   4294:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4295:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4296:                     $env{'course.'.$fromcid.'.languages'}));
                   4297:     } else {
                   4298:         my %langhash = &getlangs($touname,$toudom);
                   4299:         if ($langhash{'languages'} ne '') {
                   4300:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4301:         } else {
                   4302:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4303:             if ($domdefs{'lang_def'} ne '') {
                   4304:                 @userlangs = ($domdefs{'lang_def'});
                   4305:             }
                   4306:         }
                   4307:     }
                   4308:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4309:     my $user_lh = Apache::localize->get_handle(@languages);
                   4310:     return $user_lh;
                   4311: }
                   4312: 
                   4313: 
1.112     bowersj2 4314: ###############################################################
                   4315: ##               Student Answer Attempts                     ##
                   4316: ###############################################################
                   4317: 
                   4318: =pod
                   4319: 
                   4320: =head1 Alternate Problem Views
                   4321: 
                   4322: =over 4
                   4323: 
1.648     raeburn  4324: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4325:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4326: 
                   4327: Return string with previous attempt on problem. Arguments:
                   4328: 
                   4329: =over 4
                   4330: 
                   4331: =item * $symb: Problem, including path
                   4332: 
                   4333: =item * $username: username of the desired student
                   4334: 
                   4335: =item * $domain: domain of the desired student
1.14      harris41 4336: 
1.112     bowersj2 4337: =item * $course: Course ID
1.14      harris41 4338: 
1.112     bowersj2 4339: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4340:     something
1.14      harris41 4341: 
1.112     bowersj2 4342: =item * $regexp: if string matches this regexp, the string will be
                   4343:     sent to $gradesub
1.14      harris41 4344: 
1.112     bowersj2 4345: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4346: 
1.1199    raeburn  4347: =item * $usec: section of the desired student
                   4348: 
                   4349: =item * $identifier: counter for student (multiple students one problem) or 
                   4350:     problem (one student; whole sequence).
                   4351: 
1.112     bowersj2 4352: =back
1.14      harris41 4353: 
1.112     bowersj2 4354: The output string is a table containing all desired attempts, if any.
1.16      harris41 4355: 
1.112     bowersj2 4356: =cut
1.1       albertel 4357: 
                   4358: sub get_previous_attempt {
1.1199    raeburn  4359:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4360:   my $prevattempts='';
1.43      ng       4361:   no strict 'refs';
1.1       albertel 4362:   if ($symb) {
1.3       albertel 4363:     my (%returnhash)=
                   4364:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4365:     if ($returnhash{'version'}) {
                   4366:       my %lasthash=();
                   4367:       my $version;
                   4368:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4369:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4370:             if ($key =~ /\.rawrndseed$/) {
                   4371:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4372:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4373:             } else {
                   4374:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4375:             }
1.19      harris41 4376:         }
1.1       albertel 4377:       }
1.596     albertel 4378:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4379:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4380:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4381:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4382:       foreach my $key (sort(keys(%lasthash))) {
                   4383: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4384: 	if ($#parts > 0) {
1.31      albertel 4385: 	  my $data=$parts[-1];
1.989     raeburn  4386:           next if ($data eq 'foilorder');
1.31      albertel 4387: 	  pop(@parts);
1.1010    www      4388:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4389:           if ($data eq 'type') {
                   4390:               unless ($showsurv) {
                   4391:                   my $id = join(',',@parts);
                   4392:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4393:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4394:                       $lasthidden{$ign.'.'.$id} = 1;
                   4395:                   }
1.945     raeburn  4396:               }
1.1199    raeburn  4397:               if ($identifier ne '') {
                   4398:                   my $id = join(',',@parts);
                   4399:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4400:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4401:                       $hidestatus{$ign.'.'.$id} = 1;
                   4402:                   }
                   4403:               }
                   4404:           } elsif ($data eq 'regrader') {
                   4405:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4406:                   my $id = join(',',@parts);
                   4407:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4408:               }
1.1010    www      4409:           } 
1.31      albertel 4410: 	} else {
1.41      ng       4411: 	  if ($#parts == 0) {
                   4412: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4413: 	  } else {
                   4414: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4415: 	  }
1.31      albertel 4416: 	}
1.16      harris41 4417:       }
1.596     albertel 4418:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4419:       if ($getattempt eq '') {
1.1199    raeburn  4420:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4421:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4422:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4423:                 foreach my $id (keys(%regraded)) {
                   4424:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4425:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4426:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4427:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4428:                     }
                   4429:                 }
                   4430:             }
1.1200    raeburn  4431:         }
                   4432: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4433:             my (@hidden,@unsolved);
1.945     raeburn  4434:             if (%typeparts) {
                   4435:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4436:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4437:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4438:                         push(@hidden,$id);
1.1199    raeburn  4439:                     } elsif ($identifier ne '') {
                   4440:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4441:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4442:                                 ($hidestatus{$id})) {
1.1200    raeburn  4443:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4444:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4445:                                 push(@{$solved{$id}},$version);
                   4446:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4447:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4448:                                 my $skip;
                   4449:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4450:                                     foreach my $reset (@{$resets{$id}}) {
                   4451:                                         if ($reset > $solved{$id}[-1]) {
                   4452:                                             $skip=1;
                   4453:                                             last;
                   4454:                                         }
                   4455:                                     }
                   4456:                                 }
                   4457:                                 unless ($skip) {
                   4458:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4459:                                     push(@unsolved,$partslist);
                   4460:                                 }
                   4461:                             }
                   4462:                         }
1.945     raeburn  4463:                     }
                   4464:                 }
                   4465:             }
                   4466:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4467:                            '<td>'.&mt('Transaction [_1]',$version);
                   4468:             if (@unsolved) {
                   4469:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4470:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4471:                                  &mt('Hide').'</label></span>';
                   4472:             }
                   4473:             $prevattempts .= '</td>';
1.945     raeburn  4474:             if (@hidden) {
                   4475:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4476:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4477:                     my $hide;
                   4478:                     foreach my $id (@hidden) {
                   4479:                         if ($key =~ /^\Q$id\E/) {
                   4480:                             $hide = 1;
                   4481:                             last;
                   4482:                         }
                   4483:                     }
                   4484:                     if ($hide) {
                   4485:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4486:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4487:                             my $value = &format_previous_attempt_value($key,
                   4488:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4489:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4490:                         } else {
                   4491:                             $prevattempts.='<td>&nbsp;</td>';
                   4492:                         }
                   4493:                     } else {
                   4494:                         if ($key =~ /\./) {
1.1212    raeburn  4495:                             my $value = $returnhash{$version.':'.$key};
                   4496:                             if ($key =~ /\.rndseed$/) {
                   4497:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4498:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4499:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4500:                                 }
                   4501:                             }
                   4502:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4503:                                            '&nbsp;</td>';
1.945     raeburn  4504:                         } else {
                   4505:                             $prevattempts.='<td>&nbsp;</td>';
                   4506:                         }
                   4507:                     }
                   4508:                 }
                   4509:             } else {
                   4510: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4511:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4512:                     my $value = $returnhash{$version.':'.$key};
                   4513:                     if ($key =~ /\.rndseed$/) {
                   4514:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4515:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4516:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4517:                         }
                   4518:                     }
                   4519:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4520:                                    '&nbsp;</td>';
1.945     raeburn  4521: 	        }
                   4522:             }
                   4523: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4524: 	 }
1.1       albertel 4525:       }
1.945     raeburn  4526:       my @currhidden = keys(%lasthidden);
1.596     albertel 4527:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4528:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4529:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4530:           if (%typeparts) {
                   4531:               my $hidden;
                   4532:               foreach my $id (@currhidden) {
                   4533:                   if ($key =~ /^\Q$id\E/) {
                   4534:                       $hidden = 1;
                   4535:                       last;
                   4536:                   }
                   4537:               }
                   4538:               if ($hidden) {
                   4539:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4540:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4541:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4542:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4543:                           $value = &$gradesub($value);
                   4544:                       }
1.1173    kruse    4545:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4546:                   } else {
                   4547:                       $prevattempts.='<td>&nbsp;</td>';
                   4548:                   }
                   4549:               } else {
                   4550:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4551:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4552:                       $value = &$gradesub($value);
                   4553:                   }
1.1173    kruse    4554:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4555:               }
                   4556:           } else {
                   4557: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4558: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4559:                   $value = &$gradesub($value);
                   4560:               }
1.1173    kruse    4561: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4562:           }
1.16      harris41 4563:       }
1.596     albertel 4564:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4565:     } else {
1.596     albertel 4566:       $prevattempts=
                   4567: 	  &start_data_table().&start_data_table_row().
                   4568: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4569: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4570:     }
                   4571:   } else {
1.596     albertel 4572:     $prevattempts=
                   4573: 	  &start_data_table().&start_data_table_row().
                   4574: 	  '<td>'.&mt('No data.').'</td>'.
                   4575: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4576:   }
1.10      albertel 4577: }
                   4578: 
1.581     albertel 4579: sub format_previous_attempt_value {
                   4580:     my ($key,$value) = @_;
1.1011    www      4581:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4582:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4583:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4584:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4585:     } elsif ($key =~ /answerstring$/) {
                   4586:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4587:         my @answer = %answers;
                   4588:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4589:         my @anskeys = sort(keys(%answers));
                   4590:         if (@anskeys == 1) {
                   4591:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4592:             if ($answer =~ m{\0}) {
                   4593:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4594:             }
                   4595:             my $tag_internal_answer_name = 'INTERNAL';
                   4596:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4597:                 $value = $answer; 
                   4598:             } else {
                   4599:                 $value = $anskeys[0].'='.$answer;
                   4600:             }
                   4601:         } else {
                   4602:             foreach my $ans (@anskeys) {
                   4603:                 my $answer = $answers{$ans};
1.1001    raeburn  4604:                 if ($answer =~ m{\0}) {
                   4605:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4606:                 }
                   4607:                 $value .=  $ans.'='.$answer.'<br />';;
                   4608:             } 
                   4609:         }
1.581     albertel 4610:     } else {
1.1173    kruse    4611:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4612:     }
                   4613:     return $value;
                   4614: }
                   4615: 
                   4616: 
1.107     albertel 4617: sub relative_to_absolute {
                   4618:     my ($url,$output)=@_;
                   4619:     my $parser=HTML::TokeParser->new(\$output);
                   4620:     my $token;
                   4621:     my $thisdir=$url;
                   4622:     my @rlinks=();
                   4623:     while ($token=$parser->get_token) {
                   4624: 	if ($token->[0] eq 'S') {
                   4625: 	    if ($token->[1] eq 'a') {
                   4626: 		if ($token->[2]->{'href'}) {
                   4627: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4628: 		}
                   4629: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4630: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4631: 	    } elsif ($token->[1] eq 'base') {
                   4632: 		$thisdir=$token->[2]->{'href'};
                   4633: 	    }
                   4634: 	}
                   4635:     }
                   4636:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4637:     foreach my $link (@rlinks) {
1.726     raeburn  4638: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4639: 		($link=~/^\//) ||
                   4640: 		($link=~/^javascript:/i) ||
                   4641: 		($link=~/^mailto:/i) ||
                   4642: 		($link=~/^\#/)) {
                   4643: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4644: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4645: 	}
                   4646:     }
                   4647: # -------------------------------------------------- Deal with Applet codebases
                   4648:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4649:     return $output;
                   4650: }
                   4651: 
1.112     bowersj2 4652: =pod
                   4653: 
1.648     raeburn  4654: =item * &get_student_view()
1.112     bowersj2 4655: 
                   4656: show a snapshot of what student was looking at
                   4657: 
                   4658: =cut
                   4659: 
1.10      albertel 4660: sub get_student_view {
1.186     albertel 4661:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4662:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4663:   my (%form);
1.10      albertel 4664:   my @elements=('symb','courseid','domain','username');
                   4665:   foreach my $element (@elements) {
1.186     albertel 4666:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4667:   }
1.186     albertel 4668:   if (defined($moreenv)) {
                   4669:       %form=(%form,%{$moreenv});
                   4670:   }
1.236     albertel 4671:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4672:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4673:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4674:   $userview=~s/\<body[^\>]*\>//gi;
                   4675:   $userview=~s/\<\/body\>//gi;
                   4676:   $userview=~s/\<html\>//gi;
                   4677:   $userview=~s/\<\/html\>//gi;
                   4678:   $userview=~s/\<head\>//gi;
                   4679:   $userview=~s/\<\/head\>//gi;
                   4680:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4681:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4682:   if (wantarray) {
                   4683:      return ($userview,$response);
                   4684:   } else {
                   4685:      return $userview;
                   4686:   }
                   4687: }
                   4688: 
                   4689: sub get_student_view_with_retries {
                   4690:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4691: 
                   4692:     my $ok = 0;                 # True if we got a good response.
                   4693:     my $content;
                   4694:     my $response;
                   4695: 
                   4696:     # Try to get the student_view done. within the retries count:
                   4697:     
                   4698:     do {
                   4699:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4700:          $ok      = $response->is_success;
                   4701:          if (!$ok) {
                   4702:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4703:          }
                   4704:          $retries--;
                   4705:     } while (!$ok && ($retries > 0));
                   4706:     
                   4707:     if (!$ok) {
                   4708:        $content = '';          # On error return an empty content.
                   4709:     }
1.651     www      4710:     if (wantarray) {
                   4711:        return ($content, $response);
                   4712:     } else {
                   4713:        return $content;
                   4714:     }
1.11      albertel 4715: }
                   4716: 
1.112     bowersj2 4717: =pod
                   4718: 
1.648     raeburn  4719: =item * &get_student_answers() 
1.112     bowersj2 4720: 
                   4721: show a snapshot of how student was answering problem
                   4722: 
                   4723: =cut
                   4724: 
1.11      albertel 4725: sub get_student_answers {
1.100     sakharuk 4726:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4727:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4728:   my (%moreenv);
1.11      albertel 4729:   my @elements=('symb','courseid','domain','username');
                   4730:   foreach my $element (@elements) {
1.186     albertel 4731:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4732:   }
1.186     albertel 4733:   $moreenv{'grade_target'}='answer';
                   4734:   %moreenv=(%form,%moreenv);
1.497     raeburn  4735:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4736:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4737:   return $userview;
1.1       albertel 4738: }
1.116     albertel 4739: 
                   4740: =pod
                   4741: 
                   4742: =item * &submlink()
                   4743: 
1.242     albertel 4744: Inputs: $text $uname $udom $symb $target
1.116     albertel 4745: 
                   4746: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4747: 
                   4748: =cut
                   4749: 
                   4750: ###############################################
                   4751: sub submlink {
1.242     albertel 4752:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4753:     if (!($uname && $udom)) {
                   4754: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4755: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4756: 	if (!$symb) { $symb=$cursymb; }
                   4757:     }
1.254     matthew  4758:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4759:     $symb=&escape($symb);
1.960     bisitz   4760:     if ($target) { $target=" target=\"$target\""; }
                   4761:     return
                   4762:         '<a href="/adm/grades?command=submission'.
                   4763:         '&amp;symb='.$symb.
                   4764:         '&amp;student='.$uname.
                   4765:         '&amp;userdom='.$udom.'"'.
                   4766:         $target.'>'.$text.'</a>';
1.242     albertel 4767: }
                   4768: ##############################################
                   4769: 
                   4770: =pod
                   4771: 
                   4772: =item * &pgrdlink()
                   4773: 
                   4774: Inputs: $text $uname $udom $symb $target
                   4775: 
                   4776: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4777: 
                   4778: =cut
                   4779: 
                   4780: ###############################################
                   4781: sub pgrdlink {
                   4782:     my $link=&submlink(@_);
                   4783:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4784:     return $link;
                   4785: }
                   4786: ##############################################
                   4787: 
                   4788: =pod
                   4789: 
                   4790: =item * &pprmlink()
                   4791: 
                   4792: Inputs: $text $uname $udom $symb $target
                   4793: 
                   4794: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4795: student and a specific resource
1.242     albertel 4796: 
                   4797: =cut
                   4798: 
                   4799: ###############################################
                   4800: sub pprmlink {
                   4801:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4802:     if (!($uname && $udom)) {
                   4803: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4804: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4805: 	if (!$symb) { $symb=$cursymb; }
                   4806:     }
1.254     matthew  4807:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4808:     $symb=&escape($symb);
1.242     albertel 4809:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4810:     return '<a href="/adm/parmset?command=set&amp;'.
                   4811: 	'symb='.$symb.'&amp;uname='.$uname.
                   4812: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4813: }
                   4814: ##############################################
1.37      matthew  4815: 
1.112     bowersj2 4816: =pod
                   4817: 
                   4818: =back
                   4819: 
                   4820: =cut
                   4821: 
1.37      matthew  4822: ###############################################
1.51      www      4823: 
                   4824: 
                   4825: sub timehash {
1.687     raeburn  4826:     my ($thistime) = @_;
                   4827:     my $timezone = &Apache::lonlocal::gettimezone();
                   4828:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4829:                      ->set_time_zone($timezone);
                   4830:     my $wday = $dt->day_of_week();
                   4831:     if ($wday == 7) { $wday = 0; }
                   4832:     return ( 'second' => $dt->second(),
                   4833:              'minute' => $dt->minute(),
                   4834:              'hour'   => $dt->hour(),
                   4835:              'day'     => $dt->day_of_month(),
                   4836:              'month'   => $dt->month(),
                   4837:              'year'    => $dt->year(),
                   4838:              'weekday' => $wday,
                   4839:              'dayyear' => $dt->day_of_year(),
                   4840:              'dlsav'   => $dt->is_dst() );
1.51      www      4841: }
                   4842: 
1.370     www      4843: sub utc_string {
                   4844:     my ($date)=@_;
1.371     www      4845:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4846: }
                   4847: 
1.51      www      4848: sub maketime {
                   4849:     my %th=@_;
1.687     raeburn  4850:     my ($epoch_time,$timezone,$dt);
                   4851:     $timezone = &Apache::lonlocal::gettimezone();
                   4852:     eval {
                   4853:         $dt = DateTime->new( year   => $th{'year'},
                   4854:                              month  => $th{'month'},
                   4855:                              day    => $th{'day'},
                   4856:                              hour   => $th{'hour'},
                   4857:                              minute => $th{'minute'},
                   4858:                              second => $th{'second'},
                   4859:                              time_zone => $timezone,
                   4860:                          );
                   4861:     };
                   4862:     if (!$@) {
                   4863:         $epoch_time = $dt->epoch;
                   4864:         if ($epoch_time) {
                   4865:             return $epoch_time;
                   4866:         }
                   4867:     }
1.51      www      4868:     return POSIX::mktime(
                   4869:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4870:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4871: }
                   4872: 
                   4873: #########################################
1.51      www      4874: 
                   4875: sub findallcourses {
1.482     raeburn  4876:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4877:     my %roles;
                   4878:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4879:     my %courses;
1.51      www      4880:     my $now=time;
1.482     raeburn  4881:     if (!defined($uname)) {
                   4882:         $uname = $env{'user.name'};
                   4883:     }
                   4884:     if (!defined($udom)) {
                   4885:         $udom = $env{'user.domain'};
                   4886:     }
                   4887:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4888:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4889:         if (!%roles) {
                   4890:             %roles = (
                   4891:                        cc => 1,
1.907     raeburn  4892:                        co => 1,
1.482     raeburn  4893:                        in => 1,
                   4894:                        ep => 1,
                   4895:                        ta => 1,
                   4896:                        cr => 1,
                   4897:                        st => 1,
                   4898:              );
                   4899:         }
                   4900:         foreach my $entry (keys(%roleshash)) {
                   4901:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4902:             if ($trole =~ /^cr/) { 
                   4903:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4904:             } else {
                   4905:                 next if (!exists($roles{$trole}));
                   4906:             }
                   4907:             if ($tend) {
                   4908:                 next if ($tend < $now);
                   4909:             }
                   4910:             if ($tstart) {
                   4911:                 next if ($tstart > $now);
                   4912:             }
1.1058    raeburn  4913:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4914:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4915:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4916:             if ($secpart eq '') {
                   4917:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4918:                 $sec = 'none';
1.1058    raeburn  4919:                 $value .= $cnum.'/';
1.482     raeburn  4920:             } else {
                   4921:                 $cnum = $cnumpart;
                   4922:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4923:                 $value .= $cnum.'/'.$sec;
                   4924:             }
                   4925:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4926:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4927:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4928:                 }
                   4929:             } else {
                   4930:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4931:             }
1.482     raeburn  4932:         }
                   4933:     } else {
                   4934:         foreach my $key (keys(%env)) {
1.483     albertel 4935: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4936:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4937: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4938: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4939: 	        next if (%roles && !exists($roles{$role}));
                   4940: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4941:                 my $active=1;
                   4942:                 if ($starttime) {
                   4943: 		    if ($now<$starttime) { $active=0; }
                   4944:                 }
                   4945:                 if ($endtime) {
                   4946:                     if ($now>$endtime) { $active=0; }
                   4947:                 }
                   4948:                 if ($active) {
1.1058    raeburn  4949:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4950:                     if ($sec eq '') {
                   4951:                         $sec = 'none';
1.1058    raeburn  4952:                     } else {
                   4953:                         $value .= $sec;
                   4954:                     }
                   4955:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4956:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4957:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4958:                         }
                   4959:                     } else {
                   4960:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4961:                     }
1.474     raeburn  4962:                 }
                   4963:             }
1.51      www      4964:         }
                   4965:     }
1.474     raeburn  4966:     return %courses;
1.51      www      4967: }
1.37      matthew  4968: 
1.54      www      4969: ###############################################
1.474     raeburn  4970: 
                   4971: sub blockcheck {
1.1189    raeburn  4972:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4973: 
1.1189    raeburn  4974:     if (defined($udom) && defined($uname)) {
                   4975:         # If uname and udom are for a course, check for blocks in the course.
                   4976:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4977:             my ($startblock,$endblock,$triggerblock) =
                   4978:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4979:             return ($startblock,$endblock,$triggerblock);
                   4980:         }
                   4981:     } else {
1.490     raeburn  4982:         $udom = $env{'user.domain'};
                   4983:         $uname = $env{'user.name'};
                   4984:     }
                   4985: 
1.502     raeburn  4986:     my $startblock = 0;
                   4987:     my $endblock = 0;
1.1062    raeburn  4988:     my $triggerblock = '';
1.482     raeburn  4989:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4990: 
1.490     raeburn  4991:     # If uname is for a user, and activity is course-specific, i.e.,
                   4992:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4993: 
1.490     raeburn  4994:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  4995:          $activity eq 'groups' || $activity eq 'printout' ||
                   4996:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  4997:         ($env{'request.course.id'})) {
1.490     raeburn  4998:         foreach my $key (keys(%live_courses)) {
                   4999:             if ($key ne $env{'request.course.id'}) {
                   5000:                 delete($live_courses{$key});
                   5001:             }
                   5002:         }
                   5003:     }
                   5004: 
                   5005:     my $otheruser = 0;
                   5006:     my %own_courses;
                   5007:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5008:         # Resource belongs to user other than current user.
                   5009:         $otheruser = 1;
                   5010:         # Gather courses for current user
                   5011:         %own_courses = 
                   5012:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5013:     }
                   5014: 
                   5015:     # Gather active course roles - course coordinator, instructor, 
                   5016:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5017: 
                   5018:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5019:         my ($cdom,$cnum);
                   5020:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5021:             $cdom = $env{'course.'.$course.'.domain'};
                   5022:             $cnum = $env{'course.'.$course.'.num'};
                   5023:         } else {
1.490     raeburn  5024:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5025:         }
                   5026:         my $no_ownblock = 0;
                   5027:         my $no_userblock = 0;
1.533     raeburn  5028:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5029:             # Check if current user has 'evb' priv for this
                   5030:             if (defined($own_courses{$course})) {
                   5031:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5032:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5033:                     if ($sec ne 'none') {
                   5034:                         $checkrole .= '/'.$sec;
                   5035:                     }
                   5036:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5037:                         $no_ownblock = 1;
                   5038:                         last;
                   5039:                     }
                   5040:                 }
                   5041:             }
                   5042:             # if they have 'evb' priv and are currently not playing student
                   5043:             next if (($no_ownblock) &&
                   5044:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5045:         }
1.474     raeburn  5046:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5047:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5048:             if ($sec ne 'none') {
1.482     raeburn  5049:                 $checkrole .= '/'.$sec;
1.474     raeburn  5050:             }
1.490     raeburn  5051:             if ($otheruser) {
                   5052:                 # Resource belongs to user other than current user.
                   5053:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5054:                 my (%allroles,%userroles);
                   5055:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5056:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5057:                         my ($trole,$tdom,$tnum,$tsec);
                   5058:                         if ($entry =~ /^cr/) {
                   5059:                             ($trole,$tdom,$tnum,$tsec) = 
                   5060:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5061:                         } else {
                   5062:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5063:                         }
                   5064:                         my ($spec,$area,$trest);
                   5065:                         $area = '/'.$tdom.'/'.$tnum;
                   5066:                         $trest = $tnum;
                   5067:                         if ($tsec ne '') {
                   5068:                             $area .= '/'.$tsec;
                   5069:                             $trest .= '/'.$tsec;
                   5070:                         }
                   5071:                         $spec = $trole.'.'.$area;
                   5072:                         if ($trole =~ /^cr/) {
                   5073:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5074:                                                               $tdom,$spec,$trest,$area);
                   5075:                         } else {
                   5076:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5077:                                                                 $tdom,$spec,$trest,$area);
                   5078:                         }
                   5079:                     }
1.1276    raeburn  5080:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5081:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5082:                         if ($1) {
                   5083:                             $no_userblock = 1;
                   5084:                             last;
                   5085:                         }
1.486     raeburn  5086:                     }
                   5087:                 }
1.490     raeburn  5088:             } else {
                   5089:                 # Resource belongs to current user
                   5090:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5091:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5092:                     $no_ownblock = 1;
                   5093:                     last;
                   5094:                 }
1.474     raeburn  5095:             }
                   5096:         }
                   5097:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5098:         next if (($no_ownblock) &&
1.491     albertel 5099:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5100:         next if ($no_userblock);
1.474     raeburn  5101: 
1.866     kalberla 5102:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  5103:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5104: 
1.1062    raeburn  5105:         my ($start,$end,$trigger) = 
                   5106:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  5107:         if (($start != 0) && 
                   5108:             (($startblock == 0) || ($startblock > $start))) {
                   5109:             $startblock = $start;
1.1062    raeburn  5110:             if ($trigger ne '') {
                   5111:                 $triggerblock = $trigger;
                   5112:             }
1.502     raeburn  5113:         }
                   5114:         if (($end != 0)  &&
                   5115:             (($endblock == 0) || ($endblock < $end))) {
                   5116:             $endblock = $end;
1.1062    raeburn  5117:             if ($trigger ne '') {
                   5118:                 $triggerblock = $trigger;
                   5119:             }
1.502     raeburn  5120:         }
1.490     raeburn  5121:     }
1.1062    raeburn  5122:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5123: }
                   5124: 
                   5125: sub get_blocks {
1.1062    raeburn  5126:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  5127:     my $startblock = 0;
                   5128:     my $endblock = 0;
1.1062    raeburn  5129:     my $triggerblock = '';
1.490     raeburn  5130:     my $course = $cdom.'_'.$cnum;
                   5131:     $setters->{$course} = {};
                   5132:     $setters->{$course}{'staff'} = [];
                   5133:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5134:     $setters->{$course}{'triggers'} = [];
                   5135:     my (@blockers,%triggered);
                   5136:     my $now = time;
                   5137:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5138:     if ($activity eq 'docs') {
                   5139:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   5140:         foreach my $block (@blockers) {
                   5141:             if ($block =~ /^firstaccess____(.+)$/) {
                   5142:                 my $item = $1;
                   5143:                 my $type = 'map';
                   5144:                 my $timersymb = $item;
                   5145:                 if ($item eq 'course') {
                   5146:                     $type = 'course';
                   5147:                 } elsif ($item =~ /___\d+___/) {
                   5148:                     $type = 'resource';
                   5149:                 } else {
                   5150:                     $timersymb = &Apache::lonnet::symbread($item);
                   5151:                 }
                   5152:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5153:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5154:                 $triggered{$block} = {
                   5155:                                        start => $start,
                   5156:                                        end   => $end,
                   5157:                                        type  => $type,
                   5158:                                      };
                   5159:             }
                   5160:         }
                   5161:     } else {
                   5162:         foreach my $block (keys(%commblocks)) {
                   5163:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5164:                 my ($start,$end) = ($1,$2);
                   5165:                 if ($start <= time && $end >= time) {
                   5166:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5167:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5168:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5169:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5170:                                     push(@blockers,$block);
                   5171:                                 }
                   5172:                             }
                   5173:                         }
                   5174:                     }
                   5175:                 }
                   5176:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5177:                 my $item = $1;
                   5178:                 my $timersymb = $item; 
                   5179:                 my $type = 'map';
                   5180:                 if ($item eq 'course') {
                   5181:                     $type = 'course';
                   5182:                 } elsif ($item =~ /___\d+___/) {
                   5183:                     $type = 'resource';
                   5184:                 } else {
                   5185:                     $timersymb = &Apache::lonnet::symbread($item);
                   5186:                 }
                   5187:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5188:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5189:                 if ($start && $end) {
                   5190:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5191:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5192:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5193:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5194:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5195:                                         push(@blockers,$block);
                   5196:                                         $triggered{$block} = {
                   5197:                                                                start => $start,
                   5198:                                                                end   => $end,
                   5199:                                                                type  => $type,
                   5200:                                                              };
                   5201:                                     }
                   5202:                                 }
                   5203:                             }
1.1062    raeburn  5204:                         }
                   5205:                     }
1.490     raeburn  5206:                 }
1.1062    raeburn  5207:             }
                   5208:         }
                   5209:     }
                   5210:     foreach my $blocker (@blockers) {
                   5211:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5212:             &parse_block_record($commblocks{$blocker});
                   5213:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5214:         my ($start,$end,$triggertype);
                   5215:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5216:             ($start,$end) = ($1,$2);
                   5217:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5218:             $start = $triggered{$blocker}{'start'};
                   5219:             $end = $triggered{$blocker}{'end'};
                   5220:             $triggertype = $triggered{$blocker}{'type'};
                   5221:         }
                   5222:         if ($start) {
                   5223:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5224:             if ($triggertype) {
                   5225:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5226:             } else {
                   5227:                 push(@{$$setters{$course}{'triggers'}},0);
                   5228:             }
                   5229:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5230:                 $startblock = $start;
                   5231:                 if ($triggertype) {
                   5232:                     $triggerblock = $blocker;
1.474     raeburn  5233:                 }
                   5234:             }
1.1062    raeburn  5235:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5236:                $endblock = $end;
                   5237:                if ($triggertype) {
                   5238:                    $triggerblock = $blocker;
                   5239:                }
                   5240:             }
1.474     raeburn  5241:         }
                   5242:     }
1.1062    raeburn  5243:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5244: }
                   5245: 
                   5246: sub parse_block_record {
                   5247:     my ($record) = @_;
                   5248:     my ($setuname,$setudom,$title,$blocks);
                   5249:     if (ref($record) eq 'HASH') {
                   5250:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5251:         $title = &unescape($record->{'event'});
                   5252:         $blocks = $record->{'blocks'};
                   5253:     } else {
                   5254:         my @data = split(/:/,$record,3);
                   5255:         if (scalar(@data) eq 2) {
                   5256:             $title = $data[1];
                   5257:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5258:         } else {
                   5259:             ($setuname,$setudom,$title) = @data;
                   5260:         }
                   5261:         $blocks = { 'com' => 'on' };
                   5262:     }
                   5263:     return ($setuname,$setudom,$title,$blocks);
                   5264: }
                   5265: 
1.854     kalberla 5266: sub blocking_status {
1.1189    raeburn  5267:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  5268:     my %setters;
1.890     droeschl 5269: 
1.1061    raeburn  5270: # check for active blocking
1.1062    raeburn  5271:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  5272:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  5273:     my $blocked = 0;
                   5274:     if ($startblock && $endblock) {
                   5275:         $blocked = 1;
                   5276:     }
1.890     droeschl 5277: 
1.1061    raeburn  5278: # caller just wants to know whether a block is active
                   5279:     if (!wantarray) { return $blocked; }
                   5280: 
                   5281: # build a link to a popup window containing the details
                   5282:     my $querystring  = "?activity=$activity";
                   5283: # $uname and $udom decide whose portfolio the user is trying to look at
1.1232    raeburn  5284:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   5285:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5286:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5287:     } elsif ($activity eq 'docs') {
                   5288:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   5289:     }
1.1061    raeburn  5290: 
                   5291:     my $output .= <<'END_MYBLOCK';
                   5292: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5293:     var options = "width=" + w + ",height=" + h + ",";
                   5294:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5295:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5296:     var newWin = window.open(url, wdwName, options);
                   5297:     newWin.focus();
                   5298: }
1.890     droeschl 5299: END_MYBLOCK
1.854     kalberla 5300: 
1.1061    raeburn  5301:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5302:   
1.1061    raeburn  5303:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5304:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5305:     my $class = 'LC_comblock';
1.1062    raeburn  5306:     if ($activity eq 'docs') {
                   5307:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5308:         $class = '';
1.1063    raeburn  5309:     } elsif ($activity eq 'printout') {
                   5310:         $text = &mt('Printing Blocked');
1.1232    raeburn  5311:     } elsif ($activity eq 'passwd') {
                   5312:         $text = &mt('Password Changing Blocked');
1.1282    raeburn  5313:     } elsif ($activity eq 'alert') {
                   5314:         $text = &mt('Checking Critical Messages Blocked');
                   5315:     } elsif ($activity eq 'reinit') {
                   5316:         $text = &mt('Checking Course Update Blocked');
1.1062    raeburn  5317:     }
1.1061    raeburn  5318:     $output .= <<"END_BLOCK";
1.1217    raeburn  5319: <div class='$class'>
1.869     kalberla 5320:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5321:   title='$text'>
                   5322:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5323:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5324:   title='$text'>$text</a>
1.867     kalberla 5325: </div>
                   5326: 
                   5327: END_BLOCK
1.474     raeburn  5328: 
1.1061    raeburn  5329:     return ($blocked, $output);
1.854     kalberla 5330: }
1.490     raeburn  5331: 
1.60      matthew  5332: ###############################################
                   5333: 
1.682     raeburn  5334: sub check_ip_acc {
1.1201    raeburn  5335:     my ($acc,$clientip)=@_;
1.682     raeburn  5336:     &Apache::lonxml::debug("acc is $acc");
                   5337:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5338:         return 1;
                   5339:     }
1.1219    raeburn  5340:     my $allowed;
1.1252    raeburn  5341:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  5342: 
                   5343:     my $name;
1.1219    raeburn  5344:     my %access = (
                   5345:                      allowfrom => 1,
                   5346:                      denyfrom  => 0,
                   5347:                  );
                   5348:     my @allows;
                   5349:     my @denies;
                   5350:     foreach my $item (split(',',$acc)) {
                   5351:         $item =~ s/^\s*//;
                   5352:         $item =~ s/\s*$//;
                   5353:         my $pattern;
                   5354:         if ($item =~ /^\!(.+)$/) {
                   5355:             push(@denies,$1);
                   5356:         } else {
                   5357:             push(@allows,$item);
                   5358:         }
                   5359:    }
                   5360:    my $numdenies = scalar(@denies);
                   5361:    my $numallows = scalar(@allows);
                   5362:    my $count = 0;
                   5363:    foreach my $pattern (@denies,@allows) {
                   5364:         $count ++; 
                   5365:         my $acctype = 'allowfrom';
                   5366:         if ($count <= $numdenies) {
                   5367:             $acctype = 'denyfrom';
                   5368:         }
1.682     raeburn  5369:         if ($pattern =~ /\*$/) {
                   5370:             #35.8.*
                   5371:             $pattern=~s/\*//;
1.1219    raeburn  5372:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5373:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5374:             #35.8.3.[34-56]
                   5375:             my $low=$2;
                   5376:             my $high=$3;
                   5377:             $pattern=$1;
                   5378:             if ($ip =~ /^\Q$pattern\E/) {
                   5379:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5380:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5381:             }
                   5382:         } elsif ($pattern =~ /^\*/) {
                   5383:             #*.msu.edu
                   5384:             $pattern=~s/\*//;
                   5385:             if (!defined($name)) {
                   5386:                 use Socket;
                   5387:                 my $netaddr=inet_aton($ip);
                   5388:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5389:             }
1.1219    raeburn  5390:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5391:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5392:             #127.0.0.1
1.1219    raeburn  5393:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5394:         } else {
                   5395:             #some.name.com
                   5396:             if (!defined($name)) {
                   5397:                 use Socket;
                   5398:                 my $netaddr=inet_aton($ip);
                   5399:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5400:             }
1.1219    raeburn  5401:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5402:         }
                   5403:         if ($allowed =~ /^(0|1)$/) { last; }
                   5404:     }
                   5405:     if ($allowed eq '') {
                   5406:         if ($numdenies && !$numallows) {
                   5407:             $allowed = 1;
                   5408:         } else {
                   5409:             $allowed = 0;
1.682     raeburn  5410:         }
                   5411:     }
                   5412:     return $allowed;
                   5413: }
                   5414: 
                   5415: ###############################################
                   5416: 
1.60      matthew  5417: =pod
                   5418: 
1.112     bowersj2 5419: =head1 Domain Template Functions
                   5420: 
                   5421: =over 4
                   5422: 
                   5423: =item * &determinedomain()
1.60      matthew  5424: 
                   5425: Inputs: $domain (usually will be undef)
                   5426: 
1.63      www      5427: Returns: Determines which domain should be used for designs
1.60      matthew  5428: 
                   5429: =cut
1.54      www      5430: 
1.60      matthew  5431: ###############################################
1.63      www      5432: sub determinedomain {
                   5433:     my $domain=shift;
1.531     albertel 5434:     if (! $domain) {
1.60      matthew  5435:         # Determine domain if we have not been given one
1.893     raeburn  5436:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5437:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5438:         if ($env{'request.role.domain'}) { 
                   5439:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5440:         }
                   5441:     }
1.63      www      5442:     return $domain;
                   5443: }
                   5444: ###############################################
1.517     raeburn  5445: 
1.518     albertel 5446: sub devalidate_domconfig_cache {
                   5447:     my ($udom)=@_;
                   5448:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5449: }
                   5450: 
                   5451: # ---------------------- Get domain configuration for a domain
                   5452: sub get_domainconf {
                   5453:     my ($udom) = @_;
                   5454:     my $cachetime=1800;
                   5455:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5456:     if (defined($cached)) { return %{$result}; }
                   5457: 
                   5458:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5459: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5460:     my (%designhash,%legacy);
1.518     albertel 5461:     if (keys(%domconfig) > 0) {
                   5462:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5463:             if (keys(%{$domconfig{'login'}})) {
                   5464:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5465:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5466:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5467:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5468:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5469:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5470:                                         if ($key eq 'loginvia') {
                   5471:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5472:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5473:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5474:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5475: 
                   5476:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5477:                                                 } else {
                   5478:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5479:                                                 }
1.948     raeburn  5480:                                             }
1.1208    raeburn  5481:                                         } elsif ($key eq 'headtag') {
                   5482:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5483:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5484:                                             }
1.946     raeburn  5485:                                         }
1.1208    raeburn  5486:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5487:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5488:                                         }
1.946     raeburn  5489:                                     }
                   5490:                                 }
                   5491:                             }
                   5492:                         } else {
                   5493:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5494:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5495:                                     $domconfig{'login'}{$key}{$img};
                   5496:                             }
1.699     raeburn  5497:                         }
                   5498:                     } else {
                   5499:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5500:                     }
1.632     raeburn  5501:                 }
                   5502:             } else {
                   5503:                 $legacy{'login'} = 1;
1.518     albertel 5504:             }
1.632     raeburn  5505:         } else {
                   5506:             $legacy{'login'} = 1;
1.518     albertel 5507:         }
                   5508:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5509:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5510:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5511:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5512:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5513:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5514:                         }
1.518     albertel 5515:                     }
                   5516:                 }
1.632     raeburn  5517:             } else {
                   5518:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5519:             }
1.632     raeburn  5520:         } else {
                   5521:             $legacy{'rolecolors'} = 1;
1.518     albertel 5522:         }
1.948     raeburn  5523:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5524:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5525:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5526:             }
                   5527:         }
1.632     raeburn  5528:         if (keys(%legacy) > 0) {
                   5529:             my %legacyhash = &get_legacy_domconf($udom);
                   5530:             foreach my $item (keys(%legacyhash)) {
                   5531:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5532:                     if ($legacy{'login'}) { 
                   5533:                         $designhash{$item} = $legacyhash{$item};
                   5534:                     }
                   5535:                 } else {
                   5536:                     if ($legacy{'rolecolors'}) {
                   5537:                         $designhash{$item} = $legacyhash{$item};
                   5538:                     }
1.518     albertel 5539:                 }
                   5540:             }
                   5541:         }
1.632     raeburn  5542:     } else {
                   5543:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5544:     }
                   5545:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5546: 				  $cachetime);
                   5547:     return %designhash;
                   5548: }
                   5549: 
1.632     raeburn  5550: sub get_legacy_domconf {
                   5551:     my ($udom) = @_;
                   5552:     my %legacyhash;
                   5553:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5554:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5555:     if (-e $designfile) {
                   5556:         if ( open (my $fh,"<$designfile") ) {
                   5557:             while (my $line = <$fh>) {
                   5558:                 next if ($line =~ /^\#/);
                   5559:                 chomp($line);
                   5560:                 my ($key,$val)=(split(/\=/,$line));
                   5561:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5562:             }
                   5563:             close($fh);
                   5564:         }
                   5565:     }
1.1026    raeburn  5566:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5567:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5568:     }
                   5569:     return %legacyhash;
                   5570: }
                   5571: 
1.63      www      5572: =pod
                   5573: 
1.112     bowersj2 5574: =item * &domainlogo()
1.63      www      5575: 
                   5576: Inputs: $domain (usually will be undef)
                   5577: 
                   5578: Returns: A link to a domain logo, if the domain logo exists.
                   5579: If the domain logo does not exist, a description of the domain.
                   5580: 
                   5581: =cut
1.112     bowersj2 5582: 
1.63      www      5583: ###############################################
                   5584: sub domainlogo {
1.517     raeburn  5585:     my $domain = &determinedomain(shift);
1.518     albertel 5586:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5587:     # See if there is a logo
                   5588:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5589:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5590:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5591: 	    if ($imgsrc =~ m{^/res/}) {
                   5592: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5593: 		&Apache::lonnet::repcopy($local_name);
                   5594: 	    }
                   5595: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5596:         } 
                   5597:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5598:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5599:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5600:     } else {
1.60      matthew  5601:         return '';
1.59      www      5602:     }
                   5603: }
1.63      www      5604: ##############################################
                   5605: 
                   5606: =pod
                   5607: 
1.112     bowersj2 5608: =item * &designparm()
1.63      www      5609: 
                   5610: Inputs: $which parameter; $domain (usually will be undef)
                   5611: 
                   5612: Returns: value of designparamter $which
                   5613: 
                   5614: =cut
1.112     bowersj2 5615: 
1.397     albertel 5616: 
1.400     albertel 5617: ##############################################
1.397     albertel 5618: sub designparm {
                   5619:     my ($which,$domain)=@_;
                   5620:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5621:         return $env{'environment.color.'.$which};
1.96      www      5622:     }
1.63      www      5623:     $domain=&determinedomain($domain);
1.1016    raeburn  5624:     my %domdesign;
                   5625:     unless ($domain eq 'public') {
                   5626:         %domdesign = &get_domainconf($domain);
                   5627:     }
1.520     raeburn  5628:     my $output;
1.517     raeburn  5629:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5630:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5631:     } else {
1.520     raeburn  5632:         $output = $defaultdesign{$which};
                   5633:     }
                   5634:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5635:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5636:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5637:             if ($output =~ m{^/res/}) {
                   5638:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5639:                 &Apache::lonnet::repcopy($local_name);
                   5640:             }
1.520     raeburn  5641:             $output = &lonhttpdurl($output);
                   5642:         }
1.63      www      5643:     }
1.520     raeburn  5644:     return $output;
1.63      www      5645: }
1.59      www      5646: 
1.822     bisitz   5647: ##############################################
                   5648: =pod
                   5649: 
1.832     bisitz   5650: =item * &authorspace()
                   5651: 
1.1028    raeburn  5652: Inputs: $url (usually will be undef).
1.832     bisitz   5653: 
1.1132    raeburn  5654: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5655:          directory being viewed (or for which action is being taken). 
                   5656:          If $url is provided, and begins /priv/<domain>/<uname>
                   5657:          the path will be that portion of the $context argument.
                   5658:          Otherwise the path will be for the author space of the current
                   5659:          user when the current role is author, or for that of the 
                   5660:          co-author/assistant co-author space when the current role 
                   5661:          is co-author or assistant co-author.
1.832     bisitz   5662: 
                   5663: =cut
                   5664: 
                   5665: sub authorspace {
1.1028    raeburn  5666:     my ($url) = @_;
                   5667:     if ($url ne '') {
                   5668:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5669:            return $1;
                   5670:         }
                   5671:     }
1.832     bisitz   5672:     my $caname = '';
1.1024    www      5673:     my $cadom = '';
1.1028    raeburn  5674:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5675:         ($cadom,$caname) =
1.832     bisitz   5676:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5677:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5678:         $caname = $env{'user.name'};
1.1024    www      5679:         $cadom = $env{'user.domain'};
1.832     bisitz   5680:     }
1.1028    raeburn  5681:     if (($caname ne '') && ($cadom ne '')) {
                   5682:         return "/priv/$cadom/$caname/";
                   5683:     }
                   5684:     return;
1.832     bisitz   5685: }
                   5686: 
                   5687: ##############################################
                   5688: =pod
                   5689: 
1.822     bisitz   5690: =item * &head_subbox()
                   5691: 
                   5692: Inputs: $content (contains HTML code with page functions, etc.)
                   5693: 
                   5694: Returns: HTML div with $content
                   5695:          To be included in page header
                   5696: 
                   5697: =cut
                   5698: 
                   5699: sub head_subbox {
                   5700:     my ($content)=@_;
                   5701:     my $output =
1.993     raeburn  5702:         '<div class="LC_head_subbox">'
1.822     bisitz   5703:        .$content
                   5704:        .'</div>'
                   5705: }
                   5706: 
                   5707: ##############################################
                   5708: =pod
                   5709: 
                   5710: =item * &CSTR_pageheader()
                   5711: 
1.1026    raeburn  5712: Input: (optional) filename from which breadcrumb trail is built.
                   5713:        In most cases no input as needed, as $env{'request.filename'}
                   5714:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5715: 
                   5716: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5717:          To be included on Authoring Space pages
1.822     bisitz   5718: 
                   5719: =cut
                   5720: 
                   5721: sub CSTR_pageheader {
1.1026    raeburn  5722:     my ($trailfile) = @_;
                   5723:     if ($trailfile eq '') {
                   5724:         $trailfile = $env{'request.filename'};
                   5725:     }
                   5726: 
                   5727: # this is for resources; directories have customtitle, and crumbs
                   5728: # and select recent are created in lonpubdir.pm
                   5729: 
                   5730:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5731:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5732:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5733:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5734:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5735: 
                   5736:     my $parentpath = '';
                   5737:     my $lastitem = '';
                   5738:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5739:         $parentpath = $1;
                   5740:         $lastitem = $2;
                   5741:     } else {
                   5742:         $lastitem = $thisdisfn;
                   5743:     }
1.921     bisitz   5744: 
1.1246    raeburn  5745:     my ($crsauthor,$title);
                   5746:     if (($env{'request.course.id'}) &&
                   5747:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  5748:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  5749:         $crsauthor = 1;
                   5750:         $title = &mt('Course Authoring Space');
                   5751:     } else {
                   5752:         $title = &mt('Authoring Space');
                   5753:     }
                   5754: 
1.921     bisitz   5755:     my $output =
1.822     bisitz   5756:          '<div>'
                   5757:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  5758:         .'<b>'.$title.'</b> '
1.822     bisitz   5759:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5760:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5761:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5762: 
                   5763:     if ($lastitem) {
                   5764:         $output .=
                   5765:              '<span class="LC_filename">'
                   5766:             .$lastitem
                   5767:             .'</span>';
                   5768:     }
1.1245    raeburn  5769: 
1.1246    raeburn  5770:     if ($crsauthor) {
                   5771:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
                   5772:     } else {
                   5773:         $output .=
                   5774:              '<br />'
                   5775:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5776:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5777:             .'</form>'
                   5778:             .&Apache::lonmenu::constspaceform();
                   5779:     }
                   5780:     $output .= '</div>';
1.921     bisitz   5781: 
                   5782:     return $output;
1.822     bisitz   5783: }
                   5784: 
1.60      matthew  5785: ###############################################
                   5786: ###############################################
                   5787: 
                   5788: =pod
                   5789: 
1.112     bowersj2 5790: =back
                   5791: 
1.549     albertel 5792: =head1 HTML Helpers
1.112     bowersj2 5793: 
                   5794: =over 4
                   5795: 
                   5796: =item * &bodytag()
1.60      matthew  5797: 
                   5798: Returns a uniform header for LON-CAPA web pages.
                   5799: 
                   5800: Inputs: 
                   5801: 
1.112     bowersj2 5802: =over 4
                   5803: 
                   5804: =item * $title, A title to be displayed on the page.
                   5805: 
                   5806: =item * $function, the current role (can be undef).
                   5807: 
                   5808: =item * $addentries, extra parameters for the <body> tag.
                   5809: 
                   5810: =item * $bodyonly, if defined, only return the <body> tag.
                   5811: 
                   5812: =item * $domain, if defined, force a given domain.
                   5813: 
                   5814: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5815:             text interface only)
1.60      matthew  5816: 
1.814     bisitz   5817: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5818:                      navigational links
1.317     albertel 5819: 
1.338     albertel 5820: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5821: 
1.460     albertel 5822: =item * $args, optional argument valid values are
                   5823:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  5824:             use_absolute     -> for external resource or syllabus, this will
                   5825:                                 contain https://<hostname> if server uses
                   5826:                                 https (as per hosts.tab), but request is for http
                   5827:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5828: 
1.1096    raeburn  5829: =item * $advtoolsref, optional argument, ref to an array containing
                   5830:             inlineremote items to be added in "Functions" menu below
                   5831:             breadcrumbs.
                   5832: 
1.112     bowersj2 5833: =back
                   5834: 
1.60      matthew  5835: Returns: A uniform header for LON-CAPA web pages.  
                   5836: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5837: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5838: other decorations will be returned.
                   5839: 
                   5840: =cut
                   5841: 
1.54      www      5842: sub bodytag {
1.831     bisitz   5843:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5844:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5845: 
1.954     raeburn  5846:     my $public;
                   5847:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5848:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5849:         $public = 1;
                   5850:     }
1.460     albertel 5851:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5852:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  5853:     my $hostname = $args->{'hostname'};
1.339     albertel 5854: 
1.183     matthew  5855:     $function = &get_users_function() if (!$function);
1.339     albertel 5856:     my $img =    &designparm($function.'.img',$domain);
                   5857:     my $font =   &designparm($function.'.font',$domain);
                   5858:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5859: 
1.803     bisitz   5860:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5861: 		   'bgcolor' => $pgbg,
1.339     albertel 5862: 		   'text'    => $font,
                   5863:                    'alink'   => &designparm($function.'.alink',$domain),
                   5864: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5865: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5866:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5867: 
1.63      www      5868:  # role and realm
1.1178    raeburn  5869:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5870:     if ($realm) {
                   5871:         $realm = '/'.$realm;
                   5872:     }
1.378     raeburn  5873:     if ($role  eq 'ca') {
1.479     albertel 5874:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5875:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5876:     } 
1.55      www      5877: # realm
1.258     albertel 5878:     if ($env{'request.course.id'}) {
1.378     raeburn  5879:         if ($env{'request.role'} !~ /^cr/) {
                   5880:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  5881:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  5882:             if ($env{'request.role.desc'}) {
                   5883:                 $role = $env{'request.role.desc'};
                   5884:             } else {
                   5885:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5886:             }
1.1257    raeburn  5887:         } else {
                   5888:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  5889:         }
1.898     raeburn  5890:         if ($env{'request.course.sec'}) {
                   5891:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5892:         }   
1.359     albertel 5893: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5894:     } else {
                   5895:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5896:     }
1.433     albertel 5897: 
1.359     albertel 5898:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5899: 
1.438     albertel 5900:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5901: 
1.101     www      5902: # construct main body tag
1.359     albertel 5903:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  5904: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5905: 
1.1131    raeburn  5906:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5907: 
1.1130    raeburn  5908:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5909:         return $bodytag;
1.1130    raeburn  5910:     }
1.359     albertel 5911: 
1.954     raeburn  5912:     if ($public) {
1.433     albertel 5913: 	undef($role);
                   5914:     }
1.359     albertel 5915:     
1.762     bisitz   5916:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5917:     #
                   5918:     # Extra info if you are the DC
                   5919:     my $dc_info = '';
                   5920:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5921:                         $env{'course.'.$env{'request.course.id'}.
                   5922:                                  '.domain'}.'/'})) {
                   5923:         my $cid = $env{'request.course.id'};
1.917     raeburn  5924:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5925:         $dc_info =~ s/\s+$//;
1.359     albertel 5926:     }
                   5927: 
1.1237    raeburn  5928:     my $crstype;
                   5929:     if ($env{'request.course.id'}) {
                   5930:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                   5931:     } elsif ($args->{'crstype'}) {
                   5932:         $crstype = $args->{'crstype'};
                   5933:     }
                   5934:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   5935:         undef($role);
                   5936:     } else {
1.1242    raeburn  5937:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  5938:     }
1.853     droeschl 5939: 
1.903     droeschl 5940:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5941: 
                   5942:         #    if ($env{'request.state'} eq 'construct') {
                   5943:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5944:         #    }
                   5945: 
1.1130    raeburn  5946:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5947:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5948: 
1.1237    raeburn  5949:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
1.359     albertel 5950: 
1.916     droeschl 5951:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5952:              if ($dc_info) {
                   5953:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5954:              }
1.1130    raeburn  5955:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5956:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5957:             return $bodytag;
                   5958:         }
1.894     droeschl 5959: 
1.927     raeburn  5960:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5961:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5962:         }
1.916     droeschl 5963: 
1.1130    raeburn  5964:         $bodytag .= $right;
1.852     droeschl 5965: 
1.917     raeburn  5966:         if ($dc_info) {
                   5967:             $dc_info = &dc_courseid_toggle($dc_info);
                   5968:         }
                   5969:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5970: 
1.1169    raeburn  5971:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5972:         if ($args->{'no_secondary_menu'}) {
                   5973:             return $bodytag;
                   5974:         }
1.1169    raeburn  5975:         #don't show menus for public users
1.954     raeburn  5976:         if (!$public){
1.1154    raeburn  5977:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5978:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5979:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5980:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5981:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1274    raeburn  5982:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1096    raeburn  5983:             } elsif ($forcereg) {
                   5984:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  5985:                                                             $args->{'group'},
1.1274    raeburn  5986:                                                             $args->{'hide_buttons'},
                   5987:                                                             $hostname);
1.1096    raeburn  5988:             } else {
                   5989:                 $bodytag .= 
                   5990:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5991:                                                         $forcereg,$args->{'group'},
                   5992:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  5993:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  5994:             }
1.903     droeschl 5995:         }else{
                   5996:             # this is to seperate menu from content when there's no secondary
                   5997:             # menu. Especially needed for public accessible ressources.
                   5998:             $bodytag .= '<hr style="clear:both" />';
                   5999:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6000:         }
1.903     droeschl 6001: 
1.235     raeburn  6002:         return $bodytag;
1.182     matthew  6003: }
                   6004: 
1.917     raeburn  6005: sub dc_courseid_toggle {
                   6006:     my ($dc_info) = @_;
1.980     raeburn  6007:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6008:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6009:            &mt('(More ...)').'</a></span>'.
                   6010:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6011: }
                   6012: 
1.330     albertel 6013: sub make_attr_string {
                   6014:     my ($register,$attr_ref) = @_;
                   6015: 
                   6016:     if ($attr_ref && !ref($attr_ref)) {
                   6017: 	die("addentries Must be a hash ref ".
                   6018: 	    join(':',caller(1))." ".
                   6019: 	    join(':',caller(0))." ");
                   6020:     }
                   6021: 
                   6022:     if ($register) {
1.339     albertel 6023: 	my ($on_load,$on_unload);
                   6024: 	foreach my $key (keys(%{$attr_ref})) {
                   6025: 	    if      (lc($key) eq 'onload') {
                   6026: 		$on_load.=$attr_ref->{$key}.';';
                   6027: 		delete($attr_ref->{$key});
                   6028: 
                   6029: 	    } elsif (lc($key) eq 'onunload') {
                   6030: 		$on_unload.=$attr_ref->{$key}.';';
                   6031: 		delete($attr_ref->{$key});
                   6032: 	    }
                   6033: 	}
1.953     droeschl 6034: 	$attr_ref->{'onload'}  = $on_load;
                   6035: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6036:     }
1.339     albertel 6037: 
1.330     albertel 6038:     my $attr_string;
1.1159    raeburn  6039:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6040: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6041:     }
                   6042:     return $attr_string;
                   6043: }
                   6044: 
                   6045: 
1.182     matthew  6046: ###############################################
1.251     albertel 6047: ###############################################
                   6048: 
                   6049: =pod
                   6050: 
                   6051: =item * &endbodytag()
                   6052: 
                   6053: Returns a uniform footer for LON-CAPA web pages.
                   6054: 
1.635     raeburn  6055: Inputs: 1 - optional reference to an args hash
                   6056: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6057: a 'Continue' link is not displayed if the page contains an
                   6058: internal redirect in the <head></head> section,
                   6059: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6060: 
                   6061: =cut
                   6062: 
                   6063: sub endbodytag {
1.635     raeburn  6064:     my ($args) = @_;
1.1080    raeburn  6065:     my $endbodytag;
                   6066:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6067:         $endbodytag='</body>';
                   6068:     }
1.315     albertel 6069:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6070:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6071: 	    $endbodytag=
                   6072: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6073: 	        &mt('Continue').'</a>'.
                   6074: 	        $endbodytag;
                   6075:         }
1.315     albertel 6076:     }
1.251     albertel 6077:     return $endbodytag;
                   6078: }
                   6079: 
1.352     albertel 6080: =pod
                   6081: 
                   6082: =item * &standard_css()
                   6083: 
                   6084: Returns a style sheet
                   6085: 
                   6086: Inputs: (all optional)
                   6087:             domain         -> force to color decorate a page for a specific
                   6088:                                domain
                   6089:             function       -> force usage of a specific rolish color scheme
                   6090:             bgcolor        -> override the default page bgcolor
                   6091: 
                   6092: =cut
                   6093: 
1.343     albertel 6094: sub standard_css {
1.345     albertel 6095:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6096:     $function  = &get_users_function() if (!$function);
                   6097:     my $img    = &designparm($function.'.img',   $domain);
                   6098:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6099:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6100:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6101: #second colour for later usage
1.345     albertel 6102:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6103:     my $pgbg_or_bgcolor =
                   6104: 	         $bgcolor ||
1.352     albertel 6105: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6106:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6107:     my $alink  = &designparm($function.'.alink', $domain);
                   6108:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6109:     my $link   = &designparm($function.'.link',  $domain);
                   6110: 
1.602     albertel 6111:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6112:     my $mono                 = 'monospace';
1.850     bisitz   6113:     my $data_table_head      = $sidebg;
                   6114:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6115:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6116:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6117:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6118:     my $mail_new             = '#FFBB77';
                   6119:     my $mail_new_hover       = '#DD9955';
                   6120:     my $mail_read            = '#BBBB77';
                   6121:     my $mail_read_hover      = '#999944';
                   6122:     my $mail_replied         = '#AAAA88';
                   6123:     my $mail_replied_hover   = '#888855';
                   6124:     my $mail_other           = '#99BBBB';
                   6125:     my $mail_other_hover     = '#669999';
1.391     albertel 6126:     my $table_header         = '#DDDDDD';
1.489     raeburn  6127:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6128:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6129:     my $button_hover         = '#BF2317';
1.392     albertel 6130: 
1.608     albertel 6131:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6132:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6133:                                              : '0 3px 0 4px';
1.448     albertel 6134: 
1.523     albertel 6135: 
1.343     albertel 6136:     return <<END;
1.947     droeschl 6137: 
                   6138: /* needed for iframe to allow 100% height in FF */
                   6139: body, html { 
                   6140:     margin: 0;
                   6141:     padding: 0 0.5%;
                   6142:     height: 99%; /* to avoid scrollbars */
                   6143: }
                   6144: 
1.795     www      6145: body {
1.911     bisitz   6146:   font-family: $sans;
                   6147:   line-height:130%;
                   6148:   font-size:0.83em;
                   6149:   color:$font;
1.795     www      6150: }
                   6151: 
1.959     onken    6152: a:focus,
                   6153: a:focus img {
1.795     www      6154:   color: red;
                   6155: }
1.698     harmsja  6156: 
1.911     bisitz   6157: form, .inline {
                   6158:   display: inline;
1.795     www      6159: }
1.721     harmsja  6160: 
1.795     www      6161: .LC_right {
1.911     bisitz   6162:   text-align:right;
1.795     www      6163: }
                   6164: 
                   6165: .LC_middle {
1.911     bisitz   6166:   vertical-align:middle;
1.795     www      6167: }
1.721     harmsja  6168: 
1.1130    raeburn  6169: .LC_floatleft {
                   6170:   float: left;
                   6171: }
                   6172: 
                   6173: .LC_floatright {
                   6174:   float: right;
                   6175: }
                   6176: 
1.911     bisitz   6177: .LC_400Box {
                   6178:   width:400px;
                   6179: }
1.721     harmsja  6180: 
1.947     droeschl 6181: .LC_iframecontainer {
                   6182:     width: 98%;
                   6183:     margin: 0;
                   6184:     position: fixed;
                   6185:     top: 8.5em;
                   6186:     bottom: 0;
                   6187: }
                   6188: 
                   6189: .LC_iframecontainer iframe{
                   6190:     border: none;
                   6191:     width: 100%;
                   6192:     height: 100%;
                   6193: }
                   6194: 
1.778     bisitz   6195: .LC_filename {
                   6196:   font-family: $mono;
                   6197:   white-space:pre;
1.921     bisitz   6198:   font-size: 120%;
1.778     bisitz   6199: }
                   6200: 
                   6201: .LC_fileicon {
                   6202:   border: none;
                   6203:   height: 1.3em;
                   6204:   vertical-align: text-bottom;
                   6205:   margin-right: 0.3em;
                   6206:   text-decoration:none;
                   6207: }
                   6208: 
1.1008    www      6209: .LC_setting {
                   6210:   text-decoration:underline;
                   6211: }
                   6212: 
1.350     albertel 6213: .LC_error {
                   6214:   color: red;
                   6215: }
1.795     www      6216: 
1.1097    bisitz   6217: .LC_warning {
                   6218:   color: darkorange;
                   6219: }
                   6220: 
1.457     albertel 6221: .LC_diff_removed {
1.733     bisitz   6222:   color: red;
1.394     albertel 6223: }
1.532     albertel 6224: 
                   6225: .LC_info,
1.457     albertel 6226: .LC_success,
                   6227: .LC_diff_added {
1.350     albertel 6228:   color: green;
                   6229: }
1.795     www      6230: 
1.802     bisitz   6231: div.LC_confirm_box {
                   6232:   background-color: #FAFAFA;
                   6233:   border: 1px solid $lg_border_color;
                   6234:   margin-right: 0;
                   6235:   padding: 5px;
                   6236: }
                   6237: 
                   6238: div.LC_confirm_box .LC_error img,
                   6239: div.LC_confirm_box .LC_success img {
                   6240:   vertical-align: middle;
                   6241: }
                   6242: 
1.1242    raeburn  6243: .LC_maxwidth {
                   6244:   max-width: 100%;
                   6245:   height: auto;
                   6246: }
                   6247: 
1.1243    raeburn  6248: .LC_textsize_mobile {
                   6249:   \@media only screen and (max-device-width: 480px) {
                   6250:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6251:   }
                   6252: }
                   6253: 
1.440     albertel 6254: .LC_icon {
1.771     droeschl 6255:   border: none;
1.790     droeschl 6256:   vertical-align: middle;
1.771     droeschl 6257: }
                   6258: 
1.543     albertel 6259: .LC_docs_spacer {
                   6260:   width: 25px;
                   6261:   height: 1px;
1.771     droeschl 6262:   border: none;
1.543     albertel 6263: }
1.346     albertel 6264: 
1.532     albertel 6265: .LC_internal_info {
1.735     bisitz   6266:   color: #999999;
1.532     albertel 6267: }
                   6268: 
1.794     www      6269: .LC_discussion {
1.1050    www      6270:   background: $data_table_dark;
1.911     bisitz   6271:   border: 1px solid black;
                   6272:   margin: 2px;
1.794     www      6273: }
                   6274: 
                   6275: .LC_disc_action_left {
1.1050    www      6276:   background: $sidebg;
1.911     bisitz   6277:   text-align: left;
1.1050    www      6278:   padding: 4px;
                   6279:   margin: 2px;
1.794     www      6280: }
                   6281: 
                   6282: .LC_disc_action_right {
1.1050    www      6283:   background: $sidebg;
1.911     bisitz   6284:   text-align: right;
1.1050    www      6285:   padding: 4px;
                   6286:   margin: 2px;
1.794     www      6287: }
                   6288: 
                   6289: .LC_disc_new_item {
1.911     bisitz   6290:   background: white;
                   6291:   border: 2px solid red;
1.1050    www      6292:   margin: 4px;
                   6293:   padding: 4px;
1.794     www      6294: }
                   6295: 
                   6296: .LC_disc_old_item {
1.911     bisitz   6297:   background: white;
1.1050    www      6298:   margin: 4px;
                   6299:   padding: 4px;
1.794     www      6300: }
                   6301: 
1.458     albertel 6302: table.LC_pastsubmission {
                   6303:   border: 1px solid black;
                   6304:   margin: 2px;
                   6305: }
                   6306: 
1.924     bisitz   6307: table#LC_menubuttons {
1.345     albertel 6308:   width: 100%;
                   6309:   background: $pgbg;
1.392     albertel 6310:   border: 2px;
1.402     albertel 6311:   border-collapse: separate;
1.803     bisitz   6312:   padding: 0;
1.345     albertel 6313: }
1.392     albertel 6314: 
1.801     tempelho 6315: table#LC_title_bar a {
                   6316:   color: $fontmenu;
                   6317: }
1.836     bisitz   6318: 
1.807     droeschl 6319: table#LC_title_bar {
1.819     tempelho 6320:   clear: both;
1.836     bisitz   6321:   display: none;
1.807     droeschl 6322: }
                   6323: 
1.795     www      6324: table#LC_title_bar,
1.933     droeschl 6325: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6326: table#LC_title_bar.LC_with_remote {
1.359     albertel 6327:   width: 100%;
1.392     albertel 6328:   border-color: $pgbg;
                   6329:   border-style: solid;
                   6330:   border-width: $border;
1.379     albertel 6331:   background: $pgbg;
1.801     tempelho 6332:   color: $fontmenu;
1.392     albertel 6333:   border-collapse: collapse;
1.803     bisitz   6334:   padding: 0;
1.819     tempelho 6335:   margin: 0;
1.359     albertel 6336: }
1.795     www      6337: 
1.933     droeschl 6338: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6339:     margin: 0;
                   6340:     padding: 0;
1.933     droeschl 6341:     position: relative;
                   6342:     list-style: none;
1.913     droeschl 6343: }
1.933     droeschl 6344: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6345:     display: inline;
                   6346: }
1.933     droeschl 6347: 
                   6348: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6349:     padding: 0;
1.933     droeschl 6350:     margin: 0;
                   6351:     float: left;
1.913     droeschl 6352: }
1.933     droeschl 6353: .LC_breadcrumb_tools_tools {
                   6354:     padding: 0;
                   6355:     margin: 0;
1.913     droeschl 6356:     float: right;
                   6357: }
                   6358: 
1.1240    raeburn  6359: .LC_placement_prog {
                   6360:     padding-right: 20px;
                   6361:     font-weight: bold;
                   6362:     font-size: 90%;
                   6363: }
                   6364: 
1.359     albertel 6365: table#LC_title_bar td {
                   6366:   background: $tabbg;
                   6367: }
1.795     www      6368: 
1.911     bisitz   6369: table#LC_menubuttons img {
1.803     bisitz   6370:   border: none;
1.346     albertel 6371: }
1.795     www      6372: 
1.842     droeschl 6373: .LC_breadcrumbs_component {
1.911     bisitz   6374:   float: right;
                   6375:   margin: 0 1em;
1.357     albertel 6376: }
1.842     droeschl 6377: .LC_breadcrumbs_component img {
1.911     bisitz   6378:   vertical-align: middle;
1.777     tempelho 6379: }
1.795     www      6380: 
1.1243    raeburn  6381: .LC_breadcrumbs_hoverable {
                   6382:   background: $sidebg;
                   6383: }
                   6384: 
1.383     albertel 6385: td.LC_table_cell_checkbox {
                   6386:   text-align: center;
                   6387: }
1.795     www      6388: 
                   6389: .LC_fontsize_small {
1.911     bisitz   6390:   font-size: 70%;
1.705     tempelho 6391: }
                   6392: 
1.844     bisitz   6393: #LC_breadcrumbs {
1.911     bisitz   6394:   clear:both;
                   6395:   background: $sidebg;
                   6396:   border-bottom: 1px solid $lg_border_color;
                   6397:   line-height: 2.5em;
1.933     droeschl 6398:   overflow: hidden;
1.911     bisitz   6399:   margin: 0;
                   6400:   padding: 0;
1.995     raeburn  6401:   text-align: left;
1.819     tempelho 6402: }
1.862     bisitz   6403: 
1.1098    bisitz   6404: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6405:   clear:both;
                   6406:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6407:   border: 1px solid $sidebg;
1.1098    bisitz   6408:   margin: 0 0 10px 0;
1.966     bisitz   6409:   padding: 3px;
1.995     raeburn  6410:   text-align: left;
1.822     bisitz   6411: }
                   6412: 
1.795     www      6413: .LC_fontsize_medium {
1.911     bisitz   6414:   font-size: 85%;
1.705     tempelho 6415: }
                   6416: 
1.795     www      6417: .LC_fontsize_large {
1.911     bisitz   6418:   font-size: 120%;
1.705     tempelho 6419: }
                   6420: 
1.346     albertel 6421: .LC_menubuttons_inline_text {
                   6422:   color: $font;
1.698     harmsja  6423:   font-size: 90%;
1.701     harmsja  6424:   padding-left:3px;
1.346     albertel 6425: }
                   6426: 
1.934     droeschl 6427: .LC_menubuttons_inline_text img{
                   6428:   vertical-align: middle;
                   6429: }
                   6430: 
1.1051    www      6431: li.LC_menubuttons_inline_text img {
1.951     onken    6432:   cursor:pointer;
1.1002    droeschl 6433:   text-decoration: none;
1.951     onken    6434: }
                   6435: 
1.526     www      6436: .LC_menubuttons_link {
                   6437:   text-decoration: none;
                   6438: }
1.795     www      6439: 
1.522     albertel 6440: .LC_menubuttons_category {
1.521     www      6441:   color: $font;
1.526     www      6442:   background: $pgbg;
1.521     www      6443:   font-size: larger;
                   6444:   font-weight: bold;
                   6445: }
                   6446: 
1.346     albertel 6447: td.LC_menubuttons_text {
1.911     bisitz   6448:   color: $font;
1.346     albertel 6449: }
1.706     harmsja  6450: 
1.346     albertel 6451: .LC_current_location {
                   6452:   background: $tabbg;
                   6453: }
1.795     www      6454: 
1.1286    raeburn  6455: td.LC_zero_height {
                   6456:   line-height: 0; 
                   6457:   cellpadding: 0;
                   6458: }
                   6459: 
1.938     bisitz   6460: table.LC_data_table {
1.347     albertel 6461:   border: 1px solid #000000;
1.402     albertel 6462:   border-collapse: separate;
1.426     albertel 6463:   border-spacing: 1px;
1.610     albertel 6464:   background: $pgbg;
1.347     albertel 6465: }
1.795     www      6466: 
1.422     albertel 6467: .LC_data_table_dense {
                   6468:   font-size: small;
                   6469: }
1.795     www      6470: 
1.507     raeburn  6471: table.LC_nested_outer {
                   6472:   border: 1px solid #000000;
1.589     raeburn  6473:   border-collapse: collapse;
1.803     bisitz   6474:   border-spacing: 0;
1.507     raeburn  6475:   width: 100%;
                   6476: }
1.795     www      6477: 
1.879     raeburn  6478: table.LC_innerpickbox,
1.507     raeburn  6479: table.LC_nested {
1.803     bisitz   6480:   border: none;
1.589     raeburn  6481:   border-collapse: collapse;
1.803     bisitz   6482:   border-spacing: 0;
1.507     raeburn  6483:   width: 100%;
                   6484: }
1.795     www      6485: 
1.911     bisitz   6486: table.LC_data_table tr th,
                   6487: table.LC_calendar tr th,
1.879     raeburn  6488: table.LC_prior_tries tr th,
                   6489: table.LC_innerpickbox tr th {
1.349     albertel 6490:   font-weight: bold;
                   6491:   background-color: $data_table_head;
1.801     tempelho 6492:   color:$fontmenu;
1.701     harmsja  6493:   font-size:90%;
1.347     albertel 6494: }
1.795     www      6495: 
1.879     raeburn  6496: table.LC_innerpickbox tr th,
                   6497: table.LC_innerpickbox tr td {
                   6498:   vertical-align: top;
                   6499: }
                   6500: 
1.711     raeburn  6501: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6502:   background-color: #CCCCCC;
1.711     raeburn  6503:   font-weight: bold;
                   6504:   text-align: left;
                   6505: }
1.795     www      6506: 
1.912     bisitz   6507: table.LC_data_table tr.LC_odd_row > td {
                   6508:   background-color: $data_table_light;
                   6509:   padding: 2px;
                   6510:   vertical-align: top;
                   6511: }
                   6512: 
1.809     bisitz   6513: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6514:   background-color: $data_table_light;
1.912     bisitz   6515:   vertical-align: top;
                   6516: }
                   6517: 
                   6518: table.LC_data_table tr.LC_even_row > td {
                   6519:   background-color: $data_table_dark;
1.425     albertel 6520:   padding: 2px;
1.900     bisitz   6521:   vertical-align: top;
1.347     albertel 6522: }
1.795     www      6523: 
1.809     bisitz   6524: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6525:   background-color: $data_table_dark;
1.900     bisitz   6526:   vertical-align: top;
1.347     albertel 6527: }
1.795     www      6528: 
1.425     albertel 6529: table.LC_data_table tr.LC_data_table_highlight td {
                   6530:   background-color: $data_table_darker;
                   6531: }
1.795     www      6532: 
1.639     raeburn  6533: table.LC_data_table tr td.LC_leftcol_header {
                   6534:   background-color: $data_table_head;
                   6535:   font-weight: bold;
                   6536: }
1.795     www      6537: 
1.451     albertel 6538: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6539: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6540:   font-weight: bold;
                   6541:   font-style: italic;
                   6542:   text-align: center;
                   6543:   padding: 8px;
1.347     albertel 6544: }
1.795     www      6545: 
1.1114    raeburn  6546: table.LC_data_table tr.LC_empty_row td,
                   6547: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6548:   background-color: $sidebg;
                   6549: }
                   6550: 
                   6551: table.LC_nested tr.LC_empty_row td {
                   6552:   background-color: #FFFFFF;
                   6553: }
                   6554: 
1.890     droeschl 6555: table.LC_caption {
                   6556: }
                   6557: 
1.507     raeburn  6558: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6559:   padding: 4ex
                   6560: }
1.795     www      6561: 
1.507     raeburn  6562: table.LC_nested_outer tr th {
                   6563:   font-weight: bold;
1.801     tempelho 6564:   color:$fontmenu;
1.507     raeburn  6565:   background-color: $data_table_head;
1.701     harmsja  6566:   font-size: small;
1.507     raeburn  6567:   border-bottom: 1px solid #000000;
                   6568: }
1.795     www      6569: 
1.507     raeburn  6570: table.LC_nested_outer tr td.LC_subheader {
                   6571:   background-color: $data_table_head;
                   6572:   font-weight: bold;
                   6573:   font-size: small;
                   6574:   border-bottom: 1px solid #000000;
                   6575:   text-align: right;
1.451     albertel 6576: }
1.795     www      6577: 
1.507     raeburn  6578: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6579:   background-color: #CCCCCC;
1.451     albertel 6580:   font-weight: bold;
                   6581:   font-size: small;
1.507     raeburn  6582:   text-align: center;
                   6583: }
1.795     www      6584: 
1.589     raeburn  6585: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6586: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6587:   text-align: left;
1.451     albertel 6588: }
1.795     www      6589: 
1.507     raeburn  6590: table.LC_nested td {
1.735     bisitz   6591:   background-color: #FFFFFF;
1.451     albertel 6592:   font-size: small;
1.507     raeburn  6593: }
1.795     www      6594: 
1.507     raeburn  6595: table.LC_nested_outer tr th.LC_right_item,
                   6596: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6597: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6598: table.LC_nested tr td.LC_right_item {
1.451     albertel 6599:   text-align: right;
                   6600: }
                   6601: 
1.507     raeburn  6602: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6603:   background-color: #EEEEEE;
1.451     albertel 6604: }
                   6605: 
1.473     raeburn  6606: table.LC_createuser {
                   6607: }
                   6608: 
                   6609: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6610:   font-size: small;
1.473     raeburn  6611: }
                   6612: 
                   6613: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6614:   background-color: #CCCCCC;
1.473     raeburn  6615:   font-weight: bold;
                   6616:   text-align: center;
                   6617: }
                   6618: 
1.349     albertel 6619: table.LC_calendar {
                   6620:   border: 1px solid #000000;
                   6621:   border-collapse: collapse;
1.917     raeburn  6622:   width: 98%;
1.349     albertel 6623: }
1.795     www      6624: 
1.349     albertel 6625: table.LC_calendar_pickdate {
                   6626:   font-size: xx-small;
                   6627: }
1.795     www      6628: 
1.349     albertel 6629: table.LC_calendar tr td {
                   6630:   border: 1px solid #000000;
                   6631:   vertical-align: top;
1.917     raeburn  6632:   width: 14%;
1.349     albertel 6633: }
1.795     www      6634: 
1.349     albertel 6635: table.LC_calendar tr td.LC_calendar_day_empty {
                   6636:   background-color: $data_table_dark;
                   6637: }
1.795     www      6638: 
1.779     bisitz   6639: table.LC_calendar tr td.LC_calendar_day_current {
                   6640:   background-color: $data_table_highlight;
1.777     tempelho 6641: }
1.795     www      6642: 
1.938     bisitz   6643: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6644:   background-color: $mail_new;
                   6645: }
1.795     www      6646: 
1.938     bisitz   6647: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6648:   background-color: $mail_new_hover;
                   6649: }
1.795     www      6650: 
1.938     bisitz   6651: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6652:   background-color: $mail_read;
                   6653: }
1.795     www      6654: 
1.938     bisitz   6655: /*
                   6656: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6657:   background-color: $mail_read_hover;
                   6658: }
1.938     bisitz   6659: */
1.795     www      6660: 
1.938     bisitz   6661: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6662:   background-color: $mail_replied;
                   6663: }
1.795     www      6664: 
1.938     bisitz   6665: /*
                   6666: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6667:   background-color: $mail_replied_hover;
                   6668: }
1.938     bisitz   6669: */
1.795     www      6670: 
1.938     bisitz   6671: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6672:   background-color: $mail_other;
                   6673: }
1.795     www      6674: 
1.938     bisitz   6675: /*
                   6676: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6677:   background-color: $mail_other_hover;
                   6678: }
1.938     bisitz   6679: */
1.494     raeburn  6680: 
1.777     tempelho 6681: table.LC_data_table tr > td.LC_browser_file,
                   6682: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6683:   background: #AAEE77;
1.389     albertel 6684: }
1.795     www      6685: 
1.777     tempelho 6686: table.LC_data_table tr > td.LC_browser_file_locked,
                   6687: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6688:   background: #FFAA99;
1.387     albertel 6689: }
1.795     www      6690: 
1.777     tempelho 6691: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6692:   background: #888888;
1.779     bisitz   6693: }
1.795     www      6694: 
1.777     tempelho 6695: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6696: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6697:   background: #F8F866;
1.777     tempelho 6698: }
1.795     www      6699: 
1.696     bisitz   6700: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6701:   background: #E0E8FF;
1.387     albertel 6702: }
1.696     bisitz   6703: 
1.707     bisitz   6704: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6705:   /* background: #77FF77; */
1.707     bisitz   6706: }
1.795     www      6707: 
1.707     bisitz   6708: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6709:   border-right: 8px solid #FFFF77;
1.707     bisitz   6710: }
1.795     www      6711: 
1.707     bisitz   6712: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6713:   border-right: 8px solid #FFAA77;
1.707     bisitz   6714: }
1.795     www      6715: 
1.707     bisitz   6716: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6717:   border-right: 8px solid #FF7777;
1.707     bisitz   6718: }
1.795     www      6719: 
1.707     bisitz   6720: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6721:   border-right: 8px solid #AAFF77;
1.707     bisitz   6722: }
1.795     www      6723: 
1.707     bisitz   6724: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6725:   border-right: 8px solid #11CC55;
1.707     bisitz   6726: }
                   6727: 
1.388     albertel 6728: span.LC_current_location {
1.701     harmsja  6729:   font-size:larger;
1.388     albertel 6730:   background: $pgbg;
                   6731: }
1.387     albertel 6732: 
1.1029    www      6733: span.LC_current_nav_location {
                   6734:   font-weight:bold;
                   6735:   background: $sidebg;
                   6736: }
                   6737: 
1.395     albertel 6738: span.LC_parm_menu_item {
                   6739:   font-size: larger;
                   6740: }
1.795     www      6741: 
1.395     albertel 6742: span.LC_parm_scope_all {
                   6743:   color: red;
                   6744: }
1.795     www      6745: 
1.395     albertel 6746: span.LC_parm_scope_folder {
                   6747:   color: green;
                   6748: }
1.795     www      6749: 
1.395     albertel 6750: span.LC_parm_scope_resource {
                   6751:   color: orange;
                   6752: }
1.795     www      6753: 
1.395     albertel 6754: span.LC_parm_part {
                   6755:   color: blue;
                   6756: }
1.795     www      6757: 
1.911     bisitz   6758: span.LC_parm_folder,
                   6759: span.LC_parm_symb {
1.395     albertel 6760:   font-size: x-small;
                   6761:   font-family: $mono;
                   6762:   color: #AAAAAA;
                   6763: }
                   6764: 
1.977     bisitz   6765: ul.LC_parm_parmlist li {
                   6766:   display: inline-block;
                   6767:   padding: 0.3em 0.8em;
                   6768:   vertical-align: top;
                   6769:   width: 150px;
                   6770:   border-top:1px solid $lg_border_color;
                   6771: }
                   6772: 
1.795     www      6773: td.LC_parm_overview_level_menu,
                   6774: td.LC_parm_overview_map_menu,
                   6775: td.LC_parm_overview_parm_selectors,
                   6776: td.LC_parm_overview_restrictions  {
1.396     albertel 6777:   border: 1px solid black;
                   6778:   border-collapse: collapse;
                   6779: }
1.795     www      6780: 
1.1285    raeburn  6781: span.LC_parm_recursive,
                   6782: td.LC_parm_recursive {
                   6783:   font-weight: bold;
                   6784:   font-size: smaller;
                   6785: }
                   6786: 
1.396     albertel 6787: table.LC_parm_overview_restrictions td {
                   6788:   border-width: 1px 4px 1px 4px;
                   6789:   border-style: solid;
                   6790:   border-color: $pgbg;
                   6791:   text-align: center;
                   6792: }
1.795     www      6793: 
1.396     albertel 6794: table.LC_parm_overview_restrictions th {
                   6795:   background: $tabbg;
                   6796:   border-width: 1px 4px 1px 4px;
                   6797:   border-style: solid;
                   6798:   border-color: $pgbg;
                   6799: }
1.795     www      6800: 
1.398     albertel 6801: table#LC_helpmenu {
1.803     bisitz   6802:   border: none;
1.398     albertel 6803:   height: 55px;
1.803     bisitz   6804:   border-spacing: 0;
1.398     albertel 6805: }
                   6806: 
                   6807: table#LC_helpmenu fieldset legend {
                   6808:   font-size: larger;
                   6809: }
1.795     www      6810: 
1.397     albertel 6811: table#LC_helpmenu_links {
                   6812:   width: 100%;
                   6813:   border: 1px solid black;
                   6814:   background: $pgbg;
1.803     bisitz   6815:   padding: 0;
1.397     albertel 6816:   border-spacing: 1px;
                   6817: }
1.795     www      6818: 
1.397     albertel 6819: table#LC_helpmenu_links tr td {
                   6820:   padding: 1px;
                   6821:   background: $tabbg;
1.399     albertel 6822:   text-align: center;
                   6823:   font-weight: bold;
1.397     albertel 6824: }
1.396     albertel 6825: 
1.795     www      6826: table#LC_helpmenu_links a:link,
                   6827: table#LC_helpmenu_links a:visited,
1.397     albertel 6828: table#LC_helpmenu_links a:active {
                   6829:   text-decoration: none;
                   6830:   color: $font;
                   6831: }
1.795     www      6832: 
1.397     albertel 6833: table#LC_helpmenu_links a:hover {
                   6834:   text-decoration: underline;
                   6835:   color: $vlink;
                   6836: }
1.396     albertel 6837: 
1.417     albertel 6838: .LC_chrt_popup_exists {
                   6839:   border: 1px solid #339933;
                   6840:   margin: -1px;
                   6841: }
1.795     www      6842: 
1.417     albertel 6843: .LC_chrt_popup_up {
                   6844:   border: 1px solid yellow;
                   6845:   margin: -1px;
                   6846: }
1.795     www      6847: 
1.417     albertel 6848: .LC_chrt_popup {
                   6849:   border: 1px solid #8888FF;
                   6850:   background: #CCCCFF;
                   6851: }
1.795     www      6852: 
1.421     albertel 6853: table.LC_pick_box {
                   6854:   border-collapse: separate;
                   6855:   background: white;
                   6856:   border: 1px solid black;
                   6857:   border-spacing: 1px;
                   6858: }
1.795     www      6859: 
1.421     albertel 6860: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6861:   background: $sidebg;
1.421     albertel 6862:   font-weight: bold;
1.900     bisitz   6863:   text-align: left;
1.740     bisitz   6864:   vertical-align: top;
1.421     albertel 6865:   width: 184px;
                   6866:   padding: 8px;
                   6867: }
1.795     www      6868: 
1.579     raeburn  6869: table.LC_pick_box td.LC_pick_box_value {
                   6870:   text-align: left;
                   6871:   padding: 8px;
                   6872: }
1.795     www      6873: 
1.579     raeburn  6874: table.LC_pick_box td.LC_pick_box_select {
                   6875:   text-align: left;
                   6876:   padding: 8px;
                   6877: }
1.795     www      6878: 
1.424     albertel 6879: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6880:   padding: 0;
1.421     albertel 6881:   height: 1px;
                   6882:   background: black;
                   6883: }
1.795     www      6884: 
1.421     albertel 6885: table.LC_pick_box td.LC_pick_box_submit {
                   6886:   text-align: right;
                   6887: }
1.795     www      6888: 
1.579     raeburn  6889: table.LC_pick_box td.LC_evenrow_value {
                   6890:   text-align: left;
                   6891:   padding: 8px;
                   6892:   background-color: $data_table_light;
                   6893: }
1.795     www      6894: 
1.579     raeburn  6895: table.LC_pick_box td.LC_oddrow_value {
                   6896:   text-align: left;
                   6897:   padding: 8px;
                   6898:   background-color: $data_table_light;
                   6899: }
1.795     www      6900: 
1.579     raeburn  6901: span.LC_helpform_receipt_cat {
                   6902:   font-weight: bold;
                   6903: }
1.795     www      6904: 
1.424     albertel 6905: table.LC_group_priv_box {
                   6906:   background: white;
                   6907:   border: 1px solid black;
                   6908:   border-spacing: 1px;
                   6909: }
1.795     www      6910: 
1.424     albertel 6911: table.LC_group_priv_box td.LC_pick_box_title {
                   6912:   background: $tabbg;
                   6913:   font-weight: bold;
                   6914:   text-align: right;
                   6915:   width: 184px;
                   6916: }
1.795     www      6917: 
1.424     albertel 6918: table.LC_group_priv_box td.LC_groups_fixed {
                   6919:   background: $data_table_light;
                   6920:   text-align: center;
                   6921: }
1.795     www      6922: 
1.424     albertel 6923: table.LC_group_priv_box td.LC_groups_optional {
                   6924:   background: $data_table_dark;
                   6925:   text-align: center;
                   6926: }
1.795     www      6927: 
1.424     albertel 6928: table.LC_group_priv_box td.LC_groups_functionality {
                   6929:   background: $data_table_darker;
                   6930:   text-align: center;
                   6931:   font-weight: bold;
                   6932: }
1.795     www      6933: 
1.424     albertel 6934: table.LC_group_priv td {
                   6935:   text-align: left;
1.803     bisitz   6936:   padding: 0;
1.424     albertel 6937: }
                   6938: 
                   6939: .LC_navbuttons {
                   6940:   margin: 2ex 0ex 2ex 0ex;
                   6941: }
1.795     www      6942: 
1.423     albertel 6943: .LC_topic_bar {
                   6944:   font-weight: bold;
                   6945:   background: $tabbg;
1.918     wenzelju 6946:   margin: 1em 0em 1em 2em;
1.805     bisitz   6947:   padding: 3px;
1.918     wenzelju 6948:   font-size: 1.2em;
1.423     albertel 6949: }
1.795     www      6950: 
1.423     albertel 6951: .LC_topic_bar span {
1.918     wenzelju 6952:   left: 0.5em;
                   6953:   position: absolute;
1.423     albertel 6954:   vertical-align: middle;
1.918     wenzelju 6955:   font-size: 1.2em;
1.423     albertel 6956: }
1.795     www      6957: 
1.423     albertel 6958: table.LC_course_group_status {
                   6959:   margin: 20px;
                   6960: }
1.795     www      6961: 
1.423     albertel 6962: table.LC_status_selector td {
                   6963:   vertical-align: top;
                   6964:   text-align: center;
1.424     albertel 6965:   padding: 4px;
                   6966: }
1.795     www      6967: 
1.599     albertel 6968: div.LC_feedback_link {
1.616     albertel 6969:   clear: both;
1.829     kalberla 6970:   background: $sidebg;
1.779     bisitz   6971:   width: 100%;
1.829     kalberla 6972:   padding-bottom: 10px;
                   6973:   border: 1px $tabbg solid;
1.833     kalberla 6974:   height: 22px;
                   6975:   line-height: 22px;
                   6976:   padding-top: 5px;
                   6977: }
                   6978: 
                   6979: div.LC_feedback_link img {
                   6980:   height: 22px;
1.867     kalberla 6981:   vertical-align:middle;
1.829     kalberla 6982: }
                   6983: 
1.911     bisitz   6984: div.LC_feedback_link a {
1.829     kalberla 6985:   text-decoration: none;
1.489     raeburn  6986: }
1.795     www      6987: 
1.867     kalberla 6988: div.LC_comblock {
1.911     bisitz   6989:   display:inline;
1.867     kalberla 6990:   color:$font;
                   6991:   font-size:90%;
                   6992: }
                   6993: 
                   6994: div.LC_feedback_link div.LC_comblock {
                   6995:   padding-left:5px;
                   6996: }
                   6997: 
                   6998: div.LC_feedback_link div.LC_comblock a {
                   6999:   color:$font;
                   7000: }
                   7001: 
1.489     raeburn  7002: span.LC_feedback_link {
1.858     bisitz   7003:   /* background: $feedback_link_bg; */
1.599     albertel 7004:   font-size: larger;
                   7005: }
1.795     www      7006: 
1.599     albertel 7007: span.LC_message_link {
1.858     bisitz   7008:   /* background: $feedback_link_bg; */
1.599     albertel 7009:   font-size: larger;
                   7010:   position: absolute;
                   7011:   right: 1em;
1.489     raeburn  7012: }
1.421     albertel 7013: 
1.515     albertel 7014: table.LC_prior_tries {
1.524     albertel 7015:   border: 1px solid #000000;
                   7016:   border-collapse: separate;
                   7017:   border-spacing: 1px;
1.515     albertel 7018: }
1.523     albertel 7019: 
1.515     albertel 7020: table.LC_prior_tries td {
1.524     albertel 7021:   padding: 2px;
1.515     albertel 7022: }
1.523     albertel 7023: 
                   7024: .LC_answer_correct {
1.795     www      7025:   background: lightgreen;
                   7026:   color: darkgreen;
                   7027:   padding: 6px;
1.523     albertel 7028: }
1.795     www      7029: 
1.523     albertel 7030: .LC_answer_charged_try {
1.797     www      7031:   background: #FFAAAA;
1.795     www      7032:   color: darkred;
                   7033:   padding: 6px;
1.523     albertel 7034: }
1.795     www      7035: 
1.779     bisitz   7036: .LC_answer_not_charged_try,
1.523     albertel 7037: .LC_answer_no_grade,
                   7038: .LC_answer_late {
1.795     www      7039:   background: lightyellow;
1.523     albertel 7040:   color: black;
1.795     www      7041:   padding: 6px;
1.523     albertel 7042: }
1.795     www      7043: 
1.523     albertel 7044: .LC_answer_previous {
1.795     www      7045:   background: lightblue;
                   7046:   color: darkblue;
                   7047:   padding: 6px;
1.523     albertel 7048: }
1.795     www      7049: 
1.779     bisitz   7050: .LC_answer_no_message {
1.777     tempelho 7051:   background: #FFFFFF;
                   7052:   color: black;
1.795     www      7053:   padding: 6px;
1.779     bisitz   7054: }
1.795     www      7055: 
1.779     bisitz   7056: .LC_answer_unknown {
                   7057:   background: orange;
                   7058:   color: black;
1.795     www      7059:   padding: 6px;
1.777     tempelho 7060: }
1.795     www      7061: 
1.529     albertel 7062: span.LC_prior_numerical,
                   7063: span.LC_prior_string,
                   7064: span.LC_prior_custom,
                   7065: span.LC_prior_reaction,
                   7066: span.LC_prior_math {
1.925     bisitz   7067:   font-family: $mono;
1.523     albertel 7068:   white-space: pre;
                   7069: }
                   7070: 
1.525     albertel 7071: span.LC_prior_string {
1.925     bisitz   7072:   font-family: $mono;
1.525     albertel 7073:   white-space: pre;
                   7074: }
                   7075: 
1.523     albertel 7076: table.LC_prior_option {
                   7077:   width: 100%;
                   7078:   border-collapse: collapse;
                   7079: }
1.795     www      7080: 
1.911     bisitz   7081: table.LC_prior_rank,
1.795     www      7082: table.LC_prior_match {
1.528     albertel 7083:   border-collapse: collapse;
                   7084: }
1.795     www      7085: 
1.528     albertel 7086: table.LC_prior_option tr td,
                   7087: table.LC_prior_rank tr td,
                   7088: table.LC_prior_match tr td {
1.524     albertel 7089:   border: 1px solid #000000;
1.515     albertel 7090: }
                   7091: 
1.855     bisitz   7092: .LC_nobreak {
1.544     albertel 7093:   white-space: nowrap;
1.519     raeburn  7094: }
                   7095: 
1.576     raeburn  7096: span.LC_cusr_emph {
                   7097:   font-style: italic;
                   7098: }
                   7099: 
1.633     raeburn  7100: span.LC_cusr_subheading {
                   7101:   font-weight: normal;
                   7102:   font-size: 85%;
                   7103: }
                   7104: 
1.861     bisitz   7105: div.LC_docs_entry_move {
1.859     bisitz   7106:   border: 1px solid #BBBBBB;
1.545     albertel 7107:   background: #DDDDDD;
1.861     bisitz   7108:   width: 22px;
1.859     bisitz   7109:   padding: 1px;
                   7110:   margin: 0;
1.545     albertel 7111: }
                   7112: 
1.861     bisitz   7113: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7114: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7115:   font-size: x-small;
                   7116: }
1.795     www      7117: 
1.861     bisitz   7118: .LC_docs_entry_parameter {
                   7119:   white-space: nowrap;
                   7120: }
                   7121: 
1.544     albertel 7122: .LC_docs_copy {
1.545     albertel 7123:   color: #000099;
1.544     albertel 7124: }
1.795     www      7125: 
1.544     albertel 7126: .LC_docs_cut {
1.545     albertel 7127:   color: #550044;
1.544     albertel 7128: }
1.795     www      7129: 
1.544     albertel 7130: .LC_docs_rename {
1.545     albertel 7131:   color: #009900;
1.544     albertel 7132: }
1.795     www      7133: 
1.544     albertel 7134: .LC_docs_remove {
1.545     albertel 7135:   color: #990000;
                   7136: }
                   7137: 
1.1284    raeburn  7138: .LC_docs_alias {
                   7139:   color: #440055;  
                   7140: }
                   7141: 
1.1286    raeburn  7142: .LC_domprefs_email,
1.1284    raeburn  7143: .LC_docs_alias_name,
1.547     albertel 7144: .LC_docs_reinit_warn,
                   7145: .LC_docs_ext_edit {
                   7146:   font-size: x-small;
                   7147: }
                   7148: 
1.545     albertel 7149: table.LC_docs_adddocs td,
                   7150: table.LC_docs_adddocs th {
                   7151:   border: 1px solid #BBBBBB;
                   7152:   padding: 4px;
                   7153:   background: #DDDDDD;
1.543     albertel 7154: }
                   7155: 
1.584     albertel 7156: table.LC_sty_begin {
                   7157:   background: #BBFFBB;
                   7158: }
1.795     www      7159: 
1.584     albertel 7160: table.LC_sty_end {
                   7161:   background: #FFBBBB;
                   7162: }
                   7163: 
1.589     raeburn  7164: table.LC_double_column {
1.803     bisitz   7165:   border-width: 0;
1.589     raeburn  7166:   border-collapse: collapse;
                   7167:   width: 100%;
                   7168:   padding: 2px;
                   7169: }
                   7170: 
                   7171: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7172:   top: 2px;
1.589     raeburn  7173:   left: 2px;
                   7174:   width: 47%;
                   7175:   vertical-align: top;
                   7176: }
                   7177: 
                   7178: table.LC_double_column tr td.LC_right_col {
                   7179:   top: 2px;
1.779     bisitz   7180:   right: 2px;
1.589     raeburn  7181:   width: 47%;
                   7182:   vertical-align: top;
                   7183: }
                   7184: 
1.591     raeburn  7185: div.LC_left_float {
                   7186:   float: left;
                   7187:   padding-right: 5%;
1.597     albertel 7188:   padding-bottom: 4px;
1.591     raeburn  7189: }
                   7190: 
                   7191: div.LC_clear_float_header {
1.597     albertel 7192:   padding-bottom: 2px;
1.591     raeburn  7193: }
                   7194: 
                   7195: div.LC_clear_float_footer {
1.597     albertel 7196:   padding-top: 10px;
1.591     raeburn  7197:   clear: both;
                   7198: }
                   7199: 
1.597     albertel 7200: div.LC_grade_show_user {
1.941     bisitz   7201: /*  border-left: 5px solid $sidebg; */
                   7202:   border-top: 5px solid #000000;
                   7203:   margin: 50px 0 0 0;
1.936     bisitz   7204:   padding: 15px 0 5px 10px;
1.597     albertel 7205: }
1.795     www      7206: 
1.936     bisitz   7207: div.LC_grade_show_user_odd_row {
1.941     bisitz   7208: /*  border-left: 5px solid #000000; */
                   7209: }
                   7210: 
                   7211: div.LC_grade_show_user div.LC_Box {
                   7212:   margin-right: 50px;
1.597     albertel 7213: }
                   7214: 
                   7215: div.LC_grade_submissions,
                   7216: div.LC_grade_message_center,
1.936     bisitz   7217: div.LC_grade_info_links {
1.597     albertel 7218:   margin: 5px;
                   7219:   width: 99%;
                   7220:   background: #FFFFFF;
                   7221: }
1.795     www      7222: 
1.597     albertel 7223: div.LC_grade_submissions_header,
1.936     bisitz   7224: div.LC_grade_message_center_header {
1.705     tempelho 7225:   font-weight: bold;
                   7226:   font-size: large;
1.597     albertel 7227: }
1.795     www      7228: 
1.597     albertel 7229: div.LC_grade_submissions_body,
1.936     bisitz   7230: div.LC_grade_message_center_body {
1.597     albertel 7231:   border: 1px solid black;
                   7232:   width: 99%;
                   7233:   background: #FFFFFF;
                   7234: }
1.795     www      7235: 
1.613     albertel 7236: table.LC_scantron_action {
                   7237:   width: 100%;
                   7238: }
1.795     www      7239: 
1.613     albertel 7240: table.LC_scantron_action tr th {
1.698     harmsja  7241:   font-weight:bold;
                   7242:   font-style:normal;
1.613     albertel 7243: }
1.795     www      7244: 
1.779     bisitz   7245: .LC_edit_problem_header,
1.614     albertel 7246: div.LC_edit_problem_footer {
1.705     tempelho 7247:   font-weight: normal;
                   7248:   font-size:  medium;
1.602     albertel 7249:   margin: 2px;
1.1060    bisitz   7250:   background-color: $sidebg;
1.600     albertel 7251: }
1.795     www      7252: 
1.600     albertel 7253: div.LC_edit_problem_header,
1.602     albertel 7254: div.LC_edit_problem_header div,
1.614     albertel 7255: div.LC_edit_problem_footer,
                   7256: div.LC_edit_problem_footer div,
1.602     albertel 7257: div.LC_edit_problem_editxml_header,
                   7258: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7259:   z-index: 100;
1.600     albertel 7260: }
1.795     www      7261: 
1.600     albertel 7262: div.LC_edit_problem_header_title {
1.705     tempelho 7263:   font-weight: bold;
                   7264:   font-size: larger;
1.602     albertel 7265:   background: $tabbg;
                   7266:   padding: 3px;
1.1060    bisitz   7267:   margin: 0 0 5px 0;
1.602     albertel 7268: }
1.795     www      7269: 
1.602     albertel 7270: table.LC_edit_problem_header_title {
                   7271:   width: 100%;
1.600     albertel 7272:   background: $tabbg;
1.602     albertel 7273: }
                   7274: 
1.1205    golterma 7275: div.LC_edit_actionbar {
                   7276:     background-color: $sidebg;
1.1218    droeschl 7277:     margin: 0;
                   7278:     padding: 0;
                   7279:     line-height: 200%;
1.602     albertel 7280: }
1.795     www      7281: 
1.1218    droeschl 7282: div.LC_edit_actionbar div{
                   7283:     padding: 0;
                   7284:     margin: 0;
                   7285:     display: inline-block;
1.600     albertel 7286: }
1.795     www      7287: 
1.1124    bisitz   7288: .LC_edit_opt {
                   7289:   padding-left: 1em;
                   7290:   white-space: nowrap;
                   7291: }
                   7292: 
1.1152    golterma 7293: .LC_edit_problem_latexhelper{
                   7294:     text-align: right;
                   7295: }
                   7296: 
                   7297: #LC_edit_problem_colorful div{
                   7298:     margin-left: 40px;
                   7299: }
                   7300: 
1.1205    golterma 7301: #LC_edit_problem_codemirror div{
                   7302:     margin-left: 0px;
                   7303: }
                   7304: 
1.911     bisitz   7305: img.stift {
1.803     bisitz   7306:   border-width: 0;
                   7307:   vertical-align: middle;
1.677     riegler  7308: }
1.680     riegler  7309: 
1.923     bisitz   7310: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7311:   vertical-align: top;
1.777     tempelho 7312: }
1.795     www      7313: 
1.716     raeburn  7314: div.LC_createcourse {
1.911     bisitz   7315:   margin: 10px 10px 10px 10px;
1.716     raeburn  7316: }
                   7317: 
1.917     raeburn  7318: .LC_dccid {
1.1130    raeburn  7319:   float: right;
1.917     raeburn  7320:   margin: 0.2em 0 0 0;
                   7321:   padding: 0;
                   7322:   font-size: 90%;
                   7323:   display:none;
                   7324: }
                   7325: 
1.897     wenzelju 7326: ol.LC_primary_menu a:hover,
1.721     harmsja  7327: ol#LC_MenuBreadcrumbs a:hover,
                   7328: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7329: ul#LC_secondary_menu a:hover,
1.721     harmsja  7330: .LC_FormSectionClearButton input:hover
1.795     www      7331: ul.LC_TabContent   li:hover a {
1.952     onken    7332:   color:$button_hover;
1.911     bisitz   7333:   text-decoration:none;
1.693     droeschl 7334: }
                   7335: 
1.779     bisitz   7336: h1 {
1.911     bisitz   7337:   padding: 0;
                   7338:   line-height:130%;
1.693     droeschl 7339: }
1.698     harmsja  7340: 
1.911     bisitz   7341: h2,
                   7342: h3,
                   7343: h4,
                   7344: h5,
                   7345: h6 {
                   7346:   margin: 5px 0 5px 0;
                   7347:   padding: 0;
                   7348:   line-height:130%;
1.693     droeschl 7349: }
1.795     www      7350: 
                   7351: .LC_hcell {
1.911     bisitz   7352:   padding:3px 15px 3px 15px;
                   7353:   margin: 0;
                   7354:   background-color:$tabbg;
                   7355:   color:$fontmenu;
                   7356:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7357: }
1.795     www      7358: 
1.840     bisitz   7359: .LC_Box > .LC_hcell {
1.911     bisitz   7360:   margin: 0 -10px 10px -10px;
1.835     bisitz   7361: }
                   7362: 
1.721     harmsja  7363: .LC_noBorder {
1.911     bisitz   7364:   border: 0;
1.698     harmsja  7365: }
1.693     droeschl 7366: 
1.721     harmsja  7367: .LC_FormSectionClearButton input {
1.911     bisitz   7368:   background-color:transparent;
                   7369:   border: none;
                   7370:   cursor:pointer;
                   7371:   text-decoration:underline;
1.693     droeschl 7372: }
1.763     bisitz   7373: 
                   7374: .LC_help_open_topic {
1.911     bisitz   7375:   color: #FFFFFF;
                   7376:   background-color: #EEEEFF;
                   7377:   margin: 1px;
                   7378:   padding: 4px;
                   7379:   border: 1px solid #000033;
                   7380:   white-space: nowrap;
                   7381:   /* vertical-align: middle; */
1.759     neumanie 7382: }
1.693     droeschl 7383: 
1.911     bisitz   7384: dl,
                   7385: ul,
                   7386: div,
                   7387: fieldset {
                   7388:   margin: 10px 10px 10px 0;
                   7389:   /* overflow: hidden; */
1.693     droeschl 7390: }
1.795     www      7391: 
1.1211    raeburn  7392: article.geogebraweb div {
                   7393:     margin: 0;
                   7394: }
                   7395: 
1.838     bisitz   7396: fieldset > legend {
1.911     bisitz   7397:   font-weight: bold;
                   7398:   padding: 0 5px 0 5px;
1.838     bisitz   7399: }
                   7400: 
1.813     bisitz   7401: #LC_nav_bar {
1.911     bisitz   7402:   float: left;
1.995     raeburn  7403:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7404:   margin: 0 0 2px 0;
1.807     droeschl 7405: }
                   7406: 
1.916     droeschl 7407: #LC_realm {
                   7408:   margin: 0.2em 0 0 0;
                   7409:   padding: 0;
                   7410:   font-weight: bold;
                   7411:   text-align: center;
1.995     raeburn  7412:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7413: }
                   7414: 
1.911     bisitz   7415: #LC_nav_bar em {
                   7416:   font-weight: bold;
                   7417:   font-style: normal;
1.807     droeschl 7418: }
                   7419: 
1.897     wenzelju 7420: ol.LC_primary_menu {
1.934     droeschl 7421:   margin: 0;
1.1076    raeburn  7422:   padding: 0;
1.807     droeschl 7423: }
                   7424: 
1.852     droeschl 7425: ol#LC_PathBreadcrumbs {
1.911     bisitz   7426:   margin: 0;
1.693     droeschl 7427: }
                   7428: 
1.897     wenzelju 7429: ol.LC_primary_menu li {
1.1076    raeburn  7430:   color: RGB(80, 80, 80);
                   7431:   vertical-align: middle;
                   7432:   text-align: left;
                   7433:   list-style: none;
1.1205    golterma 7434:   position: relative;
1.1076    raeburn  7435:   float: left;
1.1205    golterma 7436:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7437:   line-height: 1.5em;
1.1076    raeburn  7438: }
                   7439: 
1.1205    golterma 7440: ol.LC_primary_menu li a,
                   7441: ol.LC_primary_menu li p {
1.1076    raeburn  7442:   display: block;
                   7443:   margin: 0;
                   7444:   padding: 0 5px 0 10px;
                   7445:   text-decoration: none;
                   7446: }
                   7447: 
1.1205    golterma 7448: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7449:   display: inline-block;
                   7450:   width: 95%;
                   7451:   text-align: left;
                   7452: }
                   7453: 
                   7454: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7455:   display: inline-block;	
                   7456:   width: 5%;
                   7457:   float: right;
                   7458:   text-align: right;
                   7459:   font-size: 70%;
                   7460: }
                   7461: 
                   7462: ol.LC_primary_menu ul {
1.1076    raeburn  7463:   display: none;
1.1205    golterma 7464:   width: 15em;
1.1076    raeburn  7465:   background-color: $data_table_light;
1.1205    golterma 7466:   position: absolute;
                   7467:   top: 100%;
1.1076    raeburn  7468: }
                   7469: 
1.1205    golterma 7470: ol.LC_primary_menu ul ul {
                   7471:   left: 100%;
                   7472:   top: 0;
                   7473: }
                   7474: 
                   7475: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7476:   display: block;
                   7477:   position: absolute;
                   7478:   margin: 0;
                   7479:   padding: 0;
1.1078    raeburn  7480:   z-index: 2;
1.1076    raeburn  7481: }
                   7482: 
                   7483: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7484: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7485:   font-size: 90%;
1.911     bisitz   7486:   vertical-align: top;
1.1076    raeburn  7487:   float: none;
1.1079    raeburn  7488:   border-left: 1px solid black;
                   7489:   border-right: 1px solid black;
1.1205    golterma 7490: /* A dark bottom border to visualize different menu options; 
                   7491: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7492:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7493: }
                   7494: 
1.1205    golterma 7495: ol.LC_primary_menu li li p:hover {
                   7496:   color:$button_hover;
                   7497:   text-decoration:none;
                   7498:   background-color:$data_table_dark;
1.1076    raeburn  7499: }
                   7500: 
                   7501: ol.LC_primary_menu li li a:hover {
                   7502:    color:$button_hover;
                   7503:    background-color:$data_table_dark;
1.693     droeschl 7504: }
                   7505: 
1.1205    golterma 7506: /* Font-size equal to the size of the predecessors*/
                   7507: ol.LC_primary_menu li:hover li li {
                   7508:   font-size: 100%;
                   7509: }
                   7510: 
1.897     wenzelju 7511: ol.LC_primary_menu li img {
1.911     bisitz   7512:   vertical-align: bottom;
1.934     droeschl 7513:   height: 1.1em;
1.1077    raeburn  7514:   margin: 0.2em 0 0 0;
1.693     droeschl 7515: }
                   7516: 
1.897     wenzelju 7517: ol.LC_primary_menu a {
1.911     bisitz   7518:   color: RGB(80, 80, 80);
                   7519:   text-decoration: none;
1.693     droeschl 7520: }
1.795     www      7521: 
1.949     droeschl 7522: ol.LC_primary_menu a.LC_new_message {
                   7523:   font-weight:bold;
                   7524:   color: darkred;
                   7525: }
                   7526: 
1.975     raeburn  7527: ol.LC_docs_parameters {
                   7528:   margin-left: 0;
                   7529:   padding: 0;
                   7530:   list-style: none;
                   7531: }
                   7532: 
                   7533: ol.LC_docs_parameters li {
                   7534:   margin: 0;
                   7535:   padding-right: 20px;
                   7536:   display: inline;
                   7537: }
                   7538: 
1.976     raeburn  7539: ol.LC_docs_parameters li:before {
                   7540:   content: "\\002022 \\0020";
                   7541: }
                   7542: 
                   7543: li.LC_docs_parameters_title {
                   7544:   font-weight: bold;
                   7545: }
                   7546: 
                   7547: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7548:   content: "";
                   7549: }
                   7550: 
1.897     wenzelju 7551: ul#LC_secondary_menu {
1.1107    raeburn  7552:   clear: right;
1.911     bisitz   7553:   color: $fontmenu;
                   7554:   background: $tabbg;
                   7555:   list-style: none;
                   7556:   padding: 0;
                   7557:   margin: 0;
                   7558:   width: 100%;
1.995     raeburn  7559:   text-align: left;
1.1107    raeburn  7560:   float: left;
1.808     droeschl 7561: }
                   7562: 
1.897     wenzelju 7563: ul#LC_secondary_menu li {
1.911     bisitz   7564:   font-weight: bold;
                   7565:   line-height: 1.8em;
1.1107    raeburn  7566:   border-right: 1px solid black;
                   7567:   float: left;
                   7568: }
                   7569: 
                   7570: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7571:   background-color: $data_table_light;
                   7572: }
                   7573: 
                   7574: ul#LC_secondary_menu li a {
1.911     bisitz   7575:   padding: 0 0.8em;
1.1107    raeburn  7576: }
                   7577: 
                   7578: ul#LC_secondary_menu li ul {
                   7579:   display: none;
                   7580: }
                   7581: 
                   7582: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7583:   display: block;
                   7584:   position: absolute;
                   7585:   margin: 0;
                   7586:   padding: 0;
                   7587:   list-style:none;
                   7588:   float: none;
                   7589:   background-color: $data_table_light;
                   7590:   z-index: 2;
                   7591:   margin-left: -1px;
                   7592: }
                   7593: 
                   7594: ul#LC_secondary_menu li ul li {
                   7595:   font-size: 90%;
                   7596:   vertical-align: top;
                   7597:   border-left: 1px solid black;
1.911     bisitz   7598:   border-right: 1px solid black;
1.1119    raeburn  7599:   background-color: $data_table_light;
1.1107    raeburn  7600:   list-style:none;
                   7601:   float: none;
                   7602: }
                   7603: 
                   7604: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7605:   background-color: $data_table_dark;
1.807     droeschl 7606: }
                   7607: 
1.847     tempelho 7608: ul.LC_TabContent {
1.911     bisitz   7609:   display:block;
                   7610:   background: $sidebg;
                   7611:   border-bottom: solid 1px $lg_border_color;
                   7612:   list-style:none;
1.1020    raeburn  7613:   margin: -1px -10px 0 -10px;
1.911     bisitz   7614:   padding: 0;
1.693     droeschl 7615: }
                   7616: 
1.795     www      7617: ul.LC_TabContent li,
                   7618: ul.LC_TabContentBigger li {
1.911     bisitz   7619:   float:left;
1.741     harmsja  7620: }
1.795     www      7621: 
1.897     wenzelju 7622: ul#LC_secondary_menu li a {
1.911     bisitz   7623:   color: $fontmenu;
                   7624:   text-decoration: none;
1.693     droeschl 7625: }
1.795     www      7626: 
1.721     harmsja  7627: ul.LC_TabContent {
1.952     onken    7628:   min-height:20px;
1.721     harmsja  7629: }
1.795     www      7630: 
                   7631: ul.LC_TabContent li {
1.911     bisitz   7632:   vertical-align:middle;
1.959     onken    7633:   padding: 0 16px 0 10px;
1.911     bisitz   7634:   background-color:$tabbg;
                   7635:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7636:   border-left: solid 1px $font;
1.721     harmsja  7637: }
1.795     www      7638: 
1.847     tempelho 7639: ul.LC_TabContent .right {
1.911     bisitz   7640:   float:right;
1.847     tempelho 7641: }
                   7642: 
1.911     bisitz   7643: ul.LC_TabContent li a,
                   7644: ul.LC_TabContent li {
                   7645:   color:rgb(47,47,47);
                   7646:   text-decoration:none;
                   7647:   font-size:95%;
                   7648:   font-weight:bold;
1.952     onken    7649:   min-height:20px;
                   7650: }
                   7651: 
1.959     onken    7652: ul.LC_TabContent li a:hover,
                   7653: ul.LC_TabContent li a:focus {
1.952     onken    7654:   color: $button_hover;
1.959     onken    7655:   background:none;
                   7656:   outline:none;
1.952     onken    7657: }
                   7658: 
                   7659: ul.LC_TabContent li:hover {
                   7660:   color: $button_hover;
                   7661:   cursor:pointer;
1.721     harmsja  7662: }
1.795     www      7663: 
1.911     bisitz   7664: ul.LC_TabContent li.active {
1.952     onken    7665:   color: $font;
1.911     bisitz   7666:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7667:   border-bottom:solid 1px #FFFFFF;
                   7668:   cursor: default;
1.744     ehlerst  7669: }
1.795     www      7670: 
1.959     onken    7671: ul.LC_TabContent li.active a {
                   7672:   color:$font;
                   7673:   background:#FFFFFF;
                   7674:   outline: none;
                   7675: }
1.1047    raeburn  7676: 
                   7677: ul.LC_TabContent li.goback {
                   7678:   float: left;
                   7679:   border-left: none;
                   7680: }
                   7681: 
1.870     tempelho 7682: #maincoursedoc {
1.911     bisitz   7683:   clear:both;
1.870     tempelho 7684: }
                   7685: 
                   7686: ul.LC_TabContentBigger {
1.911     bisitz   7687:   display:block;
                   7688:   list-style:none;
                   7689:   padding: 0;
1.870     tempelho 7690: }
                   7691: 
1.795     www      7692: ul.LC_TabContentBigger li {
1.911     bisitz   7693:   vertical-align:bottom;
                   7694:   height: 30px;
                   7695:   font-size:110%;
                   7696:   font-weight:bold;
                   7697:   color: #737373;
1.841     tempelho 7698: }
                   7699: 
1.957     onken    7700: ul.LC_TabContentBigger li.active {
                   7701:   position: relative;
                   7702:   top: 1px;
                   7703: }
                   7704: 
1.870     tempelho 7705: ul.LC_TabContentBigger li a {
1.911     bisitz   7706:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7707:   height: 30px;
                   7708:   line-height: 30px;
                   7709:   text-align: center;
                   7710:   display: block;
                   7711:   text-decoration: none;
1.958     onken    7712:   outline: none;  
1.741     harmsja  7713: }
1.795     www      7714: 
1.870     tempelho 7715: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7716:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7717:   color:$font;
1.744     ehlerst  7718: }
1.795     www      7719: 
1.870     tempelho 7720: ul.LC_TabContentBigger li b {
1.911     bisitz   7721:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7722:   display: block;
                   7723:   float: left;
                   7724:   padding: 0 30px;
1.957     onken    7725:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7726: }
                   7727: 
1.956     onken    7728: ul.LC_TabContentBigger li:hover b {
                   7729:   color:$button_hover;
                   7730: }
                   7731: 
1.870     tempelho 7732: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7733:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7734:   color:$font;
1.957     onken    7735:   border: 0;
1.741     harmsja  7736: }
1.693     droeschl 7737: 
1.870     tempelho 7738: 
1.862     bisitz   7739: ul.LC_CourseBreadcrumbs {
                   7740:   background: $sidebg;
1.1020    raeburn  7741:   height: 2em;
1.862     bisitz   7742:   padding-left: 10px;
1.1020    raeburn  7743:   margin: 0;
1.862     bisitz   7744:   list-style-position: inside;
                   7745: }
                   7746: 
1.911     bisitz   7747: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7748: ol#LC_PathBreadcrumbs {
1.911     bisitz   7749:   padding-left: 10px;
                   7750:   margin: 0;
1.933     droeschl 7751:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7752: }
                   7753: 
1.911     bisitz   7754: ol#LC_MenuBreadcrumbs li,
                   7755: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7756: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7757:   display: inline;
1.933     droeschl 7758:   white-space: normal;  
1.693     droeschl 7759: }
                   7760: 
1.823     bisitz   7761: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7762: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7763:   text-decoration: none;
                   7764:   font-size:90%;
1.693     droeschl 7765: }
1.795     www      7766: 
1.969     droeschl 7767: ol#LC_MenuBreadcrumbs h1 {
                   7768:   display: inline;
                   7769:   font-size: 90%;
                   7770:   line-height: 2.5em;
                   7771:   margin: 0;
                   7772:   padding: 0;
                   7773: }
                   7774: 
1.795     www      7775: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7776:   text-decoration:none;
                   7777:   font-size:100%;
                   7778:   font-weight:bold;
1.693     droeschl 7779: }
1.795     www      7780: 
1.840     bisitz   7781: .LC_Box {
1.911     bisitz   7782:   border: solid 1px $lg_border_color;
                   7783:   padding: 0 10px 10px 10px;
1.746     neumanie 7784: }
1.795     www      7785: 
1.1020    raeburn  7786: .LC_DocsBox {
                   7787:   border: solid 1px $lg_border_color;
                   7788:   padding: 0 0 10px 10px;
                   7789: }
                   7790: 
1.795     www      7791: .LC_AboutMe_Image {
1.911     bisitz   7792:   float:left;
                   7793:   margin-right:10px;
1.747     neumanie 7794: }
1.795     www      7795: 
                   7796: .LC_Clear_AboutMe_Image {
1.911     bisitz   7797:   clear:left;
1.747     neumanie 7798: }
1.795     www      7799: 
1.721     harmsja  7800: dl.LC_ListStyleClean dt {
1.911     bisitz   7801:   padding-right: 5px;
                   7802:   display: table-header-group;
1.693     droeschl 7803: }
                   7804: 
1.721     harmsja  7805: dl.LC_ListStyleClean dd {
1.911     bisitz   7806:   display: table-row;
1.693     droeschl 7807: }
                   7808: 
1.721     harmsja  7809: .LC_ListStyleClean,
                   7810: .LC_ListStyleSimple,
                   7811: .LC_ListStyleNormal,
1.795     www      7812: .LC_ListStyleSpecial {
1.911     bisitz   7813:   /* display:block; */
                   7814:   list-style-position: inside;
                   7815:   list-style-type: none;
                   7816:   overflow: hidden;
                   7817:   padding: 0;
1.693     droeschl 7818: }
                   7819: 
1.721     harmsja  7820: .LC_ListStyleSimple li,
                   7821: .LC_ListStyleSimple dd,
                   7822: .LC_ListStyleNormal li,
                   7823: .LC_ListStyleNormal dd,
                   7824: .LC_ListStyleSpecial li,
1.795     www      7825: .LC_ListStyleSpecial dd {
1.911     bisitz   7826:   margin: 0;
                   7827:   padding: 5px 5px 5px 10px;
                   7828:   clear: both;
1.693     droeschl 7829: }
                   7830: 
1.721     harmsja  7831: .LC_ListStyleClean li,
                   7832: .LC_ListStyleClean dd {
1.911     bisitz   7833:   padding-top: 0;
                   7834:   padding-bottom: 0;
1.693     droeschl 7835: }
                   7836: 
1.721     harmsja  7837: .LC_ListStyleSimple dd,
1.795     www      7838: .LC_ListStyleSimple li {
1.911     bisitz   7839:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7840: }
                   7841: 
1.721     harmsja  7842: .LC_ListStyleSpecial li,
                   7843: .LC_ListStyleSpecial dd {
1.911     bisitz   7844:   list-style-type: none;
                   7845:   background-color: RGB(220, 220, 220);
                   7846:   margin-bottom: 4px;
1.693     droeschl 7847: }
                   7848: 
1.721     harmsja  7849: table.LC_SimpleTable {
1.911     bisitz   7850:   margin:5px;
                   7851:   border:solid 1px $lg_border_color;
1.795     www      7852: }
1.693     droeschl 7853: 
1.721     harmsja  7854: table.LC_SimpleTable tr {
1.911     bisitz   7855:   padding: 0;
                   7856:   border:solid 1px $lg_border_color;
1.693     droeschl 7857: }
1.795     www      7858: 
                   7859: table.LC_SimpleTable thead {
1.911     bisitz   7860:   background:rgb(220,220,220);
1.693     droeschl 7861: }
                   7862: 
1.721     harmsja  7863: div.LC_columnSection {
1.911     bisitz   7864:   display: block;
                   7865:   clear: both;
                   7866:   overflow: hidden;
                   7867:   margin: 0;
1.693     droeschl 7868: }
                   7869: 
1.721     harmsja  7870: div.LC_columnSection>* {
1.911     bisitz   7871:   float: left;
                   7872:   margin: 10px 20px 10px 0;
                   7873:   overflow:hidden;
1.693     droeschl 7874: }
1.721     harmsja  7875: 
1.795     www      7876: table em {
1.911     bisitz   7877:   font-weight: bold;
                   7878:   font-style: normal;
1.748     schulted 7879: }
1.795     www      7880: 
1.779     bisitz   7881: table.LC_tableBrowseRes,
1.795     www      7882: table.LC_tableOfContent {
1.911     bisitz   7883:   border:none;
                   7884:   border-spacing: 1px;
                   7885:   padding: 3px;
                   7886:   background-color: #FFFFFF;
                   7887:   font-size: 90%;
1.753     droeschl 7888: }
1.789     droeschl 7889: 
1.911     bisitz   7890: table.LC_tableOfContent {
                   7891:   border-collapse: collapse;
1.789     droeschl 7892: }
                   7893: 
1.771     droeschl 7894: table.LC_tableBrowseRes a,
1.768     schulted 7895: table.LC_tableOfContent a {
1.911     bisitz   7896:   background-color: transparent;
                   7897:   text-decoration: none;
1.753     droeschl 7898: }
                   7899: 
1.795     www      7900: table.LC_tableOfContent img {
1.911     bisitz   7901:   border: none;
                   7902:   height: 1.3em;
                   7903:   vertical-align: text-bottom;
                   7904:   margin-right: 0.3em;
1.753     droeschl 7905: }
1.757     schulted 7906: 
1.795     www      7907: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7908:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7909: }
                   7910: 
1.795     www      7911: a#LC_content_toolbar_everything {
1.911     bisitz   7912:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7913: }
                   7914: 
1.795     www      7915: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7916:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7917: }
                   7918: 
1.795     www      7919: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7920:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7921: }
                   7922: 
1.795     www      7923: a#LC_content_toolbar_changefolder {
1.911     bisitz   7924:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7925: }
                   7926: 
1.795     www      7927: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7928:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7929: }
                   7930: 
1.1043    raeburn  7931: a#LC_content_toolbar_edittoplevel {
                   7932:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7933: }
                   7934: 
1.795     www      7935: ul#LC_toolbar li a:hover {
1.911     bisitz   7936:   background-position: bottom center;
1.757     schulted 7937: }
                   7938: 
1.795     www      7939: ul#LC_toolbar {
1.911     bisitz   7940:   padding: 0;
                   7941:   margin: 2px;
                   7942:   list-style:none;
                   7943:   position:relative;
                   7944:   background-color:white;
1.1082    raeburn  7945:   overflow: auto;
1.757     schulted 7946: }
                   7947: 
1.795     www      7948: ul#LC_toolbar li {
1.911     bisitz   7949:   border:1px solid white;
                   7950:   padding: 0;
                   7951:   margin: 0;
                   7952:   float: left;
                   7953:   display:inline;
                   7954:   vertical-align:middle;
1.1082    raeburn  7955:   white-space: nowrap;
1.911     bisitz   7956: }
1.757     schulted 7957: 
1.783     amueller 7958: 
1.795     www      7959: a.LC_toolbarItem {
1.911     bisitz   7960:   display:block;
                   7961:   padding: 0;
                   7962:   margin: 0;
                   7963:   height: 32px;
                   7964:   width: 32px;
                   7965:   color:white;
                   7966:   border: none;
                   7967:   background-repeat:no-repeat;
                   7968:   background-color:transparent;
1.757     schulted 7969: }
                   7970: 
1.915     droeschl 7971: ul.LC_funclist {
                   7972:     margin: 0;
                   7973:     padding: 0.5em 1em 0.5em 0;
                   7974: }
                   7975: 
1.933     droeschl 7976: ul.LC_funclist > li:first-child {
                   7977:     font-weight:bold; 
                   7978:     margin-left:0.8em;
                   7979: }
                   7980: 
1.915     droeschl 7981: ul.LC_funclist + ul.LC_funclist {
                   7982:     /* 
                   7983:        left border as a seperator if we have more than
                   7984:        one list 
                   7985:     */
                   7986:     border-left: 1px solid $sidebg;
                   7987:     /* 
                   7988:        this hides the left border behind the border of the 
                   7989:        outer box if element is wrapped to the next 'line' 
                   7990:     */
                   7991:     margin-left: -1px;
                   7992: }
                   7993: 
1.843     bisitz   7994: ul.LC_funclist li {
1.915     droeschl 7995:   display: inline;
1.782     bisitz   7996:   white-space: nowrap;
1.915     droeschl 7997:   margin: 0 0 0 25px;
                   7998:   line-height: 150%;
1.782     bisitz   7999: }
                   8000: 
1.974     wenzelju 8001: .LC_hidden {
                   8002:   display: none;
                   8003: }
                   8004: 
1.1030    www      8005: .LCmodal-overlay {
                   8006: 		position:fixed;
                   8007: 		top:0;
                   8008: 		right:0;
                   8009: 		bottom:0;
                   8010: 		left:0;
                   8011: 		height:100%;
                   8012: 		width:100%;
                   8013: 		margin:0;
                   8014: 		padding:0;
                   8015: 		background:#999;
                   8016: 		opacity:.75;
                   8017: 		filter: alpha(opacity=75);
                   8018: 		-moz-opacity: 0.75;
                   8019: 		z-index:101;
                   8020: }
                   8021: 
                   8022: * html .LCmodal-overlay {   
                   8023: 		position: absolute;
                   8024: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8025: }
                   8026: 
                   8027: .LCmodal-window {
                   8028: 		position:fixed;
                   8029: 		top:50%;
                   8030: 		left:50%;
                   8031: 		margin:0;
                   8032: 		padding:0;
                   8033: 		z-index:102;
                   8034: 	}
                   8035: 
                   8036: * html .LCmodal-window {
                   8037: 		position:absolute;
                   8038: }
                   8039: 
                   8040: .LCclose-window {
                   8041: 		position:absolute;
                   8042: 		width:32px;
                   8043: 		height:32px;
                   8044: 		right:8px;
                   8045: 		top:8px;
                   8046: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8047: 		text-indent:-99999px;
                   8048: 		overflow:hidden;
                   8049: 		cursor:pointer;
                   8050: }
                   8051: 
1.1100    raeburn  8052: /*
1.1231    damieng  8053:   styles used for response display
                   8054: */
                   8055: div.LC_radiofoil, div.LC_rankfoil {
                   8056:   margin: .5em 0em .5em 0em;
                   8057: }
                   8058: table.LC_itemgroup {
                   8059:   margin-top: 1em;
                   8060: }
                   8061: 
                   8062: /*
1.1100    raeburn  8063:   styles used by TTH when "Default set of options to pass to tth/m
                   8064:   when converting TeX" in course settings has been set
                   8065: 
                   8066:   option passed: -t
                   8067: 
                   8068: */
                   8069: 
                   8070: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8071: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8072: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8073: td div.norm {line-height:normal;}
                   8074: 
                   8075: /*
                   8076:   option passed -y3
                   8077: */
                   8078: 
                   8079: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8080: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8081: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8082: 
1.1230    damieng  8083: /*
                   8084:   sections with roles, for content only
                   8085: */
                   8086: section[class^="role-"] {
                   8087:   padding-left: 10px;
                   8088:   padding-right: 5px;
                   8089:   margin-top: 8px;
                   8090:   margin-bottom: 8px;
                   8091:   border: 1px solid #2A4;
                   8092:   border-radius: 5px;
                   8093:   box-shadow: 0px 1px 1px #BBB;
                   8094: }
                   8095: section[class^="role-"]>h1 {
                   8096:   position: relative;
                   8097:   margin: 0px;
                   8098:   padding-top: 10px;
                   8099:   padding-left: 40px;
                   8100: }
                   8101: section[class^="role-"]>h1:before {
                   8102:   position: absolute;
                   8103:   left: -5px;
                   8104:   top: 5px;
                   8105: }
                   8106: section.role-activity>h1:before {
                   8107:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8108: }
                   8109: section.role-advice>h1:before {
                   8110:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8111: }
                   8112: section.role-bibliography>h1:before {
                   8113:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8114: }
                   8115: section.role-citation>h1:before {
                   8116:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8117: }
                   8118: section.role-conclusion>h1:before {
                   8119:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8120: }
                   8121: section.role-definition>h1:before {
                   8122:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8123: }
                   8124: section.role-demonstration>h1:before {
                   8125:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8126: }
                   8127: section.role-example>h1:before {
                   8128:   content:url('/adm/daxe/images/section_icons/example.png');
                   8129: }
                   8130: section.role-explanation>h1:before {
                   8131:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8132: }
                   8133: section.role-introduction>h1:before {
                   8134:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8135: }
                   8136: section.role-method>h1:before {
                   8137:   content:url('/adm/daxe/images/section_icons/method.png');
                   8138: }
                   8139: section.role-more_information>h1:before {
                   8140:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8141: }
                   8142: section.role-objectives>h1:before {
                   8143:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8144: }
                   8145: section.role-prerequisites>h1:before {
                   8146:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8147: }
                   8148: section.role-remark>h1:before {
                   8149:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8150: }
                   8151: section.role-reminder>h1:before {
                   8152:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8153: }
                   8154: section.role-summary>h1:before {
                   8155:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8156: }
                   8157: section.role-syntax>h1:before {
                   8158:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8159: }
                   8160: section.role-warning>h1:before {
                   8161:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8162: }
                   8163: 
1.1269    raeburn  8164: #LC_minitab_header {
                   8165:   float:left;
                   8166:   width:100%;
                   8167:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8168:   font-size:93%;
                   8169:   line-height:normal;
                   8170:   margin: 0.5em 0 0.5em 0;
                   8171: }
                   8172: #LC_minitab_header ul {
                   8173:   margin:0;
                   8174:   padding:10px 10px 0;
                   8175:   list-style:none;
                   8176: }
                   8177: #LC_minitab_header li {
                   8178:   float:left;
                   8179:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8180:   margin:0;
                   8181:   padding:0 0 0 9px;
                   8182: }
                   8183: #LC_minitab_header a {
                   8184:   display:block;
                   8185:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8186:   padding:5px 15px 4px 6px;
                   8187: }
                   8188: #LC_minitab_header #LC_current_minitab {
                   8189:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8190: }
                   8191: #LC_minitab_header #LC_current_minitab a {
                   8192:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8193:   padding-bottom:5px;
                   8194: }
                   8195: 
                   8196: 
1.343     albertel 8197: END
                   8198: }
                   8199: 
1.306     albertel 8200: =pod
                   8201: 
                   8202: =item * &headtag()
                   8203: 
                   8204: Returns a uniform footer for LON-CAPA web pages.
                   8205: 
1.307     albertel 8206: Inputs: $title - optional title for the head
                   8207:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8208:         $args - optional arguments
1.319     albertel 8209:             force_register - if is true call registerurl so the remote is 
                   8210:                              informed
1.415     albertel 8211:             redirect       -> array ref of
                   8212:                                    1- seconds before redirect occurs
                   8213:                                    2- url to redirect to
                   8214:                                    3- whether the side effect should occur
1.315     albertel 8215:                            (side effect of setting 
                   8216:                                $env{'internal.head.redirect'} to the url 
                   8217:                                redirected too)
1.352     albertel 8218:             domain         -> force to color decorate a page for a specific
                   8219:                                domain
                   8220:             function       -> force usage of a specific rolish color scheme
                   8221:             bgcolor        -> override the default page bgcolor
1.460     albertel 8222:             no_auto_mt_title
                   8223:                            -> prevent &mt()ing the title arg
1.464     albertel 8224: 
1.306     albertel 8225: =cut
                   8226: 
                   8227: sub headtag {
1.313     albertel 8228:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8229:     
1.363     albertel 8230:     my $function = $args->{'function'} || &get_users_function();
                   8231:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8232:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8233:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8234:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8235: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8236: 		   #time(),
1.418     albertel 8237: 		   $env{'environment.color.timestamp'},
1.363     albertel 8238: 		   $function,$domain,$bgcolor);
                   8239: 
1.369     www      8240:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8241: 
1.308     albertel 8242:     my $result =
                   8243: 	'<head>'.
1.1160    raeburn  8244: 	&font_settings($args);
1.319     albertel 8245: 
1.1188    raeburn  8246:     my $inhibitprint;
                   8247:     if ($args->{'print_suppress'}) {
                   8248:         $inhibitprint = &print_suppression();
                   8249:     }
1.1064    raeburn  8250: 
1.461     albertel 8251:     if (!$args->{'frameset'}) {
                   8252: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8253:     }
1.962     droeschl 8254:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8255:         $result .= Apache::lonxml::display_title();
1.319     albertel 8256:     }
1.436     albertel 8257:     if (!$args->{'no_nav_bar'} 
                   8258: 	&& !$args->{'only_body'}
                   8259: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8260: 	$result .= &help_menu_js($httphost);
1.1032    www      8261:         $result.=&modal_window();
1.1038    www      8262:         $result.=&togglebox_script();
1.1034    www      8263:         $result.=&wishlist_window();
1.1041    www      8264:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8265:     } else {
                   8266:         if ($args->{'add_modal'}) {
                   8267:            $result.=&modal_window();
                   8268:         }
                   8269:         if ($args->{'add_wishlist'}) {
                   8270:            $result.=&wishlist_window();
                   8271:         }
1.1038    www      8272:         if ($args->{'add_togglebox'}) {
                   8273:            $result.=&togglebox_script();
                   8274:         }
1.1041    www      8275:         if ($args->{'add_progressbar'}) {
                   8276:            $result.=&LCprogressbarUpdate_script();
                   8277:         }
1.436     albertel 8278:     }
1.314     albertel 8279:     if (ref($args->{'redirect'})) {
1.414     albertel 8280: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8281: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8282: 	if (!$inhibit_continue) {
                   8283: 	    $env{'internal.head.redirect'} = $url;
                   8284: 	}
1.313     albertel 8285: 	$result.=<<ADDMETA
                   8286: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8287: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8288: ADDMETA
1.1210    raeburn  8289:     } else {
                   8290:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8291:             my $requrl = $env{'request.uri'};
                   8292:             if ($requrl eq '') {
                   8293:                 $requrl = $ENV{'REQUEST_URI'};
                   8294:                 $requrl =~ s/\?.+$//;
                   8295:             }
                   8296:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8297:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8298:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8299:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8300:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8301:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   8302:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8303:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   8304:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   8305:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   8306:                             if (($newserver) && ($newserver ne $lonhost)) {
                   8307:                                 my $numsec = 5;
                   8308:                                 my $timeout = $numsec * 1000;
                   8309:                                 my ($newurl,$locknum,%locks,$msg);
                   8310:                                 if ($env{'request.role.adv'}) {
                   8311:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8312:                                 }
                   8313:                                 my $disable_submit = 0;
                   8314:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   8315:                                     $disable_submit = 1;
                   8316:                                 }
                   8317:                                 if ($locknum) {
                   8318:                                     my @lockinfo = sort(values(%locks));
                   8319:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   8320:                                            join(", ",sort(values(%locks)))."\\n".
                   8321:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   8322:                                 } else {
                   8323:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8324:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   8325:                                     }
                   8326:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8327:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8328:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8329:                                         $newurl .= '&role='.$env{'request.role'};
                   8330:                                     }
                   8331:                                     if ($env{'request.symb'}) {
                   8332:                                         $newurl .= '&symb='.$env{'request.symb'};
                   8333:                                     } else {
                   8334:                                         $newurl .= '&origurl='.$requrl;
                   8335:                                     }
                   8336:                                 }
1.1222    damieng  8337:                                 &js_escape(\$msg);
1.1210    raeburn  8338:                                 $result.=<<OFFLOAD
                   8339: <meta http-equiv="pragma" content="no-cache" />
                   8340: <script type="text/javascript">
1.1215    raeburn  8341: // <![CDATA[
1.1210    raeburn  8342: function LC_Offload_Now() {
                   8343:     var dest = "$newurl";
                   8344:     if (dest != '') {
                   8345:         window.location.href="$newurl";
                   8346:     }
                   8347: }
1.1214    raeburn  8348: \$(document).ready(function () {
                   8349:     window.alert('$msg');
                   8350:     if ($disable_submit) {
1.1210    raeburn  8351:         \$(".LC_hwk_submit").prop("disabled", true);
                   8352:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  8353:     }
                   8354:     setTimeout('LC_Offload_Now()', $timeout);
                   8355: });
1.1215    raeburn  8356: // ]]>
1.1210    raeburn  8357: </script>
                   8358: OFFLOAD
                   8359:                             }
                   8360:                         }
                   8361:                     }
                   8362:                 }
                   8363:             }
                   8364:         }
1.313     albertel 8365:     }
1.306     albertel 8366:     if (!defined($title)) {
                   8367: 	$title = 'The LearningOnline Network with CAPA';
                   8368:     }
1.460     albertel 8369:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8370:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  8371: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8372:     if (!$args->{'frameset'}) {
                   8373:         $result .= ' /';
                   8374:     }
                   8375:     $result .= '>' 
1.1064    raeburn  8376:         .$inhibitprint
1.414     albertel 8377: 	.$head_extra;
1.1242    raeburn  8378:     my $clientmobile;
                   8379:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8380:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8381:     } else {
                   8382:         $clientmobile = $env{'browser.mobile'};
                   8383:     }
                   8384:     if ($clientmobile) {
1.1137    raeburn  8385:         $result .= '
                   8386: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8387: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8388:     }
1.1278    raeburn  8389:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8390:     return $result.'</head>';
1.306     albertel 8391: }
                   8392: 
                   8393: =pod
                   8394: 
1.340     albertel 8395: =item * &font_settings()
                   8396: 
                   8397: Returns neccessary <meta> to set the proper encoding
                   8398: 
1.1160    raeburn  8399: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8400: 
                   8401: =cut
                   8402: 
                   8403: sub font_settings {
1.1160    raeburn  8404:     my ($args) = @_;
1.340     albertel 8405:     my $headerstring='';
1.1160    raeburn  8406:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8407:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  8408:         $headerstring.=
                   8409:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8410:         if (!$args->{'frameset'}) {
                   8411: 	    $headerstring.= ' /';
                   8412:         }
                   8413: 	$headerstring .= '>'."\n";
1.340     albertel 8414:     }
                   8415:     return $headerstring;
                   8416: }
                   8417: 
1.341     albertel 8418: =pod
                   8419: 
1.1064    raeburn  8420: =item * &print_suppression()
                   8421: 
                   8422: In course context returns css which causes the body to be blank when media="print",
                   8423: if printout generation is unavailable for the current resource.
                   8424: 
                   8425: This could be because:
                   8426: 
                   8427: (a) printstartdate is in the future
                   8428: 
                   8429: (b) printenddate is in the past
                   8430: 
                   8431: (c) there is an active exam block with "printout"
                   8432: functionality blocked
                   8433: 
                   8434: Users with pav, pfo or evb privileges are exempt.
                   8435: 
                   8436: Inputs: none
                   8437: 
                   8438: =cut
                   8439: 
                   8440: 
                   8441: sub print_suppression {
                   8442:     my $noprint;
                   8443:     if ($env{'request.course.id'}) {
                   8444:         my $scope = $env{'request.course.id'};
                   8445:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8446:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8447:             return;
                   8448:         }
                   8449:         if ($env{'request.course.sec'} ne '') {
                   8450:             $scope .= "/$env{'request.course.sec'}";
                   8451:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8452:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8453:                 return;
1.1064    raeburn  8454:             }
                   8455:         }
                   8456:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8457:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  8458:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  8459:         if ($blocked) {
                   8460:             my $checkrole = "cm./$cdom/$cnum";
                   8461:             if ($env{'request.course.sec'} ne '') {
                   8462:                 $checkrole .= "/$env{'request.course.sec'}";
                   8463:             }
                   8464:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8465:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8466:                 $noprint = 1;
                   8467:             }
                   8468:         }
                   8469:         unless ($noprint) {
                   8470:             my $symb = &Apache::lonnet::symbread();
                   8471:             if ($symb ne '') {
                   8472:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8473:                 if (ref($navmap)) {
                   8474:                     my $res = $navmap->getBySymb($symb);
                   8475:                     if (ref($res)) {
                   8476:                         if (!$res->resprintable()) {
                   8477:                             $noprint = 1;
                   8478:                         }
                   8479:                     }
                   8480:                 }
                   8481:             }
                   8482:         }
                   8483:         if ($noprint) {
                   8484:             return <<"ENDSTYLE";
                   8485: <style type="text/css" media="print">
                   8486:     body { display:none }
                   8487: </style>
                   8488: ENDSTYLE
                   8489:         }
                   8490:     }
                   8491:     return;
                   8492: }
                   8493: 
                   8494: =pod
                   8495: 
1.341     albertel 8496: =item * &xml_begin()
                   8497: 
                   8498: Returns the needed doctype and <html>
                   8499: 
                   8500: Inputs: none
                   8501: 
                   8502: =cut
                   8503: 
                   8504: sub xml_begin {
1.1168    raeburn  8505:     my ($is_frameset) = @_;
1.341     albertel 8506:     my $output='';
                   8507: 
                   8508:     if ($env{'browser.mathml'}) {
                   8509: 	$output='<?xml version="1.0"?>'
                   8510:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8511: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8512:             
                   8513: #	    .'<!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">] >'
                   8514: 	    .'<!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">'
                   8515:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8516: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  8517:     } elsif ($is_frameset) {
                   8518:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8519:                 '<html>'."\n";
1.341     albertel 8520:     } else {
1.1168    raeburn  8521: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8522:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8523:     }
                   8524:     return $output;
                   8525: }
1.340     albertel 8526: 
                   8527: =pod
                   8528: 
1.306     albertel 8529: =item * &start_page()
                   8530: 
                   8531: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8532: 
1.648     raeburn  8533: Inputs:
                   8534: 
                   8535: =over 4
                   8536: 
                   8537: $title - optional title for the page
                   8538: 
                   8539: $head_extra - optional extra HTML to incude inside the <head>
                   8540: 
                   8541: $args - additional optional args supported are:
                   8542: 
                   8543: =over 8
                   8544: 
                   8545:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8546:                                     arg on
1.814     bisitz   8547:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8548:              add_entries    -> additional attributes to add to the  <body>
                   8549:              domain         -> force to color decorate a page for a 
1.317     albertel 8550:                                     specific domain
1.648     raeburn  8551:              function       -> force usage of a specific rolish color
1.317     albertel 8552:                                     scheme
1.648     raeburn  8553:              redirect       -> see &headtag()
                   8554:              bgcolor        -> override the default page bg color
                   8555:              js_ready       -> return a string ready for being used in 
1.317     albertel 8556:                                     a javascript writeln
1.648     raeburn  8557:              html_encode    -> return a string ready for being used in 
1.320     albertel 8558:                                     a html attribute
1.648     raeburn  8559:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8560:                                     $forcereg arg
1.648     raeburn  8561:              frameset       -> if true will start with a <frameset>
1.330     albertel 8562:                                     rather than <body>
1.648     raeburn  8563:              skip_phases    -> hash ref of 
1.338     albertel 8564:                                     head -> skip the <html><head> generation
                   8565:                                     body -> skip all <body> generation
1.648     raeburn  8566:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8567:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8568:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  8569:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8570:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  8571:              group          -> includes the current group, if page is for a 
1.1274    raeburn  8572:                                specific group
                   8573:              use_absolute   -> for request for external resource or syllabus, this
                   8574:                                will contain https://<hostname> if server uses
                   8575:                                https (as per hosts.tab), but request is for http
                   8576:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8577: 
1.648     raeburn  8578: =back
1.460     albertel 8579: 
1.648     raeburn  8580: =back
1.562     albertel 8581: 
1.306     albertel 8582: =cut
                   8583: 
                   8584: sub start_page {
1.309     albertel 8585:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8586:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8587: 
1.315     albertel 8588:     $env{'internal.start_page'}++;
1.1096    raeburn  8589:     my ($result,@advtools);
1.964     droeschl 8590: 
1.338     albertel 8591:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8592:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8593:     }
                   8594:     
                   8595:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8596: 	if ($args->{'frameset'}) {
                   8597: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8598: 						$args->{'add_entries'});
                   8599: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8600:         } else {
                   8601:             $result .=
                   8602:                 &bodytag($title, 
                   8603:                          $args->{'function'},       $args->{'add_entries'},
                   8604:                          $args->{'only_body'},      $args->{'domain'},
                   8605:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8606:                          $args->{'bgcolor'},        $args,
                   8607:                          \@advtools);
1.831     bisitz   8608:         }
1.330     albertel 8609:     }
1.338     albertel 8610: 
1.315     albertel 8611:     if ($args->{'js_ready'}) {
1.713     kaisler  8612: 		$result = &js_ready($result);
1.315     albertel 8613:     }
1.320     albertel 8614:     if ($args->{'html_encode'}) {
1.713     kaisler  8615: 		$result = &html_encode($result);
                   8616:     }
                   8617: 
1.813     bisitz   8618:     # Preparation for new and consistent functionlist at top of screen
                   8619:     # if ($args->{'functionlist'}) {
                   8620:     #            $result .= &build_functionlist();
                   8621:     #}
                   8622: 
1.964     droeschl 8623:     # Don't add anything more if only_body wanted or in const space
                   8624:     return $result if    $args->{'only_body'} 
                   8625:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8626: 
                   8627:     #Breadcrumbs
1.758     kaisler  8628:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8629: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8630: 		#if any br links exists, add them to the breadcrumbs
                   8631: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8632: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8633: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8634: 			}
                   8635: 		}
1.1096    raeburn  8636:                 # if @advtools array contains items add then to the breadcrumbs
                   8637:                 if (@advtools > 0) {
                   8638:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8639:                 }
1.1272    raeburn  8640:                 my $menulink;
                   8641:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8642:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   8643:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   8644:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   8645:                      (!$env{'request.role.adv'}))) {
                   8646:                     $menulink = 0;
                   8647:                 } else {
                   8648:                     undef($menulink);
                   8649:                 }
1.758     kaisler  8650: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8651: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  8652: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  8653:                 } else {
1.1272    raeburn  8654: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8655: 		}
1.320     albertel 8656:     }
1.315     albertel 8657:     return $result;
1.306     albertel 8658: }
                   8659: 
                   8660: sub end_page {
1.315     albertel 8661:     my ($args) = @_;
                   8662:     $env{'internal.end_page'}++;
1.330     albertel 8663:     my $result;
1.335     albertel 8664:     if ($args->{'discussion'}) {
                   8665: 	my ($target,$parser);
                   8666: 	if (ref($args->{'discussion'})) {
                   8667: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8668: 				$args->{'discussion'}{'parser'});
                   8669: 	}
                   8670: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8671:     }
1.330     albertel 8672:     if ($args->{'frameset'}) {
                   8673: 	$result .= '</frameset>';
                   8674:     } else {
1.635     raeburn  8675: 	$result .= &endbodytag($args);
1.330     albertel 8676:     }
1.1080    raeburn  8677:     unless ($args->{'notbody'}) {
                   8678:         $result .= "\n</html>";
                   8679:     }
1.330     albertel 8680: 
1.315     albertel 8681:     if ($args->{'js_ready'}) {
1.317     albertel 8682: 	$result = &js_ready($result);
1.315     albertel 8683:     }
1.335     albertel 8684: 
1.320     albertel 8685:     if ($args->{'html_encode'}) {
                   8686: 	$result = &html_encode($result);
                   8687:     }
1.335     albertel 8688: 
1.315     albertel 8689:     return $result;
                   8690: }
                   8691: 
1.1034    www      8692: sub wishlist_window {
                   8693:     return(<<'ENDWISHLIST');
1.1046    raeburn  8694: <script type="text/javascript">
1.1034    www      8695: // <![CDATA[
                   8696: // <!-- BEGIN LON-CAPA Internal
                   8697: function set_wishlistlink(title, path) {
                   8698:     if (!title) {
                   8699:         title = document.title;
                   8700:         title = title.replace(/^LON-CAPA /,'');
                   8701:     }
1.1175    raeburn  8702:     title = encodeURIComponent(title);
1.1203    raeburn  8703:     title = title.replace("'","\\\'");
1.1034    www      8704:     if (!path) {
                   8705:         path = location.pathname;
                   8706:     }
1.1175    raeburn  8707:     path = encodeURIComponent(path);
1.1203    raeburn  8708:     path = path.replace("'","\\\'");
1.1034    www      8709:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8710:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8711: }
                   8712: // END LON-CAPA Internal -->
                   8713: // ]]>
                   8714: </script>
                   8715: ENDWISHLIST
                   8716: }
                   8717: 
1.1030    www      8718: sub modal_window {
                   8719:     return(<<'ENDMODAL');
1.1046    raeburn  8720: <script type="text/javascript">
1.1030    www      8721: // <![CDATA[
                   8722: // <!-- BEGIN LON-CAPA Internal
                   8723: var modalWindow = {
                   8724: 	parent:"body",
                   8725: 	windowId:null,
                   8726: 	content:null,
                   8727: 	width:null,
                   8728: 	height:null,
                   8729: 	close:function()
                   8730: 	{
                   8731: 	        $(".LCmodal-window").remove();
                   8732: 	        $(".LCmodal-overlay").remove();
                   8733: 	},
                   8734: 	open:function()
                   8735: 	{
                   8736: 		var modal = "";
                   8737: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8738: 		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;\">";
                   8739: 		modal += this.content;
                   8740: 		modal += "</div>";	
                   8741: 
                   8742: 		$(this.parent).append(modal);
                   8743: 
                   8744: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8745: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8746: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8747: 	}
                   8748: };
1.1140    raeburn  8749: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8750: 	{
1.1266    raeburn  8751:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8752: 		modalWindow.windowId = "myModal";
                   8753: 		modalWindow.width = width;
                   8754: 		modalWindow.height = height;
1.1196    raeburn  8755: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8756: 		modalWindow.open();
1.1208    raeburn  8757: 	};
1.1030    www      8758: // END LON-CAPA Internal -->
                   8759: // ]]>
                   8760: </script>
                   8761: ENDMODAL
                   8762: }
                   8763: 
                   8764: sub modal_link {
1.1140    raeburn  8765:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8766:     unless ($width) { $width=480; }
                   8767:     unless ($height) { $height=400; }
1.1031    www      8768:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8769:     unless ($transparency) { $transparency='true'; }
                   8770: 
1.1074    raeburn  8771:     my $target_attr;
                   8772:     if (defined($target)) {
                   8773:         $target_attr = 'target="'.$target.'"';
                   8774:     }
                   8775:     return <<"ENDLINK";
1.1140    raeburn  8776: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8777:            $linktext</a>
                   8778: ENDLINK
1.1030    www      8779: }
                   8780: 
1.1032    www      8781: sub modal_adhoc_script {
                   8782:     my ($funcname,$width,$height,$content)=@_;
                   8783:     return (<<ENDADHOC);
1.1046    raeburn  8784: <script type="text/javascript">
1.1032    www      8785: // <![CDATA[
                   8786:         var $funcname = function()
                   8787:         {
                   8788:                 modalWindow.windowId = "myModal";
                   8789:                 modalWindow.width = $width;
                   8790:                 modalWindow.height = $height;
                   8791:                 modalWindow.content = '$content';
                   8792:                 modalWindow.open();
                   8793:         };  
                   8794: // ]]>
                   8795: </script>
                   8796: ENDADHOC
                   8797: }
                   8798: 
1.1041    www      8799: sub modal_adhoc_inner {
                   8800:     my ($funcname,$width,$height,$content)=@_;
                   8801:     my $innerwidth=$width-20;
                   8802:     $content=&js_ready(
1.1140    raeburn  8803:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8804:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8805:                  $content.
1.1041    www      8806:                  &end_scrollbox().
1.1140    raeburn  8807:                  &end_page()
1.1041    www      8808:              );
                   8809:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8810: }
                   8811: 
                   8812: sub modal_adhoc_window {
                   8813:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8814:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8815:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8816: }
                   8817: 
                   8818: sub modal_adhoc_launch {
                   8819:     my ($funcname,$width,$height,$content)=@_;
                   8820:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8821: <script type="text/javascript">
                   8822: // <![CDATA[
                   8823: $funcname();
                   8824: // ]]>
                   8825: </script>
                   8826: ENDLAUNCH
                   8827: }
                   8828: 
                   8829: sub modal_adhoc_close {
                   8830:     return (<<ENDCLOSE);
                   8831: <script type="text/javascript">
                   8832: // <![CDATA[
                   8833: modalWindow.close();
                   8834: // ]]>
                   8835: </script>
                   8836: ENDCLOSE
                   8837: }
                   8838: 
1.1038    www      8839: sub togglebox_script {
                   8840:    return(<<ENDTOGGLE);
                   8841: <script type="text/javascript"> 
                   8842: // <![CDATA[
                   8843: function LCtoggleDisplay(id,hidetext,showtext) {
                   8844:    link = document.getElementById(id + "link").childNodes[0];
                   8845:    with (document.getElementById(id).style) {
                   8846:       if (display == "none" ) {
                   8847:           display = "inline";
                   8848:           link.nodeValue = hidetext;
                   8849:         } else {
                   8850:           display = "none";
                   8851:           link.nodeValue = showtext;
                   8852:        }
                   8853:    }
                   8854: }
                   8855: // ]]>
                   8856: </script>
                   8857: ENDTOGGLE
                   8858: }
                   8859: 
1.1039    www      8860: sub start_togglebox {
                   8861:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8862:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8863:     unless ($showtext) { $showtext=&mt('show'); }
                   8864:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8865:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8866:     return &start_data_table().
                   8867:            &start_data_table_header_row().
                   8868:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8869:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8870:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8871:            &end_data_table_header_row().
                   8872:            '<tr id="'.$id.'" style="display:none""><td>';
                   8873: }
                   8874: 
                   8875: sub end_togglebox {
                   8876:     return '</td></tr>'.&end_data_table();
                   8877: }
                   8878: 
1.1041    www      8879: sub LCprogressbar_script {
1.1045    www      8880:    my ($id)=@_;
1.1041    www      8881:    return(<<ENDPROGRESS);
                   8882: <script type="text/javascript">
                   8883: // <![CDATA[
1.1045    www      8884: \$('#progressbar$id').progressbar({
1.1041    www      8885:   value: 0,
                   8886:   change: function(event, ui) {
                   8887:     var newVal = \$(this).progressbar('option', 'value');
                   8888:     \$('.pblabel', this).text(LCprogressTxt);
                   8889:   }
                   8890: });
                   8891: // ]]>
                   8892: </script>
                   8893: ENDPROGRESS
                   8894: }
                   8895: 
                   8896: sub LCprogressbarUpdate_script {
                   8897:    return(<<ENDPROGRESSUPDATE);
                   8898: <style type="text/css">
                   8899: .ui-progressbar { position:relative; }
                   8900: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8901: </style>
                   8902: <script type="text/javascript">
                   8903: // <![CDATA[
1.1045    www      8904: var LCprogressTxt='---';
                   8905: 
                   8906: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8907:    LCprogressTxt=progresstext;
1.1045    www      8908:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8909: }
                   8910: // ]]>
                   8911: </script>
                   8912: ENDPROGRESSUPDATE
                   8913: }
                   8914: 
1.1042    www      8915: my $LClastpercent;
1.1045    www      8916: my $LCidcnt;
                   8917: my $LCcurrentid;
1.1042    www      8918: 
1.1041    www      8919: sub LCprogressbar {
1.1042    www      8920:     my ($r)=(@_);
                   8921:     $LClastpercent=0;
1.1045    www      8922:     $LCidcnt++;
                   8923:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8924:     my $starting=&mt('Starting');
                   8925:     my $content=(<<ENDPROGBAR);
1.1045    www      8926:   <div id="progressbar$LCcurrentid">
1.1041    www      8927:     <span class="pblabel">$starting</span>
                   8928:   </div>
                   8929: ENDPROGBAR
1.1045    www      8930:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8931: }
                   8932: 
                   8933: sub LCprogressbarUpdate {
1.1042    www      8934:     my ($r,$val,$text)=@_;
                   8935:     unless ($val) { 
                   8936:        if ($LClastpercent) {
                   8937:            $val=$LClastpercent;
                   8938:        } else {
                   8939:            $val=0;
                   8940:        }
                   8941:     }
1.1041    www      8942:     if ($val<0) { $val=0; }
                   8943:     if ($val>100) { $val=0; }
1.1042    www      8944:     $LClastpercent=$val;
1.1041    www      8945:     unless ($text) { $text=$val.'%'; }
                   8946:     $text=&js_ready($text);
1.1044    www      8947:     &r_print($r,<<ENDUPDATE);
1.1041    www      8948: <script type="text/javascript">
                   8949: // <![CDATA[
1.1045    www      8950: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8951: // ]]>
                   8952: </script>
                   8953: ENDUPDATE
1.1035    www      8954: }
                   8955: 
1.1042    www      8956: sub LCprogressbarClose {
                   8957:     my ($r)=@_;
                   8958:     $LClastpercent=0;
1.1044    www      8959:     &r_print($r,<<ENDCLOSE);
1.1042    www      8960: <script type="text/javascript">
                   8961: // <![CDATA[
1.1045    www      8962: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8963: // ]]>
                   8964: </script>
                   8965: ENDCLOSE
1.1044    www      8966: }
                   8967: 
                   8968: sub r_print {
                   8969:     my ($r,$to_print)=@_;
                   8970:     if ($r) {
                   8971:       $r->print($to_print);
                   8972:       $r->rflush();
                   8973:     } else {
                   8974:       print($to_print);
                   8975:     }
1.1042    www      8976: }
                   8977: 
1.320     albertel 8978: sub html_encode {
                   8979:     my ($result) = @_;
                   8980: 
1.322     albertel 8981:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8982:     
                   8983:     return $result;
                   8984: }
1.1044    www      8985: 
1.317     albertel 8986: sub js_ready {
                   8987:     my ($result) = @_;
                   8988: 
1.323     albertel 8989:     $result =~ s/[\n\r]/ /xmsg;
                   8990:     $result =~ s/\\/\\\\/xmsg;
                   8991:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8992:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8993:     
                   8994:     return $result;
                   8995: }
                   8996: 
1.315     albertel 8997: sub validate_page {
                   8998:     if (  exists($env{'internal.start_page'})
1.316     albertel 8999: 	  &&     $env{'internal.start_page'} > 1) {
                   9000: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9001: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9002: 				 $ENV{'request.filename'});
1.315     albertel 9003:     }
                   9004:     if (  exists($env{'internal.end_page'})
1.316     albertel 9005: 	  &&     $env{'internal.end_page'} > 1) {
                   9006: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9007: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9008: 				 $env{'request.filename'});
1.315     albertel 9009:     }
                   9010:     if (     exists($env{'internal.start_page'})
                   9011: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9012: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9013: 				 $env{'request.filename'});
1.315     albertel 9014:     }
                   9015:     if (   ! exists($env{'internal.start_page'})
                   9016: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9017: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9018: 				 $env{'request.filename'});
1.315     albertel 9019:     }
1.306     albertel 9020: }
1.315     albertel 9021: 
1.996     www      9022: 
                   9023: sub start_scrollbox {
1.1140    raeburn  9024:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9025:     unless ($outerwidth) { $outerwidth='520px'; }
                   9026:     unless ($width) { $width='500px'; }
                   9027:     unless ($height) { $height='200px'; }
1.1075    raeburn  9028:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9029:     if ($id ne '') {
1.1140    raeburn  9030:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9031:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9032:     }
1.1075    raeburn  9033:     if ($bgcolor ne '') {
                   9034:         $tdcol = "background-color: $bgcolor;";
                   9035:     }
1.1137    raeburn  9036:     my $nicescroll_js;
                   9037:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9038:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9039:     }
                   9040:     return <<"END";
                   9041: $nicescroll_js
                   9042: 
                   9043: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9044: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9045: END
                   9046: }
                   9047: 
                   9048: sub end_scrollbox {
                   9049:     return '</div></td></tr></table>';
                   9050: }
                   9051: 
                   9052: sub nicescroll_javascript {
                   9053:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9054:     my %options;
                   9055:     if (ref($cursor) eq 'HASH') {
                   9056:         %options = %{$cursor};
                   9057:     }
                   9058:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9059:         $options{'railalign'} = 'left';
                   9060:     }
                   9061:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9062:         my $function  = &get_users_function();
                   9063:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9064:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9065:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9066:         }
1.1140    raeburn  9067:     }
                   9068:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9069:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9070:             $options{'cursoropacity'}='1.0';
                   9071:         }
1.1140    raeburn  9072:     } else {
                   9073:         $options{'cursoropacity'}='1.0';
                   9074:     }
                   9075:     if ($options{'cursorfixedheight'} eq 'none') {
                   9076:         delete($options{'cursorfixedheight'});
                   9077:     } else {
                   9078:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9079:     }
                   9080:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9081:         delete($options{'railoffset'});
                   9082:     }
                   9083:     my @niceoptions;
                   9084:     while (my($key,$value) = each(%options)) {
                   9085:         if ($value =~ /^\{.+\}$/) {
                   9086:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9087:         } else {
1.1140    raeburn  9088:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9089:         }
1.1140    raeburn  9090:     }
                   9091:     my $nicescroll_js = '
1.1137    raeburn  9092: $(document).ready(
1.1140    raeburn  9093:       function() {
                   9094:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9095:       }
1.1137    raeburn  9096: );
                   9097: ';
1.1140    raeburn  9098:     if ($framecheck) {
                   9099:         $nicescroll_js .= '
                   9100: function expand_div(caller) {
                   9101:     if (top === self) {
                   9102:         document.getElementById("'.$id.'").style.width = "auto";
                   9103:         document.getElementById("'.$id.'").style.height = "auto";
                   9104:     } else {
                   9105:         try {
                   9106:             if (parent.frames) {
                   9107:                 if (parent.frames.length > 1) {
                   9108:                     var framesrc = parent.frames[1].location.href;
                   9109:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9110:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9111:                         document.getElementById("'.$id.'").style.width = "auto";
                   9112:                         document.getElementById("'.$id.'").style.height = "auto";
                   9113:                     }
                   9114:                 }
                   9115:             }
                   9116:         } catch (e) {
                   9117:             return;
                   9118:         }
1.1137    raeburn  9119:     }
1.1140    raeburn  9120:     return;
1.996     www      9121: }
1.1140    raeburn  9122: ';
                   9123:     }
                   9124:     if ($needjsready) {
                   9125:         $nicescroll_js = '
                   9126: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9127:     } else {
                   9128:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9129:     }
                   9130:     return $nicescroll_js;
1.996     www      9131: }
                   9132: 
1.318     albertel 9133: sub simple_error_page {
1.1150    bisitz   9134:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  9135:     if (ref($args) eq 'HASH') {
                   9136:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   9137:     } else {
                   9138:         $msg = &mt($msg);
                   9139:     }
1.1150    bisitz   9140: 
1.318     albertel 9141:     my $page =
                   9142: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   9143: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9144: 	&Apache::loncommon::end_page();
                   9145:     if (ref($r)) {
                   9146: 	$r->print($page);
1.327     albertel 9147: 	return;
1.318     albertel 9148:     }
                   9149:     return $page;
                   9150: }
1.347     albertel 9151: 
                   9152: {
1.610     albertel 9153:     my @row_count;
1.961     onken    9154: 
                   9155:     sub start_data_table_count {
                   9156:         unshift(@row_count, 0);
                   9157:         return;
                   9158:     }
                   9159: 
                   9160:     sub end_data_table_count {
                   9161:         shift(@row_count);
                   9162:         return;
                   9163:     }
                   9164: 
1.347     albertel 9165:     sub start_data_table {
1.1018    raeburn  9166: 	my ($add_class,$id) = @_;
1.422     albertel 9167: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9168:         my $table_id;
                   9169:         if (defined($id)) {
                   9170:             $table_id = ' id="'.$id.'"';
                   9171:         }
1.961     onken    9172: 	&start_data_table_count();
1.1018    raeburn  9173: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9174:     }
                   9175: 
                   9176:     sub end_data_table {
1.961     onken    9177: 	&end_data_table_count();
1.389     albertel 9178: 	return '</table>'."\n";;
1.347     albertel 9179:     }
                   9180: 
                   9181:     sub start_data_table_row {
1.974     wenzelju 9182: 	my ($add_class, $id) = @_;
1.610     albertel 9183: 	$row_count[0]++;
                   9184: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9185: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9186:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9187:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9188:     }
1.471     banghart 9189:     
                   9190:     sub continue_data_table_row {
1.974     wenzelju 9191: 	my ($add_class, $id) = @_;
1.610     albertel 9192: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9193: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9194:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9195:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9196:     }
1.347     albertel 9197: 
                   9198:     sub end_data_table_row {
1.389     albertel 9199: 	return '</tr>'."\n";;
1.347     albertel 9200:     }
1.367     www      9201: 
1.421     albertel 9202:     sub start_data_table_empty_row {
1.707     bisitz   9203: #	$row_count[0]++;
1.421     albertel 9204: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9205:     }
                   9206: 
                   9207:     sub end_data_table_empty_row {
                   9208: 	return '</tr>'."\n";;
                   9209:     }
                   9210: 
1.367     www      9211:     sub start_data_table_header_row {
1.389     albertel 9212: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9213:     }
                   9214: 
                   9215:     sub end_data_table_header_row {
1.389     albertel 9216: 	return '</tr>'."\n";;
1.367     www      9217:     }
1.890     droeschl 9218: 
                   9219:     sub data_table_caption {
                   9220:         my $caption = shift;
                   9221:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9222:     }
1.347     albertel 9223: }
                   9224: 
1.548     albertel 9225: =pod
                   9226: 
                   9227: =item * &inhibit_menu_check($arg)
                   9228: 
                   9229: Checks for a inhibitmenu state and generates output to preserve it
                   9230: 
                   9231: Inputs:         $arg - can be any of
                   9232:                      - undef - in which case the return value is a string 
                   9233:                                to add  into arguments list of a uri
                   9234:                      - 'input' - in which case the return value is a HTML
                   9235:                                  <form> <input> field of type hidden to
                   9236:                                  preserve the value
                   9237:                      - a url - in which case the return value is the url with
                   9238:                                the neccesary cgi args added to preserve the
                   9239:                                inhibitmenu state
                   9240:                      - a ref to a url - no return value, but the string is
                   9241:                                         updated to include the neccessary cgi
                   9242:                                         args to preserve the inhibitmenu state
                   9243: 
                   9244: =cut
                   9245: 
                   9246: sub inhibit_menu_check {
                   9247:     my ($arg) = @_;
                   9248:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9249:     if ($arg eq 'input') {
                   9250: 	if ($env{'form.inhibitmenu'}) {
                   9251: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9252: 	} else {
                   9253: 	    return
                   9254: 	}
                   9255:     }
                   9256:     if ($env{'form.inhibitmenu'}) {
                   9257: 	if (ref($arg)) {
                   9258: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9259: 	} elsif ($arg eq '') {
                   9260: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9261: 	} else {
                   9262: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9263: 	}
                   9264:     }
                   9265:     if (!ref($arg)) {
                   9266: 	return $arg;
                   9267:     }
                   9268: }
                   9269: 
1.251     albertel 9270: ###############################################
1.182     matthew  9271: 
                   9272: =pod
                   9273: 
1.549     albertel 9274: =back
                   9275: 
                   9276: =head1 User Information Routines
                   9277: 
                   9278: =over 4
                   9279: 
1.405     albertel 9280: =item * &get_users_function()
1.182     matthew  9281: 
                   9282: Used by &bodytag to determine the current users primary role.
                   9283: Returns either 'student','coordinator','admin', or 'author'.
                   9284: 
                   9285: =cut
                   9286: 
                   9287: ###############################################
                   9288: sub get_users_function {
1.815     tempelho 9289:     my $function = 'norole';
1.818     tempelho 9290:     if ($env{'request.role'}=~/^(st)/) {
                   9291:         $function='student';
                   9292:     }
1.907     raeburn  9293:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9294:         $function='coordinator';
                   9295:     }
1.258     albertel 9296:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9297:         $function='admin';
                   9298:     }
1.826     bisitz   9299:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9300:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9301:         $function='author';
                   9302:     }
                   9303:     return $function;
1.54      www      9304: }
1.99      www      9305: 
                   9306: ###############################################
                   9307: 
1.233     raeburn  9308: =pod
                   9309: 
1.821     raeburn  9310: =item * &show_course()
                   9311: 
                   9312: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9313: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9314: 
                   9315: Inputs:
                   9316: None
                   9317: 
                   9318: Outputs:
                   9319: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9320: 
                   9321: =cut
                   9322: 
                   9323: ###############################################
                   9324: sub show_course {
                   9325:     my $course = !$env{'user.adv'};
                   9326:     if (!$env{'user.adv'}) {
                   9327:         foreach my $env (keys(%env)) {
                   9328:             next if ($env !~ m/^user\.priv\./);
                   9329:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9330:                 $course = 0;
                   9331:                 last;
                   9332:             }
                   9333:         }
                   9334:     }
                   9335:     return $course;
                   9336: }
                   9337: 
                   9338: ###############################################
                   9339: 
                   9340: =pod
                   9341: 
1.542     raeburn  9342: =item * &check_user_status()
1.274     raeburn  9343: 
                   9344: Determines current status of supplied role for a
                   9345: specific user. Roles can be active, previous or future.
                   9346: 
                   9347: Inputs: 
                   9348: user's domain, user's username, course's domain,
1.375     raeburn  9349: course's number, optional section ID.
1.274     raeburn  9350: 
                   9351: Outputs:
                   9352: role status: active, previous or future. 
                   9353: 
                   9354: =cut
                   9355: 
                   9356: sub check_user_status {
1.412     raeburn  9357:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9358:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  9359:     my @uroles = keys(%userinfo);
1.274     raeburn  9360:     my $srchstr;
                   9361:     my $active_chk = 'none';
1.412     raeburn  9362:     my $now = time;
1.274     raeburn  9363:     if (@uroles > 0) {
1.908     raeburn  9364:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9365:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9366:         } else {
1.412     raeburn  9367:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9368:         }
                   9369:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9370:             my $role_end = 0;
                   9371:             my $role_start = 0;
                   9372:             $active_chk = 'active';
1.412     raeburn  9373:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9374:                 $role_end = $1;
                   9375:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9376:                     $role_start = $1;
1.274     raeburn  9377:                 }
                   9378:             }
                   9379:             if ($role_start > 0) {
1.412     raeburn  9380:                 if ($now < $role_start) {
1.274     raeburn  9381:                     $active_chk = 'future';
                   9382:                 }
                   9383:             }
                   9384:             if ($role_end > 0) {
1.412     raeburn  9385:                 if ($now > $role_end) {
1.274     raeburn  9386:                     $active_chk = 'previous';
                   9387:                 }
                   9388:             }
                   9389:         }
                   9390:     }
                   9391:     return $active_chk;
                   9392: }
                   9393: 
                   9394: ###############################################
                   9395: 
                   9396: =pod
                   9397: 
1.405     albertel 9398: =item * &get_sections()
1.233     raeburn  9399: 
                   9400: Determines all the sections for a course including
                   9401: sections with students and sections containing other roles.
1.419     raeburn  9402: Incoming parameters: 
                   9403: 
                   9404: 1. domain
                   9405: 2. course number 
                   9406: 3. reference to array containing roles for which sections should 
                   9407: be gathered (optional).
                   9408: 4. reference to array containing status types for which sections 
                   9409: should be gathered (optional).
                   9410: 
                   9411: If the third argument is undefined, sections are gathered for any role. 
                   9412: If the fourth argument is undefined, sections are gathered for any status.
                   9413: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9414:  
1.374     raeburn  9415: Returns section hash (keys are section IDs, values are
                   9416: number of users in each section), subject to the
1.419     raeburn  9417: optional roles filter, optional status filter 
1.233     raeburn  9418: 
                   9419: =cut
                   9420: 
                   9421: ###############################################
                   9422: sub get_sections {
1.419     raeburn  9423:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9424:     if (!defined($cdom) || !defined($cnum)) {
                   9425:         my $cid =  $env{'request.course.id'};
                   9426: 
                   9427: 	return if (!defined($cid));
                   9428: 
                   9429:         $cdom = $env{'course.'.$cid.'.domain'};
                   9430:         $cnum = $env{'course.'.$cid.'.num'};
                   9431:     }
                   9432: 
                   9433:     my %sectioncount;
1.419     raeburn  9434:     my $now = time;
1.240     albertel 9435: 
1.1118    raeburn  9436:     my $check_students = 1;
                   9437:     my $only_students = 0;
                   9438:     if (ref($possible_roles) eq 'ARRAY') {
                   9439:         if (grep(/^st$/,@{$possible_roles})) {
                   9440:             if (@{$possible_roles} == 1) {
                   9441:                 $only_students = 1;
                   9442:             }
                   9443:         } else {
                   9444:             $check_students = 0;
                   9445:         }
                   9446:     }
                   9447: 
                   9448:     if ($check_students) { 
1.276     albertel 9449: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9450: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9451: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9452:         my $start_index = &Apache::loncoursedata::CL_START();
                   9453:         my $end_index = &Apache::loncoursedata::CL_END();
                   9454:         my $status;
1.366     albertel 9455: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9456: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9457: 				                     $data->[$status_index],
                   9458:                                                      $data->[$start_index],
                   9459:                                                      $data->[$end_index]);
                   9460:             if ($stu_status eq 'Active') {
                   9461:                 $status = 'active';
                   9462:             } elsif ($end < $now) {
                   9463:                 $status = 'previous';
                   9464:             } elsif ($start > $now) {
                   9465:                 $status = 'future';
                   9466:             } 
                   9467: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9468:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9469:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9470: 		    $sectioncount{$section}++;
                   9471:                 }
1.240     albertel 9472: 	    }
                   9473: 	}
                   9474:     }
1.1118    raeburn  9475:     if ($only_students) {
                   9476:         return %sectioncount;
                   9477:     }
1.240     albertel 9478:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9479:     foreach my $user (sort(keys(%courseroles))) {
                   9480: 	if ($user !~ /^(\w{2})/) { next; }
                   9481: 	my ($role) = ($user =~ /^(\w{2})/);
                   9482: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9483: 	my ($section,$status);
1.240     albertel 9484: 	if ($role eq 'cr' &&
                   9485: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9486: 	    $section=$1;
                   9487: 	}
                   9488: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9489: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9490:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9491:         if ($end == -1 && $start == -1) {
                   9492:             next; #deleted role
                   9493:         }
                   9494:         if (!defined($possible_status)) { 
                   9495:             $sectioncount{$section}++;
                   9496:         } else {
                   9497:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9498:                 $status = 'active';
                   9499:             } elsif ($end < $now) {
                   9500:                 $status = 'future';
                   9501:             } elsif ($start > $now) {
                   9502:                 $status = 'previous';
                   9503:             }
                   9504:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9505:                 $sectioncount{$section}++;
                   9506:             }
                   9507:         }
1.233     raeburn  9508:     }
1.366     albertel 9509:     return %sectioncount;
1.233     raeburn  9510: }
                   9511: 
1.274     raeburn  9512: ###############################################
1.294     raeburn  9513: 
                   9514: =pod
1.405     albertel 9515: 
                   9516: =item * &get_course_users()
                   9517: 
1.275     raeburn  9518: Retrieves usernames:domains for users in the specified course
                   9519: with specific role(s), and access status. 
                   9520: 
                   9521: Incoming parameters:
1.277     albertel 9522: 1. course domain
                   9523: 2. course number
                   9524: 3. access status: users must have - either active, 
1.275     raeburn  9525: previous, future, or all.
1.277     albertel 9526: 4. reference to array of permissible roles
1.288     raeburn  9527: 5. reference to array of section restrictions (optional)
                   9528: 6. reference to results object (hash of hashes).
                   9529: 7. reference to optional userdata hash
1.609     raeburn  9530: 8. reference to optional statushash
1.630     raeburn  9531: 9. flag if privileged users (except those set to unhide in
                   9532:    course settings) should be excluded    
1.609     raeburn  9533: Keys of top level results hash are roles.
1.275     raeburn  9534: Keys of inner hashes are username:domain, with 
                   9535: values set to access type.
1.288     raeburn  9536: Optional userdata hash returns an array with arguments in the 
                   9537: same order as loncoursedata::get_classlist() for student data.
                   9538: 
1.609     raeburn  9539: Optional statushash returns
                   9540: 
1.288     raeburn  9541: Entries for end, start, section and status are blank because
                   9542: of the possibility of multiple values for non-student roles.
                   9543: 
1.275     raeburn  9544: =cut
1.405     albertel 9545: 
1.275     raeburn  9546: ###############################################
1.405     albertel 9547: 
1.275     raeburn  9548: sub get_course_users {
1.630     raeburn  9549:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9550:     my %idx = ();
1.419     raeburn  9551:     my %seclists;
1.288     raeburn  9552: 
                   9553:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9554:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9555:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9556:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9557:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9558:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9559:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9560:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9561: 
1.290     albertel 9562:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9563:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9564:         my $now = time;
1.277     albertel 9565:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9566:             my $match = 0;
1.412     raeburn  9567:             my $secmatch = 0;
1.419     raeburn  9568:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9569:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9570:             if ($section eq '') {
                   9571:                 $section = 'none';
                   9572:             }
1.291     albertel 9573:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9574:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9575:                     $secmatch = 1;
                   9576:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9577:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9578:                         $secmatch = 1;
                   9579:                     }
                   9580:                 } else {  
1.419     raeburn  9581: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9582: 		        $secmatch = 1;
                   9583:                     }
1.290     albertel 9584: 		}
1.412     raeburn  9585:                 if (!$secmatch) {
                   9586:                     next;
                   9587:                 }
1.419     raeburn  9588:             }
1.275     raeburn  9589:             if (defined($$types{'active'})) {
1.288     raeburn  9590:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9591:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9592:                     $match = 1;
1.275     raeburn  9593:                 }
                   9594:             }
                   9595:             if (defined($$types{'previous'})) {
1.609     raeburn  9596:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9597:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9598:                     $match = 1;
1.275     raeburn  9599:                 }
                   9600:             }
                   9601:             if (defined($$types{'future'})) {
1.609     raeburn  9602:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9603:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9604:                     $match = 1;
1.275     raeburn  9605:                 }
                   9606:             }
1.609     raeburn  9607:             if ($match) {
                   9608:                 push(@{$seclists{$student}},$section);
                   9609:                 if (ref($userdata) eq 'HASH') {
                   9610:                     $$userdata{$student} = $$classlist{$student};
                   9611:                 }
                   9612:                 if (ref($statushash) eq 'HASH') {
                   9613:                     $statushash->{$student}{'st'}{$section} = $status;
                   9614:                 }
1.288     raeburn  9615:             }
1.275     raeburn  9616:         }
                   9617:     }
1.412     raeburn  9618:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9619:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9620:         my $now = time;
1.609     raeburn  9621:         my %displaystatus = ( previous => 'Expired',
                   9622:                               active   => 'Active',
                   9623:                               future   => 'Future',
                   9624:                             );
1.1121    raeburn  9625:         my (%nothide,@possdoms);
1.630     raeburn  9626:         if ($hidepriv) {
                   9627:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9628:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9629:                 if ($user !~ /:/) {
                   9630:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9631:                 } else {
                   9632:                     $nothide{$user} = 1;
                   9633:                 }
                   9634:             }
1.1121    raeburn  9635:             my @possdoms = ($cdom);
                   9636:             if ($coursehash{'checkforpriv'}) {
                   9637:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9638:             }
1.630     raeburn  9639:         }
1.439     raeburn  9640:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9641:             my $match = 0;
1.412     raeburn  9642:             my $secmatch = 0;
1.439     raeburn  9643:             my $status;
1.412     raeburn  9644:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9645:             $user =~ s/:$//;
1.439     raeburn  9646:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9647:             if ($end == -1 || $start == -1) {
                   9648:                 next;
                   9649:             }
                   9650:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9651:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9652:                 my ($uname,$udom) = split(/:/,$user);
                   9653:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9654:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9655:                         $secmatch = 1;
                   9656:                     } elsif ($usec eq '') {
1.420     albertel 9657:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9658:                             $secmatch = 1;
                   9659:                         }
                   9660:                     } else {
                   9661:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9662:                             $secmatch = 1;
                   9663:                         }
                   9664:                     }
                   9665:                     if (!$secmatch) {
                   9666:                         next;
                   9667:                     }
1.288     raeburn  9668:                 }
1.419     raeburn  9669:                 if ($usec eq '') {
                   9670:                     $usec = 'none';
                   9671:                 }
1.275     raeburn  9672:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9673:                     if ($hidepriv) {
1.1121    raeburn  9674:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9675:                             (!$nothide{$uname.':'.$udom})) {
                   9676:                             next;
                   9677:                         }
                   9678:                     }
1.503     raeburn  9679:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9680:                         $status = 'previous';
                   9681:                     } elsif ($start > $now) {
                   9682:                         $status = 'future';
                   9683:                     } else {
                   9684:                         $status = 'active';
                   9685:                     }
1.277     albertel 9686:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9687:                         if ($status eq $type) {
1.420     albertel 9688:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9689:                                 push(@{$$users{$role}{$user}},$type);
                   9690:                             }
1.288     raeburn  9691:                             $match = 1;
                   9692:                         }
                   9693:                     }
1.419     raeburn  9694:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9695:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9696: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9697:                         }
1.420     albertel 9698:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9699:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9700:                         }
1.609     raeburn  9701:                         if (ref($statushash) eq 'HASH') {
                   9702:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9703:                         }
1.275     raeburn  9704:                     }
                   9705:                 }
                   9706:             }
                   9707:         }
1.290     albertel 9708:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9709:             if ((defined($cdom)) && (defined($cnum))) {
                   9710:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9711:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9712:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9713:                     next if ($owner eq '');
                   9714:                     my ($ownername,$ownerdom);
                   9715:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9716:                         $ownername = $1;
                   9717:                         $ownerdom = $2;
                   9718:                     } else {
                   9719:                         $ownername = $owner;
                   9720:                         $ownerdom = $cdom;
                   9721:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9722:                     }
                   9723:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9724:                     if (defined($userdata) && 
1.609     raeburn  9725: 			!exists($$userdata{$owner})) {
                   9726: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9727:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9728:                             push(@{$seclists{$owner}},'none');
                   9729:                         }
                   9730:                         if (ref($statushash) eq 'HASH') {
                   9731:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9732:                         }
1.290     albertel 9733: 		    }
1.279     raeburn  9734:                 }
                   9735:             }
                   9736:         }
1.419     raeburn  9737:         foreach my $user (keys(%seclists)) {
                   9738:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9739:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9740:         }
1.275     raeburn  9741:     }
                   9742:     return;
                   9743: }
                   9744: 
1.288     raeburn  9745: sub get_user_info {
                   9746:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9747:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9748: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9749:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9750:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9751:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9752:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9753:     return;
                   9754: }
1.275     raeburn  9755: 
1.472     raeburn  9756: ###############################################
                   9757: 
                   9758: =pod
                   9759: 
                   9760: =item * &get_user_quota()
                   9761: 
1.1134    raeburn  9762: Retrieves quota assigned for storage of user files.
                   9763: Default is to report quota for portfolio files.
1.472     raeburn  9764: 
                   9765: Incoming parameters:
                   9766: 1. user's username
                   9767: 2. user's domain
1.1134    raeburn  9768: 3. quota name - portfolio, author, or course
1.1136    raeburn  9769:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  9770: 4. crstype - official, unofficial, textbook, placement or community, 
                   9771:    if quota name is course
1.472     raeburn  9772: 
                   9773: Returns:
1.1163    raeburn  9774: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9775: 2. (Optional) Type of setting: custom or default
                   9776:    (individually assigned or default for user's 
                   9777:    institutional status).
                   9778: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9779:    or student - types as defined in localenroll::inst_usertypes 
                   9780:    for user's domain, which determines default quota for user.
                   9781: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9782: 
                   9783: If a value has been stored in the user's environment, 
1.536     raeburn  9784: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9785: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9786: 
                   9787: =cut
                   9788: 
                   9789: ###############################################
                   9790: 
                   9791: 
                   9792: sub get_user_quota {
1.1136    raeburn  9793:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9794:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9795:     if (!defined($udom)) {
                   9796:         $udom = $env{'user.domain'};
                   9797:     }
                   9798:     if (!defined($uname)) {
                   9799:         $uname = $env{'user.name'};
                   9800:     }
                   9801:     if (($udom eq '' || $uname eq '') ||
                   9802:         ($udom eq 'public') && ($uname eq 'public')) {
                   9803:         $quota = 0;
1.536     raeburn  9804:         $quotatype = 'default';
                   9805:         $defquota = 0; 
1.472     raeburn  9806:     } else {
1.536     raeburn  9807:         my $inststatus;
1.1134    raeburn  9808:         if ($quotaname eq 'course') {
                   9809:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9810:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9811:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9812:             } else {
                   9813:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9814:                 $quota = $cenv{'internal.uploadquota'};
                   9815:             }
1.536     raeburn  9816:         } else {
1.1134    raeburn  9817:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9818:                 if ($quotaname eq 'author') {
                   9819:                     $quota = $env{'environment.authorquota'};
                   9820:                 } else {
                   9821:                     $quota = $env{'environment.portfolioquota'};
                   9822:                 }
                   9823:                 $inststatus = $env{'environment.inststatus'};
                   9824:             } else {
                   9825:                 my %userenv = 
                   9826:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9827:                                          'authorquota','inststatus'],$udom,$uname);
                   9828:                 my ($tmp) = keys(%userenv);
                   9829:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9830:                     if ($quotaname eq 'author') {
                   9831:                         $quota = $userenv{'authorquota'};
                   9832:                     } else {
                   9833:                         $quota = $userenv{'portfolioquota'};
                   9834:                     }
                   9835:                     $inststatus = $userenv{'inststatus'};
                   9836:                 } else {
                   9837:                     undef(%userenv);
                   9838:                 }
                   9839:             }
                   9840:         }
                   9841:         if ($quota eq '' || wantarray) {
                   9842:             if ($quotaname eq 'course') {
                   9843:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9844:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  9845:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   9846:                     ($crstype eq 'placement')) { 
1.1136    raeburn  9847:                     $defquota = $domdefs{$crstype.'quota'};
                   9848:                 }
                   9849:                 if ($defquota eq '') {
                   9850:                     $defquota = 500;
                   9851:                 }
1.1134    raeburn  9852:             } else {
                   9853:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9854:             }
                   9855:             if ($quota eq '') {
                   9856:                 $quota = $defquota;
                   9857:                 $quotatype = 'default';
                   9858:             } else {
                   9859:                 $quotatype = 'custom';
                   9860:             }
1.472     raeburn  9861:         }
                   9862:     }
1.536     raeburn  9863:     if (wantarray) {
                   9864:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9865:     } else {
                   9866:         return $quota;
                   9867:     }
1.472     raeburn  9868: }
                   9869: 
                   9870: ###############################################
                   9871: 
                   9872: =pod
                   9873: 
                   9874: =item * &default_quota()
                   9875: 
1.536     raeburn  9876: Retrieves default quota assigned for storage of user portfolio files,
                   9877: given an (optional) user's institutional status.
1.472     raeburn  9878: 
                   9879: Incoming parameters:
1.1142    raeburn  9880: 
1.472     raeburn  9881: 1. domain
1.536     raeburn  9882: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9883:    status types (e.g., faculty, staff, student etc.)
                   9884:    which apply to the user for whom the default is being retrieved.
                   9885:    If the institutional status string in undefined, the domain
1.1134    raeburn  9886:    default quota will be returned.
                   9887: 3.  quota name - portfolio, author, or course
                   9888:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9889: 
                   9890: Returns:
1.1142    raeburn  9891: 
1.1163    raeburn  9892: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9893: 2. (Optional) institutional type which determined the value of the
                   9894:    default quota.
1.472     raeburn  9895: 
                   9896: If a value has been stored in the domain's configuration db,
                   9897: it will return that, otherwise it returns 20 (for backwards 
                   9898: compatibility with domains which have not set up a configuration
1.1163    raeburn  9899: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9900: 
1.536     raeburn  9901: If the user's status includes multiple types (e.g., staff and student),
                   9902: the largest default quota which applies to the user determines the
                   9903: default quota returned.
                   9904: 
1.472     raeburn  9905: =cut
                   9906: 
                   9907: ###############################################
                   9908: 
                   9909: 
                   9910: sub default_quota {
1.1134    raeburn  9911:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9912:     my ($defquota,$settingstatus);
                   9913:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9914:                                             ['quotas'],$udom);
1.1134    raeburn  9915:     my $key = 'defaultquota';
                   9916:     if ($quotaname eq 'author') {
                   9917:         $key = 'authorquota';
                   9918:     }
1.622     raeburn  9919:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9920:         if ($inststatus ne '') {
1.765     raeburn  9921:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9922:             foreach my $item (@statuses) {
1.1134    raeburn  9923:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9924:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9925:                         if ($defquota eq '') {
1.1134    raeburn  9926:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9927:                             $settingstatus = $item;
1.1134    raeburn  9928:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9929:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9930:                             $settingstatus = $item;
                   9931:                         }
                   9932:                     }
1.1134    raeburn  9933:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9934:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9935:                         if ($defquota eq '') {
                   9936:                             $defquota = $quotahash{'quotas'}{$item};
                   9937:                             $settingstatus = $item;
                   9938:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9939:                             $defquota = $quotahash{'quotas'}{$item};
                   9940:                             $settingstatus = $item;
                   9941:                         }
1.536     raeburn  9942:                     }
                   9943:                 }
                   9944:             }
                   9945:         }
                   9946:         if ($defquota eq '') {
1.1134    raeburn  9947:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9948:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9949:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9950:                 $defquota = $quotahash{'quotas'}{'default'};
                   9951:             }
1.536     raeburn  9952:             $settingstatus = 'default';
1.1139    raeburn  9953:             if ($defquota eq '') {
                   9954:                 if ($quotaname eq 'author') {
                   9955:                     $defquota = 500;
                   9956:                 }
                   9957:             }
1.536     raeburn  9958:         }
                   9959:     } else {
                   9960:         $settingstatus = 'default';
1.1134    raeburn  9961:         if ($quotaname eq 'author') {
                   9962:             $defquota = 500;
                   9963:         } else {
                   9964:             $defquota = 20;
                   9965:         }
1.536     raeburn  9966:     }
                   9967:     if (wantarray) {
                   9968:         return ($defquota,$settingstatus);
1.472     raeburn  9969:     } else {
1.536     raeburn  9970:         return $defquota;
1.472     raeburn  9971:     }
                   9972: }
                   9973: 
1.1135    raeburn  9974: ###############################################
                   9975: 
                   9976: =pod
                   9977: 
1.1136    raeburn  9978: =item * &excess_filesize_warning()
1.1135    raeburn  9979: 
                   9980: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9981: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9982: space to be exceeded.
1.1136    raeburn  9983: 
                   9984: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9985: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9986: 
1.1165    raeburn  9987: Inputs: 7 
1.1136    raeburn  9988: 1. username or coursenum
1.1135    raeburn  9989: 2. domain
1.1136    raeburn  9990: 3. context ('author' or 'course')
1.1135    raeburn  9991: 4. filename of file for which action is being requested
                   9992: 5. filesize (kB) of file
                   9993: 6. action being taken: copy or upload.
1.1237    raeburn  9994: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  9995: 
                   9996: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9997:          otherwise return null.
                   9998: 
                   9999: =back
1.1135    raeburn  10000: 
                   10001: =cut
                   10002: 
1.1136    raeburn  10003: sub excess_filesize_warning {
1.1165    raeburn  10004:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10005:     my $current_disk_usage = 0;
1.1165    raeburn  10006:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10007:     if ($context eq 'author') {
                   10008:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10009:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10010:     } else {
                   10011:         foreach my $subdir ('docs','supplemental') {
                   10012:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10013:         }
                   10014:     }
1.1135    raeburn  10015:     $disk_quota = int($disk_quota * 1000);
                   10016:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10017:         return '<p class="LC_warning">'.
1.1135    raeburn  10018:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10019:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10020:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10021:                             $disk_quota,$current_disk_usage).
                   10022:                '</p>';
                   10023:     }
                   10024:     return;
                   10025: }
                   10026: 
                   10027: ###############################################
                   10028: 
                   10029: 
1.1136    raeburn  10030: 
                   10031: 
1.384     raeburn  10032: sub get_secgrprole_info {
                   10033:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10034:     my %sections_count = &get_sections($cdom,$cnum);
                   10035:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10036:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10037:     my @groups = sort(keys(%curr_groups));
                   10038:     my $allroles = [];
                   10039:     my $rolehash;
                   10040:     my $accesshash = {
                   10041:                      active => 'Currently has access',
                   10042:                      future => 'Will have future access',
                   10043:                      previous => 'Previously had access',
                   10044:                   };
                   10045:     if ($needroles) {
                   10046:         $rolehash = {'all' => 'all'};
1.385     albertel 10047:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10048: 	if (&Apache::lonnet::error(%user_roles)) {
                   10049: 	    undef(%user_roles);
                   10050: 	}
                   10051:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10052:             my ($role)=split(/\:/,$item,2);
                   10053:             if ($role eq 'cr') { next; }
                   10054:             if ($role =~ /^cr/) {
                   10055:                 $$rolehash{$role} = (split('/',$role))[3];
                   10056:             } else {
                   10057:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10058:             }
                   10059:         }
                   10060:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10061:             push(@{$allroles},$key);
                   10062:         }
                   10063:         push (@{$allroles},'st');
                   10064:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10065:     }
                   10066:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10067: }
                   10068: 
1.555     raeburn  10069: sub user_picker {
1.1279    raeburn  10070:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10071:     my $currdom = $dom;
1.1253    raeburn  10072:     my @alldoms = &Apache::lonnet::all_domains();
                   10073:     if (@alldoms == 1) {
                   10074:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10075:                                                ['directorysrch'],$alldoms[0]);
                   10076:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10077:         my $showdom = $domdesc;
                   10078:         if ($showdom eq '') {
                   10079:             $showdom = $dom;
                   10080:         }
                   10081:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10082:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10083:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10084:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10085:             }
                   10086:         }
                   10087:     }
1.555     raeburn  10088:     my %curr_selected = (
                   10089:                         srchin => 'dom',
1.580     raeburn  10090:                         srchby => 'lastname',
1.555     raeburn  10091:                       );
                   10092:     my $srchterm;
1.625     raeburn  10093:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10094:         if ($srch->{'srchby'} ne '') {
                   10095:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10096:         }
                   10097:         if ($srch->{'srchin'} ne '') {
                   10098:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10099:         }
                   10100:         if ($srch->{'srchtype'} ne '') {
                   10101:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10102:         }
                   10103:         if ($srch->{'srchdomain'} ne '') {
                   10104:             $currdom = $srch->{'srchdomain'};
                   10105:         }
                   10106:         $srchterm = $srch->{'srchterm'};
                   10107:     }
1.1222    damieng  10108:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10109:                     'usr'       => 'Search criteria',
1.563     raeburn  10110:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10111:                     'uname'     => 'username',
                   10112:                     'lastname'  => 'last name',
1.555     raeburn  10113:                     'lastfirst' => 'last name, first name',
1.558     albertel 10114:                     'crs'       => 'in this course',
1.576     raeburn  10115:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10116:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10117:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10118:                     'exact'     => 'is',
                   10119:                     'contains'  => 'contains',
1.569     raeburn  10120:                     'begins'    => 'begins with',
1.1222    damieng  10121:                                        );
                   10122:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10123:                     'youm'      => "You must include some text to search for.",
                   10124:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10125:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10126:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10127:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10128:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10129:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10130:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10131:                                        );
1.1222    damieng  10132:     &html_escape(\%html_lt);
                   10133:     &js_escape(\%js_lt);
1.1255    raeburn  10134:     my $domform;
1.1277    raeburn  10135:     my $allow_blank = 1;
1.1255    raeburn  10136:     if ($fixeddom) {
1.1277    raeburn  10137:         $allow_blank = 0;
                   10138:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  10139:     } else {
1.1287  ! raeburn  10140:         my $defdom = $env{'request.role.domain'};
        !          10141:         my ($trustedref,$untrustedref);
        !          10142:         if (($context eq 'requestcrs') || ($context eq 'course')) {
        !          10143:             ($trustedref,$untrustedref) = &Apache::lonnet::trusted_domains('enroll',$defdom);
        !          10144:         } elsif ($context eq 'author') {
        !          10145:             ($trustedref,$untrustedref) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
        !          10146:         } elsif ($context eq 'domain') {
        !          10147:             ($trustedref,$untrustedref) = &Apache::lonnet::trusted_domains('domroles',$defdom);
        !          10148:         }
        !          10149:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trustedref,$untrustedref);
1.1255    raeburn  10150:     }
1.563     raeburn  10151:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10152: 
                   10153:     my @srchins = ('crs','dom','alc','instd');
                   10154: 
                   10155:     foreach my $option (@srchins) {
                   10156:         # FIXME 'alc' option unavailable until 
                   10157:         #       loncreateuser::print_user_query_page()
                   10158:         #       has been completed.
                   10159:         next if ($option eq 'alc');
1.880     raeburn  10160:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10161:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  10162:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10163:         if ($curr_selected{'srchin'} eq $option) {
                   10164:             $srchinsel .= ' 
1.1222    damieng  10165:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10166:         } else {
                   10167:             $srchinsel .= '
1.1222    damieng  10168:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10169:         }
1.555     raeburn  10170:     }
1.563     raeburn  10171:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10172: 
                   10173:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10174:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10175:         if ($curr_selected{'srchby'} eq $option) {
                   10176:             $srchbysel .= '
1.1222    damieng  10177:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10178:         } else {
                   10179:             $srchbysel .= '
1.1222    damieng  10180:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10181:          }
                   10182:     }
                   10183:     $srchbysel .= "\n  </select>\n";
                   10184: 
                   10185:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10186:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10187:         if ($curr_selected{'srchtype'} eq $option) {
                   10188:             $srchtypesel .= '
1.1222    damieng  10189:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10190:         } else {
                   10191:             $srchtypesel .= '
1.1222    damieng  10192:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10193:         }
                   10194:     }
                   10195:     $srchtypesel .= "\n  </select>\n";
                   10196: 
1.558     albertel 10197:     my ($newuserscript,$new_user_create);
1.994     raeburn  10198:     my $context_dom = $env{'request.role.domain'};
                   10199:     if ($context eq 'requestcrs') {
                   10200:         if ($env{'form.coursedom'} ne '') { 
                   10201:             $context_dom = $env{'form.coursedom'};
                   10202:         }
                   10203:     }
1.556     raeburn  10204:     if ($forcenewuser) {
1.576     raeburn  10205:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10206:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10207:                 if ($cancreate) {
                   10208:                     $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>';
                   10209:                 } else {
1.799     bisitz   10210:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10211:                     my %usertypetext = (
                   10212:                         official   => 'institutional',
                   10213:                         unofficial => 'non-institutional',
                   10214:                     );
1.799     bisitz   10215:                     $new_user_create = '<p class="LC_warning">'
                   10216:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10217:                                       .' '
                   10218:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10219:                                           ,'<a href="'.$helplink.'">','</a>')
                   10220:                                       .'</p><br />';
1.627     raeburn  10221:                 }
1.576     raeburn  10222:             }
                   10223:         }
                   10224: 
1.556     raeburn  10225:         $newuserscript = <<"ENDSCRIPT";
                   10226: 
1.570     raeburn  10227: function setSearch(createnew,callingForm) {
1.556     raeburn  10228:     if (createnew == 1) {
1.570     raeburn  10229:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10230:             if (callingForm.srchby.options[i].value == 'uname') {
                   10231:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10232:             }
                   10233:         }
1.570     raeburn  10234:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10235:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10236: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10237:             }
                   10238:         }
1.570     raeburn  10239:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10240:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10241:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10242:             }
                   10243:         }
1.570     raeburn  10244:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10245:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10246:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10247:             }
                   10248:         }
                   10249:     }
                   10250: }
                   10251: ENDSCRIPT
1.558     albertel 10252: 
1.556     raeburn  10253:     }
                   10254: 
1.555     raeburn  10255:     my $output = <<"END_BLOCK";
1.556     raeburn  10256: <script type="text/javascript">
1.824     bisitz   10257: // <![CDATA[
1.570     raeburn  10258: function validateEntry(callingForm) {
1.558     albertel 10259: 
1.556     raeburn  10260:     var checkok = 1;
1.558     albertel 10261:     var srchin;
1.570     raeburn  10262:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10263: 	if ( callingForm.srchin[i].checked ) {
                   10264: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10265: 	}
                   10266:     }
                   10267: 
1.570     raeburn  10268:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10269:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10270:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10271:     var srchterm =  callingForm.srchterm.value;
                   10272:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10273:     var msg = "";
                   10274: 
                   10275:     if (srchterm == "") {
                   10276:         checkok = 0;
1.1222    damieng  10277:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10278:     }
                   10279: 
1.569     raeburn  10280:     if (srchtype== 'begins') {
                   10281:         if (srchterm.length < 2) {
                   10282:             checkok = 0;
1.1222    damieng  10283:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10284:         }
                   10285:     }
                   10286: 
1.556     raeburn  10287:     if (srchtype== 'contains') {
                   10288:         if (srchterm.length < 3) {
                   10289:             checkok = 0;
1.1222    damieng  10290:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10291:         }
                   10292:     }
                   10293:     if (srchin == 'instd') {
                   10294:         if (srchdomain == '') {
                   10295:             checkok = 0;
1.1222    damieng  10296:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10297:         }
                   10298:     }
                   10299:     if (srchin == 'dom') {
                   10300:         if (srchdomain == '') {
                   10301:             checkok = 0;
1.1222    damieng  10302:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10303:         }
                   10304:     }
                   10305:     if (srchby == 'lastfirst') {
                   10306:         if (srchterm.indexOf(",") == -1) {
                   10307:             checkok = 0;
1.1222    damieng  10308:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10309:         }
                   10310:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10311:             checkok = 0;
1.1222    damieng  10312:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10313:         }
                   10314:     }
                   10315:     if (checkok == 0) {
1.1222    damieng  10316:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10317:         return;
                   10318:     }
                   10319:     if (checkok == 1) {
1.570     raeburn  10320:         callingForm.submit();
1.556     raeburn  10321:     }
                   10322: }
                   10323: 
                   10324: $newuserscript
                   10325: 
1.824     bisitz   10326: // ]]>
1.556     raeburn  10327: </script>
1.558     albertel 10328: 
                   10329: $new_user_create
                   10330: 
1.555     raeburn  10331: END_BLOCK
1.558     albertel 10332: 
1.876     raeburn  10333:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  10334:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10335:                $domform.
                   10336:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  10337:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10338:                $srchbysel.
                   10339:                $srchtypesel. 
                   10340:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10341:                $srchinsel.
                   10342:                &Apache::lonhtmlcommon::row_closure(1). 
                   10343:                &Apache::lonhtmlcommon::end_pick_box().
                   10344:                '<br />';
1.1253    raeburn  10345:     return ($output,1);
1.555     raeburn  10346: }
                   10347: 
1.612     raeburn  10348: sub user_rule_check {
1.615     raeburn  10349:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  10350:     my ($response,%inst_response);
1.612     raeburn  10351:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  10352:         if (keys(%{$usershash}) > 1) {
                   10353:             my (%by_username,%by_id,%userdoms);
                   10354:             my $checkid; 
                   10355:             if (ref($checks) eq 'HASH') {
                   10356:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10357:                     $checkid = 1;
                   10358:                 }
                   10359:             }
                   10360:             foreach my $user (keys(%{$usershash})) {
                   10361:                 my ($uname,$udom) = split(/:/,$user);
                   10362:                 if ($checkid) {
                   10363:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10364:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  10365:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  10366:                             $userdoms{$udom} = 1;
1.1227    raeburn  10367:                             if (ref($inst_results) eq 'HASH') {
                   10368:                                 $inst_results->{$uname.':'.$udom} = {};
                   10369:                             }
1.1226    raeburn  10370:                         }
                   10371:                     }
                   10372:                 } else {
                   10373:                     $by_username{$udom}{$uname} = 1;
                   10374:                     $userdoms{$udom} = 1;
1.1227    raeburn  10375:                     if (ref($inst_results) eq 'HASH') {
                   10376:                         $inst_results->{$uname.':'.$udom} = {};
                   10377:                     }
1.1226    raeburn  10378:                 }
                   10379:             }
                   10380:             foreach my $udom (keys(%userdoms)) {
                   10381:                 if (!$got_rules->{$udom}) {
                   10382:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10383:                                                              ['usercreation'],$udom);
                   10384:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10385:                         foreach my $item ('username','id') {
                   10386:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  10387:                                 $$curr_rules{$udom}{$item} =
                   10388:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  10389:                             }
                   10390:                         }
                   10391:                     }
                   10392:                     $got_rules->{$udom} = 1;
                   10393:                 }
1.612     raeburn  10394:             }
1.1226    raeburn  10395:             if ($checkid) {
                   10396:                 foreach my $udom (keys(%by_id)) {
                   10397:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10398:                     if ($outcome eq 'ok') {
1.1227    raeburn  10399:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10400:                             my $uname = $by_id{$udom}{$id};
                   10401:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10402:                         }
1.1226    raeburn  10403:                         if (ref($results) eq 'HASH') {
                   10404:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  10405:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10406:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10407:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10408:                                 }
1.1226    raeburn  10409:                             }
                   10410:                         }
                   10411:                     }
1.612     raeburn  10412:                 }
1.615     raeburn  10413:             } else {
1.1226    raeburn  10414:                 foreach my $udom (keys(%by_username)) {
                   10415:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10416:                     if ($outcome eq 'ok') {
1.1227    raeburn  10417:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10418:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10419:                         }
1.1226    raeburn  10420:                         if (ref($results) eq 'HASH') {
                   10421:                             foreach my $uname (keys(%{$results})) {
                   10422:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10423:                             }
                   10424:                         }
                   10425:                     }
                   10426:                 }
1.612     raeburn  10427:             }
1.1226    raeburn  10428:         } elsif (keys(%{$usershash}) == 1) {
                   10429:             my $user = (keys(%{$usershash}))[0];
                   10430:             my ($uname,$udom) = split(/:/,$user);
                   10431:             if (($udom ne '') && ($uname ne '')) {
                   10432:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10433:                     if (ref($checks) eq 'HASH') {
                   10434:                         if (defined($checks->{'username'})) {
                   10435:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   10436:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10437:                         } elsif (defined($checks->{'id'})) {
                   10438:                             if ($usershash->{$user}->{'id'} ne '') {
                   10439:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10440:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10441:                                                                   $usershash->{$user}->{'id'});
                   10442:                             } else {
                   10443:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10444:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10445:                             }
1.585     raeburn  10446:                         }
1.1226    raeburn  10447:                     } else {
                   10448:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10449:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10450:                        return;
                   10451:                     }
                   10452:                     if (!$got_rules->{$udom}) {
                   10453:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10454:                                                                  ['usercreation'],$udom);
                   10455:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10456:                             foreach my $item ('username','id') {
                   10457:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10458:                                    $$curr_rules{$udom}{$item} = 
                   10459:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10460:                                 }
                   10461:                             }
                   10462:                         }
                   10463:                         $got_rules->{$udom} = 1;
1.585     raeburn  10464:                     }
                   10465:                 }
1.1226    raeburn  10466:             } else {
                   10467:                 return;
                   10468:             }
                   10469:         } else {
                   10470:             return;
                   10471:         }
                   10472:         foreach my $user (keys(%{$usershash})) {
                   10473:             my ($uname,$udom) = split(/:/,$user);
                   10474:             next if (($udom eq '') || ($uname eq ''));
                   10475:             my $id;
1.1227    raeburn  10476:             if (ref($inst_results) eq 'HASH') {
                   10477:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10478:                     $id = $inst_results->{$user}->{'id'};
                   10479:                 }
                   10480:             }
                   10481:             if ($id eq '') { 
                   10482:                 if (ref($usershash->{$user})) {
                   10483:                     $id = $usershash->{$user}->{'id'};
                   10484:                 }
1.585     raeburn  10485:             }
1.612     raeburn  10486:             foreach my $item (keys(%{$checks})) {
                   10487:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10488:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10489:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  10490:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10491:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10492:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10493:                                 if ($rule_check{$rule}) {
                   10494:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  10495:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10496:                                         if (ref($inst_results) eq 'HASH') {
                   10497:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10498:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10499:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  10500:                                                 } elsif ($item eq 'id') {
                   10501:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10502:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10503:                                                     }
1.615     raeburn  10504:                                                 }
1.612     raeburn  10505:                                             }
                   10506:                                         }
1.615     raeburn  10507:                                     }
                   10508:                                     last;
1.585     raeburn  10509:                                 }
                   10510:                             }
                   10511:                         }
                   10512:                     }
                   10513:                 }
                   10514:             }
                   10515:         }
                   10516:     }
1.612     raeburn  10517:     return;
                   10518: }
                   10519: 
                   10520: sub user_rule_formats {
                   10521:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10522:     my %text = ( 
                   10523:                  'username' => 'Usernames',
                   10524:                  'id'       => 'IDs',
                   10525:                );
                   10526:     my $output;
                   10527:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10528:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10529:         if (@{$ruleorder} > 0) {
1.1102    raeburn  10530:             $output = '<br />'.
                   10531:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10532:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10533:                       ' <ul>';
1.612     raeburn  10534:             foreach my $rule (@{$ruleorder}) {
                   10535:                 if (ref($curr_rules) eq 'ARRAY') {
                   10536:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10537:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10538:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10539:                                         $rules->{$rule}{'desc'}.'</li>';
                   10540:                         }
                   10541:                     }
                   10542:                 }
                   10543:             }
                   10544:             $output .= '</ul>';
                   10545:         }
                   10546:     }
                   10547:     return $output;
                   10548: }
                   10549: 
                   10550: sub instrule_disallow_msg {
1.615     raeburn  10551:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10552:     my $response;
                   10553:     my %text = (
                   10554:                   item   => 'username',
                   10555:                   items  => 'usernames',
                   10556:                   match  => 'matches',
                   10557:                   do     => 'does',
                   10558:                   action => 'a username',
                   10559:                   one    => 'one',
                   10560:                );
                   10561:     if ($count > 1) {
                   10562:         $text{'item'} = 'usernames';
                   10563:         $text{'match'} ='match';
                   10564:         $text{'do'} = 'do';
                   10565:         $text{'action'} = 'usernames',
                   10566:         $text{'one'} = 'ones';
                   10567:     }
                   10568:     if ($checkitem eq 'id') {
                   10569:         $text{'items'} = 'IDs';
                   10570:         $text{'item'} = 'ID';
                   10571:         $text{'action'} = 'an ID';
1.615     raeburn  10572:         if ($count > 1) {
                   10573:             $text{'item'} = 'IDs';
                   10574:             $text{'action'} = 'IDs';
                   10575:         }
1.612     raeburn  10576:     }
1.674     bisitz   10577:     $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  10578:     if ($mode eq 'upload') {
                   10579:         if ($checkitem eq 'username') {
                   10580:             $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'}.");
                   10581:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10582:             $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  10583:         }
1.669     raeburn  10584:     } elsif ($mode eq 'selfcreate') {
                   10585:         if ($checkitem eq 'id') {
                   10586:             $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.");
                   10587:         }
1.615     raeburn  10588:     } else {
                   10589:         if ($checkitem eq 'username') {
                   10590:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10591:         } elsif ($checkitem eq 'id') {
                   10592:             $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.");
                   10593:         }
1.612     raeburn  10594:     }
                   10595:     return $response;
1.585     raeburn  10596: }
                   10597: 
1.624     raeburn  10598: sub personal_data_fieldtitles {
                   10599:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10600:                         id => 'Student/Employee ID',
                   10601:                         permanentemail => 'E-mail address',
                   10602:                         lastname => 'Last Name',
                   10603:                         firstname => 'First Name',
                   10604:                         middlename => 'Middle Name',
                   10605:                         generation => 'Generation',
                   10606:                         gen => 'Generation',
1.765     raeburn  10607:                         inststatus => 'Affiliation',
1.624     raeburn  10608:                    );
                   10609:     return %fieldtitles;
                   10610: }
                   10611: 
1.642     raeburn  10612: sub sorted_inst_types {
                   10613:     my ($dom) = @_;
1.1185    raeburn  10614:     my ($usertypes,$order);
                   10615:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10616:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10617:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10618:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10619:     } else {
                   10620:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10621:     }
1.642     raeburn  10622:     my $othertitle = &mt('All users');
                   10623:     if ($env{'request.course.id'}) {
1.668     raeburn  10624:         $othertitle  = &mt('Any users');
1.642     raeburn  10625:     }
                   10626:     my @types;
                   10627:     if (ref($order) eq 'ARRAY') {
                   10628:         @types = @{$order};
                   10629:     }
                   10630:     if (@types == 0) {
                   10631:         if (ref($usertypes) eq 'HASH') {
                   10632:             @types = sort(keys(%{$usertypes}));
                   10633:         }
                   10634:     }
                   10635:     if (keys(%{$usertypes}) > 0) {
                   10636:         $othertitle = &mt('Other users');
                   10637:     }
                   10638:     return ($othertitle,$usertypes,\@types);
                   10639: }
                   10640: 
1.645     raeburn  10641: sub get_institutional_codes {
                   10642:     my ($settings,$allcourses,$LC_code) = @_;
                   10643: # Get complete list of course sections to update
                   10644:     my @currsections = ();
                   10645:     my @currxlists = ();
                   10646:     my $coursecode = $$settings{'internal.coursecode'};
                   10647: 
                   10648:     if ($$settings{'internal.sectionnums'} ne '') {
                   10649:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10650:     }
                   10651: 
                   10652:     if ($$settings{'internal.crosslistings'} ne '') {
                   10653:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10654:     }
                   10655: 
                   10656:     if (@currxlists > 0) {
                   10657:         foreach (@currxlists) {
                   10658:             if (m/^([^:]+):(\w*)$/) {
                   10659:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  10660:                     push(@{$allcourses},$1);
1.645     raeburn  10661:                     $$LC_code{$1} = $2;
                   10662:                 }
                   10663:             }
                   10664:         }
                   10665:     }
                   10666:  
                   10667:     if (@currsections > 0) {
                   10668:         foreach (@currsections) {
                   10669:             if (m/^(\w+):(\w*)$/) {
                   10670:                 my $sec = $coursecode.$1;
                   10671:                 my $lc_sec = $2;
                   10672:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1263    raeburn  10673:                     push(@{$allcourses},$sec);
1.645     raeburn  10674:                     $$LC_code{$sec} = $lc_sec;
                   10675:                 }
                   10676:             }
                   10677:         }
                   10678:     }
                   10679:     return;
                   10680: }
                   10681: 
1.971     raeburn  10682: sub get_standard_codeitems {
                   10683:     return ('Year','Semester','Department','Number','Section');
                   10684: }
                   10685: 
1.112     bowersj2 10686: =pod
                   10687: 
1.780     raeburn  10688: =head1 Slot Helpers
                   10689: 
                   10690: =over 4
                   10691: 
                   10692: =item * sorted_slots()
                   10693: 
1.1040    raeburn  10694: Sorts an array of slot names in order of an optional sort key,
                   10695: default sort is by slot start time (earliest first). 
1.780     raeburn  10696: 
                   10697: Inputs:
                   10698: 
                   10699: =over 4
                   10700: 
                   10701: slotsarr  - Reference to array of unsorted slot names.
                   10702: 
                   10703: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10704: 
1.1040    raeburn  10705: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10706: 
1.549     albertel 10707: =back
                   10708: 
1.780     raeburn  10709: Returns:
                   10710: 
                   10711: =over 4
                   10712: 
1.1040    raeburn  10713: sorted   - An array of slot names sorted by a specified sort key 
                   10714:            (default sort key is start time of the slot).
1.780     raeburn  10715: 
                   10716: =back
                   10717: 
                   10718: =cut
                   10719: 
                   10720: 
                   10721: sub sorted_slots {
1.1040    raeburn  10722:     my ($slotsarr,$slots,$sortkey) = @_;
                   10723:     if ($sortkey eq '') {
                   10724:         $sortkey = 'starttime';
                   10725:     }
1.780     raeburn  10726:     my @sorted;
                   10727:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10728:         @sorted =
                   10729:             sort {
                   10730:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10731:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10732:                      }
                   10733:                      if (ref($slots->{$a})) { return -1;}
                   10734:                      if (ref($slots->{$b})) { return 1;}
                   10735:                      return 0;
                   10736:                  } @{$slotsarr};
                   10737:     }
                   10738:     return @sorted;
                   10739: }
                   10740: 
1.1040    raeburn  10741: =pod
                   10742: 
                   10743: =item * get_future_slots()
                   10744: 
                   10745: Inputs:
                   10746: 
                   10747: =over 4
                   10748: 
                   10749: cnum - course number
                   10750: 
                   10751: cdom - course domain
                   10752: 
                   10753: now - current UNIX time
                   10754: 
                   10755: symb - optional symb
                   10756: 
                   10757: =back
                   10758: 
                   10759: Returns:
                   10760: 
                   10761: =over 4
                   10762: 
                   10763: sorted_reservable - ref to array of student_schedulable slots currently 
                   10764:                     reservable, ordered by end date of reservation period.
                   10765: 
                   10766: reservable_now - ref to hash of student_schedulable slots currently
                   10767:                  reservable.
                   10768: 
                   10769:     Keys in inner hash are:
                   10770:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10771:     (b) endreserve: end date of reservation period.
                   10772:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10773:         selected.
1.1040    raeburn  10774: 
                   10775: sorted_future - ref to array of student_schedulable slots reservable in
                   10776:                 the future, ordered by start date of reservation period.
                   10777: 
                   10778: future_reservable - ref to hash of student_schedulable slots reservable
                   10779:                     in the future.
                   10780: 
                   10781:     Keys in inner hash are:
                   10782:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  10783:     (b) startreserve: start date of reservation period.
                   10784:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10785:         selected.
1.1040    raeburn  10786: 
                   10787: =back
                   10788: 
                   10789: =cut
                   10790: 
                   10791: sub get_future_slots {
                   10792:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  10793:     my $map;
                   10794:     if ($symb) {
                   10795:         ($map) = &Apache::lonnet::decode_symb($symb);
                   10796:     }
1.1040    raeburn  10797:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10798:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10799:     foreach my $slot (keys(%slots)) {
                   10800:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10801:         if ($symb) {
1.1229    raeburn  10802:             if ($slots{$slot}->{'symb'} ne '') {
                   10803:                 my $canuse;
                   10804:                 my %oksymbs;
                   10805:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   10806:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   10807:                 if ($oksymbs{$symb}) {
                   10808:                     $canuse = 1;
                   10809:                 } else {
                   10810:                     foreach my $item (@slotsymbs) {
                   10811:                         if ($item =~ /\.(page|sequence)$/) {
                   10812:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   10813:                             if (($map ne '') && ($map eq $sloturl)) {
                   10814:                                 $canuse = 1;
                   10815:                                 last;
                   10816:                             }
                   10817:                         }
                   10818:                     }
                   10819:                 }
                   10820:                 next unless ($canuse);
                   10821:             }
1.1040    raeburn  10822:         }
                   10823:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10824:             ($slots{$slot}->{'endtime'} > $now)) {
                   10825:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10826:                 my $userallowed = 0;
                   10827:                 if ($slots{$slot}->{'allowedsections'}) {
                   10828:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10829:                     if (!defined($env{'request.role.sec'})
                   10830:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10831:                         $userallowed=1;
                   10832:                     } else {
                   10833:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10834:                             $userallowed=1;
                   10835:                         }
                   10836:                     }
                   10837:                     unless ($userallowed) {
                   10838:                         if (defined($env{'request.course.groups'})) {
                   10839:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10840:                             foreach my $group (@groups) {
                   10841:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10842:                                     $userallowed=1;
                   10843:                                     last;
                   10844:                                 }
                   10845:                             }
                   10846:                         }
                   10847:                     }
                   10848:                 }
                   10849:                 if ($slots{$slot}->{'allowedusers'}) {
                   10850:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10851:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10852:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10853:                         $userallowed = 1;
                   10854:                     }
                   10855:                 }
                   10856:                 next unless($userallowed);
                   10857:             }
                   10858:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10859:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10860:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  10861:             my $uniqueperiod;
                   10862:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10863:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10864:             }
1.1040    raeburn  10865:             if (($startreserve < $now) &&
                   10866:                 (!$endreserve || $endreserve > $now)) {
                   10867:                 my $lastres = $endreserve;
                   10868:                 if (!$lastres) {
                   10869:                     $lastres = $slots{$slot}->{'starttime'};
                   10870:                 }
                   10871:                 $reservable_now{$slot} = {
                   10872:                                            symb       => $symb,
1.1250    raeburn  10873:                                            endreserve => $lastres,
                   10874:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  10875:                                          };
                   10876:             } elsif (($startreserve > $now) &&
                   10877:                      (!$endreserve || $endreserve > $startreserve)) {
                   10878:                 $future_reservable{$slot} = {
                   10879:                                               symb         => $symb,
1.1250    raeburn  10880:                                               startreserve => $startreserve,
                   10881:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10882:                                             };
                   10883:             }
                   10884:         }
                   10885:     }
                   10886:     my @unsorted_reservable = keys(%reservable_now);
                   10887:     if (@unsorted_reservable > 0) {
                   10888:         @sorted_reservable = 
                   10889:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10890:     }
                   10891:     my @unsorted_future = keys(%future_reservable);
                   10892:     if (@unsorted_future > 0) {
                   10893:         @sorted_future =
                   10894:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10895:     }
                   10896:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10897: }
1.780     raeburn  10898: 
                   10899: =pod
                   10900: 
1.1057    foxr     10901: =back
                   10902: 
1.549     albertel 10903: =head1 HTTP Helpers
                   10904: 
                   10905: =over 4
                   10906: 
1.648     raeburn  10907: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10908: 
1.258     albertel 10909: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10910: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10911: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10912: 
                   10913: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10914: $possible_names is an ref to an array of form element names.  As an example:
                   10915: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10916: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10917: 
                   10918: =cut
1.1       albertel 10919: 
1.6       albertel 10920: sub get_unprocessed_cgi {
1.25      albertel 10921:   my ($query,$possible_names)= @_;
1.26      matthew  10922:   # $Apache::lonxml::debug=1;
1.356     albertel 10923:   foreach my $pair (split(/&/,$query)) {
                   10924:     my ($name, $value) = split(/=/,$pair);
1.369     www      10925:     $name = &unescape($name);
1.25      albertel 10926:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10927:       $value =~ tr/+/ /;
                   10928:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10929:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10930:     }
1.16      harris41 10931:   }
1.6       albertel 10932: }
                   10933: 
1.112     bowersj2 10934: =pod
                   10935: 
1.648     raeburn  10936: =item * &cacheheader() 
1.112     bowersj2 10937: 
                   10938: returns cache-controlling header code
                   10939: 
                   10940: =cut
                   10941: 
1.7       albertel 10942: sub cacheheader {
1.258     albertel 10943:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10944:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10945:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10946:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10947:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10948:     return $output;
1.7       albertel 10949: }
                   10950: 
1.112     bowersj2 10951: =pod
                   10952: 
1.648     raeburn  10953: =item * &no_cache($r) 
1.112     bowersj2 10954: 
                   10955: specifies header code to not have cache
                   10956: 
                   10957: =cut
                   10958: 
1.9       albertel 10959: sub no_cache {
1.216     albertel 10960:     my ($r) = @_;
                   10961:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10962: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10963:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10964:     $r->no_cache(1);
                   10965:     $r->header_out("Expires" => $date);
                   10966:     $r->header_out("Pragma" => "no-cache");
1.123     www      10967: }
                   10968: 
                   10969: sub content_type {
1.181     albertel 10970:     my ($r,$type,$charset) = @_;
1.299     foxr     10971:     if ($r) {
                   10972: 	#  Note that printout.pl calls this with undef for $r.
                   10973: 	&no_cache($r);
                   10974:     }
1.258     albertel 10975:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10976:     unless ($charset) {
                   10977: 	$charset=&Apache::lonlocal::current_encoding;
                   10978:     }
                   10979:     if ($charset) { $type.='; charset='.$charset; }
                   10980:     if ($r) {
                   10981: 	$r->content_type($type);
                   10982:     } else {
                   10983: 	print("Content-type: $type\n\n");
                   10984:     }
1.9       albertel 10985: }
1.25      albertel 10986: 
1.112     bowersj2 10987: =pod
                   10988: 
1.648     raeburn  10989: =item * &add_to_env($name,$value) 
1.112     bowersj2 10990: 
1.258     albertel 10991: adds $name to the %env hash with value
1.112     bowersj2 10992: $value, if $name already exists, the entry is converted to an array
                   10993: reference and $value is added to the array.
                   10994: 
                   10995: =cut
                   10996: 
1.25      albertel 10997: sub add_to_env {
                   10998:   my ($name,$value)=@_;
1.258     albertel 10999:   if (defined($env{$name})) {
                   11000:     if (ref($env{$name})) {
1.25      albertel 11001:       #already have multiple values
1.258     albertel 11002:       push(@{ $env{$name} },$value);
1.25      albertel 11003:     } else {
                   11004:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11005:       my $first=$env{$name};
                   11006:       undef($env{$name});
                   11007:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11008:     }
                   11009:   } else {
1.258     albertel 11010:     $env{$name}=$value;
1.25      albertel 11011:   }
1.31      albertel 11012: }
1.149     albertel 11013: 
                   11014: =pod
                   11015: 
1.648     raeburn  11016: =item * &get_env_multiple($name) 
1.149     albertel 11017: 
1.258     albertel 11018: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11019: values may be defined and end up as an array ref.
                   11020: 
                   11021: returns an array of values
                   11022: 
                   11023: =cut
                   11024: 
                   11025: sub get_env_multiple {
                   11026:     my ($name) = @_;
                   11027:     my @values;
1.258     albertel 11028:     if (defined($env{$name})) {
1.149     albertel 11029:         # exists is it an array
1.258     albertel 11030:         if (ref($env{$name})) {
                   11031:             @values=@{ $env{$name} };
1.149     albertel 11032:         } else {
1.258     albertel 11033:             $values[0]=$env{$name};
1.149     albertel 11034:         }
                   11035:     }
                   11036:     return(@values);
                   11037: }
                   11038: 
1.1249    damieng  11039: # Looks at given dependencies, and returns something depending on the context.
                   11040: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11041: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11042: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11043: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11044: # $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.
                   11045: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11046: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11047: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11048: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11049: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11050: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11051: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11052: # @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)
                   11053: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11054: sub ask_for_embedded_content {
1.1249    damieng  11055:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11056:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11057:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11058:         %currsubfile,%unused,$rem);
1.1071    raeburn  11059:     my $counter = 0;
                   11060:     my $numnew = 0;
1.987     raeburn  11061:     my $numremref = 0;
                   11062:     my $numinvalid = 0;
                   11063:     my $numpathchg = 0;
                   11064:     my $numexisting = 0;
1.1071    raeburn  11065:     my $numunused = 0;
                   11066:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11067:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11068:     my $heading = &mt('Upload embedded files');
                   11069:     my $buttontext = &mt('Upload');
                   11070: 
1.1249    damieng  11071:     # fills these variables based on the context:
                   11072:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11073:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11074:     if ($env{'request.course.id'}) {
1.1123    raeburn  11075:         if ($actionurl eq '/adm/dependencies') {
                   11076:             $navmap = Apache::lonnavmaps::navmap->new();
                   11077:         }
                   11078:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11079:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11080:     }
1.1123    raeburn  11081:     if (($actionurl eq '/adm/portfolio') || 
                   11082:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11083:         my $current_path='/';
                   11084:         if ($env{'form.currentpath'}) {
                   11085:             $current_path = $env{'form.currentpath'};
                   11086:         }
                   11087:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  11088:             $udom = $cdom;
                   11089:             $uname = $cnum;
1.984     raeburn  11090:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11091:         } else {
                   11092:             $udom = $env{'user.domain'};
                   11093:             $uname = $env{'user.name'};
                   11094:             $url = '/userfiles/portfolio';
                   11095:         }
1.987     raeburn  11096:         $toplevel = $url.'/';
1.984     raeburn  11097:         $url .= $current_path;
                   11098:         $getpropath = 1;
1.987     raeburn  11099:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11100:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11101:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11102:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11103:         $toplevel = $url;
1.984     raeburn  11104:         if ($rest ne '') {
1.987     raeburn  11105:             $url .= $rest;
                   11106:         }
                   11107:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11108:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11109:             $url = $args->{'docs_url'};
                   11110:             $toplevel = $url;
1.1084    raeburn  11111:             if ($args->{'context'} eq 'paste') {
                   11112:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11113:                 ($path) = 
                   11114:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11115:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11116:                 $fileloc =~ s{^/}{};
                   11117:             }
1.1071    raeburn  11118:         }
1.1084    raeburn  11119:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  11120:         if ($env{'request.course.id'} ne '') {
                   11121:             if (ref($args) eq 'HASH') {
                   11122:                 $url = $args->{'docs_url'};
                   11123:                 $title = $args->{'docs_title'};
1.1126    raeburn  11124:                 $toplevel = $url; 
                   11125:                 unless ($toplevel =~ m{^/}) {
                   11126:                     $toplevel = "/$url";
                   11127:                 }
1.1085    raeburn  11128:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  11129:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11130:                     $path = $1;
                   11131:                 } else {
                   11132:                     ($path) =
                   11133:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11134:                 }
1.1195    raeburn  11135:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11136:                     $fileloc = $toplevel;
                   11137:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11138:                     my ($udom,$uname,$fname) =
                   11139:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11140:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11141:                 } else {
                   11142:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11143:                 }
1.1071    raeburn  11144:                 $fileloc =~ s{^/}{};
                   11145:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11146:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11147:             }
1.987     raeburn  11148:         }
1.1123    raeburn  11149:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11150:         $udom = $cdom;
                   11151:         $uname = $cnum;
                   11152:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11153:         $toplevel = $url;
                   11154:         $path = $url;
                   11155:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11156:         $fileloc =~ s{^/}{};
1.987     raeburn  11157:     }
1.1249    damieng  11158:     
                   11159:     # parses the dependency paths to get some info
                   11160:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   11161:     # $newfiles: hash URL -> 1 for new files or external URLs
                   11162:     # (will be completed later)
                   11163:     # $mapping:
                   11164:     #   for external URLs: external URL -> external URL
                   11165:     #   for relative paths: clean path -> original path
                   11166:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   11167:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  11168:     foreach my $file (keys(%{$allfiles})) {
                   11169:         my $embed_file;
                   11170:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11171:             $embed_file = $1;
                   11172:         } else {
                   11173:             $embed_file = $file;
                   11174:         }
1.1158    raeburn  11175:         my ($absolutepath,$cleaned_file);
                   11176:         if ($embed_file =~ m{^\w+://}) {
                   11177:             $cleaned_file = $embed_file;
1.1147    raeburn  11178:             $newfiles{$cleaned_file} = 1;
                   11179:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11180:         } else {
1.1158    raeburn  11181:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11182:             if ($embed_file =~ m{^/}) {
                   11183:                 $absolutepath = $embed_file;
                   11184:             }
1.1147    raeburn  11185:             if ($cleaned_file =~ m{/}) {
                   11186:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11187:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11188:                 my $item = $fname;
                   11189:                 if ($path ne '') {
                   11190:                     $item = $path.'/'.$fname;
                   11191:                     $subdependencies{$path}{$fname} = 1;
                   11192:                 } else {
                   11193:                     $dependencies{$item} = 1;
                   11194:                 }
                   11195:                 if ($absolutepath) {
                   11196:                     $mapping{$item} = $absolutepath;
                   11197:                 } else {
                   11198:                     $mapping{$item} = $embed_file;
                   11199:                 }
                   11200:             } else {
                   11201:                 $dependencies{$embed_file} = 1;
                   11202:                 if ($absolutepath) {
1.1147    raeburn  11203:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11204:                 } else {
1.1147    raeburn  11205:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11206:                 }
                   11207:             }
1.984     raeburn  11208:         }
                   11209:     }
1.1249    damieng  11210:     
                   11211:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   11212:     # and lists
                   11213:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   11214:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   11215:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   11216:     #                                    the path had to be cleaned up
                   11217:     # $existing: hash clean path -> 1 if the file exists
                   11218:     # $numexisting: number of keys in $existing
                   11219:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   11220:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   11221:     #                                      dependency subdirectories that are
                   11222:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  11223:     my $dirptr = 16384;
1.984     raeburn  11224:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11225:         $currsubfile{$path} = {};
1.1123    raeburn  11226:         if (($actionurl eq '/adm/portfolio') || 
                   11227:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11228:             my ($sublistref,$listerror) =
                   11229:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11230:             if (ref($sublistref) eq 'ARRAY') {
                   11231:                 foreach my $line (@{$sublistref}) {
                   11232:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11233:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11234:                 }
1.984     raeburn  11235:             }
1.987     raeburn  11236:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11237:             if (opendir(my $dir,$url.'/'.$path)) {
                   11238:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11239:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11240:             }
1.1084    raeburn  11241:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11242:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11243:                   ($args->{'context'} eq 'paste')) ||
                   11244:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11245:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  11246:                 my $dir;
                   11247:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11248:                     $dir = $fileloc;
                   11249:                 } else {
                   11250:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11251:                 }
1.1071    raeburn  11252:                 if ($dir ne '') {
                   11253:                     my ($sublistref,$listerror) =
                   11254:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11255:                     if (ref($sublistref) eq 'ARRAY') {
                   11256:                         foreach my $line (@{$sublistref}) {
                   11257:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11258:                                 undef,$mtime)=split(/\&/,$line,12);
                   11259:                             unless (($testdir&$dirptr) ||
                   11260:                                     ($file_name =~ /^\.\.?$/)) {
                   11261:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11262:                             }
                   11263:                         }
                   11264:                     }
                   11265:                 }
1.984     raeburn  11266:             }
                   11267:         }
                   11268:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11269:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11270:                 my $item = $path.'/'.$file;
                   11271:                 unless ($mapping{$item} eq $item) {
                   11272:                     $pathchanges{$item} = 1;
                   11273:                 }
                   11274:                 $existing{$item} = 1;
                   11275:                 $numexisting ++;
                   11276:             } else {
                   11277:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11278:             }
                   11279:         }
1.1071    raeburn  11280:         if ($actionurl eq '/adm/dependencies') {
                   11281:             foreach my $path (keys(%currsubfile)) {
                   11282:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11283:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11284:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  11285:                              next if (($rem ne '') &&
                   11286:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11287:                                        (ref($navmap) &&
                   11288:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11289:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11290:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11291:                              $unused{$path.'/'.$file} = 1; 
                   11292:                          }
                   11293:                     }
                   11294:                 }
                   11295:             }
                   11296:         }
1.984     raeburn  11297:     }
1.1249    damieng  11298:     
                   11299:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   11300:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  11301:     my %currfile;
1.1123    raeburn  11302:     if (($actionurl eq '/adm/portfolio') ||
                   11303:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11304:         my ($dirlistref,$listerror) =
                   11305:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11306:         if (ref($dirlistref) eq 'ARRAY') {
                   11307:             foreach my $line (@{$dirlistref}) {
                   11308:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11309:                 $currfile{$file_name} = 1;
                   11310:             }
1.984     raeburn  11311:         }
1.987     raeburn  11312:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11313:         if (opendir(my $dir,$url)) {
1.987     raeburn  11314:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11315:             map {$currfile{$_} = 1;} @dir_list;
                   11316:         }
1.1084    raeburn  11317:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11318:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  11319:               ($args->{'context'} eq 'paste')) ||
                   11320:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11321:         if ($env{'request.course.id'} ne '') {
                   11322:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11323:             if ($dir ne '') {
                   11324:                 my ($dirlistref,$listerror) =
                   11325:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11326:                 if (ref($dirlistref) eq 'ARRAY') {
                   11327:                     foreach my $line (@{$dirlistref}) {
                   11328:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11329:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11330:                         unless (($testdir&$dirptr) ||
                   11331:                                 ($file_name =~ /^\.\.?$/)) {
                   11332:                             $currfile{$file_name} = [$size,$mtime];
                   11333:                         }
                   11334:                     }
                   11335:                 }
                   11336:             }
                   11337:         }
1.984     raeburn  11338:     }
1.1249    damieng  11339:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   11340:     # are not in subdirectories, using $currfile
1.984     raeburn  11341:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11342:         if (exists($currfile{$file})) {
1.987     raeburn  11343:             unless ($mapping{$file} eq $file) {
                   11344:                 $pathchanges{$file} = 1;
                   11345:             }
                   11346:             $existing{$file} = 1;
                   11347:             $numexisting ++;
                   11348:         } else {
1.984     raeburn  11349:             $newfiles{$file} = 1;
                   11350:         }
                   11351:     }
1.1071    raeburn  11352:     foreach my $file (keys(%currfile)) {
                   11353:         unless (($file eq $filename) ||
                   11354:                 ($file eq $filename.'.bak') ||
                   11355:                 ($dependencies{$file})) {
1.1085    raeburn  11356:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  11357:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11358:                     next if (($rem ne '') &&
                   11359:                              (($env{"httpref.$rem".$file} ne '') ||
                   11360:                               (ref($navmap) &&
                   11361:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11362:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11363:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11364:                 }
1.1085    raeburn  11365:             }
1.1071    raeburn  11366:             $unused{$file} = 1;
                   11367:         }
                   11368:     }
1.1249    damieng  11369:     
                   11370:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  11371:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11372:         ($args->{'context'} eq 'paste')) {
                   11373:         $counter = scalar(keys(%existing));
                   11374:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  11375:         return ($output,$counter,$numpathchg,\%existing);
                   11376:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   11377:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11378:         $counter = scalar(keys(%existing));
                   11379:         $numpathchg = scalar(keys(%pathchanges));
                   11380:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  11381:     }
1.1249    damieng  11382:     
                   11383:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   11384:     
                   11385:     # $upload_output: missing dependencies (with upload form)
                   11386:     # $modify_output: uploaded dependencies (in use)
                   11387:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  11388:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11389:         if ($actionurl eq '/adm/dependencies') {
                   11390:             next if ($embed_file =~ m{^\w+://});
                   11391:         }
1.660     raeburn  11392:         $upload_output .= &start_data_table_row().
1.1123    raeburn  11393:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11394:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11395:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  11396:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11397:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11398:         }
1.1123    raeburn  11399:         $upload_output .= '</td>';
1.1071    raeburn  11400:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  11401:             $upload_output.='<td align="right">'.
                   11402:                             '<span class="LC_info LC_fontsize_medium">'.
                   11403:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11404:             $numremref++;
1.660     raeburn  11405:         } elsif ($args->{'error_on_invalid_names'}
                   11406:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  11407:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11408:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11409:             $numinvalid++;
1.660     raeburn  11410:         } else {
1.1123    raeburn  11411:             $upload_output .= '<td>'.
                   11412:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11413:                                                      $embed_file,\%mapping,
1.1071    raeburn  11414:                                                      $allfiles,$codebase,'upload');
                   11415:             $counter ++;
                   11416:             $numnew ++;
1.987     raeburn  11417:         }
                   11418:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11419:     }
                   11420:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11421:         if ($actionurl eq '/adm/dependencies') {
                   11422:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11423:             $modify_output .= &start_data_table_row().
                   11424:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11425:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11426:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11427:                               '<td>'.$size.'</td>'.
                   11428:                               '<td>'.$mtime.'</td>'.
                   11429:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11430:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11431:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11432:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11433:                               &embedded_file_element('upload_embedded',$counter,
                   11434:                                                      $embed_file,\%mapping,
                   11435:                                                      $allfiles,$codebase,'modify').
                   11436:                               '</div></td>'.
                   11437:                               &end_data_table_row()."\n";
                   11438:             $counter ++;
                   11439:         } else {
                   11440:             $upload_output .= &start_data_table_row().
1.1123    raeburn  11441:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11442:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11443:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11444:                               &Apache::loncommon::end_data_table_row()."\n";
                   11445:         }
                   11446:     }
                   11447:     my $delidx = $counter;
                   11448:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11449:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11450:         $delete_output .= &start_data_table_row().
                   11451:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11452:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11453:                           '<td>'.$size.'</td>'.
                   11454:                           '<td>'.$mtime.'</td>'.
                   11455:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11456:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11457:                           &embedded_file_element('upload_embedded',$delidx,
                   11458:                                                  $oldfile,\%mapping,$allfiles,
                   11459:                                                  $codebase,'delete').'</td>'.
                   11460:                           &end_data_table_row()."\n"; 
                   11461:         $numunused ++;
                   11462:         $delidx ++;
1.987     raeburn  11463:     }
                   11464:     if ($upload_output) {
                   11465:         $upload_output = &start_data_table().
                   11466:                          $upload_output.
                   11467:                          &end_data_table()."\n";
                   11468:     }
1.1071    raeburn  11469:     if ($modify_output) {
                   11470:         $modify_output = &start_data_table().
                   11471:                          &start_data_table_header_row().
                   11472:                          '<th>'.&mt('File').'</th>'.
                   11473:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11474:                          '<th>'.&mt('Modified').'</th>'.
                   11475:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11476:                          &end_data_table_header_row().
                   11477:                          $modify_output.
                   11478:                          &end_data_table()."\n";
                   11479:     }
                   11480:     if ($delete_output) {
                   11481:         $delete_output = &start_data_table().
                   11482:                          &start_data_table_header_row().
                   11483:                          '<th>'.&mt('File').'</th>'.
                   11484:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11485:                          '<th>'.&mt('Modified').'</th>'.
                   11486:                          '<th>'.&mt('Delete?').'</th>'.
                   11487:                          &end_data_table_header_row().
                   11488:                          $delete_output.
                   11489:                          &end_data_table()."\n";
                   11490:     }
1.987     raeburn  11491:     my $applies = 0;
                   11492:     if ($numremref) {
                   11493:         $applies ++;
                   11494:     }
                   11495:     if ($numinvalid) {
                   11496:         $applies ++;
                   11497:     }
                   11498:     if ($numexisting) {
                   11499:         $applies ++;
                   11500:     }
1.1071    raeburn  11501:     if ($counter || $numunused) {
1.987     raeburn  11502:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11503:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11504:                   $state.'<h3>'.$heading.'</h3>'; 
                   11505:         if ($actionurl eq '/adm/dependencies') {
                   11506:             if ($numnew) {
                   11507:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11508:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11509:                            $upload_output.'<br />'."\n";
                   11510:             }
                   11511:             if ($numexisting) {
                   11512:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11513:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11514:                            $modify_output.'<br />'."\n";
                   11515:                            $buttontext = &mt('Save changes');
                   11516:             }
                   11517:             if ($numunused) {
                   11518:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11519:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11520:                            $delete_output.'<br />'."\n";
                   11521:                            $buttontext = &mt('Save changes');
                   11522:             }
                   11523:         } else {
                   11524:             $output .= $upload_output.'<br />'."\n";
                   11525:         }
                   11526:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11527:                    $counter.'" />'."\n";
                   11528:         if ($actionurl eq '/adm/dependencies') { 
                   11529:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11530:                        $numnew.'" />'."\n";
                   11531:         } elsif ($actionurl eq '') {
1.987     raeburn  11532:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11533:         }
                   11534:     } elsif ($applies) {
                   11535:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11536:         if ($applies > 1) {
                   11537:             $output .=  
1.1123    raeburn  11538:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11539:             if ($numremref) {
                   11540:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11541:             }
                   11542:             if ($numinvalid) {
                   11543:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11544:             }
                   11545:             if ($numexisting) {
                   11546:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11547:             }
                   11548:             $output .= '</ul><br />';
                   11549:         } elsif ($numremref) {
                   11550:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11551:         } elsif ($numinvalid) {
                   11552:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11553:         } elsif ($numexisting) {
                   11554:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11555:         }
                   11556:         $output .= $upload_output.'<br />';
                   11557:     }
                   11558:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11559:     $chgcount = $counter;
1.987     raeburn  11560:     if (keys(%pathchanges) > 0) {
                   11561:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11562:             if ($counter) {
1.987     raeburn  11563:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11564:                                                   $embed_file,\%mapping,
1.1071    raeburn  11565:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11566:             } else {
                   11567:                 $pathchange_output .= 
                   11568:                     &start_data_table_row().
                   11569:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11570:                     $chgcount.'" checked="checked" /></td>'.
                   11571:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11572:                     '<td>'.$embed_file.
                   11573:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11574:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11575:                     '</td>'.&end_data_table_row();
1.660     raeburn  11576:             }
1.987     raeburn  11577:             $numpathchg ++;
                   11578:             $chgcount ++;
1.660     raeburn  11579:         }
                   11580:     }
1.1127    raeburn  11581:     if (($counter) || ($numunused)) {
1.987     raeburn  11582:         if ($numpathchg) {
                   11583:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11584:                        $numpathchg.'" />'."\n";
                   11585:         }
                   11586:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11587:             ($actionurl eq '/adm/imsimport')) {
                   11588:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11589:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11590:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11591:         } elsif ($actionurl eq '/adm/dependencies') {
                   11592:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11593:         }
1.1123    raeburn  11594:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11595:     } elsif ($numpathchg) {
                   11596:         my %pathchange = ();
                   11597:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11598:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11599:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  11600:         }
1.987     raeburn  11601:     }
1.1071    raeburn  11602:     return ($output,$counter,$numpathchg);
1.987     raeburn  11603: }
                   11604: 
1.1147    raeburn  11605: =pod
                   11606: 
                   11607: =item * clean_path($name)
                   11608: 
                   11609: Performs clean-up of directories, subdirectories and filename in an
                   11610: embedded object, referenced in an HTML file which is being uploaded
                   11611: to a course or portfolio, where 
                   11612: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11613: checked.
                   11614: 
                   11615: Clean-up is similar to replacements in lonnet::clean_filename()
                   11616: except each / between sub-directory and next level is preserved.
                   11617: 
                   11618: =cut
                   11619: 
                   11620: sub clean_path {
                   11621:     my ($embed_file) = @_;
                   11622:     $embed_file =~s{^/+}{};
                   11623:     my @contents;
                   11624:     if ($embed_file =~ m{/}) {
                   11625:         @contents = split(/\//,$embed_file);
                   11626:     } else {
                   11627:         @contents = ($embed_file);
                   11628:     }
                   11629:     my $lastidx = scalar(@contents)-1;
                   11630:     for (my $i=0; $i<=$lastidx; $i++) { 
                   11631:         $contents[$i]=~s{\\}{/}g;
                   11632:         $contents[$i]=~s/\s+/\_/g;
                   11633:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11634:         if ($i == $lastidx) {
                   11635:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11636:         }
                   11637:     }
                   11638:     if ($lastidx > 0) {
                   11639:         return join('/',@contents);
                   11640:     } else {
                   11641:         return $contents[0];
                   11642:     }
                   11643: }
                   11644: 
1.987     raeburn  11645: sub embedded_file_element {
1.1071    raeburn  11646:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11647:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11648:                    (ref($codebase) eq 'HASH'));
                   11649:     my $output;
1.1071    raeburn  11650:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11651:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11652:     }
                   11653:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11654:                &escape($embed_file).'" />';
                   11655:     unless (($context eq 'upload_embedded') && 
                   11656:             ($mapping->{$embed_file} eq $embed_file)) {
                   11657:         $output .='
                   11658:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11659:     }
                   11660:     my $attrib;
                   11661:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11662:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11663:     }
                   11664:     $output .=
                   11665:         "\n\t\t".
                   11666:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11667:         $attrib.'" />';
                   11668:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11669:         $output .=
                   11670:             "\n\t\t".
                   11671:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11672:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11673:     }
1.987     raeburn  11674:     return $output;
1.660     raeburn  11675: }
                   11676: 
1.1071    raeburn  11677: sub get_dependency_details {
                   11678:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11679:     my ($size,$mtime,$showsize,$showmtime);
                   11680:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11681:         if ($embed_file =~ m{/}) {
                   11682:             my ($path,$fname) = split(/\//,$embed_file);
                   11683:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11684:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11685:             }
                   11686:         } else {
                   11687:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11688:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11689:             }
                   11690:         }
                   11691:         $showsize = $size/1024.0;
                   11692:         $showsize = sprintf("%.1f",$showsize);
                   11693:         if ($mtime > 0) {
                   11694:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11695:         }
                   11696:     }
                   11697:     return ($showsize,$showmtime);
                   11698: }
                   11699: 
                   11700: sub ask_embedded_js {
                   11701:     return <<"END";
                   11702: <script type="text/javascript"">
                   11703: // <![CDATA[
                   11704: function toggleBrowse(counter) {
                   11705:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11706:     var fileid = document.getElementById('embedded_item_'+counter);
                   11707:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11708:     if (chkboxid.checked == true) {
                   11709:         uploaddivid.style.display='block';
                   11710:     } else {
                   11711:         uploaddivid.style.display='none';
                   11712:         fileid.value = '';
                   11713:     }
                   11714: }
                   11715: // ]]>
                   11716: </script>
                   11717: 
                   11718: END
                   11719: }
                   11720: 
1.661     raeburn  11721: sub upload_embedded {
                   11722:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11723:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11724:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11725:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11726:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11727:         my $orig_uploaded_filename =
                   11728:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11729:         foreach my $type ('orig','ref','attrib','codebase') {
                   11730:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11731:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11732:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11733:             }
                   11734:         }
1.661     raeburn  11735:         my ($path,$fname) =
                   11736:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11737:         # no path, whole string is fname
                   11738:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11739:         $fname = &Apache::lonnet::clean_filename($fname);
                   11740:         # See if there is anything left
                   11741:         next if ($fname eq '');
                   11742: 
                   11743:         # Check if file already exists as a file or directory.
                   11744:         my ($state,$msg);
                   11745:         if ($context eq 'portfolio') {
                   11746:             my $port_path = $dirpath;
                   11747:             if ($group ne '') {
                   11748:                 $port_path = "groups/$group/$port_path";
                   11749:             }
1.987     raeburn  11750:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11751:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11752:                                               $dir_root,$port_path,$disk_quota,
                   11753:                                               $current_disk_usage,$uname,$udom);
                   11754:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11755:                 || $state eq 'file_locked') {
1.661     raeburn  11756:                 $output .= $msg;
                   11757:                 next;
                   11758:             }
                   11759:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11760:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11761:             if ($state eq 'exists') {
                   11762:                 $output .= $msg;
                   11763:                 next;
                   11764:             }
                   11765:         }
                   11766:         # Check if extension is valid
                   11767:         if (($fname =~ /\.(\w+)$/) &&
                   11768:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   11769:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11770:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11771:             next;
                   11772:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11773:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11774:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11775:             next;
                   11776:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   11777:             $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  11778:             next;
                   11779:         }
                   11780:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  11781:         my $subdir = $path;
                   11782:         $subdir =~ s{/+$}{};
1.661     raeburn  11783:         if ($context eq 'portfolio') {
1.984     raeburn  11784:             my $result;
                   11785:             if ($state eq 'existingfile') {
                   11786:                 $result=
                   11787:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  11788:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11789:             } else {
1.984     raeburn  11790:                 $result=
                   11791:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11792:                                                     $dirpath.
1.1123    raeburn  11793:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11794:                 if ($result !~ m|^/uploaded/|) {
                   11795:                     $output .= '<span class="LC_error">'
                   11796:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11797:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11798:                                .'</span><br />';
                   11799:                     next;
                   11800:                 } else {
1.987     raeburn  11801:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11802:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11803:                 }
1.661     raeburn  11804:             }
1.1123    raeburn  11805:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  11806:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11807:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11808:             my $result =
1.1126    raeburn  11809:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11810:             if ($result !~ m|^/uploaded/|) {
                   11811:                 $output .= '<span class="LC_error">'
                   11812:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11813:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11814:                            .'</span><br />';
                   11815:                     next;
                   11816:             } else {
                   11817:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11818:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11819:                 if ($context eq 'syllabus') {
                   11820:                     &Apache::lonnet::make_public_indefinitely($result);
                   11821:                 }
1.987     raeburn  11822:             }
1.661     raeburn  11823:         } else {
                   11824: # Save the file
                   11825:             my $target = $env{'form.embedded_item_'.$i};
                   11826:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11827:             my $dest = $fullpath.$fname;
                   11828:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11829:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11830:             my $count;
                   11831:             my $filepath = $dir_root;
1.1027    raeburn  11832:             foreach my $subdir (@parts) {
                   11833:                 $filepath .= "/$subdir";
                   11834:                 if (!-e $filepath) {
1.661     raeburn  11835:                     mkdir($filepath,0770);
                   11836:                 }
                   11837:             }
                   11838:             my $fh;
                   11839:             if (!open($fh,'>'.$dest)) {
                   11840:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11841:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11842:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11843:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11844:                            '</span><br />';
                   11845:             } else {
                   11846:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11847:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11848:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11849:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11850:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11851:                               '</span><br />';
                   11852:                 } else {
1.987     raeburn  11853:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11854:                                $url.'</span>').'<br />';
                   11855:                     unless ($context eq 'testbank') {
                   11856:                         $footer .= &mt('View embedded file: [_1]',
                   11857:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11858:                     }
                   11859:                 }
                   11860:                 close($fh);
                   11861:             }
                   11862:         }
                   11863:         if ($env{'form.embedded_ref_'.$i}) {
                   11864:             $pathchange{$i} = 1;
                   11865:         }
                   11866:     }
                   11867:     if ($output) {
                   11868:         $output = '<p>'.$output.'</p>';
                   11869:     }
                   11870:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11871:     $returnflag = 'ok';
1.1071    raeburn  11872:     my $numpathchgs = scalar(keys(%pathchange));
                   11873:     if ($numpathchgs > 0) {
1.987     raeburn  11874:         if ($context eq 'portfolio') {
                   11875:             $output .= '<p>'.&mt('or').'</p>';
                   11876:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11877:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11878:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11879:             $returnflag = 'modify_orightml';
                   11880:         }
                   11881:     }
1.1071    raeburn  11882:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11883: }
                   11884: 
                   11885: sub modify_html_form {
                   11886:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11887:     my $end = 0;
                   11888:     my $modifyform;
                   11889:     if ($context eq 'upload_embedded') {
                   11890:         return unless (ref($pathchange) eq 'HASH');
                   11891:         if ($env{'form.number_embedded_items'}) {
                   11892:             $end += $env{'form.number_embedded_items'};
                   11893:         }
                   11894:         if ($env{'form.number_pathchange_items'}) {
                   11895:             $end += $env{'form.number_pathchange_items'};
                   11896:         }
                   11897:         if ($end) {
                   11898:             for (my $i=0; $i<$end; $i++) {
                   11899:                 if ($i < $env{'form.number_embedded_items'}) {
                   11900:                     next unless($pathchange->{$i});
                   11901:                 }
                   11902:                 $modifyform .=
                   11903:                     &start_data_table_row().
                   11904:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11905:                     'checked="checked" /></td>'.
                   11906:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11907:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11908:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11909:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11910:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11911:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11912:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11913:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11914:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11915:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11916:                     &end_data_table_row();
1.1071    raeburn  11917:             }
1.987     raeburn  11918:         }
                   11919:     } else {
                   11920:         $modifyform = $pathchgtable;
                   11921:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11922:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11923:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11924:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11925:         }
                   11926:     }
                   11927:     if ($modifyform) {
1.1071    raeburn  11928:         if ($actionurl eq '/adm/dependencies') {
                   11929:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11930:         }
1.987     raeburn  11931:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11932:                '<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".
                   11933:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11934:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11935:                '</ol></p>'."\n".'<p>'.
                   11936:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11937:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11938:                &start_data_table()."\n".
                   11939:                &start_data_table_header_row().
                   11940:                '<th>'.&mt('Change?').'</th>'.
                   11941:                '<th>'.&mt('Current reference').'</th>'.
                   11942:                '<th>'.&mt('Required reference').'</th>'.
                   11943:                &end_data_table_header_row()."\n".
                   11944:                $modifyform.
                   11945:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11946:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11947:                '</form>'."\n";
                   11948:     }
                   11949:     return;
                   11950: }
                   11951: 
                   11952: sub modify_html_refs {
1.1123    raeburn  11953:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11954:     my $container;
                   11955:     if ($context eq 'portfolio') {
                   11956:         $container = $env{'form.container'};
                   11957:     } elsif ($context eq 'coursedoc') {
                   11958:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11959:     } elsif ($context eq 'manage_dependencies') {
                   11960:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11961:         $container = "/$container";
1.1123    raeburn  11962:     } elsif ($context eq 'syllabus') {
                   11963:         $container = $url;
1.987     raeburn  11964:     } else {
1.1027    raeburn  11965:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11966:     }
                   11967:     my (%allfiles,%codebase,$output,$content);
                   11968:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11969:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11970:         if (wantarray) {
                   11971:             return ('',0,0); 
                   11972:         } else {
                   11973:             return;
                   11974:         }
                   11975:     }
                   11976:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11977:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11978:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11979:             if (wantarray) {
                   11980:                 return ('',0,0);
                   11981:             } else {
                   11982:                 return;
                   11983:             }
                   11984:         } 
1.987     raeburn  11985:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11986:         if ($content eq '-1') {
                   11987:             if (wantarray) {
                   11988:                 return ('',0,0);
                   11989:             } else {
                   11990:                 return;
                   11991:             }
                   11992:         }
1.987     raeburn  11993:     } else {
1.1071    raeburn  11994:         unless ($container =~ /^\Q$dir_root\E/) {
                   11995:             if (wantarray) {
                   11996:                 return ('',0,0);
                   11997:             } else {
                   11998:                 return;
                   11999:             }
                   12000:         } 
1.987     raeburn  12001:         if (open(my $fh,"<$container")) {
                   12002:             $content = join('', <$fh>);
                   12003:             close($fh);
                   12004:         } else {
1.1071    raeburn  12005:             if (wantarray) {
                   12006:                 return ('',0,0);
                   12007:             } else {
                   12008:                 return;
                   12009:             }
1.987     raeburn  12010:         }
                   12011:     }
                   12012:     my ($count,$codebasecount) = (0,0);
                   12013:     my $mm = new File::MMagic;
                   12014:     my $mime_type = $mm->checktype_contents($content);
                   12015:     if ($mime_type eq 'text/html') {
                   12016:         my $parse_result = 
                   12017:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12018:                                                     \%codebase,\$content);
                   12019:         if ($parse_result eq 'ok') {
                   12020:             foreach my $i (@changes) {
                   12021:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12022:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12023:                 if ($allfiles{$ref}) {
                   12024:                     my $newname =  $orig;
                   12025:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12026:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12027:                     if ($attrib_regexp =~ /:/) {
                   12028:                         $attrib_regexp =~ s/\:/|/g;
                   12029:                     }
                   12030:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12031:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12032:                         $count += $numchg;
1.1123    raeburn  12033:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12034:                         delete($allfiles{$ref});
1.987     raeburn  12035:                     }
                   12036:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12037:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12038:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12039:                         $codebasecount ++;
                   12040:                     }
                   12041:                 }
                   12042:             }
1.1123    raeburn  12043:             my $skiprewrites;
1.987     raeburn  12044:             if ($count || $codebasecount) {
                   12045:                 my $saveresult;
1.1071    raeburn  12046:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12047:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12048:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12049:                     if ($url eq $container) {
                   12050:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12051:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12052:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12053:                                             $fname.'</span>').'</p>';
1.987     raeburn  12054:                     } else {
                   12055:                          $output = '<p class="LC_error">'.
                   12056:                                    &mt('Error: update failed for: [_1].',
                   12057:                                    '<span class="LC_filename">'.
                   12058:                                    $container.'</span>').'</p>';
                   12059:                     }
1.1123    raeburn  12060:                     if ($context eq 'syllabus') {
                   12061:                         unless ($saveresult eq 'ok') {
                   12062:                             $skiprewrites = 1;
                   12063:                         }
                   12064:                     }
1.987     raeburn  12065:                 } else {
                   12066:                     if (open(my $fh,">$container")) {
                   12067:                         print $fh $content;
                   12068:                         close($fh);
                   12069:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12070:                                   $count,'<span class="LC_filename">'.
                   12071:                                   $container.'</span>').'</p>';
1.661     raeburn  12072:                     } else {
1.987     raeburn  12073:                          $output = '<p class="LC_error">'.
                   12074:                                    &mt('Error: could not update [_1].',
                   12075:                                    '<span class="LC_filename">'.
                   12076:                                    $container.'</span>').'</p>';
1.661     raeburn  12077:                     }
                   12078:                 }
                   12079:             }
1.1123    raeburn  12080:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12081:                 my ($actionurl,$state);
                   12082:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12083:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12084:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12085:                                               \%codebase,
                   12086:                                               {'context' => 'rewrites',
                   12087:                                                'ignore_remote_references' => 1,});
                   12088:                 if (ref($mapping) eq 'HASH') {
                   12089:                     my $rewrites = 0;
                   12090:                     foreach my $key (keys(%{$mapping})) {
                   12091:                         next if ($key =~ m{^https?://});
                   12092:                         my $ref = $mapping->{$key};
                   12093:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12094:                         my $attrib;
                   12095:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12096:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12097:                         }
                   12098:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12099:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12100:                             $rewrites += $numchg;
                   12101:                         }
                   12102:                     }
                   12103:                     if ($rewrites) {
                   12104:                         my $saveresult; 
                   12105:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12106:                         if ($url eq $container) {
                   12107:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12108:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12109:                                             $count,'<span class="LC_filename">'.
                   12110:                                             $fname.'</span>').'</p>';
                   12111:                         } else {
                   12112:                             $output .= '<p class="LC_error">'.
                   12113:                                        &mt('Error: could not update links in [_1].',
                   12114:                                        '<span class="LC_filename">'.
                   12115:                                        $container.'</span>').'</p>';
                   12116: 
                   12117:                         }
                   12118:                     }
                   12119:                 }
                   12120:             }
1.987     raeburn  12121:         } else {
                   12122:             &logthis('Failed to parse '.$container.
                   12123:                      ' to modify references: '.$parse_result);
1.661     raeburn  12124:         }
                   12125:     }
1.1071    raeburn  12126:     if (wantarray) {
                   12127:         return ($output,$count,$codebasecount);
                   12128:     } else {
                   12129:         return $output;
                   12130:     }
1.661     raeburn  12131: }
                   12132: 
                   12133: sub check_for_existing {
                   12134:     my ($path,$fname,$element) = @_;
                   12135:     my ($state,$msg);
                   12136:     if (-d $path.'/'.$fname) {
                   12137:         $state = 'exists';
                   12138:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12139:     } elsif (-e $path.'/'.$fname) {
                   12140:         $state = 'exists';
                   12141:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12142:     }
                   12143:     if ($state eq 'exists') {
                   12144:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12145:     }
                   12146:     return ($state,$msg);
                   12147: }
                   12148: 
                   12149: sub check_for_upload {
                   12150:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12151:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12152:     my $filesize = length($env{'form.'.$element});
                   12153:     if (!$filesize) {
                   12154:         my $msg = '<span class="LC_error">'.
                   12155:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12156:                       '<span class="LC_filename">'.$fname.'</span>',
                   12157:                       $filesize).'<br />'.
1.1007    raeburn  12158:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12159:                   '</span>';
                   12160:         return ('zero_bytes',$msg);
                   12161:     }
                   12162:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12163:     my $getpropath = 1;
1.1021    raeburn  12164:     my ($dirlistref,$listerror) =
                   12165:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12166:     my $found_file = 0;
                   12167:     my $locked_file = 0;
1.991     raeburn  12168:     my @lockers;
                   12169:     my $navmap;
                   12170:     if ($env{'request.course.id'}) {
                   12171:         $navmap = Apache::lonnavmaps::navmap->new();
                   12172:     }
1.1021    raeburn  12173:     if (ref($dirlistref) eq 'ARRAY') {
                   12174:         foreach my $line (@{$dirlistref}) {
                   12175:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12176:             if ($file_name eq $fname){
                   12177:                 $file_name = $path.$file_name;
                   12178:                 if ($group ne '') {
                   12179:                     $file_name = $group.$file_name;
                   12180:                 }
                   12181:                 $found_file = 1;
                   12182:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12183:                     foreach my $lock (@lockers) {
                   12184:                         if (ref($lock) eq 'ARRAY') {
                   12185:                             my ($symb,$crsid) = @{$lock};
                   12186:                             if ($crsid eq $env{'request.course.id'}) {
                   12187:                                 if (ref($navmap)) {
                   12188:                                     my $res = $navmap->getBySymb($symb);
                   12189:                                     foreach my $part (@{$res->parts()}) { 
                   12190:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12191:                                         unless (($slot_status == $res->RESERVED) ||
                   12192:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12193:                                             $locked_file = 1;
                   12194:                                         }
1.991     raeburn  12195:                                     }
1.1021    raeburn  12196:                                 } else {
                   12197:                                     $locked_file = 1;
1.991     raeburn  12198:                                 }
                   12199:                             } else {
                   12200:                                 $locked_file = 1;
                   12201:                             }
                   12202:                         }
1.1021    raeburn  12203:                    }
                   12204:                 } else {
                   12205:                     my @info = split(/\&/,$rest);
                   12206:                     my $currsize = $info[6]/1000;
                   12207:                     if ($currsize < $filesize) {
                   12208:                         my $extra = $filesize - $currsize;
                   12209:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   12210:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12211:                                       &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   12212:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12213:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12214:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12215:                             return ('will_exceed_quota',$msg);
                   12216:                         }
1.984     raeburn  12217:                     }
                   12218:                 }
1.661     raeburn  12219:             }
                   12220:         }
                   12221:     }
                   12222:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   12223:         my $msg = '<p class="LC_warning">'.
                   12224:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  12225:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12226:         return ('will_exceed_quota',$msg);
                   12227:     } elsif ($found_file) {
                   12228:         if ($locked_file) {
1.1179    bisitz   12229:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12230:             $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   12231:             $msg .= '</p>';
1.661     raeburn  12232:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12233:             return ('file_locked',$msg);
                   12234:         } else {
1.1179    bisitz   12235:             my $msg = '<p class="LC_error">';
1.984     raeburn  12236:             $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   12237:             $msg .= '</p>';
1.984     raeburn  12238:             return ('existingfile',$msg);
1.661     raeburn  12239:         }
                   12240:     }
                   12241: }
                   12242: 
1.987     raeburn  12243: sub check_for_traversal {
                   12244:     my ($path,$url,$toplevel) = @_;
                   12245:     my @parts=split(/\//,$path);
                   12246:     my $cleanpath;
                   12247:     my $fullpath = $url;
                   12248:     for (my $i=0;$i<@parts;$i++) {
                   12249:         next if ($parts[$i] eq '.');
                   12250:         if ($parts[$i] eq '..') {
                   12251:             $fullpath =~ s{([^/]+/)$}{};
                   12252:         } else {
                   12253:             $fullpath .= $parts[$i].'/';
                   12254:         }
                   12255:     }
                   12256:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12257:         $cleanpath = $1;
                   12258:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12259:         my $curr_toprel = $1;
                   12260:         my @parts = split(/\//,$curr_toprel);
                   12261:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12262:         my @urlparts = split(/\//,$url_toprel);
                   12263:         my $doubledots;
                   12264:         my $startdiff = -1;
                   12265:         for (my $i=0; $i<@urlparts; $i++) {
                   12266:             if ($startdiff == -1) {
                   12267:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12268:                     $startdiff = $i;
                   12269:                     $doubledots .= '../';
                   12270:                 }
                   12271:             } else {
                   12272:                 $doubledots .= '../';
                   12273:             }
                   12274:         }
                   12275:         if ($startdiff > -1) {
                   12276:             $cleanpath = $doubledots;
                   12277:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12278:                 $cleanpath .= $parts[$i].'/';
                   12279:             }
                   12280:         }
                   12281:     }
                   12282:     $cleanpath =~ s{(/)$}{};
                   12283:     return $cleanpath;
                   12284: }
1.31      albertel 12285: 
1.1053    raeburn  12286: sub is_archive_file {
                   12287:     my ($mimetype) = @_;
                   12288:     if (($mimetype eq 'application/octet-stream') ||
                   12289:         ($mimetype eq 'application/x-stuffit') ||
                   12290:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12291:         return 1;
                   12292:     }
                   12293:     return;
                   12294: }
                   12295: 
                   12296: sub decompress_form {
1.1065    raeburn  12297:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12298:     my %lt = &Apache::lonlocal::texthash (
                   12299:         this => 'This file is an archive file.',
1.1067    raeburn  12300:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12301:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12302:         youm => 'You may wish to extract its contents.',
                   12303:         extr => 'Extract contents',
1.1067    raeburn  12304:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12305:         proa => 'Process automatically?',
1.1053    raeburn  12306:         yes  => 'Yes',
                   12307:         no   => 'No',
1.1067    raeburn  12308:         fold => 'Title for folder containing movie',
                   12309:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12310:     );
1.1065    raeburn  12311:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12312:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12313:     my $info = &list_archive_contents($fileloc,\@paths);
                   12314:     if (@paths) {
                   12315:         foreach my $path (@paths) {
                   12316:             $path =~ s{^/}{};
1.1067    raeburn  12317:             if ($path =~ m{^([^/]+)/$}) {
                   12318:                 $topdir = $1;
                   12319:             }
1.1065    raeburn  12320:             if ($path =~ m{^([^/]+)/}) {
                   12321:                 $toplevel{$1} = $path;
                   12322:             } else {
                   12323:                 $toplevel{$path} = $path;
                   12324:             }
                   12325:         }
                   12326:     }
1.1067    raeburn  12327:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  12328:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12329:                         "$topdir/media/",
                   12330:                         "$topdir/media/$topdir.mp4",
                   12331:                         "$topdir/media/FirstFrame.png",
                   12332:                         "$topdir/media/player.swf",
                   12333:                         "$topdir/media/swfobject.js",
                   12334:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  12335:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  12336:                          "$topdir/$topdir.mp4",
                   12337:                          "$topdir/$topdir\_config.xml",
                   12338:                          "$topdir/$topdir\_controller.swf",
                   12339:                          "$topdir/$topdir\_embed.css",
                   12340:                          "$topdir/$topdir\_First_Frame.png",
                   12341:                          "$topdir/$topdir\_player.html",
                   12342:                          "$topdir/$topdir\_Thumbnails.png",
                   12343:                          "$topdir/playerProductInstall.swf",
                   12344:                          "$topdir/scripts/",
                   12345:                          "$topdir/scripts/config_xml.js",
                   12346:                          "$topdir/scripts/handlebars.js",
                   12347:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12348:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12349:                          "$topdir/scripts/modernizr.js",
                   12350:                          "$topdir/scripts/player-min.js",
                   12351:                          "$topdir/scripts/swfobject.js",
                   12352:                          "$topdir/skins/",
                   12353:                          "$topdir/skins/configuration_express.xml",
                   12354:                          "$topdir/skins/express_show/",
                   12355:                          "$topdir/skins/express_show/player-min.css",
                   12356:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  12357:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12358:                          "$topdir/$topdir.mp4",
                   12359:                          "$topdir/$topdir\_config.xml",
                   12360:                          "$topdir/$topdir\_controller.swf",
                   12361:                          "$topdir/$topdir\_embed.css",
                   12362:                          "$topdir/$topdir\_First_Frame.png",
                   12363:                          "$topdir/$topdir\_player.html",
                   12364:                          "$topdir/$topdir\_Thumbnails.png",
                   12365:                          "$topdir/playerProductInstall.swf",
                   12366:                          "$topdir/scripts/",
                   12367:                          "$topdir/scripts/config_xml.js",
                   12368:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12369:                          "$topdir/skins/",
                   12370:                          "$topdir/skins/configuration_express.xml",
                   12371:                          "$topdir/skins/express_show/",
                   12372:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12373:                          "$topdir/skins/express_show/spritesheet.png",
                   12374:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  12375:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12376:         if (@diffs == 0) {
1.1164    raeburn  12377:             $is_camtasia = 6;
                   12378:         } else {
1.1197    raeburn  12379:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  12380:             if (@diffs == 0) {
                   12381:                 $is_camtasia = 8;
1.1197    raeburn  12382:             } else {
                   12383:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12384:                 if (@diffs == 0) {
                   12385:                     $is_camtasia = 8;
                   12386:                 }
1.1164    raeburn  12387:             }
1.1067    raeburn  12388:         }
                   12389:     }
                   12390:     my $output;
                   12391:     if ($is_camtasia) {
                   12392:         $output = <<"ENDCAM";
                   12393: <script type="text/javascript" language="Javascript">
                   12394: // <![CDATA[
                   12395: 
                   12396: function camtasiaToggle() {
                   12397:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12398:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  12399:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12400:                 document.getElementById('camtasia_titles').style.display='block';
                   12401:             } else {
                   12402:                 document.getElementById('camtasia_titles').style.display='none';
                   12403:             }
                   12404:         }
                   12405:     }
                   12406:     return;
                   12407: }
                   12408: 
                   12409: // ]]>
                   12410: </script>
                   12411: <p>$lt{'camt'}</p>
                   12412: ENDCAM
1.1065    raeburn  12413:     } else {
1.1067    raeburn  12414:         $output = '<p>'.$lt{'this'};
                   12415:         if ($info eq '') {
                   12416:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12417:         } else {
                   12418:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12419:                        '<div><pre>'.$info.'</pre></div>';
                   12420:         }
1.1065    raeburn  12421:     }
1.1067    raeburn  12422:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12423:     my $duplicates;
                   12424:     my $num = 0;
                   12425:     if (ref($dirlist) eq 'ARRAY') {
                   12426:         foreach my $item (@{$dirlist}) {
                   12427:             if (ref($item) eq 'ARRAY') {
                   12428:                 if (exists($toplevel{$item->[0]})) {
                   12429:                     $duplicates .= 
                   12430:                         &start_data_table_row().
                   12431:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12432:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12433:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12434:                         'value="1" />'.&mt('Yes').'</label>'.
                   12435:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12436:                         '<td>'.$item->[0].'</td>';
                   12437:                     if ($item->[2]) {
                   12438:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12439:                     } else {
                   12440:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12441:                     }
                   12442:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12443:                                    '<td>'.
                   12444:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12445:                                    '</td>'.
                   12446:                                    &end_data_table_row();
                   12447:                     $num ++;
                   12448:                 }
                   12449:             }
                   12450:         }
                   12451:     }
                   12452:     my $itemcount;
                   12453:     if (@paths > 0) {
                   12454:         $itemcount = scalar(@paths);
                   12455:     } else {
                   12456:         $itemcount = 1;
                   12457:     }
1.1067    raeburn  12458:     if ($is_camtasia) {
                   12459:         $output .= $lt{'auto'}.'<br />'.
                   12460:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  12461:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12462:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12463:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12464:                    $lt{'no'}.'</label></span><br />'.
                   12465:                    '<div id="camtasia_titles" style="display:block">'.
                   12466:                    &Apache::lonhtmlcommon::start_pick_box().
                   12467:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12468:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12469:                    &Apache::lonhtmlcommon::row_closure().
                   12470:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12471:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12472:                    &Apache::lonhtmlcommon::row_closure(1).
                   12473:                    &Apache::lonhtmlcommon::end_pick_box().
                   12474:                    '</div>';
                   12475:     }
1.1065    raeburn  12476:     $output .= 
                   12477:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12478:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12479:         "\n";
1.1065    raeburn  12480:     if ($duplicates ne '') {
                   12481:         $output .= '<p><span class="LC_warning">'.
                   12482:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12483:                    &start_data_table().
                   12484:                    &start_data_table_header_row().
                   12485:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12486:                    '<th>'.&mt('Name').'</th>'.
                   12487:                    '<th>'.&mt('Type').'</th>'.
                   12488:                    '<th>'.&mt('Size').'</th>'.
                   12489:                    '<th>'.&mt('Last modified').'</th>'.
                   12490:                    &end_data_table_header_row().
                   12491:                    $duplicates.
                   12492:                    &end_data_table().
                   12493:                    '</p>';
                   12494:     }
1.1067    raeburn  12495:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12496:     if (ref($hiddenelements) eq 'HASH') {
                   12497:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12498:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12499:         }
                   12500:     }
                   12501:     $output .= <<"END";
1.1067    raeburn  12502: <br />
1.1053    raeburn  12503: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12504: </form>
                   12505: $noextract
                   12506: END
                   12507:     return $output;
                   12508: }
                   12509: 
1.1065    raeburn  12510: sub decompression_utility {
                   12511:     my ($program) = @_;
                   12512:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12513:     my $location;
                   12514:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12515:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12516:                          '/usr/sbin/') {
                   12517:             if (-x $dir.$program) {
                   12518:                 $location = $dir.$program;
                   12519:                 last;
                   12520:             }
                   12521:         }
                   12522:     }
                   12523:     return $location;
                   12524: }
                   12525: 
                   12526: sub list_archive_contents {
                   12527:     my ($file,$pathsref) = @_;
                   12528:     my (@cmd,$output);
                   12529:     my $needsregexp;
                   12530:     if ($file =~ /\.zip$/) {
                   12531:         @cmd = (&decompression_utility('unzip'),"-l");
                   12532:         $needsregexp = 1;
                   12533:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12534:              ($file =~ /\.tgz$/)) {
                   12535:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12536:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12537:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12538:     } elsif ($file =~ m|\.tar$|) {
                   12539:         @cmd = (&decompression_utility('tar'),"-tf");
                   12540:     }
                   12541:     if (@cmd) {
                   12542:         undef($!);
                   12543:         undef($@);
                   12544:         if (open(my $fh,"-|", @cmd, $file)) {
                   12545:             while (my $line = <$fh>) {
                   12546:                 $output .= $line;
                   12547:                 chomp($line);
                   12548:                 my $item;
                   12549:                 if ($needsregexp) {
                   12550:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12551:                 } else {
                   12552:                     $item = $line;
                   12553:                 }
                   12554:                 if ($item ne '') {
                   12555:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12556:                         push(@{$pathsref},$item);
                   12557:                     } 
                   12558:                 }
                   12559:             }
                   12560:             close($fh);
                   12561:         }
                   12562:     }
                   12563:     return $output;
                   12564: }
                   12565: 
1.1053    raeburn  12566: sub decompress_uploaded_file {
                   12567:     my ($file,$dir) = @_;
                   12568:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12569:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12570:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12571:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12572:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12573:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12574:     my $decompressed = $env{'cgi.decompressed'};
                   12575:     &Apache::lonnet::delenv('cgi.file');
                   12576:     &Apache::lonnet::delenv('cgi.dir');
                   12577:     &Apache::lonnet::delenv('cgi.decompressed');
                   12578:     return ($decompressed,$result);
                   12579: }
                   12580: 
1.1055    raeburn  12581: sub process_decompression {
                   12582:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   12583:     my ($dir,$error,$warning,$output);
1.1180    raeburn  12584:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   12585:         $error = &mt('Filename not a supported archive file type.').
                   12586:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12587:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12588:     } else {
                   12589:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12590:         if ($docuhome eq 'no_host') {
                   12591:             $error = &mt('Could not determine home server for course.');
                   12592:         } else {
                   12593:             my @ids=&Apache::lonnet::current_machine_ids();
                   12594:             my $currdir = "$dir_root/$destination";
                   12595:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12596:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12597:                        "$dir_root/$destination";
                   12598:             } else {
                   12599:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12600:                        "$dir_root/$docudom/$docuname/$destination";
                   12601:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12602:                     $error = &mt('Archive file not found.');
                   12603:                 }
                   12604:             }
1.1065    raeburn  12605:             my (@to_overwrite,@to_skip);
                   12606:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12607:                 my $total = $env{'form.archive_overwrite_total'};
                   12608:                 for (my $i=0; $i<$total; $i++) {
                   12609:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12610:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12611:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12612:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12613:                     }
                   12614:                 }
                   12615:             }
                   12616:             my $numskip = scalar(@to_skip);
                   12617:             if (($numskip > 0) && 
                   12618:                 ($numskip == $env{'form.archive_itemcount'})) {
                   12619:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12620:             } elsif ($dir eq '') {
1.1055    raeburn  12621:                 $error = &mt('Directory containing archive file unavailable.');
                   12622:             } elsif (!$error) {
1.1065    raeburn  12623:                 my ($decompressed,$display);
                   12624:                 if ($numskip > 0) {
                   12625:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12626:                     mkdir("$dir/$tempdir",0755);
                   12627:                     system("mv $dir/$file $dir/$tempdir/$file");
                   12628:                     ($decompressed,$display) = 
                   12629:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   12630:                     foreach my $item (@to_skip) {
                   12631:                         if (($item ne '') && ($item !~ /\.\./)) {
                   12632:                             if (-f "$dir/$tempdir/$item") { 
                   12633:                                 unlink("$dir/$tempdir/$item");
                   12634:                             } elsif (-d "$dir/$tempdir/$item") {
                   12635:                                 system("rm -rf $dir/$tempdir/$item");
                   12636:                             }
                   12637:                         }
                   12638:                     }
                   12639:                     system("mv $dir/$tempdir/* $dir");
                   12640:                     rmdir("$dir/$tempdir");   
                   12641:                 } else {
                   12642:                     ($decompressed,$display) = 
                   12643:                         &decompress_uploaded_file($file,$dir);
                   12644:                 }
1.1055    raeburn  12645:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12646:                     $output = '<p class="LC_info">'.
                   12647:                               &mt('Files extracted successfully from archive.').
                   12648:                               '</p>'."\n";
1.1055    raeburn  12649:                     my ($warning,$result,@contents);
                   12650:                     my ($newdirlistref,$newlisterror) =
                   12651:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12652:                                                  $docuname,1);
                   12653:                     my (%is_dir,%changes,@newitems);
                   12654:                     my $dirptr = 16384;
1.1065    raeburn  12655:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12656:                         foreach my $dir_line (@{$newdirlistref}) {
                   12657:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  12658:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   12659:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  12660:                                 push(@newitems,$item);
                   12661:                                 if ($dirptr&$testdir) {
                   12662:                                     $is_dir{$item} = 1;
                   12663:                                 }
                   12664:                                 $changes{$item} = 1;
                   12665:                             }
                   12666:                         }
                   12667:                     }
                   12668:                     if (keys(%changes) > 0) {
                   12669:                         foreach my $item (sort(@newitems)) {
                   12670:                             if ($changes{$item}) {
                   12671:                                 push(@contents,$item);
                   12672:                             }
                   12673:                         }
                   12674:                     }
                   12675:                     if (@contents > 0) {
1.1067    raeburn  12676:                         my $wantform;
                   12677:                         unless ($env{'form.autoextract_camtasia'}) {
                   12678:                             $wantform = 1;
                   12679:                         }
1.1056    raeburn  12680:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12681:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12682:                                                                 $currdir,\%is_dir,
                   12683:                                                                 \%children,\%parent,
1.1056    raeburn  12684:                                                                 \@contents,\%dirorder,
                   12685:                                                                 \%titles,$wantform);
1.1055    raeburn  12686:                         if ($datatable ne '') {
                   12687:                             $output .= &archive_options_form('decompressed',$datatable,
                   12688:                                                              $count,$hiddenelem);
1.1065    raeburn  12689:                             my $startcount = 6;
1.1055    raeburn  12690:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12691:                                                            \%titles,\%children);
1.1055    raeburn  12692:                         }
1.1067    raeburn  12693:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  12694:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12695:                             my %displayed;
                   12696:                             my $total = 1;
                   12697:                             $env{'form.archive_directory'} = [];
                   12698:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12699:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12700:                                 $path =~ s{/$}{};
                   12701:                                 my $item;
                   12702:                                 if ($path ne '') {
                   12703:                                     $item = "$path/$titles{$i}";
                   12704:                                 } else {
                   12705:                                     $item = $titles{$i};
                   12706:                                 }
                   12707:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12708:                                 if ($item eq $contents[0]) {
                   12709:                                     push(@{$env{'form.archive_directory'}},$i);
                   12710:                                     $env{'form.archive_'.$i} = 'display';
                   12711:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12712:                                     $displayed{'folder'} = $i;
1.1164    raeburn  12713:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12714:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  12715:                                     $env{'form.archive_'.$i} = 'display';
                   12716:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12717:                                     $displayed{'web'} = $i;
                   12718:                                 } else {
1.1164    raeburn  12719:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12720:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12721:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12722:                                         push(@{$env{'form.archive_directory'}},$i);
                   12723:                                     }
                   12724:                                     $env{'form.archive_'.$i} = 'dependency';
                   12725:                                 }
                   12726:                                 $total ++;
                   12727:                             }
                   12728:                             for (my $i=1; $i<$total; $i++) {
                   12729:                                 next if ($i == $displayed{'web'});
                   12730:                                 next if ($i == $displayed{'folder'});
                   12731:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12732:                             }
                   12733:                             $env{'form.phase'} = 'decompress_cleanup';
                   12734:                             $env{'form.archivedelete'} = 1;
                   12735:                             $env{'form.archive_count'} = $total-1;
                   12736:                             $output .=
                   12737:                                 &process_extracted_files('coursedocs',$docudom,
                   12738:                                                          $docuname,$destination,
                   12739:                                                          $dir_root,$hiddenelem);
                   12740:                         }
1.1055    raeburn  12741:                     } else {
                   12742:                         $warning = &mt('No new items extracted from archive file.');
                   12743:                     }
                   12744:                 } else {
                   12745:                     $output = $display;
                   12746:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12747:                 }
                   12748:             }
                   12749:         }
                   12750:     }
                   12751:     if ($error) {
                   12752:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12753:                    $error.'</p>'."\n";
                   12754:     }
                   12755:     if ($warning) {
                   12756:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12757:     }
                   12758:     return $output;
                   12759: }
                   12760: 
                   12761: sub get_extracted {
1.1056    raeburn  12762:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12763:         $titles,$wantform) = @_;
1.1055    raeburn  12764:     my $count = 0;
                   12765:     my $depth = 0;
                   12766:     my $datatable;
1.1056    raeburn  12767:     my @hierarchy;
1.1055    raeburn  12768:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12769:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12770:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12771:     foreach my $item (@{$contents}) {
                   12772:         $count ++;
1.1056    raeburn  12773:         @{$dirorder->{$count}} = @hierarchy;
                   12774:         $titles->{$count} = $item;
1.1055    raeburn  12775:         &archive_hierarchy($depth,$count,$parent,$children);
                   12776:         if ($wantform) {
                   12777:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12778:                                        $currdir,$depth,$count);
                   12779:         }
                   12780:         if ($is_dir->{$item}) {
                   12781:             $depth ++;
1.1056    raeburn  12782:             push(@hierarchy,$count);
                   12783:             $parent->{$depth} = $count;
1.1055    raeburn  12784:             $datatable .=
                   12785:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12786:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12787:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12788:             $depth --;
1.1056    raeburn  12789:             pop(@hierarchy);
1.1055    raeburn  12790:         }
                   12791:     }
                   12792:     return ($count,$datatable);
                   12793: }
                   12794: 
                   12795: sub recurse_extracted_archive {
1.1056    raeburn  12796:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12797:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12798:     my $result='';
1.1056    raeburn  12799:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12800:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12801:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12802:         return $result;
                   12803:     }
                   12804:     my $dirptr = 16384;
                   12805:     my ($newdirlistref,$newlisterror) =
                   12806:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12807:     if (ref($newdirlistref) eq 'ARRAY') {
                   12808:         foreach my $dir_line (@{$newdirlistref}) {
                   12809:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12810:             unless ($item =~ /^\.+$/) {
                   12811:                 $$count ++;
1.1056    raeburn  12812:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12813:                 $titles->{$$count} = $item;
1.1055    raeburn  12814:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12815: 
1.1055    raeburn  12816:                 my $is_dir;
                   12817:                 if ($dirptr&$testdir) {
                   12818:                     $is_dir = 1;
                   12819:                 }
                   12820:                 if ($wantform) {
                   12821:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12822:                 }
                   12823:                 if ($is_dir) {
                   12824:                     $$depth ++;
1.1056    raeburn  12825:                     push(@{$hierarchy},$$count);
                   12826:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12827:                     $result .=
                   12828:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12829:                                                    $docuname,$depth,$count,
1.1056    raeburn  12830:                                                    $hierarchy,$dirorder,$children,
                   12831:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12832:                     $$depth --;
1.1056    raeburn  12833:                     pop(@{$hierarchy});
1.1055    raeburn  12834:                 }
                   12835:             }
                   12836:         }
                   12837:     }
                   12838:     return $result;
                   12839: }
                   12840: 
                   12841: sub archive_hierarchy {
                   12842:     my ($depth,$count,$parent,$children) =@_;
                   12843:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12844:         if (exists($parent->{$depth})) {
                   12845:              $children->{$parent->{$depth}} .= $count.':';
                   12846:         }
                   12847:     }
                   12848:     return;
                   12849: }
                   12850: 
                   12851: sub archive_row {
                   12852:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12853:     my ($name) = ($item =~ m{([^/]+)$});
                   12854:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12855:                                        'display'    => 'Add as file',
1.1055    raeburn  12856:                                        'dependency' => 'Include as dependency',
                   12857:                                        'discard'    => 'Discard',
                   12858:                                       );
                   12859:     if ($is_dir) {
1.1059    raeburn  12860:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12861:     }
1.1056    raeburn  12862:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12863:     my $offset = 0;
1.1055    raeburn  12864:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12865:         $offset ++;
1.1065    raeburn  12866:         if ($action ne 'display') {
                   12867:             $offset ++;
                   12868:         }  
1.1055    raeburn  12869:         $output .= '<td><span class="LC_nobreak">'.
                   12870:                    '<label><input type="radio" name="archive_'.$count.
                   12871:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12872:         my $text = $choices{$action};
                   12873:         if ($is_dir) {
                   12874:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12875:             if ($action eq 'display') {
1.1059    raeburn  12876:                 $text = &mt('Add as folder');
1.1055    raeburn  12877:             }
1.1056    raeburn  12878:         } else {
                   12879:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12880: 
                   12881:         }
                   12882:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12883:         if ($action eq 'dependency') {
                   12884:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12885:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12886:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12887:                        '<option value=""></option>'."\n".
                   12888:                        '</select>'."\n".
                   12889:                        '</div>';
1.1059    raeburn  12890:         } elsif ($action eq 'display') {
                   12891:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12892:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12893:                        '</div>';
1.1055    raeburn  12894:         }
1.1056    raeburn  12895:         $output .= '</td>';
1.1055    raeburn  12896:     }
                   12897:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12898:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12899:     for (my $i=0; $i<$depth; $i++) {
                   12900:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12901:     }
                   12902:     if ($is_dir) {
                   12903:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12904:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12905:     } else {
                   12906:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12907:     }
                   12908:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12909:                &end_data_table_row();
                   12910:     return $output;
                   12911: }
                   12912: 
                   12913: sub archive_options_form {
1.1065    raeburn  12914:     my ($form,$display,$count,$hiddenelem) = @_;
                   12915:     my %lt = &Apache::lonlocal::texthash(
                   12916:                perm => 'Permanently remove archive file?',
                   12917:                hows => 'How should each extracted item be incorporated in the course?',
                   12918:                cont => 'Content actions for all',
                   12919:                addf => 'Add as folder/file',
                   12920:                incd => 'Include as dependency for a displayed file',
                   12921:                disc => 'Discard',
                   12922:                no   => 'No',
                   12923:                yes  => 'Yes',
                   12924:                save => 'Save',
                   12925:     );
                   12926:     my $output = <<"END";
                   12927: <form name="$form" method="post" action="">
                   12928: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12929: <label>
                   12930:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12931: </label>
                   12932: &nbsp;
                   12933: <label>
                   12934:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12935: </span>
                   12936: </p>
                   12937: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12938: <br />$lt{'hows'}
                   12939: <div class="LC_columnSection">
                   12940:   <fieldset>
                   12941:     <legend>$lt{'cont'}</legend>
                   12942:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12943:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12944:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12945:   </fieldset>
                   12946: </div>
                   12947: END
                   12948:     return $output.
1.1055    raeburn  12949:            &start_data_table()."\n".
1.1065    raeburn  12950:            $display."\n".
1.1055    raeburn  12951:            &end_data_table()."\n".
                   12952:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12953:            $hiddenelem.
1.1065    raeburn  12954:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12955:            '</form>';
                   12956: }
                   12957: 
                   12958: sub archive_javascript {
1.1056    raeburn  12959:     my ($startcount,$numitems,$titles,$children) = @_;
                   12960:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12961:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12962:     my $scripttag = <<START;
                   12963: <script type="text/javascript">
                   12964: // <![CDATA[
                   12965: 
                   12966: function checkAll(form,prefix) {
                   12967:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12968:     for (var i=0; i < form.elements.length; i++) {
                   12969:         var id = form.elements[i].id;
                   12970:         if ((id != '') && (id != undefined)) {
                   12971:             if (idstr.test(id)) {
                   12972:                 if (form.elements[i].type == 'radio') {
                   12973:                     form.elements[i].checked = true;
1.1056    raeburn  12974:                     var nostart = i-$startcount;
1.1059    raeburn  12975:                     var offset = nostart%7;
                   12976:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12977:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12978:                 }
                   12979:             }
                   12980:         }
                   12981:     }
                   12982: }
                   12983: 
                   12984: function propagateCheck(form,count) {
                   12985:     if (count > 0) {
1.1059    raeburn  12986:         var startelement = $startcount + ((count-1) * 7);
                   12987:         for (var j=1; j<6; j++) {
                   12988:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12989:                 var item = startelement + j; 
                   12990:                 if (form.elements[item].type == 'radio') {
                   12991:                     if (form.elements[item].checked) {
                   12992:                         containerCheck(form,count,j);
                   12993:                         break;
                   12994:                     }
1.1055    raeburn  12995:                 }
                   12996:             }
                   12997:         }
                   12998:     }
                   12999: }
                   13000: 
                   13001: numitems = $numitems
1.1056    raeburn  13002: var titles = new Array(numitems);
                   13003: var parents = new Array(numitems);
1.1055    raeburn  13004: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13005:     parents[i] = new Array;
1.1055    raeburn  13006: }
1.1059    raeburn  13007: var maintitle = '$maintitle';
1.1055    raeburn  13008: 
                   13009: START
                   13010: 
1.1056    raeburn  13011:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13012:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13013:         for (my $i=0; $i<@contents; $i ++) {
                   13014:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13015:         }
                   13016:     }
                   13017: 
1.1056    raeburn  13018:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13019:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13020:     }
                   13021: 
1.1055    raeburn  13022:     $scripttag .= <<END;
                   13023: 
                   13024: function containerCheck(form,count,offset) {
                   13025:     if (count > 0) {
1.1056    raeburn  13026:         dependencyCheck(form,count,offset);
1.1059    raeburn  13027:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13028:         form.elements[item].checked = true;
                   13029:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13030:             if (parents[count].length > 0) {
                   13031:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13032:                     containerCheck(form,parents[count][j],offset);
                   13033:                 }
                   13034:             }
                   13035:         }
                   13036:     }
                   13037: }
                   13038: 
                   13039: function dependencyCheck(form,count,offset) {
                   13040:     if (count > 0) {
1.1059    raeburn  13041:         var chosen = (offset+$startcount)+7*(count-1);
                   13042:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13043:         var currtype = form.elements[depitem].type;
                   13044:         if (form.elements[chosen].value == 'dependency') {
                   13045:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13046:             form.elements[depitem].options.length = 0;
                   13047:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13048:             for (var i=1; i<=numitems; i++) {
                   13049:                 if (i == count) {
                   13050:                     continue;
                   13051:                 }
1.1059    raeburn  13052:                 var startelement = $startcount + (i-1) * 7;
                   13053:                 for (var j=1; j<6; j++) {
                   13054:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13055:                         var item = startelement + j;
                   13056:                         if (form.elements[item].type == 'radio') {
                   13057:                             if (form.elements[item].checked) {
                   13058:                                 if (form.elements[item].value == 'display') {
                   13059:                                     var n = form.elements[depitem].options.length;
                   13060:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13061:                                 }
                   13062:                             }
                   13063:                         }
                   13064:                     }
                   13065:                 }
                   13066:             }
                   13067:         } else {
                   13068:             document.getElementById('arc_depon_'+count).style.display='none';
                   13069:             form.elements[depitem].options.length = 0;
                   13070:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13071:         }
1.1059    raeburn  13072:         titleCheck(form,count,offset);
1.1056    raeburn  13073:     }
                   13074: }
                   13075: 
                   13076: function propagateSelect(form,count,offset) {
                   13077:     if (count > 0) {
1.1065    raeburn  13078:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13079:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13080:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13081:             if (parents[count].length > 0) {
                   13082:                 for (var j=0; j<parents[count].length; j++) {
                   13083:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13084:                 }
                   13085:             }
                   13086:         }
                   13087:     }
                   13088: }
1.1056    raeburn  13089: 
                   13090: function containerSelect(form,count,offset,picked) {
                   13091:     if (count > 0) {
1.1065    raeburn  13092:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13093:         if (form.elements[item].type == 'radio') {
                   13094:             if (form.elements[item].value == 'dependency') {
                   13095:                 if (form.elements[item+1].type == 'select-one') {
                   13096:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13097:                         if (form.elements[item+1].options[i].value == picked) {
                   13098:                             form.elements[item+1].selectedIndex = i;
                   13099:                             break;
                   13100:                         }
                   13101:                     }
                   13102:                 }
                   13103:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13104:                     if (parents[count].length > 0) {
                   13105:                         for (var j=0; j<parents[count].length; j++) {
                   13106:                             containerSelect(form,parents[count][j],offset,picked);
                   13107:                         }
                   13108:                     }
                   13109:                 }
                   13110:             }
                   13111:         }
                   13112:     }
                   13113: }
                   13114: 
1.1059    raeburn  13115: function titleCheck(form,count,offset) {
                   13116:     if (count > 0) {
                   13117:         var chosen = (offset+$startcount)+7*(count-1);
                   13118:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13119:         var currtype = form.elements[depitem].type;
                   13120:         if (form.elements[chosen].value == 'display') {
                   13121:             document.getElementById('arc_title_'+count).style.display='block';
                   13122:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13123:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13124:             }
                   13125:         } else {
                   13126:             document.getElementById('arc_title_'+count).style.display='none';
                   13127:             if (currtype == 'text') { 
                   13128:                 document.getElementById('archive_title_'+count).value='';
                   13129:             }
                   13130:         }
                   13131:     }
                   13132:     return;
                   13133: }
                   13134: 
1.1055    raeburn  13135: // ]]>
                   13136: </script>
                   13137: END
                   13138:     return $scripttag;
                   13139: }
                   13140: 
                   13141: sub process_extracted_files {
1.1067    raeburn  13142:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13143:     my $numitems = $env{'form.archive_count'};
                   13144:     return unless ($numitems);
                   13145:     my @ids=&Apache::lonnet::current_machine_ids();
                   13146:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13147:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13148:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13149:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13150:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13151:         $pathtocheck = "$dir_root/$destination";
                   13152:         $dir = $dir_root;
                   13153:         $ishome = 1;
                   13154:     } else {
                   13155:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13156:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   13157:         $dir = "$dir_root/$docudom/$docuname";    
                   13158:     }
                   13159:     my $currdir = "$dir_root/$destination";
                   13160:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13161:     if ($env{'form.folderpath'}) {
                   13162:         my @items = split('&',$env{'form.folderpath'});
                   13163:         $folders{'0'} = $items[-2];
1.1099    raeburn  13164:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13165:             $containers{'0'}='page';
                   13166:         } else {  
                   13167:             $containers{'0'}='sequence';
                   13168:         }
1.1055    raeburn  13169:     }
                   13170:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13171:     if ($numitems) {
                   13172:         for (my $i=1; $i<=$numitems; $i++) {
                   13173:             my $path = $env{'form.archive_content_'.$i};
                   13174:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13175:                 my $item = $1;
                   13176:                 $toplevelitems{$item} = $i;
                   13177:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13178:                     $is_dir{$item} = 1;
                   13179:                 }
                   13180:             }
                   13181:         }
                   13182:     }
1.1067    raeburn  13183:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13184:     if (keys(%toplevelitems) > 0) {
                   13185:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13186:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13187:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13188:     }
1.1066    raeburn  13189:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13190:     if ($numitems) {
                   13191:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  13192:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13193:             my $path = $env{'form.archive_content_'.$i};
                   13194:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13195:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13196:                     if ($prefix ne '' && $path ne '') {
                   13197:                         if (-e $prefix.$path) {
1.1066    raeburn  13198:                             if ((@archdirs > 0) && 
                   13199:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13200:                                 $todeletedir{$prefix.$path} = 1;
                   13201:                             } else {
                   13202:                                 $todelete{$prefix.$path} = 1;
                   13203:                             }
1.1055    raeburn  13204:                         }
                   13205:                     }
                   13206:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13207:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13208:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13209:                     $docstitle = $env{'form.archive_title_'.$i};
                   13210:                     if ($docstitle eq '') {
                   13211:                         $docstitle = $title;
                   13212:                     }
1.1055    raeburn  13213:                     $outer = 0;
1.1056    raeburn  13214:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13215:                         if (@{$dirorder{$i}} > 0) {
                   13216:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13217:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13218:                                     $outer = $item;
                   13219:                                     last;
                   13220:                                 }
                   13221:                             }
                   13222:                         }
                   13223:                     }
                   13224:                     my ($errtext,$fatal) = 
                   13225:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13226:                                                '/'.$folders{$outer}.'.'.
                   13227:                                                $containers{$outer});
                   13228:                     next if ($fatal);
                   13229:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13230:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13231:                             $mapinner{$i} = time;
1.1055    raeburn  13232:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13233:                             $containers{$i} = 'sequence';
                   13234:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13235:                                       $folders{$i}.'.'.$containers{$i};
                   13236:                             my $newidx = &LONCAPA::map::getresidx();
                   13237:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13238:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13239:                             push(@LONCAPA::map::order,$newidx);
                   13240:                             my ($outtext,$errtext) =
                   13241:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13242:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13243:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13244:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13245:                             unless ($errtext) {
                   13246:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   13247:                             }
1.1055    raeburn  13248:                         }
                   13249:                     } else {
                   13250:                         if ($context eq 'coursedocs') {
                   13251:                             my $newidx=&LONCAPA::map::getresidx();
                   13252:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13253:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13254:                                       $title;
                   13255:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13256:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   13257:                             }
                   13258:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13259:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13260:                             }
                   13261:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13262:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  13263:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  13264:                                 unless ($ishome) {
                   13265:                                     my $fetch = "$newdest{$i}/$title";
                   13266:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13267:                                     $prompttofetch{$fetch} = 1;
                   13268:                                 }
1.1055    raeburn  13269:                             }
                   13270:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13271:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13272:                             push(@LONCAPA::map::order, $newidx);
                   13273:                             my ($outtext,$errtext)=
                   13274:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13275:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  13276:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  13277:                             unless ($errtext) {
                   13278:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13279:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   13280:                                 }
                   13281:                             }
1.1055    raeburn  13282:                         }
                   13283:                     }
1.1086    raeburn  13284:                 }
                   13285:             } else {
                   13286:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13287:             }
                   13288:         }
                   13289:         for (my $i=1; $i<=$numitems; $i++) {
                   13290:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13291:             my $path = $env{'form.archive_content_'.$i};
                   13292:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13293:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13294:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13295:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13296:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13297:                         my ($itemidx,$fullpath,$relpath);
                   13298:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13299:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13300:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  13301:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13302:                                     $itemidx = $j;
1.1056    raeburn  13303:                                 }
                   13304:                             }
1.1086    raeburn  13305:                         }
                   13306:                         if ($itemidx eq '') {
                   13307:                             $itemidx =  0;
                   13308:                         } 
                   13309:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13310:                             if ($mapinner{$referrer{$i}}) {
                   13311:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13312:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13313:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13314:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13315:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13316:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13317:                                             if (!-e $fullpath) {
                   13318:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13319:                                             }
                   13320:                                         }
1.1086    raeburn  13321:                                     } else {
                   13322:                                         last;
1.1056    raeburn  13323:                                     }
1.1086    raeburn  13324:                                 }
                   13325:                             }
                   13326:                         } elsif ($newdest{$referrer{$i}}) {
                   13327:                             $fullpath = $newdest{$referrer{$i}};
                   13328:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13329:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13330:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13331:                                     last;
                   13332:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13333:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13334:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13335:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13336:                                         if (!-e $fullpath) {
                   13337:                                             mkdir($fullpath,0755);
1.1056    raeburn  13338:                                         }
                   13339:                                     }
1.1086    raeburn  13340:                                 } else {
                   13341:                                     last;
1.1056    raeburn  13342:                                 }
1.1055    raeburn  13343:                             }
                   13344:                         }
1.1086    raeburn  13345:                         if ($fullpath ne '') {
                   13346:                             if (-e "$prefix$path") {
                   13347:                                 system("mv $prefix$path $fullpath/$title");
                   13348:                             }
                   13349:                             if (-e "$fullpath/$title") {
                   13350:                                 my $showpath;
                   13351:                                 if ($relpath ne '') {
                   13352:                                     $showpath = "$relpath/$title";
                   13353:                                 } else {
                   13354:                                     $showpath = "/$title";
                   13355:                                 } 
                   13356:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   13357:                             } 
                   13358:                             unless ($ishome) {
                   13359:                                 my $fetch = "$fullpath/$title";
                   13360:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   13361:                                 $prompttofetch{$fetch} = 1;
                   13362:                             }
                   13363:                         }
1.1055    raeburn  13364:                     }
1.1086    raeburn  13365:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13366:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   13367:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  13368:                 }
                   13369:             } else {
                   13370:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   13371:             }
                   13372:         }
                   13373:         if (keys(%todelete)) {
                   13374:             foreach my $key (keys(%todelete)) {
                   13375:                 unlink($key);
1.1066    raeburn  13376:             }
                   13377:         }
                   13378:         if (keys(%todeletedir)) {
                   13379:             foreach my $key (keys(%todeletedir)) {
                   13380:                 rmdir($key);
                   13381:             }
                   13382:         }
                   13383:         foreach my $dir (sort(keys(%is_dir))) {
                   13384:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13385:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13386:             }
                   13387:         }
1.1067    raeburn  13388:         if ($result ne '') {
                   13389:             $output .= '<ul>'."\n".
                   13390:                        $result."\n".
                   13391:                        '</ul>';
                   13392:         }
                   13393:         unless ($ishome) {
                   13394:             my $replicationfail;
                   13395:             foreach my $item (keys(%prompttofetch)) {
                   13396:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13397:                 unless ($fetchresult eq 'ok') {
                   13398:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13399:                 }
                   13400:             }
                   13401:             if ($replicationfail) {
                   13402:                 $output .= '<p class="LC_error">'.
                   13403:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13404:                            $replicationfail.
                   13405:                            '</ul></p>';
                   13406:             }
                   13407:         }
1.1055    raeburn  13408:     } else {
                   13409:         $warning = &mt('No items found in archive.');
                   13410:     }
                   13411:     if ($error) {
                   13412:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13413:                    $error.'</p>'."\n";
                   13414:     }
                   13415:     if ($warning) {
                   13416:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13417:     }
                   13418:     return $output;
                   13419: }
                   13420: 
1.1066    raeburn  13421: sub cleanup_empty_dirs {
                   13422:     my ($path) = @_;
                   13423:     if (($path ne '') && (-d $path)) {
                   13424:         if (opendir(my $dirh,$path)) {
                   13425:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13426:             my $numitems = 0;
                   13427:             foreach my $item (@dircontents) {
                   13428:                 if (-d "$path/$item") {
1.1111    raeburn  13429:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13430:                     if (-e "$path/$item") {
                   13431:                         $numitems ++;
                   13432:                     }
                   13433:                 } else {
                   13434:                     $numitems ++;
                   13435:                 }
                   13436:             }
                   13437:             if ($numitems == 0) {
                   13438:                 rmdir($path);
                   13439:             }
                   13440:             closedir($dirh);
                   13441:         }
                   13442:     }
                   13443:     return;
                   13444: }
                   13445: 
1.41      ng       13446: =pod
1.45      matthew  13447: 
1.1162    raeburn  13448: =item * &get_folder_hierarchy()
1.1068    raeburn  13449: 
                   13450: Provides hierarchy of names of folders/sub-folders containing the current
                   13451: item,
                   13452: 
                   13453: Inputs: 3
                   13454:      - $navmap - navmaps object
                   13455: 
                   13456:      - $map - url for map (either the trigger itself, or map containing
                   13457:                            the resource, which is the trigger).
                   13458: 
                   13459:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13460: 
                   13461: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13462: 
                   13463: =cut
                   13464: 
                   13465: sub get_folder_hierarchy {
                   13466:     my ($navmap,$map,$showitem) = @_;
                   13467:     my @pathitems;
                   13468:     if (ref($navmap)) {
                   13469:         my $mapres = $navmap->getResourceByUrl($map);
                   13470:         if (ref($mapres)) {
                   13471:             my $pcslist = $mapres->map_hierarchy();
                   13472:             if ($pcslist ne '') {
                   13473:                 my @pcs = split(/,/,$pcslist);
                   13474:                 foreach my $pc (@pcs) {
                   13475:                     if ($pc == 1) {
1.1129    raeburn  13476:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13477:                     } else {
                   13478:                         my $res = $navmap->getByMapPc($pc);
                   13479:                         if (ref($res)) {
                   13480:                             my $title = $res->compTitle();
                   13481:                             $title =~ s/\W+/_/g;
                   13482:                             if ($title ne '') {
                   13483:                                 push(@pathitems,$title);
                   13484:                             }
                   13485:                         }
                   13486:                     }
                   13487:                 }
                   13488:             }
1.1071    raeburn  13489:             if ($showitem) {
                   13490:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  13491:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13492:                 } else {
                   13493:                     my $maptitle = $mapres->compTitle();
                   13494:                     $maptitle =~ s/\W+/_/g;
                   13495:                     if ($maptitle ne '') {
                   13496:                         push(@pathitems,$maptitle);
                   13497:                     }
1.1068    raeburn  13498:                 }
                   13499:             }
                   13500:         }
                   13501:     }
                   13502:     return @pathitems;
                   13503: }
                   13504: 
                   13505: =pod
                   13506: 
1.1015    raeburn  13507: =item * &get_turnedin_filepath()
                   13508: 
                   13509: Determines path in a user's portfolio file for storage of files uploaded
                   13510: to a specific essayresponse or dropbox item.
                   13511: 
                   13512: Inputs: 3 required + 1 optional.
                   13513: $symb is symb for resource, $uname and $udom are for current user (required).
                   13514: $caller is optional (can be "submission", if routine is called when storing
                   13515: an upoaded file when "Submit Answer" button was pressed).
                   13516: 
                   13517: Returns array containing $path and $multiresp. 
                   13518: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13519: than one file upload item.  Callers of routine should append partid as a 
                   13520: subdirectory to $path in cases where $multiresp is 1.
                   13521: 
                   13522: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13523: 
                   13524: =cut
                   13525: 
                   13526: sub get_turnedin_filepath {
                   13527:     my ($symb,$uname,$udom,$caller) = @_;
                   13528:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13529:     my $turnindir;
                   13530:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13531:     $turnindir = $userhash{'turnindir'};
                   13532:     my ($path,$multiresp);
                   13533:     if ($turnindir eq '') {
                   13534:         if ($caller eq 'submission') {
                   13535:             $turnindir = &mt('turned in');
                   13536:             $turnindir =~ s/\W+/_/g;
                   13537:             my %newhash = (
                   13538:                             'turnindir' => $turnindir,
                   13539:                           );
                   13540:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13541:         }
                   13542:     }
                   13543:     if ($turnindir ne '') {
                   13544:         $path = '/'.$turnindir.'/';
                   13545:         my ($multipart,$turnin,@pathitems);
                   13546:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13547:         if (defined($navmap)) {
                   13548:             my $mapres = $navmap->getResourceByUrl($map);
                   13549:             if (ref($mapres)) {
                   13550:                 my $pcslist = $mapres->map_hierarchy();
                   13551:                 if ($pcslist ne '') {
                   13552:                     foreach my $pc (split(/,/,$pcslist)) {
                   13553:                         my $res = $navmap->getByMapPc($pc);
                   13554:                         if (ref($res)) {
                   13555:                             my $title = $res->compTitle();
                   13556:                             $title =~ s/\W+/_/g;
                   13557:                             if ($title ne '') {
1.1149    raeburn  13558:                                 if (($pc > 1) && (length($title) > 12)) {
                   13559:                                     $title = substr($title,0,12);
                   13560:                                 }
1.1015    raeburn  13561:                                 push(@pathitems,$title);
                   13562:                             }
                   13563:                         }
                   13564:                     }
                   13565:                 }
                   13566:                 my $maptitle = $mapres->compTitle();
                   13567:                 $maptitle =~ s/\W+/_/g;
                   13568:                 if ($maptitle ne '') {
1.1149    raeburn  13569:                     if (length($maptitle) > 12) {
                   13570:                         $maptitle = substr($maptitle,0,12);
                   13571:                     }
1.1015    raeburn  13572:                     push(@pathitems,$maptitle);
                   13573:                 }
                   13574:                 unless ($env{'request.state'} eq 'construct') {
                   13575:                     my $res = $navmap->getBySymb($symb);
                   13576:                     if (ref($res)) {
                   13577:                         my $partlist = $res->parts();
                   13578:                         my $totaluploads = 0;
                   13579:                         if (ref($partlist) eq 'ARRAY') {
                   13580:                             foreach my $part (@{$partlist}) {
                   13581:                                 my @types = $res->responseType($part);
                   13582:                                 my @ids = $res->responseIds($part);
                   13583:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13584:                                     if ($types[$i] eq 'essay') {
                   13585:                                         my $partid = $part.'_'.$ids[$i];
                   13586:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13587:                                             $totaluploads ++;
                   13588:                                         }
                   13589:                                     }
                   13590:                                 }
                   13591:                             }
                   13592:                             if ($totaluploads > 1) {
                   13593:                                 $multiresp = 1;
                   13594:                             }
                   13595:                         }
                   13596:                     }
                   13597:                 }
                   13598:             } else {
                   13599:                 return;
                   13600:             }
                   13601:         } else {
                   13602:             return;
                   13603:         }
                   13604:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13605:         $restitle =~ s/\W+/_/g;
                   13606:         if ($restitle eq '') {
                   13607:             $restitle = ($resurl =~ m{/[^/]+$});
                   13608:             if ($restitle eq '') {
                   13609:                 $restitle = time;
                   13610:             }
                   13611:         }
1.1149    raeburn  13612:         if (length($restitle) > 12) {
                   13613:             $restitle = substr($restitle,0,12);
                   13614:         }
1.1015    raeburn  13615:         push(@pathitems,$restitle);
                   13616:         $path .= join('/',@pathitems);
                   13617:     }
                   13618:     return ($path,$multiresp);
                   13619: }
                   13620: 
                   13621: =pod
                   13622: 
1.464     albertel 13623: =back
1.41      ng       13624: 
1.112     bowersj2 13625: =head1 CSV Upload/Handling functions
1.38      albertel 13626: 
1.41      ng       13627: =over 4
                   13628: 
1.648     raeburn  13629: =item * &upfile_store($r)
1.41      ng       13630: 
                   13631: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13632: needs $env{'form.upfile'}
1.41      ng       13633: returns $datatoken to be put into hidden field
                   13634: 
                   13635: =cut
1.31      albertel 13636: 
                   13637: sub upfile_store {
                   13638:     my $r=shift;
1.258     albertel 13639:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13640:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13641:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13642:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13643: 
1.258     albertel 13644:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   13645: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 13646:     {
1.158     raeburn  13647:         my $datafile = $r->dir_config('lonDaemons').
                   13648:                            '/tmp/'.$datatoken.'.tmp';
                   13649:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 13650:             print $fh $env{'form.upfile'};
1.158     raeburn  13651:             close($fh);
                   13652:         }
1.31      albertel 13653:     }
                   13654:     return $datatoken;
                   13655: }
                   13656: 
1.56      matthew  13657: =pod
                   13658: 
1.648     raeburn  13659: =item * &load_tmp_file($r)
1.41      ng       13660: 
                   13661: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 13662: needs $env{'form.datatoken'},
                   13663: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13664: 
                   13665: =cut
1.31      albertel 13666: 
                   13667: sub load_tmp_file {
                   13668:     my $r=shift;
                   13669:     my @studentdata=();
                   13670:     {
1.158     raeburn  13671:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 13672:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  13673:         if ( open(my $fh,"<$studentfile") ) {
                   13674:             @studentdata=<$fh>;
                   13675:             close($fh);
                   13676:         }
1.31      albertel 13677:     }
1.258     albertel 13678:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13679: }
                   13680: 
1.56      matthew  13681: =pod
                   13682: 
1.648     raeburn  13683: =item * &upfile_record_sep()
1.41      ng       13684: 
                   13685: Separate uploaded file into records
                   13686: returns array of records,
1.258     albertel 13687: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13688: 
                   13689: =cut
1.31      albertel 13690: 
                   13691: sub upfile_record_sep {
1.258     albertel 13692:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13693:     } else {
1.248     albertel 13694: 	my @records;
1.258     albertel 13695: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13696: 	    if ($line=~/^\s*$/) { next; }
                   13697: 	    push(@records,$line);
                   13698: 	}
                   13699: 	return @records;
1.31      albertel 13700:     }
                   13701: }
                   13702: 
1.56      matthew  13703: =pod
                   13704: 
1.648     raeburn  13705: =item * &record_sep($record)
1.41      ng       13706: 
1.258     albertel 13707: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13708: 
                   13709: =cut
                   13710: 
1.263     www      13711: sub takeleft {
                   13712:     my $index=shift;
                   13713:     return substr('0000'.$index,-4,4);
                   13714: }
                   13715: 
1.31      albertel 13716: sub record_sep {
                   13717:     my $record=shift;
                   13718:     my %components=();
1.258     albertel 13719:     if ($env{'form.upfiletype'} eq 'xml') {
                   13720:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13721:         my $i=0;
1.356     albertel 13722:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13723:             $field=~s/^(\"|\')//;
                   13724:             $field=~s/(\"|\')$//;
1.263     www      13725:             $components{&takeleft($i)}=$field;
1.31      albertel 13726:             $i++;
                   13727:         }
1.258     albertel 13728:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13729:         my $i=0;
1.356     albertel 13730:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13731:             $field=~s/^(\"|\')//;
                   13732:             $field=~s/(\"|\')$//;
1.263     www      13733:             $components{&takeleft($i)}=$field;
1.31      albertel 13734:             $i++;
                   13735:         }
                   13736:     } else {
1.561     www      13737:         my $separator=',';
1.480     banghart 13738:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13739:             $separator=';';
1.480     banghart 13740:         }
1.31      albertel 13741:         my $i=0;
1.561     www      13742: # the character we are looking for to indicate the end of a quote or a record 
                   13743:         my $looking_for=$separator;
                   13744: # do not add the characters to the fields
                   13745:         my $ignore=0;
                   13746: # we just encountered a separator (or the beginning of the record)
                   13747:         my $just_found_separator=1;
                   13748: # store the field we are working on here
                   13749:         my $field='';
                   13750: # work our way through all characters in record
                   13751:         foreach my $character ($record=~/(.)/g) {
                   13752:             if ($character eq $looking_for) {
                   13753:                if ($character ne $separator) {
                   13754: # Found the end of a quote, again looking for separator
                   13755:                   $looking_for=$separator;
                   13756:                   $ignore=1;
                   13757:                } else {
                   13758: # Found a separator, store away what we got
                   13759:                   $components{&takeleft($i)}=$field;
                   13760: 	          $i++;
                   13761:                   $just_found_separator=1;
                   13762:                   $ignore=0;
                   13763:                   $field='';
                   13764:                }
                   13765:                next;
                   13766:             }
                   13767: # single or double quotation marks after a separator indicate beginning of a quote
                   13768: # we are now looking for the end of the quote and need to ignore separators
                   13769:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13770:                $looking_for=$character;
                   13771:                next;
                   13772:             }
                   13773: # ignore would be true after we reached the end of a quote
                   13774:             if ($ignore) { next; }
                   13775:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13776:             $field.=$character;
                   13777:             $just_found_separator=0; 
1.31      albertel 13778:         }
1.561     www      13779: # catch the very last entry, since we never encountered the separator
                   13780:         $components{&takeleft($i)}=$field;
1.31      albertel 13781:     }
                   13782:     return %components;
                   13783: }
                   13784: 
1.144     matthew  13785: ######################################################
                   13786: ######################################################
                   13787: 
1.56      matthew  13788: =pod
                   13789: 
1.648     raeburn  13790: =item * &upfile_select_html()
1.41      ng       13791: 
1.144     matthew  13792: Return HTML code to select a file from the users machine and specify 
                   13793: the file type.
1.41      ng       13794: 
                   13795: =cut
                   13796: 
1.144     matthew  13797: ######################################################
                   13798: ######################################################
1.31      albertel 13799: sub upfile_select_html {
1.144     matthew  13800:     my %Types = (
                   13801:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13802:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13803:                  space => &mt('Space separated'),
                   13804:                  tab   => &mt('Tabulator separated'),
                   13805: #                 xml   => &mt('HTML/XML'),
                   13806:                  );
                   13807:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13808:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13809:     foreach my $type (sort(keys(%Types))) {
                   13810:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13811:     }
                   13812:     $Str .= "</select>\n";
                   13813:     return $Str;
1.31      albertel 13814: }
                   13815: 
1.301     albertel 13816: sub get_samples {
                   13817:     my ($records,$toget) = @_;
                   13818:     my @samples=({});
                   13819:     my $got=0;
                   13820:     foreach my $rec (@$records) {
                   13821: 	my %temp = &record_sep($rec);
                   13822: 	if (! grep(/\S/, values(%temp))) { next; }
                   13823: 	if (%temp) {
                   13824: 	    $samples[$got]=\%temp;
                   13825: 	    $got++;
                   13826: 	    if ($got == $toget) { last; }
                   13827: 	}
                   13828:     }
                   13829:     return \@samples;
                   13830: }
                   13831: 
1.144     matthew  13832: ######################################################
                   13833: ######################################################
                   13834: 
1.56      matthew  13835: =pod
                   13836: 
1.648     raeburn  13837: =item * &csv_print_samples($r,$records)
1.41      ng       13838: 
                   13839: Prints a table of sample values from each column uploaded $r is an
                   13840: Apache Request ref, $records is an arrayref from
                   13841: &Apache::loncommon::upfile_record_sep
                   13842: 
                   13843: =cut
                   13844: 
1.144     matthew  13845: ######################################################
                   13846: ######################################################
1.31      albertel 13847: sub csv_print_samples {
                   13848:     my ($r,$records) = @_;
1.662     bisitz   13849:     my $samples = &get_samples($records,5);
1.301     albertel 13850: 
1.594     raeburn  13851:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13852:               &start_data_table_header_row());
1.356     albertel 13853:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13854:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13855:     $r->print(&end_data_table_header_row());
1.301     albertel 13856:     foreach my $hash (@$samples) {
1.594     raeburn  13857: 	$r->print(&start_data_table_row());
1.356     albertel 13858: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13859: 	    $r->print('<td>');
1.356     albertel 13860: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13861: 	    $r->print('</td>');
                   13862: 	}
1.594     raeburn  13863: 	$r->print(&end_data_table_row());
1.31      albertel 13864:     }
1.594     raeburn  13865:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13866: }
                   13867: 
1.144     matthew  13868: ######################################################
                   13869: ######################################################
                   13870: 
1.56      matthew  13871: =pod
                   13872: 
1.648     raeburn  13873: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13874: 
                   13875: Prints a table to create associations between values and table columns.
1.144     matthew  13876: 
1.41      ng       13877: $r is an Apache Request ref,
                   13878: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13879: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13880: 
                   13881: =cut
                   13882: 
1.144     matthew  13883: ######################################################
                   13884: ######################################################
1.31      albertel 13885: sub csv_print_select_table {
                   13886:     my ($r,$records,$d) = @_;
1.301     albertel 13887:     my $i=0;
                   13888:     my $samples = &get_samples($records,1);
1.144     matthew  13889:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13890: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13891:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13892:               '<th>'.&mt('Column').'</th>'.
                   13893:               &end_data_table_header_row()."\n");
1.356     albertel 13894:     foreach my $array_ref (@$d) {
                   13895: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13896: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13897: 
1.875     bisitz   13898: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13899: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13900: 	$r->print('<option value="none"></option>');
1.356     albertel 13901: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13902: 	    $r->print('<option value="'.$sample.'"'.
                   13903:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13904:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13905: 	}
1.594     raeburn  13906: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13907: 	$i++;
                   13908:     }
1.594     raeburn  13909:     $r->print(&end_data_table());
1.31      albertel 13910:     $i--;
                   13911:     return $i;
                   13912: }
1.56      matthew  13913: 
1.144     matthew  13914: ######################################################
                   13915: ######################################################
                   13916: 
1.56      matthew  13917: =pod
1.31      albertel 13918: 
1.648     raeburn  13919: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13920: 
                   13921: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13922: 
                   13923: $r is an Apache Request ref,
                   13924: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13925: $d is an array of 2 element arrays (internal name, displayed name)
                   13926: 
                   13927: =cut
                   13928: 
1.144     matthew  13929: ######################################################
                   13930: ######################################################
1.31      albertel 13931: sub csv_samples_select_table {
                   13932:     my ($r,$records,$d) = @_;
                   13933:     my $i=0;
1.144     matthew  13934:     #
1.662     bisitz   13935:     my $max_samples = 5;
                   13936:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13937:     $r->print(&start_data_table().
                   13938:               &start_data_table_header_row().'<th>'.
                   13939:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13940:               &end_data_table_header_row());
1.301     albertel 13941: 
                   13942:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13943: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13944: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13945: 	foreach my $option (@$d) {
                   13946: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13947: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13948:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13949:                       $display.'</option>');
1.31      albertel 13950: 	}
                   13951: 	$r->print('</select></td><td>');
1.662     bisitz   13952: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13953: 	    if (defined($samples->[$line]{$key})) { 
                   13954: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13955: 	    }
                   13956: 	}
1.594     raeburn  13957: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13958: 	$i++;
                   13959:     }
1.594     raeburn  13960:     $r->print(&end_data_table());
1.31      albertel 13961:     $i--;
                   13962:     return($i);
1.115     matthew  13963: }
                   13964: 
1.144     matthew  13965: ######################################################
                   13966: ######################################################
                   13967: 
1.115     matthew  13968: =pod
                   13969: 
1.648     raeburn  13970: =item * &clean_excel_name($name)
1.115     matthew  13971: 
                   13972: Returns a replacement for $name which does not contain any illegal characters.
                   13973: 
                   13974: =cut
                   13975: 
1.144     matthew  13976: ######################################################
                   13977: ######################################################
1.115     matthew  13978: sub clean_excel_name {
                   13979:     my ($name) = @_;
                   13980:     $name =~ s/[:\*\?\/\\]//g;
                   13981:     if (length($name) > 31) {
                   13982:         $name = substr($name,0,31);
                   13983:     }
                   13984:     return $name;
1.25      albertel 13985: }
1.84      albertel 13986: 
1.85      albertel 13987: =pod
                   13988: 
1.648     raeburn  13989: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13990: 
                   13991: Returns either 1 or undef
                   13992: 
                   13993: 1 if the part is to be hidden, undef if it is to be shown
                   13994: 
                   13995: Arguments are:
                   13996: 
                   13997: $id the id of the part to be checked
                   13998: $symb, optional the symb of the resource to check
                   13999: $udom, optional the domain of the user to check for
                   14000: $uname, optional the username of the user to check for
                   14001: 
                   14002: =cut
1.84      albertel 14003: 
                   14004: sub check_if_partid_hidden {
                   14005:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14006:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14007: 					 $symb,$udom,$uname);
1.141     albertel 14008:     my $truth=1;
                   14009:     #if the string starts with !, then the list is the list to show not hide
                   14010:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14011:     my @hiddenlist=split(/,/,$hiddenparts);
                   14012:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14013: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14014:     }
1.141     albertel 14015:     return !$truth;
1.84      albertel 14016: }
1.127     matthew  14017: 
1.138     matthew  14018: 
                   14019: ############################################################
                   14020: ############################################################
                   14021: 
                   14022: =pod
                   14023: 
1.157     matthew  14024: =back 
                   14025: 
1.138     matthew  14026: =head1 cgi-bin script and graphing routines
                   14027: 
1.157     matthew  14028: =over 4
                   14029: 
1.648     raeburn  14030: =item * &get_cgi_id()
1.138     matthew  14031: 
                   14032: Inputs: none
                   14033: 
                   14034: Returns an id which can be used to pass environment variables
                   14035: to various cgi-bin scripts.  These environment variables will
                   14036: be removed from the users environment after a given time by
                   14037: the routine &Apache::lonnet::transfer_profile_to_env.
                   14038: 
                   14039: =cut
                   14040: 
                   14041: ############################################################
                   14042: ############################################################
1.152     albertel 14043: my $uniq=0;
1.136     matthew  14044: sub get_cgi_id {
1.154     albertel 14045:     $uniq=($uniq+1)%100000;
1.280     albertel 14046:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14047: }
                   14048: 
1.127     matthew  14049: ############################################################
                   14050: ############################################################
                   14051: 
                   14052: =pod
                   14053: 
1.648     raeburn  14054: =item * &DrawBarGraph()
1.127     matthew  14055: 
1.138     matthew  14056: Facilitates the plotting of data in a (stacked) bar graph.
                   14057: Puts plot definition data into the users environment in order for 
                   14058: graph.png to plot it.  Returns an <img> tag for the plot.
                   14059: The bars on the plot are labeled '1','2',...,'n'.
                   14060: 
                   14061: Inputs:
                   14062: 
                   14063: =over 4
                   14064: 
                   14065: =item $Title: string, the title of the plot
                   14066: 
                   14067: =item $xlabel: string, text describing the X-axis of the plot
                   14068: 
                   14069: =item $ylabel: string, text describing the Y-axis of the plot
                   14070: 
                   14071: =item $Max: scalar, the maximum Y value to use in the plot
                   14072: If $Max is < any data point, the graph will not be rendered.
                   14073: 
1.140     matthew  14074: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14075: they are plotted.  If undefined, default values will be used.
                   14076: 
1.178     matthew  14077: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14078: 
1.138     matthew  14079: =item @Values: An array of array references.  Each array reference holds data
                   14080: to be plotted in a stacked bar chart.
                   14081: 
1.239     matthew  14082: =item If the final element of @Values is a hash reference the key/value
                   14083: pairs will be added to the graph definition.
                   14084: 
1.138     matthew  14085: =back
                   14086: 
                   14087: Returns:
                   14088: 
                   14089: An <img> tag which references graph.png and the appropriate identifying
                   14090: information for the plot.
                   14091: 
1.127     matthew  14092: =cut
                   14093: 
                   14094: ############################################################
                   14095: ############################################################
1.134     matthew  14096: sub DrawBarGraph {
1.178     matthew  14097:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14098:     #
                   14099:     if (! defined($colors)) {
                   14100:         $colors = ['#33ff00', 
                   14101:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14102:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14103:                   ]; 
                   14104:     }
1.228     matthew  14105:     my $extra_settings = {};
                   14106:     if (ref($Values[-1]) eq 'HASH') {
                   14107:         $extra_settings = pop(@Values);
                   14108:     }
1.127     matthew  14109:     #
1.136     matthew  14110:     my $identifier = &get_cgi_id();
                   14111:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14112:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14113:         return '';
                   14114:     }
1.225     matthew  14115:     #
                   14116:     my @Labels;
                   14117:     if (defined($labels)) {
                   14118:         @Labels = @$labels;
                   14119:     } else {
                   14120:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  14121:             push(@Labels,$i+1);
1.225     matthew  14122:         }
                   14123:     }
                   14124:     #
1.129     matthew  14125:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14126:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14127:     my %ValuesHash;
                   14128:     my $NumSets=1;
                   14129:     foreach my $array (@Values) {
                   14130:         next if (! ref($array));
1.136     matthew  14131:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14132:             join(',',@$array);
1.129     matthew  14133:     }
1.127     matthew  14134:     #
1.136     matthew  14135:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14136:     if ($NumBars < 3) {
                   14137:         $width = 120+$NumBars*32;
1.220     matthew  14138:         $xskip = 1;
1.225     matthew  14139:         $bar_width = 30;
                   14140:     } elsif ($NumBars < 5) {
                   14141:         $width = 120+$NumBars*20;
                   14142:         $xskip = 1;
                   14143:         $bar_width = 20;
1.220     matthew  14144:     } elsif ($NumBars < 10) {
1.136     matthew  14145:         $width = 120+$NumBars*15;
                   14146:         $xskip = 1;
                   14147:         $bar_width = 15;
                   14148:     } elsif ($NumBars <= 25) {
                   14149:         $width = 120+$NumBars*11;
                   14150:         $xskip = 5;
                   14151:         $bar_width = 8;
                   14152:     } elsif ($NumBars <= 50) {
                   14153:         $width = 120+$NumBars*8;
                   14154:         $xskip = 5;
                   14155:         $bar_width = 4;
                   14156:     } else {
                   14157:         $width = 120+$NumBars*8;
                   14158:         $xskip = 5;
                   14159:         $bar_width = 4;
                   14160:     }
                   14161:     #
1.137     matthew  14162:     $Max = 1 if ($Max < 1);
                   14163:     if ( int($Max) < $Max ) {
                   14164:         $Max++;
                   14165:         $Max = int($Max);
                   14166:     }
1.127     matthew  14167:     $Title  = '' if (! defined($Title));
                   14168:     $xlabel = '' if (! defined($xlabel));
                   14169:     $ylabel = '' if (! defined($ylabel));
1.369     www      14170:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14171:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14172:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14173:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14174:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14175:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14176:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14177:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14178:     $ValuesHash{$id.'.height'}   = $height;
                   14179:     $ValuesHash{$id.'.width'}    = $width;
                   14180:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14181:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14182:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14183:     #
1.228     matthew  14184:     # Deal with other parameters
                   14185:     while (my ($key,$value) = each(%$extra_settings)) {
                   14186:         $ValuesHash{$id.'.'.$key} = $value;
                   14187:     }
                   14188:     #
1.646     raeburn  14189:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14190:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14191: }
                   14192: 
                   14193: ############################################################
                   14194: ############################################################
                   14195: 
                   14196: =pod
                   14197: 
1.648     raeburn  14198: =item * &DrawXYGraph()
1.137     matthew  14199: 
1.138     matthew  14200: Facilitates the plotting of data in an XY graph.
                   14201: Puts plot definition data into the users environment in order for 
                   14202: graph.png to plot it.  Returns an <img> tag for the plot.
                   14203: 
                   14204: Inputs:
                   14205: 
                   14206: =over 4
                   14207: 
                   14208: =item $Title: string, the title of the plot
                   14209: 
                   14210: =item $xlabel: string, text describing the X-axis of the plot
                   14211: 
                   14212: =item $ylabel: string, text describing the Y-axis of the plot
                   14213: 
                   14214: =item $Max: scalar, the maximum Y value to use in the plot
                   14215: If $Max is < any data point, the graph will not be rendered.
                   14216: 
                   14217: =item $colors: Array ref containing the hex color codes for the data to be 
                   14218: plotted in.  If undefined, default values will be used.
                   14219: 
                   14220: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14221: 
                   14222: =item $Ydata: Array ref containing Array refs.  
1.185     www      14223: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14224: 
                   14225: =item %Values: hash indicating or overriding any default values which are 
                   14226: passed to graph.png.  
                   14227: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14228: 
                   14229: =back
                   14230: 
                   14231: Returns:
                   14232: 
                   14233: An <img> tag which references graph.png and the appropriate identifying
                   14234: information for the plot.
                   14235: 
1.137     matthew  14236: =cut
                   14237: 
                   14238: ############################################################
                   14239: ############################################################
                   14240: sub DrawXYGraph {
                   14241:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14242:     #
                   14243:     # Create the identifier for the graph
                   14244:     my $identifier = &get_cgi_id();
                   14245:     my $id = 'cgi.'.$identifier;
                   14246:     #
                   14247:     $Title  = '' if (! defined($Title));
                   14248:     $xlabel = '' if (! defined($xlabel));
                   14249:     $ylabel = '' if (! defined($ylabel));
                   14250:     my %ValuesHash = 
                   14251:         (
1.369     www      14252:          $id.'.title'  => &escape($Title),
                   14253:          $id.'.xlabel' => &escape($xlabel),
                   14254:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14255:          $id.'.y_max_value'=> $Max,
                   14256:          $id.'.labels'     => join(',',@$Xlabels),
                   14257:          $id.'.PlotType'   => 'XY',
                   14258:          );
                   14259:     #
                   14260:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14261:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14262:     }
                   14263:     #
                   14264:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14265:         return '';
                   14266:     }
                   14267:     my $NumSets=1;
1.138     matthew  14268:     foreach my $array (@{$Ydata}){
1.137     matthew  14269:         next if (! ref($array));
                   14270:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14271:     }
1.138     matthew  14272:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14273:     #
                   14274:     # Deal with other parameters
                   14275:     while (my ($key,$value) = each(%Values)) {
                   14276:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14277:     }
                   14278:     #
1.646     raeburn  14279:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14280:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14281: }
                   14282: 
                   14283: ############################################################
                   14284: ############################################################
                   14285: 
                   14286: =pod
                   14287: 
1.648     raeburn  14288: =item * &DrawXYYGraph()
1.138     matthew  14289: 
                   14290: Facilitates the plotting of data in an XY graph with two Y axes.
                   14291: Puts plot definition data into the users environment in order for 
                   14292: graph.png to plot it.  Returns an <img> tag for the plot.
                   14293: 
                   14294: Inputs:
                   14295: 
                   14296: =over 4
                   14297: 
                   14298: =item $Title: string, the title of the plot
                   14299: 
                   14300: =item $xlabel: string, text describing the X-axis of the plot
                   14301: 
                   14302: =item $ylabel: string, text describing the Y-axis of the plot
                   14303: 
                   14304: =item $colors: Array ref containing the hex color codes for the data to be 
                   14305: plotted in.  If undefined, default values will be used.
                   14306: 
                   14307: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14308: 
                   14309: =item $Ydata1: The first data set
                   14310: 
                   14311: =item $Min1: The minimum value of the left Y-axis
                   14312: 
                   14313: =item $Max1: The maximum value of the left Y-axis
                   14314: 
                   14315: =item $Ydata2: The second data set
                   14316: 
                   14317: =item $Min2: The minimum value of the right Y-axis
                   14318: 
                   14319: =item $Max2: The maximum value of the left Y-axis
                   14320: 
                   14321: =item %Values: hash indicating or overriding any default values which are 
                   14322: passed to graph.png.  
                   14323: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14324: 
                   14325: =back
                   14326: 
                   14327: Returns:
                   14328: 
                   14329: An <img> tag which references graph.png and the appropriate identifying
                   14330: information for the plot.
1.136     matthew  14331: 
                   14332: =cut
                   14333: 
                   14334: ############################################################
                   14335: ############################################################
1.137     matthew  14336: sub DrawXYYGraph {
                   14337:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14338:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14339:     #
                   14340:     # Create the identifier for the graph
                   14341:     my $identifier = &get_cgi_id();
                   14342:     my $id = 'cgi.'.$identifier;
                   14343:     #
                   14344:     $Title  = '' if (! defined($Title));
                   14345:     $xlabel = '' if (! defined($xlabel));
                   14346:     $ylabel = '' if (! defined($ylabel));
                   14347:     my %ValuesHash = 
                   14348:         (
1.369     www      14349:          $id.'.title'  => &escape($Title),
                   14350:          $id.'.xlabel' => &escape($xlabel),
                   14351:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14352:          $id.'.labels' => join(',',@$Xlabels),
                   14353:          $id.'.PlotType' => 'XY',
                   14354:          $id.'.NumSets' => 2,
1.137     matthew  14355:          $id.'.two_axes' => 1,
                   14356:          $id.'.y1_max_value' => $Max1,
                   14357:          $id.'.y1_min_value' => $Min1,
                   14358:          $id.'.y2_max_value' => $Max2,
                   14359:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14360:          );
                   14361:     #
1.137     matthew  14362:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14363:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14364:     }
                   14365:     #
                   14366:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14367:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14368:         return '';
                   14369:     }
                   14370:     my $NumSets=1;
1.137     matthew  14371:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14372:         next if (! ref($array));
                   14373:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14374:     }
                   14375:     #
                   14376:     # Deal with other parameters
                   14377:     while (my ($key,$value) = each(%Values)) {
                   14378:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14379:     }
                   14380:     #
1.646     raeburn  14381:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14382:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14383: }
                   14384: 
                   14385: ############################################################
                   14386: ############################################################
                   14387: 
                   14388: =pod
                   14389: 
1.157     matthew  14390: =back 
                   14391: 
1.139     matthew  14392: =head1 Statistics helper routines?  
                   14393: 
                   14394: Bad place for them but what the hell.
                   14395: 
1.157     matthew  14396: =over 4
                   14397: 
1.648     raeburn  14398: =item * &chartlink()
1.139     matthew  14399: 
                   14400: Returns a link to the chart for a specific student.  
                   14401: 
                   14402: Inputs:
                   14403: 
                   14404: =over 4
                   14405: 
                   14406: =item $linktext: The text of the link
                   14407: 
                   14408: =item $sname: The students username
                   14409: 
                   14410: =item $sdomain: The students domain
                   14411: 
                   14412: =back
                   14413: 
1.157     matthew  14414: =back
                   14415: 
1.139     matthew  14416: =cut
                   14417: 
                   14418: ############################################################
                   14419: ############################################################
                   14420: sub chartlink {
                   14421:     my ($linktext, $sname, $sdomain) = @_;
                   14422:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14423:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14424:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14425:        '">'.$linktext.'</a>';
1.153     matthew  14426: }
                   14427: 
                   14428: #######################################################
                   14429: #######################################################
                   14430: 
                   14431: =pod
                   14432: 
                   14433: =head1 Course Environment Routines
1.157     matthew  14434: 
                   14435: =over 4
1.153     matthew  14436: 
1.648     raeburn  14437: =item * &restore_course_settings()
1.153     matthew  14438: 
1.648     raeburn  14439: =item * &store_course_settings()
1.153     matthew  14440: 
                   14441: Restores/Store indicated form parameters from the course environment.
                   14442: Will not overwrite existing values of the form parameters.
                   14443: 
                   14444: Inputs: 
                   14445: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14446: 
                   14447: a hash ref describing the data to be stored.  For example:
                   14448:    
                   14449: %Save_Parameters = ('Status' => 'scalar',
                   14450:     'chartoutputmode' => 'scalar',
                   14451:     'chartoutputdata' => 'scalar',
                   14452:     'Section' => 'array',
1.373     raeburn  14453:     'Group' => 'array',
1.153     matthew  14454:     'StudentData' => 'array',
                   14455:     'Maps' => 'array');
                   14456: 
                   14457: Returns: both routines return nothing
                   14458: 
1.631     raeburn  14459: =back
                   14460: 
1.153     matthew  14461: =cut
                   14462: 
                   14463: #######################################################
                   14464: #######################################################
                   14465: sub store_course_settings {
1.496     albertel 14466:     return &store_settings($env{'request.course.id'},@_);
                   14467: }
                   14468: 
                   14469: sub store_settings {
1.153     matthew  14470:     # save to the environment
                   14471:     # appenv the same items, just to be safe
1.300     albertel 14472:     my $udom  = $env{'user.domain'};
                   14473:     my $uname = $env{'user.name'};
1.496     albertel 14474:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14475:     my %SaveHash;
                   14476:     my %AppHash;
                   14477:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14478:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14479:         my $envname = 'environment.'.$basename;
1.258     albertel 14480:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14481:             # Save this value away
                   14482:             if ($type eq 'scalar' &&
1.258     albertel 14483:                 (! exists($env{$envname}) || 
                   14484:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14485:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14486:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14487:             } elsif ($type eq 'array') {
                   14488:                 my $stored_form;
1.258     albertel 14489:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14490:                     $stored_form = join(',',
                   14491:                                         map {
1.369     www      14492:                                             &escape($_);
1.258     albertel 14493:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14494:                 } else {
                   14495:                     $stored_form = 
1.369     www      14496:                         &escape($env{'form.'.$setting});
1.153     matthew  14497:                 }
                   14498:                 # Determine if the array contents are the same.
1.258     albertel 14499:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14500:                     $SaveHash{$basename} = $stored_form;
                   14501:                     $AppHash{$envname}   = $stored_form;
                   14502:                 }
                   14503:             }
                   14504:         }
                   14505:     }
                   14506:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14507:                                           $udom,$uname);
1.153     matthew  14508:     if ($put_result !~ /^(ok|delayed)/) {
                   14509:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14510:                                  'got error:'.$put_result);
                   14511:     }
                   14512:     # Make sure these settings stick around in this session, too
1.646     raeburn  14513:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14514:     return;
                   14515: }
                   14516: 
                   14517: sub restore_course_settings {
1.499     albertel 14518:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14519: }
                   14520: 
                   14521: sub restore_settings {
                   14522:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14523:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14524:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14525:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14526:             '.'.$setting;
1.258     albertel 14527:         if (exists($env{$envname})) {
1.153     matthew  14528:             if ($type eq 'scalar') {
1.258     albertel 14529:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14530:             } elsif ($type eq 'array') {
1.258     albertel 14531:                 $env{'form.'.$setting} = [ 
1.153     matthew  14532:                                            map { 
1.369     www      14533:                                                &unescape($_); 
1.258     albertel 14534:                                            } split(',',$env{$envname})
1.153     matthew  14535:                                            ];
                   14536:             }
                   14537:         }
                   14538:     }
1.127     matthew  14539: }
                   14540: 
1.618     raeburn  14541: #######################################################
                   14542: #######################################################
                   14543: 
                   14544: =pod
                   14545: 
                   14546: =head1 Domain E-mail Routines  
                   14547: 
                   14548: =over 4
                   14549: 
1.648     raeburn  14550: =item * &build_recipient_list()
1.618     raeburn  14551: 
1.1144    raeburn  14552: Build recipient lists for following types of e-mail:
1.766     raeburn  14553: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  14554: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14555: module change checking, student/employee ID conflict checks, as
                   14556: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14557: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14558: 
                   14559: Inputs:
1.619     raeburn  14560: defmail (scalar - email address of default recipient), 
1.1144    raeburn  14561: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14562: requestsmail, updatesmail, or idconflictsmail).
                   14563: 
1.619     raeburn  14564: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  14565: 
1.619     raeburn  14566: origmail (scalar - email address of recipient from loncapa.conf, 
                   14567: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  14568: 
1.655     raeburn  14569: Returns: comma separated list of addresses to which to send e-mail.
                   14570: 
                   14571: =back
1.618     raeburn  14572: 
                   14573: =cut
                   14574: 
                   14575: ############################################################
                   14576: ############################################################
                   14577: sub build_recipient_list {
1.619     raeburn  14578:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14579:     my @recipients;
1.1270    raeburn  14580:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14581:     my %domconfig =
1.1270    raeburn  14582:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14583:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14584:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14585:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14586:                 my @contacts = ('adminemail','supportemail');
                   14587:                 foreach my $item (@contacts) {
                   14588:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14589:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14590:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14591:                             push(@recipients,$addr);
                   14592:                         }
1.619     raeburn  14593:                     }
1.1270    raeburn  14594:                 }
                   14595:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14596:                 if ($mailing eq 'helpdeskmail') {
                   14597:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14598:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14599:                         my @ok_bccs;
                   14600:                         foreach my $bcc (@bccs) {
                   14601:                             $bcc =~ s/^\s+//g;
                   14602:                             $bcc =~ s/\s+$//g;
                   14603:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14604:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14605:                                     push(@ok_bccs,$bcc);
                   14606:                                 }
                   14607:                             }
                   14608:                         }
                   14609:                         if (@ok_bccs > 0) {
                   14610:                             $allbcc = join(', ',@ok_bccs);
                   14611:                         }
                   14612:                     }
                   14613:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14614:                 }
                   14615:             }
1.766     raeburn  14616:         } elsif ($origmail ne '') {
1.1270    raeburn  14617:             $lastresort = $origmail;
1.618     raeburn  14618:         }
1.619     raeburn  14619:     } elsif ($origmail ne '') {
1.1270    raeburn  14620:         $lastresort = $origmail;
                   14621:     }
                   14622: 
                   14623:     if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
                   14624:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14625:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14626:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14627:             my %what = (
                   14628:                           perlvar => 1,
                   14629:                        );
                   14630:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14631:             if ($primary) {
                   14632:                 my $gotaddr;
                   14633:                 my ($result,$returnhash) =
                   14634:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14635:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14636:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14637:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14638:                         $gotaddr = 1;
                   14639:                     }
                   14640:                 }
                   14641:                 unless ($gotaddr) {
                   14642:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14643:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14644:                     unless ($uintdom eq $intdom) {
                   14645:                         my %domconfig =
                   14646:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14647:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14648:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14649:                                 my @contacts = ('adminemail','supportemail');
                   14650:                                 foreach my $item (@contacts) {
                   14651:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14652:                                         my $addr = $domconfig{'contacts'}{$item};
                   14653:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14654:                                             push(@recipients,$addr);
                   14655:                                         }
                   14656:                                     }
                   14657:                                 }
                   14658:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14659:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14660:                                 }
                   14661:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14662:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14663:                                     my @ok_bccs;
                   14664:                                     foreach my $bcc (@bccs) {
                   14665:                                         $bcc =~ s/^\s+//g;
                   14666:                                         $bcc =~ s/\s+$//g;
                   14667:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14668:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14669:                                                 push(@ok_bccs,$bcc);
                   14670:                                             }
                   14671:                                         }
                   14672:                                     }
                   14673:                                     if (@ok_bccs > 0) {
                   14674:                                         $allbcc = join(', ',@ok_bccs);
                   14675:                                     }
                   14676:                                 }
                   14677:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14678:                             }
                   14679:                         }
                   14680:                     }
                   14681:                 }
                   14682:             }
                   14683:         }
1.618     raeburn  14684:     }
1.688     raeburn  14685:     if (defined($defmail)) {
                   14686:         if ($defmail ne '') {
                   14687:             push(@recipients,$defmail);
                   14688:         }
1.618     raeburn  14689:     }
                   14690:     if ($otheremails) {
1.619     raeburn  14691:         my @others;
                   14692:         if ($otheremails =~ /,/) {
                   14693:             @others = split(/,/,$otheremails);
1.618     raeburn  14694:         } else {
1.619     raeburn  14695:             push(@others,$otheremails);
                   14696:         }
                   14697:         foreach my $addr (@others) {
                   14698:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14699:                 push(@recipients,$addr);
                   14700:             }
1.618     raeburn  14701:         }
                   14702:     }
1.1270    raeburn  14703:     if ($mailing eq 'helpdesk') {
                   14704:         if ((!@recipients) && ($lastresort ne '')) {
                   14705:             push(@recipients,$lastresort);
                   14706:         }
                   14707:     } elsif ($lastresort ne '') {
                   14708:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14709:             push(@recipients,$lastresort);
                   14710:         }
                   14711:     }
1.1271    raeburn  14712:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  14713:     if (wantarray) {
                   14714:         return ($recipientlist,$allbcc,$addtext);
                   14715:     } else {
                   14716:         return $recipientlist;
                   14717:     }
1.618     raeburn  14718: }
                   14719: 
1.127     matthew  14720: ############################################################
                   14721: ############################################################
1.154     albertel 14722: 
1.655     raeburn  14723: =pod
                   14724: 
1.1224    musolffc 14725: =over 4
                   14726: 
1.1223    musolffc 14727: =item * &mime_email()
                   14728: 
                   14729: Sends an email with a possible attachment
                   14730: 
                   14731: Inputs:
                   14732: 
                   14733: =over 4
                   14734: 
                   14735: from -              Sender's email address
                   14736: 
                   14737: to -                Email address of recipient
                   14738: 
                   14739: subject -           Subject of email
                   14740: 
                   14741: body -              Body of email
                   14742: 
                   14743: cc_string -         Carbon copy email address
                   14744: 
                   14745: bcc -               Blind carbon copy email address
                   14746: 
                   14747: type -              File type of attachment
                   14748: 
                   14749: attachment_path -   Path of file to be attached
                   14750: 
                   14751: file_name -         Name of file to be attached
                   14752: 
                   14753: attachment_text -   The body of an attachment of type "TEXT"
                   14754: 
                   14755: =back
                   14756: 
                   14757: =back
                   14758: 
                   14759: =cut
                   14760: 
                   14761: ############################################################
                   14762: ############################################################
                   14763: 
                   14764: sub mime_email {
                   14765:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
                   14766:         $file_name, $attachment_text) = @_;
                   14767:     my $msg = MIME::Lite->new(
                   14768:              From    => $from,
                   14769:              To      => $to,
                   14770:              Subject => $subject,
                   14771:              Type    =>'TEXT',
                   14772:              Data    => $body,
                   14773:              );
                   14774:     if ($cc_string ne '') {
                   14775:         $msg->add("Cc" => $cc_string);
                   14776:     }
                   14777:     if ($bcc ne '') {
                   14778:         $msg->add("Bcc" => $bcc);
                   14779:     }
                   14780:     $msg->attr("content-type"         => "text/plain");
                   14781:     $msg->attr("content-type.charset" => "UTF-8");
                   14782:     # Attach file if given
                   14783:     if ($attachment_path) {
                   14784:         unless ($file_name) {
                   14785:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   14786:         }
                   14787:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   14788:         $msg->attach(Type     => $type,
                   14789:                      Path     => $attachment_path,
                   14790:                      Filename => $file_name
                   14791:                      );
                   14792:     # Otherwise attach text if given
                   14793:     } elsif ($attachment_text) {
                   14794:         $msg->attach(Type => 'TEXT',
                   14795:                      Data => $attachment_text);
                   14796:     }
                   14797:     # Send it
                   14798:     $msg->send('sendmail');
                   14799: }
                   14800: 
                   14801: ############################################################
                   14802: ############################################################
                   14803: 
                   14804: =pod
                   14805: 
1.655     raeburn  14806: =head1 Course Catalog Routines
                   14807: 
                   14808: =over 4
                   14809: 
                   14810: =item * &gather_categories()
                   14811: 
                   14812: Converts category definitions - keys of categories hash stored in  
                   14813: coursecategories in configuration.db on the primary library server in a 
                   14814: domain - to an array.  Also generates javascript and idx hash used to 
                   14815: generate Domain Coordinator interface for editing Course Categories.
                   14816: 
                   14817: Inputs:
1.663     raeburn  14818: 
1.655     raeburn  14819: categories (reference to hash of category definitions).
1.663     raeburn  14820: 
1.655     raeburn  14821: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14822:       categories and subcategories).
1.663     raeburn  14823: 
1.655     raeburn  14824: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14825:       editing Course Categories).
1.663     raeburn  14826: 
1.655     raeburn  14827: jsarray (reference to array of categories used to create Javascript arrays for
                   14828:          Domain Coordinator interface for editing Course Categories).
                   14829: 
                   14830: Returns: nothing
                   14831: 
                   14832: Side effects: populates cats, idx and jsarray. 
                   14833: 
                   14834: =cut
                   14835: 
                   14836: sub gather_categories {
                   14837:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14838:     my %counters;
                   14839:     my $num = 0;
                   14840:     foreach my $item (keys(%{$categories})) {
                   14841:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14842:         if ($container eq '' && $depth == 0) {
                   14843:             $cats->[$depth][$categories->{$item}] = $cat;
                   14844:         } else {
                   14845:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14846:         }
                   14847:         my ($escitem,$tail) = split(/:/,$item,2);
                   14848:         if ($counters{$tail} eq '') {
                   14849:             $counters{$tail} = $num;
                   14850:             $num ++;
                   14851:         }
                   14852:         if (ref($idx) eq 'HASH') {
                   14853:             $idx->{$item} = $counters{$tail};
                   14854:         }
                   14855:         if (ref($jsarray) eq 'ARRAY') {
                   14856:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14857:         }
                   14858:     }
                   14859:     return;
                   14860: }
                   14861: 
                   14862: =pod
                   14863: 
                   14864: =item * &extract_categories()
                   14865: 
                   14866: Used to generate breadcrumb trails for course categories.
                   14867: 
                   14868: Inputs:
1.663     raeburn  14869: 
1.655     raeburn  14870: categories (reference to hash of category definitions).
1.663     raeburn  14871: 
1.655     raeburn  14872: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14873:       categories and subcategories).
1.663     raeburn  14874: 
1.655     raeburn  14875: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14876: 
1.655     raeburn  14877: allitems (reference to hash - key is category key 
                   14878:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14879: 
1.655     raeburn  14880: idx (reference to hash of counters used in Domain Coordinator interface for
                   14881:       editing Course Categories).
1.663     raeburn  14882: 
1.655     raeburn  14883: jsarray (reference to array of categories used to create Javascript arrays for
                   14884:          Domain Coordinator interface for editing Course Categories).
                   14885: 
1.665     raeburn  14886: subcats (reference to hash of arrays containing all subcategories within each 
                   14887:          category, -recursive)
                   14888: 
1.655     raeburn  14889: Returns: nothing
                   14890: 
                   14891: Side effects: populates trails and allitems hash references.
                   14892: 
                   14893: =cut
                   14894: 
                   14895: sub extract_categories {
1.665     raeburn  14896:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  14897:     if (ref($categories) eq 'HASH') {
                   14898:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14899:         if (ref($cats->[0]) eq 'ARRAY') {
                   14900:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14901:                 my $name = $cats->[0][$i];
                   14902:                 my $item = &escape($name).'::0';
                   14903:                 my $trailstr;
                   14904:                 if ($name eq 'instcode') {
                   14905:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14906:                 } elsif ($name eq 'communities') {
                   14907:                     $trailstr = &mt('Communities');
1.1239    raeburn  14908:                 } elsif ($name eq 'placement') {
                   14909:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  14910:                 } else {
                   14911:                     $trailstr = $name;
                   14912:                 }
                   14913:                 if ($allitems->{$item} eq '') {
                   14914:                     push(@{$trails},$trailstr);
                   14915:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14916:                 }
                   14917:                 my @parents = ($name);
                   14918:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14919:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14920:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14921:                         if (ref($subcats) eq 'HASH') {
                   14922:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14923:                         }
                   14924:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   14925:                     }
                   14926:                 } else {
                   14927:                     if (ref($subcats) eq 'HASH') {
                   14928:                         $subcats->{$item} = [];
1.655     raeburn  14929:                     }
                   14930:                 }
                   14931:             }
                   14932:         }
                   14933:     }
                   14934:     return;
                   14935: }
                   14936: 
                   14937: =pod
                   14938: 
1.1162    raeburn  14939: =item * &recurse_categories()
1.655     raeburn  14940: 
                   14941: Recursively used to generate breadcrumb trails for course categories.
                   14942: 
                   14943: Inputs:
1.663     raeburn  14944: 
1.655     raeburn  14945: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14946:       categories and subcategories).
1.663     raeburn  14947: 
1.655     raeburn  14948: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14949: 
                   14950: category (current course category, for which breadcrumb trail is being generated).
                   14951: 
                   14952: trails (reference to array of breadcrumb trails for each category).
                   14953: 
1.655     raeburn  14954: allitems (reference to hash - key is category key
                   14955:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14956: 
1.655     raeburn  14957: parents (array containing containers directories for current category, 
                   14958:          back to top level). 
                   14959: 
                   14960: Returns: nothing
                   14961: 
                   14962: Side effects: populates trails and allitems hash references
                   14963: 
                   14964: =cut
                   14965: 
                   14966: sub recurse_categories {
1.665     raeburn  14967:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  14968:     my $shallower = $depth - 1;
                   14969:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14970:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14971:             my $name = $cats->[$depth]{$category}[$k];
                   14972:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14973:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14974:             if ($allitems->{$item} eq '') {
                   14975:                 push(@{$trails},$trailstr);
                   14976:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14977:             }
                   14978:             my $deeper = $depth+1;
                   14979:             push(@{$parents},$category);
1.665     raeburn  14980:             if (ref($subcats) eq 'HASH') {
                   14981:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14982:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14983:                     my $higher;
                   14984:                     if ($j > 0) {
                   14985:                         $higher = &escape($parents->[$j]).':'.
                   14986:                                   &escape($parents->[$j-1]).':'.$j;
                   14987:                     } else {
                   14988:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14989:                     }
                   14990:                     push(@{$subcats->{$higher}},$subcat);
                   14991:                 }
                   14992:             }
                   14993:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14994:                                 $subcats);
1.655     raeburn  14995:             pop(@{$parents});
                   14996:         }
                   14997:     } else {
                   14998:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14999:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   15000:         if ($allitems->{$item} eq '') {
                   15001:             push(@{$trails},$trailstr);
                   15002:             $allitems->{$item} = scalar(@{$trails})-1;
                   15003:         }
                   15004:     }
                   15005:     return;
                   15006: }
                   15007: 
1.663     raeburn  15008: =pod
                   15009: 
1.1162    raeburn  15010: =item * &assign_categories_table()
1.663     raeburn  15011: 
                   15012: Create a datatable for display of hierarchical categories in a domain,
                   15013: with checkboxes to allow a course to be categorized. 
                   15014: 
                   15015: Inputs:
                   15016: 
                   15017: cathash - reference to hash of categories defined for the domain (from
                   15018:           configuration.db)
                   15019: 
                   15020: currcat - scalar with an & separated list of categories assigned to a course. 
                   15021: 
1.919     raeburn  15022: type    - scalar contains course type (Course or Community).
                   15023: 
1.1260    raeburn  15024: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15025:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15026: 
1.663     raeburn  15027: Returns: $output (markup to be displayed) 
                   15028: 
                   15029: =cut
                   15030: 
                   15031: sub assign_categories_table {
1.1259    raeburn  15032:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15033:     my $output;
                   15034:     if (ref($cathash) eq 'HASH') {
                   15035:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   15036:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   15037:         $maxdepth = scalar(@cats);
                   15038:         if (@cats > 0) {
                   15039:             my $itemcount = 0;
                   15040:             if (ref($cats[0]) eq 'ARRAY') {
                   15041:                 my @currcategories;
                   15042:                 if ($currcat ne '') {
                   15043:                     @currcategories = split('&',$currcat);
                   15044:                 }
1.919     raeburn  15045:                 my $table;
1.663     raeburn  15046:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15047:                     my $parent = $cats[0][$i];
1.919     raeburn  15048:                     next if ($parent eq 'instcode');
                   15049:                     if ($type eq 'Community') {
                   15050:                         next unless ($parent eq 'communities');
1.1239    raeburn  15051:                     } elsif ($type eq 'Placement') {
                   15052:                         next unless ($parent eq 'placement');
1.919     raeburn  15053:                     } else {
1.1239    raeburn  15054:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  15055:                     }
1.663     raeburn  15056:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15057:                     my $item = &escape($parent).'::0';
                   15058:                     my $checked = '';
                   15059:                     if (@currcategories > 0) {
                   15060:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15061:                             $checked = ' checked="checked"';
1.663     raeburn  15062:                         }
                   15063:                     }
1.919     raeburn  15064:                     my $parent_title = $parent;
                   15065:                     if ($parent eq 'communities') {
                   15066:                         $parent_title = &mt('Communities');
1.1239    raeburn  15067:                     } elsif ($parent eq 'placement') {
                   15068:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  15069:                     }
                   15070:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15071:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15072:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15073:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15074:                     my $depth = 1;
                   15075:                     push(@path,$parent);
1.1259    raeburn  15076:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15077:                     pop(@path);
1.919     raeburn  15078:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15079:                     $itemcount ++;
                   15080:                 }
1.919     raeburn  15081:                 if ($itemcount) {
                   15082:                     $output = &Apache::loncommon::start_data_table().
                   15083:                               $table.
                   15084:                               &Apache::loncommon::end_data_table();
                   15085:                 }
1.663     raeburn  15086:             }
                   15087:         }
                   15088:     }
                   15089:     return $output;
                   15090: }
                   15091: 
                   15092: =pod
                   15093: 
1.1162    raeburn  15094: =item * &assign_category_rows()
1.663     raeburn  15095: 
                   15096: Create a datatable row for display of nested categories in a domain,
                   15097: with checkboxes to allow a course to be categorized,called recursively.
                   15098: 
                   15099: Inputs:
                   15100: 
                   15101: itemcount - track row number for alternating colors
                   15102: 
                   15103: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15104:       categories and subcategories.
                   15105: 
                   15106: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15107: 
                   15108: parent - parent of current category item
                   15109: 
                   15110: path - Array containing all categories back up through the hierarchy from the
                   15111:        current category to the top level.
                   15112: 
                   15113: currcategories - reference to array of current categories assigned to the course
                   15114: 
1.1260    raeburn  15115: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15116:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15117: 
1.663     raeburn  15118: Returns: $output (markup to be displayed).
                   15119: 
                   15120: =cut
                   15121: 
                   15122: sub assign_category_rows {
1.1259    raeburn  15123:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15124:     my ($text,$name,$item,$chgstr);
                   15125:     if (ref($cats) eq 'ARRAY') {
                   15126:         my $maxdepth = scalar(@{$cats});
                   15127:         if (ref($cats->[$depth]) eq 'HASH') {
                   15128:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15129:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15130:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  15131:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15132:                 for (my $j=0; $j<$numchildren; $j++) {
                   15133:                     $name = $cats->[$depth]{$parent}[$j];
                   15134:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15135:                     my $deeper = $depth+1;
                   15136:                     my $checked = '';
                   15137:                     if (ref($currcategories) eq 'ARRAY') {
                   15138:                         if (@{$currcategories} > 0) {
                   15139:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15140:                                 $checked = ' checked="checked"';
1.663     raeburn  15141:                             }
                   15142:                         }
                   15143:                     }
1.664     raeburn  15144:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15145:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  15146:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15147:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15148:                              '</td><td>';
1.663     raeburn  15149:                     if (ref($path) eq 'ARRAY') {
                   15150:                         push(@{$path},$name);
1.1259    raeburn  15151:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15152:                         pop(@{$path});
                   15153:                     }
                   15154:                     $text .= '</td></tr>';
                   15155:                 }
                   15156:                 $text .= '</table></td>';
                   15157:             }
                   15158:         }
                   15159:     }
                   15160:     return $text;
                   15161: }
                   15162: 
1.1181    raeburn  15163: =pod
                   15164: 
                   15165: =back
                   15166: 
                   15167: =cut
                   15168: 
1.655     raeburn  15169: ############################################################
                   15170: ############################################################
                   15171: 
                   15172: 
1.443     albertel 15173: sub commit_customrole {
1.664     raeburn  15174:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15175:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15176:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15177:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15178:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15179:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15180:                  '</b><br />';
                   15181:     return $output;
                   15182: }
                   15183: 
                   15184: sub commit_standardrole {
1.1116    raeburn  15185:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15186:     my ($output,$logmsg,$linefeed);
                   15187:     if ($context eq 'auto') {
                   15188:         $linefeed = "\n";
                   15189:     } else {
                   15190:         $linefeed = "<br />\n";
                   15191:     }  
1.443     albertel 15192:     if ($three eq 'st') {
1.541     raeburn  15193:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  15194:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15195:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15196:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15197:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15198:         } else {
1.541     raeburn  15199:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15200:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15201:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15202:             if ($context eq 'auto') {
                   15203:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15204:             } else {
                   15205:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15206:                &mt('Add to classlist').': <b>ok</b>';
                   15207:             }
                   15208:             $output .= $linefeed;
1.443     albertel 15209:         }
                   15210:     } else {
                   15211:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15212:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15213:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15214:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15215:         if ($context eq 'auto') {
                   15216:             $output .= $result.$linefeed;
                   15217:         } else {
                   15218:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15219:         }
1.443     albertel 15220:     }
                   15221:     return $output;
                   15222: }
                   15223: 
                   15224: sub commit_studentrole {
1.1116    raeburn  15225:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15226:         $credits) = @_;
1.626     raeburn  15227:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15228:     if ($context eq 'auto') {
                   15229:         $linefeed = "\n";
                   15230:     } else {
                   15231:         $linefeed = '<br />'."\n";
                   15232:     }
1.443     albertel 15233:     if (defined($one) && defined($two)) {
                   15234:         my $cid=$one.'_'.$two;
                   15235:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15236:         my $secchange = 0;
                   15237:         my $expire_role_result;
                   15238:         my $modify_section_result;
1.628     raeburn  15239:         if ($oldsec ne '-1') { 
                   15240:             if ($oldsec ne $sec) {
1.443     albertel 15241:                 $secchange = 1;
1.628     raeburn  15242:                 my $now = time;
1.443     albertel 15243:                 my $uurl='/'.$cid;
                   15244:                 $uurl=~s/\_/\//g;
                   15245:                 if ($oldsec) {
                   15246:                     $uurl.='/'.$oldsec;
                   15247:                 }
1.626     raeburn  15248:                 $oldsecurl = $uurl;
1.628     raeburn  15249:                 $expire_role_result = 
1.652     raeburn  15250:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  15251:                 if ($env{'request.course.sec'} ne '') { 
                   15252:                     if ($expire_role_result eq 'refused') {
                   15253:                         my @roles = ('st');
                   15254:                         my @statuses = ('previous');
                   15255:                         my @roledoms = ($one);
                   15256:                         my $withsec = 1;
                   15257:                         my %roleshash = 
                   15258:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15259:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15260:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15261:                             my ($oldstart,$oldend) = 
                   15262:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15263:                             if ($oldend > 0 && $oldend <= $now) {
                   15264:                                 $expire_role_result = 'ok';
                   15265:                             }
                   15266:                         }
                   15267:                     }
                   15268:                 }
1.443     albertel 15269:                 $result = $expire_role_result;
                   15270:             }
                   15271:         }
                   15272:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  15273:             $modify_section_result = 
                   15274:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15275:                                                            undef,undef,undef,$sec,
                   15276:                                                            $end,$start,'','',$cid,
                   15277:                                                            '',$context,$credits);
1.443     albertel 15278:             if ($modify_section_result =~ /^ok/) {
                   15279:                 if ($secchange == 1) {
1.628     raeburn  15280:                     if ($sec eq '') {
                   15281:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15282:                     } else {
                   15283:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15284:                     }
1.443     albertel 15285:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15286:                     if ($sec eq '') {
                   15287:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15288:                     } else {
                   15289:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15290:                     }
1.443     albertel 15291:                 } else {
1.628     raeburn  15292:                     if ($sec eq '') {
                   15293:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15294:                     } else {
                   15295:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15296:                     }
1.443     albertel 15297:                 }
                   15298:             } else {
1.1115    raeburn  15299:                 if ($secchange) { 
1.628     raeburn  15300:                     $$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;
                   15301:                 } else {
                   15302:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15303:                 }
1.443     albertel 15304:             }
                   15305:             $result = $modify_section_result;
                   15306:         } elsif ($secchange == 1) {
1.628     raeburn  15307:             if ($oldsec eq '') {
1.1103    raeburn  15308:                 $$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  15309:             } else {
                   15310:                 $$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;
                   15311:             }
1.626     raeburn  15312:             if ($expire_role_result eq 'refused') {
                   15313:                 my $newsecurl = '/'.$cid;
                   15314:                 $newsecurl =~ s/\_/\//g;
                   15315:                 if ($sec ne '') {
                   15316:                     $newsecurl.='/'.$sec;
                   15317:                 }
                   15318:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15319:                     if ($sec eq '') {
                   15320:                         $$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;
                   15321:                     } else {
                   15322:                         $$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;
                   15323:                     }
                   15324:                 }
                   15325:             }
1.443     albertel 15326:         }
                   15327:     } else {
1.626     raeburn  15328:         $$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 15329:         $result = "error: incomplete course id\n";
                   15330:     }
                   15331:     return $result;
                   15332: }
                   15333: 
1.1108    raeburn  15334: sub show_role_extent {
                   15335:     my ($scope,$context,$role) = @_;
                   15336:     $scope =~ s{^/}{};
                   15337:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15338:     push(@courseroles,'co');
                   15339:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15340:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15341:         $scope =~ s{/}{_};
                   15342:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15343:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15344:         my ($audom,$auname) = split(/\//,$scope);
                   15345:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15346:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15347:     } else {
                   15348:         $scope =~ s{/$}{};
                   15349:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15350:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15351:     }
                   15352: }
                   15353: 
1.443     albertel 15354: ############################################################
                   15355: ############################################################
                   15356: 
1.566     albertel 15357: sub check_clone {
1.578     raeburn  15358:     my ($args,$linefeed) = @_;
1.566     albertel 15359:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15360:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15361:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   15362:     my $clonemsg;
                   15363:     my $can_clone = 0;
1.944     raeburn  15364:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15365:     if ($lctype ne 'community') {
                   15366:         $lctype = 'course';
                   15367:     }
1.566     albertel 15368:     if ($clonehome eq 'no_host') {
1.944     raeburn  15369:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15370:             $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'});
                   15371:         } else {
                   15372:             $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'});
                   15373:         }     
1.566     albertel 15374:     } else {
                   15375: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  15376:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15377:             if ($clonedesc{'type'} ne 'Community') {
1.1262    raeburn  15378:                 $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  15379:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15380:             }
                   15381:         }
1.1262    raeburn  15382: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15383:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15384: 	    $can_clone = 1;
                   15385: 	} else {
1.1221    raeburn  15386: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15387: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  15388:             if ($clonehash{'cloners'} eq '') {
                   15389:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15390:                 if ($domdefs{'canclone'}) {
                   15391:                     unless ($domdefs{'canclone'} eq 'none') {
                   15392:                         if ($domdefs{'canclone'} eq 'domain') {
                   15393:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15394:                                 $can_clone = 1;
                   15395:                             }
                   15396:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15397:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15398:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15399:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15400:                                 $can_clone = 1;
                   15401:                             }
                   15402:                         }
                   15403:                     }
                   15404:                 }
1.578     raeburn  15405:             } else {
1.1221    raeburn  15406: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15407:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15408:                     $can_clone = 1;
1.1221    raeburn  15409:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15410:                     $can_clone = 1;
1.1225    raeburn  15411:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15412:                     $can_clone = 1;
1.1221    raeburn  15413:                 }
                   15414:                 unless ($can_clone) {
1.1225    raeburn  15415:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   15416:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  15417:                         my (%gotdomdefaults,%gotcodedefaults);
                   15418:                         foreach my $cloner (@cloners) {
                   15419:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15420:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15421:                                 my (%codedefaults,@code_order);
                   15422:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15423:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15424:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15425:                                     }
                   15426:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15427:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15428:                                     }
                   15429:                                 } else {
                   15430:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15431:                                                                             \%codedefaults,
                   15432:                                                                             \@code_order);
                   15433:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15434:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15435:                                 }
                   15436:                                 if (@code_order > 0) {
                   15437:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15438:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15439:                                                                                 $args->{'crscode'})) {
                   15440:                                         $can_clone = 1;
                   15441:                                         last;
                   15442:                                     }
                   15443:                                 }
                   15444:                             }
                   15445:                         }
                   15446:                     }
1.1225    raeburn  15447:                 }
                   15448:             }
                   15449:             unless ($can_clone) {
                   15450:                 my $ccrole = 'cc';
                   15451:                 if ($args->{'crstype'} eq 'Community') {
                   15452:                     $ccrole = 'co';
                   15453:                 }
                   15454: 	        my %roleshash =
                   15455: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15456: 					          $args->{'ccdomain'},
                   15457:                                                   'userroles',['active'],[$ccrole],
                   15458: 					          [$args->{'clonedomain'}]);
                   15459: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15460:                     $can_clone = 1;
                   15461:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15462:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15463:                     $can_clone = 1;
1.1221    raeburn  15464:                 }
                   15465:             }
                   15466:             unless ($can_clone) {
                   15467:                 if ($args->{'crstype'} eq 'Community') {
                   15468:                     $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  15469:                 } else {
1.1221    raeburn  15470:                     $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'});
                   15471:                 }
1.566     albertel 15472: 	    }
1.578     raeburn  15473:         }
1.566     albertel 15474:     }
                   15475:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15476: }
                   15477: 
1.444     albertel 15478: sub construct_course {
1.1262    raeburn  15479:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   15480:         $cnum,$category,$coderef) = @_;
1.444     albertel 15481:     my $outcome;
1.541     raeburn  15482:     my $linefeed =  '<br />'."\n";
                   15483:     if ($context eq 'auto') {
                   15484:         $linefeed = "\n";
                   15485:     }
1.566     albertel 15486: 
                   15487: #
                   15488: # Are we cloning?
                   15489: #
                   15490:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   15491:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  15492: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 15493: 	if ($context ne 'auto') {
1.578     raeburn  15494:             if ($clonemsg ne '') {
                   15495: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   15496:             }
1.566     albertel 15497: 	}
                   15498: 	$outcome .= $clonemsg.$linefeed;
                   15499: 
                   15500:         if (!$can_clone) {
                   15501: 	    return (0,$outcome);
                   15502: 	}
                   15503:     }
                   15504: 
1.444     albertel 15505: #
                   15506: # Open course
                   15507: #
1.1239    raeburn  15508:     my $showncrstype;
                   15509:     if ($args->{'crstype'} eq 'Placement') {
                   15510:         $showncrstype = 'placement test'; 
                   15511:     } else {  
                   15512:         $showncrstype = lc($args->{'crstype'});
                   15513:     }
1.444     albertel 15514:     my %cenv=();
                   15515:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   15516:                                              $args->{'cdescr'},
                   15517:                                              $args->{'curl'},
                   15518:                                              $args->{'course_home'},
                   15519:                                              $args->{'nonstandard'},
                   15520:                                              $args->{'crscode'},
                   15521:                                              $args->{'ccuname'}.':'.
                   15522:                                              $args->{'ccdomain'},
1.882     raeburn  15523:                                              $args->{'crstype'},
1.885     raeburn  15524:                                              $cnum,$context,$category);
1.444     albertel 15525: 
                   15526:     # Note: The testing routines depend on this being output; see 
                   15527:     # Utils::Course. This needs to at least be output as a comment
                   15528:     # if anyone ever decides to not show this, and Utils::Course::new
                   15529:     # will need to be suitably modified.
1.1239    raeburn  15530:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
1.943     raeburn  15531:     if ($$courseid =~ /^error:/) {
                   15532:         return (0,$outcome);
                   15533:     }
                   15534: 
1.444     albertel 15535: #
                   15536: # Check if created correctly
                   15537: #
1.479     albertel 15538:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 15539:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  15540:     if ($crsuhome eq 'no_host') {
                   15541:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   15542:         return (0,$outcome);
                   15543:     }
1.541     raeburn  15544:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 15545: 
1.444     albertel 15546: #
1.566     albertel 15547: # Do the cloning
                   15548: #   
                   15549:     if ($can_clone && $cloneid) {
1.1239    raeburn  15550: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
1.566     albertel 15551: 	if ($context ne 'auto') {
                   15552: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15553: 	}
                   15554: 	$outcome .= $clonemsg.$linefeed;
                   15555: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15556: # Copy all files
1.637     www      15557: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15558: # Restore URL
1.566     albertel 15559: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15560: # Restore title
1.566     albertel 15561: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15562: # Restore creation date, creator and creation context.
                   15563:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15564:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15565:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15566: # Mark as cloned
1.566     albertel 15567: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15568: # Need to clone grading mode
                   15569:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15570:         $cenv{'grading'}=$newenv{'grading'};
                   15571: # Do not clone these environment entries
                   15572:         &Apache::lonnet::del('environment',
                   15573:                   ['default_enrollment_start_date',
                   15574:                    'default_enrollment_end_date',
                   15575:                    'question.email',
                   15576:                    'policy.email',
                   15577:                    'comment.email',
                   15578:                    'pch.users.denied',
1.725     raeburn  15579:                    'plc.users.denied',
                   15580:                    'hidefromcat',
1.1121    raeburn  15581:                    'checkforpriv',
1.1166    raeburn  15582:                    'categories',
                   15583:                    'internal.uniquecode'],
1.638     www      15584:                    $$crsudom,$$crsunum);
1.1170    raeburn  15585:         if ($args->{'textbook'}) {
                   15586:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15587:         }
1.444     albertel 15588:     }
1.566     albertel 15589: 
1.444     albertel 15590: #
                   15591: # Set environment (will override cloned, if existing)
                   15592: #
                   15593:     my @sections = ();
                   15594:     my @xlists = ();
                   15595:     if ($args->{'crstype'}) {
                   15596:         $cenv{'type'}=$args->{'crstype'};
                   15597:     }
                   15598:     if ($args->{'crsid'}) {
                   15599:         $cenv{'courseid'}=$args->{'crsid'};
                   15600:     }
                   15601:     if ($args->{'crscode'}) {
                   15602:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15603:     }
                   15604:     if ($args->{'crsquota'} ne '') {
                   15605:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15606:     } else {
                   15607:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15608:     }
                   15609:     if ($args->{'ccuname'}) {
                   15610:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15611:                                         ':'.$args->{'ccdomain'};
                   15612:     } else {
                   15613:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15614:     }
1.1116    raeburn  15615:     if ($args->{'defaultcredits'}) {
                   15616:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15617:     }
1.444     albertel 15618:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15619:     if ($args->{'crssections'}) {
                   15620:         $cenv{'internal.sectionnums'} = '';
                   15621:         if ($args->{'crssections'} =~ m/,/) {
                   15622:             @sections = split/,/,$args->{'crssections'};
                   15623:         } else {
                   15624:             $sections[0] = $args->{'crssections'};
                   15625:         }
                   15626:         if (@sections > 0) {
                   15627:             foreach my $item (@sections) {
                   15628:                 my ($sec,$gp) = split/:/,$item;
                   15629:                 my $class = $args->{'crscode'}.$sec;
                   15630:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15631:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15632:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15633:                     push(@badclasses,$class);
1.444     albertel 15634:                 }
                   15635:             }
                   15636:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15637:         }
                   15638:     }
                   15639: # do not hide course coordinator from staff listing, 
                   15640: # even if privileged
                   15641:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  15642: # add course coordinator's domain to domains to check for privileged users
                   15643: # if different to course domain
                   15644:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15645:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15646:     }
1.444     albertel 15647: # add crosslistings
                   15648:     if ($args->{'crsxlist'}) {
                   15649:         $cenv{'internal.crosslistings'}='';
                   15650:         if ($args->{'crsxlist'} =~ m/,/) {
                   15651:             @xlists = split/,/,$args->{'crsxlist'};
                   15652:         } else {
                   15653:             $xlists[0] = $args->{'crsxlist'};
                   15654:         }
                   15655:         if (@xlists > 0) {
                   15656:             foreach my $item (@xlists) {
                   15657:                 my ($xl,$gp) = split/:/,$item;
                   15658:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15659:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15660:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  15661:                     push(@badclasses,$xl);
1.444     albertel 15662:                 }
                   15663:             }
                   15664:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15665:         }
                   15666:     }
                   15667:     if ($args->{'autoadds'}) {
                   15668:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15669:     }
                   15670:     if ($args->{'autodrops'}) {
                   15671:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15672:     }
                   15673: # check for notification of enrollment changes
                   15674:     my @notified = ();
                   15675:     if ($args->{'notify_owner'}) {
                   15676:         if ($args->{'ccuname'} ne '') {
                   15677:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15678:         }
                   15679:     }
                   15680:     if ($args->{'notify_dc'}) {
                   15681:         if ($uname ne '') { 
1.630     raeburn  15682:             push(@notified,$uname.':'.$udom);
1.444     albertel 15683:         }
                   15684:     }
                   15685:     if (@notified > 0) {
                   15686:         my $notifylist;
                   15687:         if (@notified > 1) {
                   15688:             $notifylist = join(',',@notified);
                   15689:         } else {
                   15690:             $notifylist = $notified[0];
                   15691:         }
                   15692:         $cenv{'internal.notifylist'} = $notifylist;
                   15693:     }
                   15694:     if (@badclasses > 0) {
                   15695:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  15696:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15697:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15698:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15699:         );
1.1264    raeburn  15700:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15701:                            &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  15702:         if ($context eq 'auto') {
                   15703:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  15704:         } else {
1.566     albertel 15705:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  15706:         }
                   15707:         foreach my $item (@badclasses) {
1.541     raeburn  15708:             if ($context eq 'auto') {
1.1261    raeburn  15709:                 $outcome .= " - $item\n";
1.541     raeburn  15710:             } else {
1.1261    raeburn  15711:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15712:             }
1.1261    raeburn  15713:         }
                   15714:         if ($context eq 'auto') {
                   15715:             $outcome .= $linefeed;
                   15716:         } else {
                   15717:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  15718:         } 
1.444     albertel 15719:     }
                   15720:     if ($args->{'no_end_date'}) {
                   15721:         $args->{'endaccess'} = 0;
                   15722:     }
                   15723:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15724:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15725:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15726:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15727:     if ($args->{'showphotos'}) {
                   15728:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15729:     }
                   15730:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15731:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15732:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15733:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15734:             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'); 
                   15735:             if ($context eq 'auto') {
                   15736:                 $outcome .= $krb_msg;
                   15737:             } else {
1.566     albertel 15738:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15739:             }
                   15740:             $outcome .= $linefeed;
1.444     albertel 15741:         }
                   15742:     }
                   15743:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15744:        if ($args->{'setpolicy'}) {
                   15745:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15746:        }
                   15747:        if ($args->{'setcontent'}) {
                   15748:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15749:        }
1.1251    raeburn  15750:        if ($args->{'setcomment'}) {
                   15751:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15752:        }
1.444     albertel 15753:     }
                   15754:     if ($args->{'reshome'}) {
                   15755: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15756: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15757:     }
                   15758: #
                   15759: # course has keyed access
                   15760: #
                   15761:     if ($args->{'setkeys'}) {
                   15762:        $cenv{'keyaccess'}='yes';
                   15763:     }
                   15764: # if specified, key authority is not course, but user
                   15765: # only active if keyaccess is yes
                   15766:     if ($args->{'keyauth'}) {
1.487     albertel 15767: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15768: 	$user = &LONCAPA::clean_username($user);
                   15769: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15770: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15771: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15772: 	}
                   15773:     }
                   15774: 
1.1166    raeburn  15775: #
1.1167    raeburn  15776: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  15777: #
                   15778:     if ($args->{'uniquecode'}) {
                   15779:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15780:         if ($code) {
                   15781:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  15782:             my %crsinfo =
                   15783:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15784:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15785:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15786:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15787:             } 
1.1166    raeburn  15788:             if (ref($coderef)) {
                   15789:                 $$coderef = $code;
                   15790:             }
                   15791:         }
                   15792:     }
                   15793: 
1.444     albertel 15794:     if ($args->{'disresdis'}) {
                   15795:         $cenv{'pch.roles.denied'}='st';
                   15796:     }
                   15797:     if ($args->{'disablechat'}) {
                   15798:         $cenv{'plc.roles.denied'}='st';
                   15799:     }
                   15800: 
                   15801:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15802:     # course
                   15803:     $cenv{'course.helper.not.run'} = 1;
                   15804:     #
                   15805:     # Use new Randomseed
                   15806:     #
                   15807:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15808:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15809:     #
                   15810:     # The encryption code and receipt prefix for this course
                   15811:     #
                   15812:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15813:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15814:     #
                   15815:     # By default, use standard grading
                   15816:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15817: 
1.541     raeburn  15818:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15819:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15820: #
                   15821: # Open all assignments
                   15822: #
                   15823:     if ($args->{'openall'}) {
                   15824:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15825:        my %storecontent = ($storeunder         => time,
                   15826:                            $storeunder.'.type' => 'date_start');
                   15827:        
                   15828:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15829:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15830:    }
                   15831: #
                   15832: # Set first page
                   15833: #
                   15834:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15835: 	    || ($cloneid)) {
1.445     albertel 15836: 	use LONCAPA::map;
1.444     albertel 15837: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15838: 
                   15839: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15840:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15841: 
1.444     albertel 15842:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15843:         my $title; my $url;
                   15844:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15845: 	    $title=&mt('Syllabus');
1.444     albertel 15846:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15847:         } else {
1.963     raeburn  15848:             $title=&mt('Table of Contents');
1.444     albertel 15849:             $url='/adm/navmaps';
                   15850:         }
1.445     albertel 15851: 
                   15852:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15853: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15854: 
                   15855: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15856:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15857:     }
1.566     albertel 15858: 
1.1237    raeburn  15859: # 
                   15860: # Set params for Placement Tests
                   15861: #
1.1239    raeburn  15862:     if ($args->{'crstype'} eq 'Placement') {
                   15863:        my %storecontent; 
                   15864:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   15865:        my %defaults = (
                   15866:                         buttonshide   => { value => 'yes',
                   15867:                                            type => 'string_yesno',},
                   15868:                         type          => { value => 'randomizetry',
                   15869:                                            type  => 'string_questiontype',},
                   15870:                         maxtries      => { value => 1,
                   15871:                                            type => 'int_pos',},
                   15872:                         problemstatus => { value => 'no',
                   15873:                                            type  => 'string_problemstatus',},
                   15874:                       );
                   15875:        foreach my $key (keys(%defaults)) {
                   15876:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   15877:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   15878:        }
1.1237    raeburn  15879:        &Apache::lonnet::cput
                   15880:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   15881:     }
                   15882: 
1.566     albertel 15883:     return (1,$outcome);
1.444     albertel 15884: }
                   15885: 
1.1166    raeburn  15886: sub make_unique_code {
                   15887:     my ($cdom,$cnum) = @_;
                   15888:     # get lock on uniquecodes db
                   15889:     my $lockhash = {
                   15890:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15891:                                                   ':'.$env{'user.domain'},
                   15892:                    };
                   15893:     my $tries = 0;
                   15894:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15895:     my ($code,$error);
                   15896:   
                   15897:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15898:         $tries ++;
                   15899:         sleep 1;
                   15900:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15901:     }
                   15902:     if ($gotlock eq 'ok') {
                   15903:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15904:         my $gotcode;
                   15905:         my $attempts = 0;
                   15906:         while ((!$gotcode) && ($attempts < 100)) {
                   15907:             $code = &generate_code();
                   15908:             if (!exists($currcodes{$code})) {
                   15909:                 $gotcode = 1;
                   15910:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15911:                     $error = 'nostore';
                   15912:                 }
                   15913:             }
                   15914:             $attempts ++;
                   15915:         }
                   15916:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15917:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15918:     } else {
                   15919:         $error = 'nolock';
                   15920:     }
                   15921:     return ($code,$error);
                   15922: }
                   15923: 
                   15924: sub generate_code {
                   15925:     my $code;
                   15926:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15927:     for (my $i=0; $i<6; $i++) {
                   15928:         my $lettnum = int (rand 2);
                   15929:         my $item = '';
                   15930:         if ($lettnum) {
                   15931:             $item = $letts[int( rand(18) )];
                   15932:         } else {
                   15933:             $item = 1+int( rand(8) );
                   15934:         }
                   15935:         $code .= $item;
                   15936:     }
                   15937:     return $code;
                   15938: }
                   15939: 
1.444     albertel 15940: ############################################################
                   15941: ############################################################
                   15942: 
1.1237    raeburn  15943: # Community, Course and Placement Test
1.378     raeburn  15944: sub course_type {
                   15945:     my ($cid) = @_;
                   15946:     if (!defined($cid)) {
                   15947:         $cid = $env{'request.course.id'};
                   15948:     }
1.404     albertel 15949:     if (defined($env{'course.'.$cid.'.type'})) {
                   15950:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15951:     } else {
                   15952:         return 'Course';
1.377     raeburn  15953:     }
                   15954: }
1.156     albertel 15955: 
1.406     raeburn  15956: sub group_term {
                   15957:     my $crstype = &course_type();
                   15958:     my %names = (
                   15959:                   'Course' => 'group',
1.865     raeburn  15960:                   'Community' => 'group',
1.1237    raeburn  15961:                   'Placement' => 'group',
1.406     raeburn  15962:                 );
                   15963:     return $names{$crstype};
                   15964: }
                   15965: 
1.902     raeburn  15966: sub course_types {
1.1237    raeburn  15967:     my @types = ('official','unofficial','community','textbook','placement');
1.902     raeburn  15968:     my %typename = (
                   15969:                          official   => 'Official course',
                   15970:                          unofficial => 'Unofficial course',
                   15971:                          community  => 'Community',
1.1165    raeburn  15972:                          textbook   => 'Textbook course',
1.1237    raeburn  15973:                          placement  => 'Placement test',
1.902     raeburn  15974:                    );
                   15975:     return (\@types,\%typename);
                   15976: }
                   15977: 
1.156     albertel 15978: sub icon {
                   15979:     my ($file)=@_;
1.505     albertel 15980:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15981:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15982:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15983:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15984: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15985: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15986: 	            $curfext.".gif") {
                   15987: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15988: 		$curfext.".gif";
                   15989: 	}
                   15990:     }
1.249     albertel 15991:     return &lonhttpdurl($iconname);
1.154     albertel 15992: } 
1.84      albertel 15993: 
1.575     albertel 15994: sub lonhttpdurl {
1.692     www      15995: #
                   15996: # Had been used for "small fry" static images on separate port 8080.
                   15997: # Modify here if lightweight http functionality desired again.
                   15998: # Currently eliminated due to increasing firewall issues.
                   15999: #
1.575     albertel 16000:     my ($url)=@_;
1.692     www      16001:     return $url;
1.215     albertel 16002: }
                   16003: 
1.213     albertel 16004: sub connection_aborted {
                   16005:     my ($r)=@_;
                   16006:     $r->print(" ");$r->rflush();
                   16007:     my $c = $r->connection;
                   16008:     return $c->aborted();
                   16009: }
                   16010: 
1.221     foxr     16011: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16012: #    strings as 'strings'.
                   16013: sub escape_single {
1.221     foxr     16014:     my ($input) = @_;
1.223     albertel 16015:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16016:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16017:     return $input;
                   16018: }
1.223     albertel 16019: 
1.222     foxr     16020: #  Same as escape_single, but escape's "'s  This 
                   16021: #  can be used for  "strings"
                   16022: sub escape_double {
                   16023:     my ($input) = @_;
                   16024:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16025:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16026:     return $input;
                   16027: }
1.223     albertel 16028:  
1.222     foxr     16029: #   Escapes the last element of a full URL.
                   16030: sub escape_url {
                   16031:     my ($url)   = @_;
1.238     raeburn  16032:     my @urlslices = split(/\//, $url,-1);
1.369     www      16033:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  16034:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16035: }
1.462     albertel 16036: 
1.820     raeburn  16037: sub compare_arrays {
                   16038:     my ($arrayref1,$arrayref2) = @_;
                   16039:     my (@difference,%count);
                   16040:     @difference = ();
                   16041:     %count = ();
                   16042:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16043:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16044:         foreach my $element (keys(%count)) {
                   16045:             if ($count{$element} == 1) {
                   16046:                 push(@difference,$element);
                   16047:             }
                   16048:         }
                   16049:     }
                   16050:     return @difference;
                   16051: }
                   16052: 
1.817     bisitz   16053: # -------------------------------------------------------- Initialize user login
1.462     albertel 16054: sub init_user_environment {
1.463     albertel 16055:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16056:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16057: 
                   16058:     my $public=($username eq 'public' && $domain eq 'public');
                   16059: 
1.1062    raeburn  16060:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16061:     my $now=time;
                   16062: 
                   16063:     if ($public) {
                   16064: 	my $max_public=100;
                   16065: 	my $oldest;
                   16066: 	my $oldest_time=0;
                   16067: 	for(my $next=1;$next<=$max_public;$next++) {
                   16068: 	    if (-e $lonids."/publicuser_$next.id") {
                   16069: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16070: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16071: 		    $oldest_time=$mtime;
                   16072: 		    $oldest=$next;
                   16073: 		}
                   16074: 	    } else {
                   16075: 		$cookie="publicuser_$next";
                   16076: 		last;
                   16077: 	    }
                   16078: 	}
                   16079: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16080:     } else {
1.1275    raeburn  16081: 	# See if old ID present, if so, remove if this isn't a robot,
                   16082: 	# killing any existing non-robot sessions
1.463     albertel 16083: 	if (!$args->{'robot'}) {
                   16084: 	    opendir(DIR,$lonids);
                   16085: 	    while ($filename=readdir(DIR)) {
                   16086: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   16087: 		    unlink($lonids.'/'.$filename);
                   16088: 		}
1.462     albertel 16089: 	    }
1.463     albertel 16090: 	    closedir(DIR);
1.1204    raeburn  16091: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16092:             my $namespace = 'nohist_courseeditor';
                   16093:             my $lockingkey = 'paste'."\0".'locked_num';
                   16094:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16095:                                                 $domain,$username);
                   16096:             if (exists($lockhash{$lockingkey})) {
                   16097:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16098:                 unless ($delresult eq 'ok') {
                   16099:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16100:                 }
                   16101:             }
1.462     albertel 16102: 	}
                   16103: # Give them a new cookie
1.463     albertel 16104: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16105: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16106: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16107:     
                   16108: # Initialize roles
                   16109: 
1.1062    raeburn  16110: 	($userroles,$firstaccenv,$timerintenv) = 
                   16111:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16112:     }
                   16113: # ------------------------------------ Check browser type and MathML capability
                   16114: 
1.1194    raeburn  16115:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16116:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16117: 
                   16118: # ------------------------------------------------------------- Get environment
                   16119: 
                   16120:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16121:     my ($tmp) = keys(%userenv);
1.1275    raeburn  16122:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 16123: 	undef(%userenv);
                   16124:     }
                   16125:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16126: 	$form->{'interface'}=$userenv{'interface'};
                   16127:     }
                   16128:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16129: 
                   16130: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16131:     foreach my $option ('interface','localpath','localres') {
                   16132:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16133:     }
                   16134: # --------------------------------------------------------- Write first profile
                   16135: 
                   16136:     {
                   16137: 	my %initial_env = 
                   16138: 	    ("user.name"          => $username,
                   16139: 	     "user.domain"        => $domain,
                   16140: 	     "user.home"          => $authhost,
                   16141: 	     "browser.type"       => $clientbrowser,
                   16142: 	     "browser.version"    => $clientversion,
                   16143: 	     "browser.mathml"     => $clientmathml,
                   16144: 	     "browser.unicode"    => $clientunicode,
                   16145: 	     "browser.os"         => $clientos,
1.1137    raeburn  16146:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  16147:              "browser.info"       => $clientinfo,
1.1194    raeburn  16148:              "browser.osversion"  => $clientosversion,
1.462     albertel 16149: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16150: 	     "request.course.fn"  => '',
                   16151: 	     "request.course.uri" => '',
                   16152: 	     "request.course.sec" => '',
                   16153: 	     "request.role"       => 'cm',
                   16154: 	     "request.role.adv"   => $env{'user.adv'},
                   16155: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   16156: 
                   16157:         if ($form->{'localpath'}) {
                   16158: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16159: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16160:         }
                   16161: 	
                   16162: 	if ($form->{'interface'}) {
                   16163: 	    $form->{'interface'}=~s/\W//gs;
                   16164: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16165: 	    $env{'browser.interface'}=$form->{'interface'};
                   16166: 	}
                   16167: 
1.1157    raeburn  16168:         if ($form->{'iptoken'}) {
                   16169:             my $lonhost = $r->dir_config('lonHostID');
                   16170:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16171:             $env{'user.noloadbalance'} = $lonhost;
                   16172:         }
                   16173: 
1.1268    raeburn  16174:         if ($form->{'noloadbalance'}) {
                   16175:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16176:             my $hosthere = $form->{'noloadbalance'};
                   16177:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16178:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16179:                 $env{'user.noloadbalance'} = $hosthere;
                   16180:             }
                   16181:         }
                   16182: 
1.1016    raeburn  16183:         unless ($domain eq 'public') {
1.1273    raeburn  16184:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16185:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   16186: 
                   16187:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   16188:                 $userenv{'availabletools.'.$tool} = 
                   16189:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16190:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16191:             }
1.980     raeburn  16192: 
1.1273    raeburn  16193:             foreach my $crstype ('official','unofficial','community','textbook','placement') {
                   16194:                 $userenv{'canrequest.'.$crstype} =
                   16195:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16196:                                                       'reload','requestcourses',
                   16197:                                                       \%userenv,\%domdef,\%is_adv);
                   16198:             }
1.724     raeburn  16199: 
1.1273    raeburn  16200:             $userenv{'canrequest.author'} =
                   16201:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16202:                                                   'reload','requestauthor',
1.980     raeburn  16203:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  16204:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16205:                                                  $domain,$username);
                   16206:             my $reqstatus = $reqauthor{'author_status'};
                   16207:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   16208:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16209:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16210:                                                       $reqauthor{'author'}{'timestamp'};
                   16211:                 }
1.1092    raeburn  16212:             }
1.1287  ! raeburn  16213:             my ($types,$typename) = &course_types();
        !          16214:             if (ref($types) eq 'ARRAY') {
        !          16215:                 my @options = ('approval','validate','autolimit');
        !          16216:                 my $optregex = join('|',@options);
        !          16217:                 my (%willtrust,%trustchecked);
        !          16218:                 foreach my $type (@{$types}) {
        !          16219:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
        !          16220:                     if ($dom_str ne '') {
        !          16221:                         my $updatedstr = '';
        !          16222:                         my @possdomains = split(',',$dom_str);
        !          16223:                         foreach my $entry (@possdomains) {
        !          16224:                             my ($extdom,$extopt) = split(':',$entry);
        !          16225:                             unless ($trustchecked{$extdom}) {
        !          16226:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
        !          16227:                                 $trustchecked{$extdom} = 1;
        !          16228:                             }
        !          16229:                             if ($willtrust{$extdom}) {
        !          16230:                                 $updatedstr .= $entry.',';
        !          16231:                             }
        !          16232:                         }
        !          16233:                         $updatedstr =~ s/,$//;
        !          16234:                         if ($updatedstr) {
        !          16235:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
        !          16236:                         } else {
        !          16237:                             delete($userenv{'reqcrsotherdom.'.$type});
        !          16238:                         }
        !          16239:                     }
        !          16240:                 }
        !          16241:             }
1.1092    raeburn  16242:         }
1.462     albertel 16243: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16244: 
1.462     albertel 16245: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16246: 		 &GDBM_WRCREAT(),0640)) {
                   16247: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16248: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16249: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16250:             if (ref($firstaccenv) eq 'HASH') {
                   16251:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16252:             }
                   16253:             if (ref($timerintenv) eq 'HASH') {
                   16254:                 &_add_to_env(\%disk_env,$timerintenv);
                   16255:             }
1.463     albertel 16256: 	    if (ref($args->{'extra_env'})) {
                   16257: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16258: 	    }
1.462     albertel 16259: 	    untie(%disk_env);
                   16260: 	} else {
1.705     tempelho 16261: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16262: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16263: 	    return 'error: '.$!;
                   16264: 	}
                   16265:     }
                   16266:     $env{'request.role'}='cm';
                   16267:     $env{'request.role.adv'}=$env{'user.adv'};
                   16268:     $env{'browser.type'}=$clientbrowser;
                   16269: 
                   16270:     return $cookie;
                   16271: 
                   16272: }
                   16273: 
                   16274: sub _add_to_env {
                   16275:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16276:     if (ref($env_data) eq 'HASH') {
                   16277:         while (my ($key,$value) = each(%$env_data)) {
                   16278: 	    $idf->{$prefix.$key} = $value;
                   16279: 	    $env{$prefix.$key}   = $value;
                   16280:         }
1.462     albertel 16281:     }
                   16282: }
                   16283: 
1.685     tempelho 16284: # --- Get the symbolic name of a problem and the url
                   16285: sub get_symb {
                   16286:     my ($request,$silent) = @_;
1.726     raeburn  16287:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16288:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16289:     if ($symb eq '') {
                   16290:         if (!$silent) {
1.1071    raeburn  16291:             if (ref($request)) { 
                   16292:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16293:             }
1.685     tempelho 16294:             return ();
                   16295:         }
                   16296:     }
                   16297:     &Apache::lonenc::check_decrypt(\$symb);
                   16298:     return ($symb);
                   16299: }
                   16300: 
                   16301: # --------------------------------------------------------------Get annotation
                   16302: 
                   16303: sub get_annotation {
                   16304:     my ($symb,$enc) = @_;
                   16305: 
                   16306:     my $key = $symb;
                   16307:     if (!$enc) {
                   16308:         $key =
                   16309:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16310:     }
                   16311:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16312:     return $annotation{$key};
                   16313: }
                   16314: 
                   16315: sub clean_symb {
1.731     raeburn  16316:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16317: 
                   16318:     &Apache::lonenc::check_decrypt(\$symb);
                   16319:     my $enc = $env{'request.enc'};
1.731     raeburn  16320:     if ($delete_enc) {
1.730     raeburn  16321:         delete($env{'request.enc'});
                   16322:     }
1.685     tempelho 16323: 
                   16324:     return ($symb,$enc);
                   16325: }
1.462     albertel 16326: 
1.1181    raeburn  16327: ############################################################
                   16328: ############################################################
                   16329: 
                   16330: =pod
                   16331: 
                   16332: =head1 Routines for building display used to search for courses
                   16333: 
                   16334: 
                   16335: =over 4
                   16336: 
                   16337: =item * &build_filters()
                   16338: 
                   16339: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  16340: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16341: and quotacheck.pl
                   16342: 
1.1181    raeburn  16343: 
                   16344: Inputs:
                   16345: 
                   16346: filterlist - anonymous array of fields to include as potential filters 
                   16347: 
                   16348: crstype - course type
                   16349: 
                   16350: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16351:               to pop-open a course selector (will contain "extra element"). 
                   16352: 
                   16353: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16354: 
                   16355: filter - anonymous hash of criteria and their values
                   16356: 
                   16357: action - form action
                   16358: 
                   16359: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16360: 
1.1182    raeburn  16361: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  16362: 
                   16363: cloneruname - username of owner of new course who wants to clone
                   16364: 
                   16365: clonerudom - domain of owner of new course who wants to clone
                   16366: 
                   16367: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   16368: 
                   16369: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16370: 
                   16371: codedom - domain
                   16372: 
                   16373: formname - value of form element named "form". 
                   16374: 
                   16375: fixeddom - domain, if fixed.
                   16376: 
                   16377: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   16378: 
                   16379: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   16380: 
                   16381: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16382: 
                   16383: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16384: 
                   16385: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16386: 
                   16387: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16388: 
                   16389: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16390: 
1.1182    raeburn  16391: 
1.1181    raeburn  16392: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16393: 
1.1182    raeburn  16394: 
1.1181    raeburn  16395: Side Effects: None
                   16396: 
                   16397: =cut
                   16398: 
                   16399: # ---------------------------------------------- search for courses based on last activity etc.
                   16400: 
                   16401: sub build_filters {
                   16402:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16403:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16404:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16405:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16406:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  16407:     my ($list,$jscript);
1.1181    raeburn  16408:     my $onchange = 'javascript:updateFilters(this)';
                   16409:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16410:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16411:         $typeselectform,$instcodetitle);
                   16412:     if ($formname eq '') {
                   16413:         $formname = $caller;
                   16414:     }
                   16415:     foreach my $item (@{$filterlist}) {
                   16416:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16417:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16418:             if ($item eq 'domainfilter') {
                   16419:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16420:             } elsif ($item eq 'coursefilter') {
                   16421:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16422:             } elsif ($item eq 'ownerfilter') {
                   16423:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16424:             } elsif ($item eq 'ownerdomfilter') {
                   16425:                 $filter->{'ownerdomfilter'} =
                   16426:                     &LONCAPA::clean_domain($filter->{$item});
                   16427:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16428:                                                        'ownerdomfilter',1);
                   16429:             } elsif ($item eq 'personfilter') {
                   16430:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16431:             } elsif ($item eq 'persondomfilter') {
                   16432:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16433:                                                         'persondomfilter',1);
                   16434:             } else {
                   16435:                 $filter->{$item} =~ s/\W//g;
                   16436:             }
                   16437:             if (!$filter->{$item}) {
                   16438:                 $filter->{$item} = '';
                   16439:             }
                   16440:         }
                   16441:         if ($item eq 'domainfilter') {
                   16442:             my $allow_blank = 1;
                   16443:             if ($formname eq 'portform') {
                   16444:                 $allow_blank=0;
                   16445:             } elsif ($formname eq 'studentform') {
                   16446:                 $allow_blank=0;
                   16447:             }
                   16448:             if ($fixeddom) {
                   16449:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16450:                                     ' value="'.$codedom.'" />'.
                   16451:                                     &Apache::lonnet::domain($codedom,'description');
                   16452:             } else {
                   16453:                 $domainselectform = &select_dom_form($filter->{$item},
                   16454:                                                      'domainfilter',
                   16455:                                                       $allow_blank,'',$onchange);
                   16456:             }
                   16457:         } else {
                   16458:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16459:         }
                   16460:     }
                   16461: 
                   16462:     # last course activity filter and selection
                   16463:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   16464: 
                   16465:     # course created filter and selection
                   16466:     if (exists($filter->{'createdfilter'})) {
                   16467:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   16468:     }
                   16469: 
1.1239    raeburn  16470:     my $prefix = $crstype;
                   16471:     if ($crstype eq 'Placement') {
                   16472:         $prefix = 'Placement Test'
                   16473:     }
1.1181    raeburn  16474:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  16475:                 'cac' => "$prefix Activity",
                   16476:                 'ccr' => "$prefix Created",
                   16477:                 'cde' => "$prefix Title",
                   16478:                 'cdo' => "$prefix Domain",
1.1181    raeburn  16479:                 'ins' => 'Institutional Code',
                   16480:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  16481:                 'cow' => "$prefix Owner/Co-owner",
                   16482:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  16483:                 'cog' => 'Type',
                   16484:              );
                   16485: 
                   16486:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16487:         my $typeval = 'Course';
                   16488:         if ($crstype eq 'Community') {
                   16489:             $typeval = 'Community';
1.1239    raeburn  16490:         } elsif ($crstype eq 'Placement') {
                   16491:             $typeval = 'Placement';
1.1181    raeburn  16492:         }
                   16493:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   16494:     } else {
                   16495:         $typeselectform =  '<select name="type" size="1"';
                   16496:         if ($onchange) {
                   16497:             $typeselectform .= ' onchange="'.$onchange.'"';
                   16498:         }
                   16499:         $typeselectform .= '>'."\n";
1.1237    raeburn  16500:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  16501:             my $shown;
                   16502:             if ($posstype eq 'Placement') {
                   16503:                 $shown = &mt('Placement Test');
                   16504:             } else {
                   16505:                 $shown = &mt($posstype);
                   16506:             }
1.1181    raeburn  16507:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  16508:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  16509:         }
                   16510:         $typeselectform.="</select>";
                   16511:     }
                   16512: 
                   16513:     my ($cloneableonlyform,$cloneabletitle);
                   16514:     if (exists($filter->{'cloneableonly'})) {
                   16515:         my $cloneableon = '';
                   16516:         my $cloneableoff = ' checked="checked"';
                   16517:         if ($filter->{'cloneableonly'}) {
                   16518:             $cloneableon = $cloneableoff;
                   16519:             $cloneableoff = '';
                   16520:         }
                   16521:         $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>';
                   16522:         if ($formname eq 'ccrs') {
1.1187    bisitz   16523:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  16524:         } else {
                   16525:             $cloneabletitle = &mt('Cloneable by you');
                   16526:         }
                   16527:     }
                   16528:     my $officialjs;
                   16529:     if ($crstype eq 'Course') {
                   16530:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  16531: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   16532: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   16533:             if ($codedom) { 
1.1181    raeburn  16534:                 $officialjs = 1;
                   16535:                 ($instcodeform,$jscript,$$numtitlesref) =
                   16536:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   16537:                                                                   $officialjs,$codetitlesref);
                   16538:                 if ($jscript) {
1.1182    raeburn  16539:                     $jscript = '<script type="text/javascript">'."\n".
                   16540:                                '// <![CDATA['."\n".
                   16541:                                $jscript."\n".
                   16542:                                '// ]]>'."\n".
                   16543:                                '</script>'."\n";
1.1181    raeburn  16544:                 }
                   16545:             }
                   16546:             if ($instcodeform eq '') {
                   16547:                 $instcodeform =
                   16548:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   16549:                     $list->{'instcodefilter'}.'" />';
                   16550:                 $instcodetitle = $lt{'ins'};
                   16551:             } else {
                   16552:                 $instcodetitle = $lt{'inc'};
                   16553:             }
                   16554:             if ($fixeddom) {
                   16555:                 $instcodetitle .= '<br />('.$codedom.')';
                   16556:             }
                   16557:         }
                   16558:     }
                   16559:     my $output = qq|
                   16560: <form method="post" name="filterpicker" action="$action">
                   16561: <input type="hidden" name="form" value="$formname" />
                   16562: |;
                   16563:     if ($formname eq 'modifycourse') {
                   16564:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   16565:                    '<input type="hidden" name="prevphase" value="'.
                   16566:                    $prevphase.'" />'."\n";
1.1198    musolffc 16567:     } elsif ($formname eq 'quotacheck') {
                   16568:         $output .= qq|
                   16569: <input type="hidden" name="sortby" value="" />
                   16570: <input type="hidden" name="sortorder" value="" />
                   16571: |;
                   16572:     } else {
1.1181    raeburn  16573:         my $name_input;
                   16574:         if ($cnameelement ne '') {
                   16575:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   16576:                           $cnameelement.'" />';
                   16577:         }
                   16578:         $output .= qq|
1.1182    raeburn  16579: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   16580: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  16581: $name_input
                   16582: $roleelement
                   16583: $multelement
                   16584: $typeelement
                   16585: |;
                   16586:         if ($formname eq 'portform') {
                   16587:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   16588:         }
                   16589:     }
                   16590:     if ($fixeddom) {
                   16591:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   16592:     }
                   16593:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   16594:     if ($sincefilterform) {
                   16595:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   16596:                   .$sincefilterform
                   16597:                   .&Apache::lonhtmlcommon::row_closure();
                   16598:     }
                   16599:     if ($createdfilterform) {
                   16600:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   16601:                   .$createdfilterform
                   16602:                   .&Apache::lonhtmlcommon::row_closure();
                   16603:     }
                   16604:     if ($domainselectform) {
                   16605:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   16606:                   .$domainselectform
                   16607:                   .&Apache::lonhtmlcommon::row_closure();
                   16608:     }
                   16609:     if ($typeselectform) {
                   16610:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16611:             $output .= $typeselectform;
                   16612:         } else {
                   16613:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16614:                       .$typeselectform
                   16615:                       .&Apache::lonhtmlcommon::row_closure();
                   16616:         }
                   16617:     }
                   16618:     if ($instcodeform) {
                   16619:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16620:                   .$instcodeform
                   16621:                   .&Apache::lonhtmlcommon::row_closure();
                   16622:     }
                   16623:     if (exists($filter->{'ownerfilter'})) {
                   16624:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16625:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16626:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16627:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16628:                    $ownerdomselectform.'</td></tr></table>'.
                   16629:                    &Apache::lonhtmlcommon::row_closure();
                   16630:     }
                   16631:     if (exists($filter->{'personfilter'})) {
                   16632:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16633:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16634:                    '<input type="text" name="personfilter" size="20" value="'.
                   16635:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16636:                    $persondomselectform.'</td></tr></table>'.
                   16637:                    &Apache::lonhtmlcommon::row_closure();
                   16638:     }
                   16639:     if (exists($filter->{'coursefilter'})) {
                   16640:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16641:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16642:                   .$list->{'coursefilter'}.'" />'
                   16643:                   .&Apache::lonhtmlcommon::row_closure();
                   16644:     }
                   16645:     if ($cloneableonlyform) {
                   16646:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16647:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16648:     }
                   16649:     if (exists($filter->{'descriptfilter'})) {
                   16650:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16651:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16652:                   .$list->{'descriptfilter'}.'" />'
                   16653:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16654:     }
                   16655:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16656:                '<input type="hidden" name="updater" value="" />'."\n".
                   16657:                '<input type="submit" name="gosearch" value="'.
                   16658:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16659:     return $jscript.$clonewarning.$output;
                   16660: }
                   16661: 
                   16662: =pod 
                   16663: 
                   16664: =item * &timebased_select_form()
                   16665: 
1.1182    raeburn  16666: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  16667: filter e.g., Course Activity, Course Created, when searching for courses
                   16668: or communities
                   16669: 
                   16670: Inputs:
                   16671: 
                   16672: item - name of form element (sincefilter or createdfilter)
                   16673: 
                   16674: filter - anonymous hash of criteria and their values
                   16675: 
                   16676: Returns: HTML for a select box contained a blank, then six time selections,
                   16677:          with value set in incoming form variables currently selected. 
                   16678: 
                   16679: Side Effects: None
                   16680: 
                   16681: =cut
                   16682: 
                   16683: sub timebased_select_form {
                   16684:     my ($item,$filter) = @_;
                   16685:     if (ref($filter) eq 'HASH') {
                   16686:         $filter->{$item} =~ s/[^\d-]//g;
                   16687:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16688:         return &select_form(
                   16689:                             $filter->{$item},
                   16690:                             $item,
                   16691:                             {      '-1' => '',
                   16692:                                 '86400' => &mt('today'),
                   16693:                                '604800' => &mt('last week'),
                   16694:                               '2592000' => &mt('last month'),
                   16695:                               '7776000' => &mt('last three months'),
                   16696:                              '15552000' => &mt('last six months'),
                   16697:                              '31104000' => &mt('last year'),
                   16698:                     'select_form_order' =>
                   16699:                            ['-1','86400','604800','2592000','7776000',
                   16700:                             '15552000','31104000']});
                   16701:     }
                   16702: }
                   16703: 
                   16704: =pod
                   16705: 
                   16706: =item * &js_changer()
                   16707: 
                   16708: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  16709: when course type or domain is changed, and also to hide 'Searching ...' on
                   16710: page load completion for page showing search result.
1.1181    raeburn  16711: 
                   16712: Inputs: None
                   16713: 
1.1183    raeburn  16714: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  16715: 
                   16716: Side Effects: None
                   16717: 
                   16718: =cut
                   16719: 
                   16720: sub js_changer {
                   16721:     return <<ENDJS;
                   16722: <script type="text/javascript">
                   16723: // <![CDATA[
                   16724: function updateFilters(caller) {
                   16725:     if (typeof(caller) != "undefined") {
                   16726:         document.filterpicker.updater.value = caller.name;
                   16727:     }
                   16728:     document.filterpicker.submit();
                   16729: }
1.1183    raeburn  16730: 
                   16731: function hideSearching() {
                   16732:     if (document.getElementById('searching')) {
                   16733:         document.getElementById('searching').style.display = 'none';
                   16734:     }
                   16735:     return;
                   16736: }
                   16737: 
1.1181    raeburn  16738: // ]]>
                   16739: </script>
                   16740: 
                   16741: ENDJS
                   16742: }
                   16743: 
                   16744: =pod
                   16745: 
1.1182    raeburn  16746: =item * &search_courses()
                   16747: 
                   16748: Process selected filters form course search form and pass to lonnet::courseiddump
                   16749: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16750: 
                   16751: Inputs:
                   16752: 
                   16753: dom - domain being searched 
                   16754: 
                   16755: type - course type ('Course' or 'Community' or '.' if any).
                   16756: 
                   16757: filter - anonymous hash of criteria and their values
                   16758: 
                   16759: numtitles - for institutional codes - number of categories
                   16760: 
                   16761: cloneruname - optional username of new course owner
                   16762: 
                   16763: clonerudom - optional domain of new course owner
                   16764: 
1.1221    raeburn  16765: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  16766:             (used when DC is using course creation form)
                   16767: 
                   16768: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16769: 
1.1221    raeburn  16770: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16771:            (and so can clone automatically)
                   16772: 
                   16773: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16774: 
                   16775: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   16776:               courses to clone 
1.1182    raeburn  16777: 
                   16778: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16779: 
                   16780: 
                   16781: Side Effects: None
                   16782: 
                   16783: =cut
                   16784: 
                   16785: 
                   16786: sub search_courses {
1.1221    raeburn  16787:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16788:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  16789:     my (%courses,%showcourses,$cloner);
                   16790:     if (($filter->{'ownerfilter'} ne '') ||
                   16791:         ($filter->{'ownerdomfilter'} ne '')) {
                   16792:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16793:                                        $filter->{'ownerdomfilter'};
                   16794:     }
                   16795:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16796:         if (!$filter->{$item}) {
                   16797:             $filter->{$item}='.';
                   16798:         }
                   16799:     }
                   16800:     my $now = time;
                   16801:     my $timefilter =
                   16802:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16803:     my ($createdbefore,$createdafter);
                   16804:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16805:         $createdbefore = $now;
                   16806:         $createdafter = $now-$filter->{'createdfilter'};
                   16807:     }
                   16808:     my ($instcodefilter,$regexpok);
                   16809:     if ($numtitles) {
                   16810:         if ($env{'form.official'} eq 'on') {
                   16811:             $instcodefilter =
                   16812:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16813:             $regexpok = 1;
                   16814:         } elsif ($env{'form.official'} eq 'off') {
                   16815:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16816:             unless ($instcodefilter eq '') {
                   16817:                 $regexpok = -1;
                   16818:             }
                   16819:         }
                   16820:     } else {
                   16821:         $instcodefilter = $filter->{'instcodefilter'};
                   16822:     }
                   16823:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16824:     if ($type eq '') { $type = '.'; }
                   16825: 
                   16826:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16827:         $cloner = $cloneruname.':'.$clonerudom;
                   16828:     }
                   16829:     %courses = &Apache::lonnet::courseiddump($dom,
                   16830:                                              $filter->{'descriptfilter'},
                   16831:                                              $timefilter,
                   16832:                                              $instcodefilter,
                   16833:                                              $filter->{'combownerfilter'},
                   16834:                                              $filter->{'coursefilter'},
                   16835:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  16836:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  16837:                                              $filter->{'cloneableonly'},
                   16838:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  16839:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  16840:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16841:         my $ccrole;
                   16842:         if ($type eq 'Community') {
                   16843:             $ccrole = 'co';
                   16844:         } else {
                   16845:             $ccrole = 'cc';
                   16846:         }
                   16847:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16848:                                                      $filter->{'persondomfilter'},
                   16849:                                                      'userroles',undef,
                   16850:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16851:                                                      $dom);
                   16852:         foreach my $role (keys(%rolehash)) {
                   16853:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16854:             my $cid = $cdom.'_'.$cnum;
                   16855:             if (exists($courses{$cid})) {
                   16856:                 if (ref($courses{$cid}) eq 'HASH') {
                   16857:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16858:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  16859:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  16860:                         }
                   16861:                     } else {
                   16862:                         $courses{$cid}{roles} = [$courserole];
                   16863:                     }
                   16864:                     $showcourses{$cid} = $courses{$cid};
                   16865:                 }
                   16866:             }
                   16867:         }
                   16868:         %courses = %showcourses;
                   16869:     }
                   16870:     return %courses;
                   16871: }
                   16872: 
                   16873: =pod
                   16874: 
1.1181    raeburn  16875: =back
                   16876: 
1.1207    raeburn  16877: =head1 Routines for version requirements for current course.
                   16878: 
                   16879: =over 4
                   16880: 
                   16881: =item * &check_release_required()
                   16882: 
                   16883: Compares required LON-CAPA version with version on server, and
                   16884: if required version is newer looks for a server with the required version.
                   16885: 
                   16886: Looks first at servers in user's owen domain; if none suitable, looks at
                   16887: servers in course's domain are permitted to host sessions for user's domain.
                   16888: 
                   16889: Inputs:
                   16890: 
                   16891: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16892: 
                   16893: $courseid - Course ID of current course
                   16894: 
                   16895: $rolecode - User's current role in course (for switchserver query string).
                   16896: 
                   16897: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16898: 
                   16899: 
                   16900: Returns:
                   16901: 
                   16902: $switchserver - query string tp append to /adm/switchserver call (if 
                   16903:                 current server's LON-CAPA version is too old. 
                   16904: 
                   16905: $warning - Message is displayed if no suitable server could be found.
                   16906: 
                   16907: =cut
                   16908: 
                   16909: sub check_release_required {
                   16910:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16911:     my ($switchserver,$warning);
                   16912:     if ($required ne '') {
                   16913:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16914:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16915:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16916:             my $otherserver;
                   16917:             if (($major eq '' && $minor eq '') ||
                   16918:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16919:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16920:                 my $switchlcrev =
                   16921:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16922:                                                            $userdomserver);
                   16923:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16924:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16925:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16926:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16927:                     if ($cdom ne $env{'user.domain'}) {
                   16928:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16929:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16930:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16931:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16932:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16933:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16934:                         my $canhost =
                   16935:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16936:                                                               $coursedomserver,
                   16937:                                                               $remoterev,
                   16938:                                                               $udomdefaults{'remotesessions'},
                   16939:                                                               $defdomdefaults{'hostedsessions'});
                   16940: 
                   16941:                         if ($canhost) {
                   16942:                             $otherserver = $coursedomserver;
                   16943:                         } else {
                   16944:                             $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.");
                   16945:                         }
                   16946:                     } else {
                   16947:                         $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).");
                   16948:                     }
                   16949:                 } else {
                   16950:                     $otherserver = $userdomserver;
                   16951:                 }
                   16952:             }
                   16953:             if ($otherserver ne '') {
                   16954:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16955:             }
                   16956:         }
                   16957:     }
                   16958:     return ($switchserver,$warning);
                   16959: }
                   16960: 
                   16961: =pod
                   16962: 
                   16963: =item * &check_release_result()
                   16964: 
                   16965: Inputs:
                   16966: 
                   16967: $switchwarning - Warning message if no suitable server found to host session.
                   16968: 
                   16969: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16970:                 and current role.
                   16971: 
                   16972: Returns: HTML to display with information about requirement to switch server.
                   16973:          Either displaying warning with link to Roles/Courses screen or
                   16974:          display link to switchserver.
                   16975: 
1.1181    raeburn  16976: =cut
                   16977: 
1.1207    raeburn  16978: sub check_release_result {
                   16979:     my ($switchwarning,$switchserver) = @_;
                   16980:     my $output = &start_page('Selected course unavailable on this server').
                   16981:                  '<p class="LC_warning">';
                   16982:     if ($switchwarning) {
                   16983:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16984:         if (&show_course()) {
                   16985:             $output .= &mt('Display courses');
                   16986:         } else {
                   16987:             $output .= &mt('Display roles');
                   16988:         }
                   16989:         $output .= '</a>';
                   16990:     } elsif ($switchserver) {
                   16991:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16992:                    '<br />'.
                   16993:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16994:                    &mt('Switch Server').
                   16995:                    '</a>';
                   16996:     }
                   16997:     $output .= '</p>'.&end_page();
                   16998:     return $output;
                   16999: }
                   17000: 
                   17001: =pod
                   17002: 
                   17003: =item * &needs_coursereinit()
                   17004: 
                   17005: Determine if course contents stored for user's session needs to be
                   17006: refreshed, because content has changed since "Big Hash" last tied.
                   17007: 
                   17008: Check for change is made if time last checked is more than 10 minutes ago
                   17009: (by default).
                   17010: 
                   17011: Inputs:
                   17012: 
                   17013: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17014: 
                   17015: $interval (optional) - Time which may elapse (in s) between last check for content
                   17016:                        change in current course. (default: 600 s).  
                   17017: 
                   17018: Returns: an array; first element is:
                   17019: 
                   17020: =over 4
                   17021: 
                   17022: 'switch' - if content updates mean user's session
                   17023:            needs to be switched to a server running a newer LON-CAPA version
                   17024:  
                   17025: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17026:            on current server hosting user's session                
                   17027: 
                   17028: ''       - if no action required.
                   17029: 
                   17030: =back
                   17031: 
                   17032: If first item element is 'switch':
                   17033: 
                   17034: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   17035: 
                   17036: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17037:                               and current role. 
                   17038: 
                   17039: otherwise: no other elements returned.
                   17040: 
                   17041: =back
                   17042: 
                   17043: =cut
                   17044: 
                   17045: sub needs_coursereinit {
                   17046:     my ($loncaparev,$interval) = @_;
                   17047:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17048:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17049:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17050:     my $now = time;
                   17051:     if ($interval eq '') {
                   17052:         $interval = 600;
                   17053:     }
                   17054:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  17055:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1283    raeburn  17056:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
1.1282    raeburn  17057:         if ($blocked) {
                   17058:             return ();
                   17059:         }
1.1207    raeburn  17060:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17061:         if ($lastchange > $env{'request.course.tied'}) {
                   17062:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17063:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17064:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17065:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17066:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17067:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   17068:                     my ($switchserver,$switchwarning) =
                   17069:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17070:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   17071:                     if ($switchwarning ne '' || $switchserver ne '') {
                   17072:                         return ('switch',$switchwarning,$switchserver);
                   17073:                     }
                   17074:                 }
                   17075:             }
                   17076:             return ('update');
                   17077:         }
                   17078:     }
                   17079:     return ();
                   17080: }
1.1181    raeburn  17081: 
1.1083    raeburn  17082: sub update_content_constraints {
                   17083:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17084:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17085:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   17086:     my %checkresponsetypes;
                   17087:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  17088:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  17089:         if ($item eq 'resourcetag') {
                   17090:             if ($name eq 'responsetype') {
                   17091:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17092:             }
                   17093:         }
                   17094:     }
                   17095:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17096:     if (defined($navmap)) {
                   17097:         my %allresponses;
                   17098:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   17099:             my %responses = $res->responseTypes();
                   17100:             foreach my $key (keys(%responses)) {
                   17101:                 next unless(exists($checkresponsetypes{$key}));
                   17102:                 $allresponses{$key} += $responses{$key};
                   17103:             }
                   17104:         }
                   17105:         foreach my $key (keys(%allresponses)) {
                   17106:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17107:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17108:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17109:             }
                   17110:         }
                   17111:         undef($navmap);
                   17112:     }
                   17113:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17114:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17115:     }
                   17116:     return;
                   17117: }
                   17118: 
1.1110    raeburn  17119: sub allmaps_incourse {
                   17120:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17121:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17122:         $cid = $env{'request.course.id'};
                   17123:         $cdom = $env{'course.'.$cid.'.domain'};
                   17124:         $cnum = $env{'course.'.$cid.'.num'};
                   17125:         $chome = $env{'course.'.$cid.'.home'};
                   17126:     }
                   17127:     my %allmaps = ();
                   17128:     my $lastchange =
                   17129:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17130:     if ($lastchange > $env{'request.course.tied'}) {
                   17131:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17132:         unless ($ferr) {
                   17133:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17134:         }
                   17135:     }
                   17136:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17137:     if (defined($navmap)) {
                   17138:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17139:             $allmaps{$res->src()} = 1;
                   17140:         }
                   17141:     }
                   17142:     return \%allmaps;
                   17143: }
                   17144: 
1.1083    raeburn  17145: sub parse_supplemental_title {
                   17146:     my ($title) = @_;
                   17147: 
                   17148:     my ($foldertitle,$renametitle);
                   17149:     if ($title =~ /&amp;&amp;&amp;/) {
                   17150:         $title = &HTML::Entites::decode($title);
                   17151:     }
                   17152:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17153:         $renametitle=$4;
                   17154:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17155:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17156:         my $name =  &plainname($uname,$udom);
                   17157:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17158:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17159:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17160:             $name.': <br />'.$foldertitle;
                   17161:     }
                   17162:     if (wantarray) {
                   17163:         return ($title,$foldertitle,$renametitle);
                   17164:     }
                   17165:     return $title;
                   17166: }
                   17167: 
1.1143    raeburn  17168: sub recurse_supplemental {
                   17169:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   17170:     if ($suppmap) {
                   17171:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17172:         if ($fatal) {
                   17173:             $errors ++;
                   17174:         } else {
                   17175:             if ($#LONCAPA::map::resources > 0) {
                   17176:                 foreach my $res (@LONCAPA::map::resources) {
                   17177:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   17178:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  17179:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   17180:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  17181:                         } else {
                   17182:                             $numfiles ++;
                   17183:                         }
                   17184:                     }
                   17185:                 }
                   17186:             }
                   17187:         }
                   17188:     }
                   17189:     return ($numfiles,$errors);
                   17190: }
                   17191: 
1.1101    raeburn  17192: sub symb_to_docspath {
1.1267    raeburn  17193:     my ($symb,$navmapref) = @_;
                   17194:     return unless ($symb && ref($navmapref));
1.1101    raeburn  17195:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17196:     if ($resurl=~/\.(sequence|page)$/) {
                   17197:         $mapurl=$resurl;
                   17198:     } elsif ($resurl eq 'adm/navmaps') {
                   17199:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17200:     }
                   17201:     my $mapresobj;
1.1267    raeburn  17202:     unless (ref($$navmapref)) {
                   17203:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17204:     }
                   17205:     if (ref($$navmapref)) {
                   17206:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  17207:     }
                   17208:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17209:     my $type=$2;
                   17210:     my $path;
                   17211:     if (ref($mapresobj)) {
                   17212:         my $pcslist = $mapresobj->map_hierarchy();
                   17213:         if ($pcslist ne '') {
                   17214:             foreach my $pc (split(/,/,$pcslist)) {
                   17215:                 next if ($pc <= 1);
1.1267    raeburn  17216:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  17217:                 if (ref($res)) {
                   17218:                     my $thisurl = $res->src();
                   17219:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17220:                     my $thistitle = $res->title();
                   17221:                     $path .= '&'.
                   17222:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  17223:                              &escape($thistitle).
1.1101    raeburn  17224:                              ':'.$res->randompick().
                   17225:                              ':'.$res->randomout().
                   17226:                              ':'.$res->encrypted().
                   17227:                              ':'.$res->randomorder().
                   17228:                              ':'.$res->is_page();
                   17229:                 }
                   17230:             }
                   17231:         }
                   17232:         $path =~ s/^\&//;
                   17233:         my $maptitle = $mapresobj->title();
                   17234:         if ($mapurl eq 'default') {
1.1129    raeburn  17235:             $maptitle = 'Main Content';
1.1101    raeburn  17236:         }
                   17237:         $path .= (($path ne '')? '&' : '').
                   17238:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17239:                  &escape($maptitle).
1.1101    raeburn  17240:                  ':'.$mapresobj->randompick().
                   17241:                  ':'.$mapresobj->randomout().
                   17242:                  ':'.$mapresobj->encrypted().
                   17243:                  ':'.$mapresobj->randomorder().
                   17244:                  ':'.$mapresobj->is_page();
                   17245:     } else {
                   17246:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17247:         my $ispage = (($type eq 'page')? 1 : '');
                   17248:         if ($mapurl eq 'default') {
1.1129    raeburn  17249:             $maptitle = 'Main Content';
1.1101    raeburn  17250:         }
                   17251:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  17252:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  17253:     }
                   17254:     unless ($mapurl eq 'default') {
                   17255:         $path = 'default&'.
1.1146    raeburn  17256:                 &escape('Main Content').
1.1101    raeburn  17257:                 ':::::&'.$path;
                   17258:     }
                   17259:     return $path;
                   17260: }
                   17261: 
1.1094    raeburn  17262: sub captcha_display {
                   17263:     my ($context,$lonhost) = @_;
                   17264:     my ($output,$error);
1.1234    raeburn  17265:     my ($captcha,$pubkey,$privkey,$version) = 
                   17266:         &get_captcha_config($context,$lonhost);
1.1095    raeburn  17267:     if ($captcha eq 'original') {
1.1094    raeburn  17268:         $output = &create_captcha();
                   17269:         unless ($output) {
1.1172    raeburn  17270:             $error = 'captcha';
1.1094    raeburn  17271:         }
                   17272:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17273:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  17274:         unless ($output) {
1.1172    raeburn  17275:             $error = 'recaptcha';
1.1094    raeburn  17276:         }
                   17277:     }
1.1234    raeburn  17278:     return ($output,$error,$captcha,$version);
1.1094    raeburn  17279: }
                   17280: 
                   17281: sub captcha_response {
                   17282:     my ($context,$lonhost) = @_;
                   17283:     my ($captcha_chk,$captcha_error);
1.1234    raeburn  17284:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  17285:     if ($captcha eq 'original') {
1.1094    raeburn  17286:         ($captcha_chk,$captcha_error) = &check_captcha();
                   17287:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  17288:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  17289:     } else {
                   17290:         $captcha_chk = 1;
                   17291:     }
                   17292:     return ($captcha_chk,$captcha_error);
                   17293: }
                   17294: 
                   17295: sub get_captcha_config {
                   17296:     my ($context,$lonhost) = @_;
1.1234    raeburn  17297:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  17298:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   17299:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   17300:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  17301:     if ($context eq 'usercreation') {
                   17302:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   17303:         if (ref($domconfig{$context}) eq 'HASH') {
                   17304:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   17305:             if (ref($hashtocheck) eq 'HASH') {
                   17306:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   17307:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   17308:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   17309:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   17310:                     }
                   17311:                     if ($privkey && $pubkey) {
                   17312:                         $captcha = 'recaptcha';
1.1234    raeburn  17313:                         $version = $hashtocheck->{'recaptchaversion'};
                   17314:                         if ($version ne '2') {
                   17315:                             $version = 1;
                   17316:                         }
1.1095    raeburn  17317:                     } else {
                   17318:                         $captcha = 'original';
                   17319:                     }
                   17320:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   17321:                     $captcha = 'original';
                   17322:                 }
1.1094    raeburn  17323:             }
1.1095    raeburn  17324:         } else {
                   17325:             $captcha = 'captcha';
                   17326:         }
                   17327:     } elsif ($context eq 'login') {
                   17328:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   17329:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   17330:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   17331:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  17332:             if ($privkey && $pubkey) {
                   17333:                 $captcha = 'recaptcha';
1.1234    raeburn  17334:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   17335:                 if ($version ne '2') {
                   17336:                     $version = 1; 
                   17337:                 }
1.1095    raeburn  17338:             } else {
                   17339:                 $captcha = 'original';
1.1094    raeburn  17340:             }
1.1095    raeburn  17341:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   17342:             $captcha = 'original';
1.1094    raeburn  17343:         }
                   17344:     }
1.1234    raeburn  17345:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  17346: }
                   17347: 
                   17348: sub create_captcha {
                   17349:     my %captcha_params = &captcha_settings();
                   17350:     my ($output,$maxtries,$tries) = ('',10,0);
                   17351:     while ($tries < $maxtries) {
                   17352:         $tries ++;
                   17353:         my $captcha = Authen::Captcha->new (
                   17354:                                            output_folder => $captcha_params{'output_dir'},
                   17355:                                            data_folder   => $captcha_params{'db_dir'},
                   17356:                                           );
                   17357:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   17358: 
                   17359:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   17360:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   17361:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  17362:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   17363:                       '<br />'.
                   17364:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  17365:             last;
                   17366:         }
                   17367:     }
                   17368:     return $output;
                   17369: }
                   17370: 
                   17371: sub captcha_settings {
                   17372:     my %captcha_params = (
                   17373:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   17374:                            www_output_dir => "/captchaspool",
                   17375:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   17376:                            numchars       => '5',
                   17377:                          );
                   17378:     return %captcha_params;
                   17379: }
                   17380: 
                   17381: sub check_captcha {
                   17382:     my ($captcha_chk,$captcha_error);
                   17383:     my $code = $env{'form.code'};
                   17384:     my $md5sum = $env{'form.crypt'};
                   17385:     my %captcha_params = &captcha_settings();
                   17386:     my $captcha = Authen::Captcha->new(
                   17387:                       output_folder => $captcha_params{'output_dir'},
                   17388:                       data_folder   => $captcha_params{'db_dir'},
                   17389:                   );
1.1109    raeburn  17390:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  17391:     my %captcha_hash = (
                   17392:                         0       => 'Code not checked (file error)',
                   17393:                        -1      => 'Failed: code expired',
                   17394:                        -2      => 'Failed: invalid code (not in database)',
                   17395:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   17396:     );
                   17397:     if ($captcha_chk != 1) {
                   17398:         $captcha_error = $captcha_hash{$captcha_chk}
                   17399:     }
                   17400:     return ($captcha_chk,$captcha_error);
                   17401: }
                   17402: 
                   17403: sub create_recaptcha {
1.1234    raeburn  17404:     my ($pubkey,$version) = @_;
                   17405:     if ($version >= 2) {
                   17406:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   17407:     } else {
                   17408:         my $use_ssl;
                   17409:         if ($ENV{'SERVER_PORT'} == 443) {
                   17410:             $use_ssl = 1;
                   17411:         }
                   17412:         my $captcha = Captcha::reCAPTCHA->new;
                   17413:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   17414:                $captcha->get_html($pubkey,undef,$use_ssl).
                   17415:                &mt('If the text is hard to read, [_1] will replace them.',
                   17416:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   17417:                '<br /><br />';
                   17418:     }
1.1094    raeburn  17419: }
                   17420: 
                   17421: sub check_recaptcha {
1.1234    raeburn  17422:     my ($privkey,$version) = @_;
1.1094    raeburn  17423:     my $captcha_chk;
1.1234    raeburn  17424:     if ($version >= 2) {
                   17425:         my %info = (
                   17426:                      secret   => $privkey, 
                   17427:                      response => $env{'form.g-recaptcha-response'},
                   17428:                      remoteip => $ENV{'REMOTE_ADDR'},
                   17429:                    );
1.1280    raeburn  17430:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   17431:         $request->content(join('&',map {
                   17432:                          my $name = escape($_);
                   17433:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   17434:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   17435:                          : &escape($info{$_}) );
                   17436:         } keys(%info)));
                   17437:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  17438:         if ($response->is_success)  {
                   17439:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   17440:             if (ref($data) eq 'HASH') {
                   17441:                 if ($data->{'success'}) {
                   17442:                     $captcha_chk = 1;
                   17443:                 }
                   17444:             }
                   17445:         }
                   17446:     } else {
                   17447:         my $captcha = Captcha::reCAPTCHA->new;
                   17448:         my $captcha_result =
                   17449:             $captcha->check_answer(
                   17450:                                     $privkey,
                   17451:                                     $ENV{'REMOTE_ADDR'},
                   17452:                                     $env{'form.recaptcha_challenge_field'},
                   17453:                                     $env{'form.recaptcha_response_field'},
                   17454:                                   );
                   17455:         if ($captcha_result->{is_valid}) {
                   17456:             $captcha_chk = 1;
                   17457:         }
1.1094    raeburn  17458:     }
                   17459:     return $captcha_chk;
                   17460: }
                   17461: 
1.1174    raeburn  17462: sub emailusername_info {
1.1244    raeburn  17463:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  17464:     my %titles = &Apache::lonlocal::texthash (
                   17465:                      lastname      => 'Last Name',
                   17466:                      firstname     => 'First Name',
                   17467:                      institution   => 'School/college/university',
                   17468:                      location      => "School's city, state/province, country",
                   17469:                      web           => "School's web address",
                   17470:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  17471:                      id            => 'Student/Employee ID',
1.1174    raeburn  17472:                  );
                   17473:     return (\@fields,\%titles);
                   17474: }
                   17475: 
1.1161    raeburn  17476: sub cleanup_html {
                   17477:     my ($incoming) = @_;
                   17478:     my $outgoing;
                   17479:     if ($incoming ne '') {
                   17480:         $outgoing = $incoming;
                   17481:         $outgoing =~ s/;/&#059;/g;
                   17482:         $outgoing =~ s/\#/&#035;/g;
                   17483:         $outgoing =~ s/\&/&#038;/g;
                   17484:         $outgoing =~ s/</&#060;/g;
                   17485:         $outgoing =~ s/>/&#062;/g;
                   17486:         $outgoing =~ s/\(/&#040/g;
                   17487:         $outgoing =~ s/\)/&#041;/g;
                   17488:         $outgoing =~ s/"/&#034;/g;
                   17489:         $outgoing =~ s/'/&#039;/g;
                   17490:         $outgoing =~ s/\$/&#036;/g;
                   17491:         $outgoing =~ s{/}{&#047;}g;
                   17492:         $outgoing =~ s/=/&#061;/g;
                   17493:         $outgoing =~ s/\\/&#092;/g
                   17494:     }
                   17495:     return $outgoing;
                   17496: }
                   17497: 
1.1190    musolffc 17498: # Checks for critical messages and returns a redirect url if one exists.
                   17499: # $interval indicates how often to check for messages.
1.1282    raeburn  17500: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 17501: sub critical_redirect {
1.1282    raeburn  17502:     my ($interval,$context) = @_;
1.1190    musolffc 17503:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  17504:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   17505:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17506:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17507:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
                   17508:             if ($blocked) {
                   17509:                 my $checkrole = "cm./$cdom/$cnum";
                   17510:                 if ($env{'request.course.sec'} ne '') {
                   17511:                     $checkrole .= "/$env{'request.course.sec'}";
                   17512:                 }
                   17513:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   17514:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   17515:                     return;
                   17516:                 }
                   17517:             }
                   17518:         }
1.1190    musolffc 17519:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   17520:                                         $env{'user.name'});
                   17521:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  17522:         my $redirecturl;
1.1190    musolffc 17523:         if ($what[0]) {
                   17524: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   17525: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  17526: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   17527:                 return (1, $url);
1.1190    musolffc 17528:             }
1.1191    raeburn  17529:         }
                   17530:     } 
                   17531:     return ();
1.1190    musolffc 17532: }
                   17533: 
1.1174    raeburn  17534: # Use:
                   17535: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   17536: #
                   17537: ##################################################
                   17538: #          password associated functions         #
                   17539: ##################################################
                   17540: sub des_keys {
                   17541:     # Make a new key for DES encryption.
                   17542:     # Each key has two parts which are returned separately.
                   17543:     # Please note:  Each key must be passed through the &hex function
                   17544:     # before it is output to the web browser.  The hex versions cannot
                   17545:     # be used to decrypt.
                   17546:     my @hexstr=('0','1','2','3','4','5','6','7',
                   17547:                 '8','9','a','b','c','d','e','f');
                   17548:     my $lkey='';
                   17549:     for (0..7) {
                   17550:         $lkey.=$hexstr[rand(15)];
                   17551:     }
                   17552:     my $ukey='';
                   17553:     for (0..7) {
                   17554:         $ukey.=$hexstr[rand(15)];
                   17555:     }
                   17556:     return ($lkey,$ukey);
                   17557: }
                   17558: 
                   17559: sub des_decrypt {
                   17560:     my ($key,$cyphertext) = @_;
                   17561:     my $keybin=pack("H16",$key);
                   17562:     my $cypher;
                   17563:     if ($Crypt::DES::VERSION>=2.03) {
                   17564:         $cypher=new Crypt::DES $keybin;
                   17565:     } else {
                   17566:         $cypher=new DES $keybin;
                   17567:     }
1.1233    raeburn  17568:     my $plaintext='';
                   17569:     my $cypherlength = length($cyphertext);
                   17570:     my $numchunks = int($cypherlength/32);
                   17571:     for (my $j=0; $j<$numchunks; $j++) {
                   17572:         my $start = $j*32;
                   17573:         my $cypherblock = substr($cyphertext,$start,32);
                   17574:         my $chunk =
                   17575:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   17576:         $chunk .=
                   17577:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   17578:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   17579:         $plaintext .= $chunk;
                   17580:     }
1.1174    raeburn  17581:     return $plaintext;
                   17582: }
                   17583: 
1.112     bowersj2 17584: 1;
                   17585: __END__;
1.41      ng       17586: 

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