File:  [LON-CAPA] / loncom / interface / lonsyllabus.pm
Revision 1.139: download - view: text, annotated - select for diffs
Tue Jan 26 14:30:25 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754. Make LON-CAPA an LTI Tool Consumer (LTI 1.1). Work in progress.

    1: # The LearningOnline Network
    2: # Syllabus
    3: #
    4: # $Id: lonsyllabus.pm,v 1.139 2016/01/26 14:30:25 raeburn Exp $
    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: #
   28: 
   29: package Apache::lonsyllabus;
   30: 
   31: use strict;
   32: use Apache::lontemplate;
   33: use Apache::Constants qw(:common);
   34: use Apache::loncommon;
   35: use Apache::lonnet;
   36: use Apache::lontexconvert;
   37: use Apache::lonfeedback;
   38: use Apache::lonhtmlgateway;
   39: use Apache::lonannounce;
   40: use Apache::lonlocal;
   41: use Apache::lonhtmlcommon;
   42: use Apache::lonspeller();
   43: use HTML::Entities();
   44: 
   45: sub handler {
   46:     my $r = shift;
   47:     &Apache::loncommon::content_type($r,'text/html');
   48:     $r->send_http_header;
   49:     return OK if $r->header_only;
   50: 
   51:     my $target=$env{'form.grade_target'};
   52: # --------------------------------------------------- Get course info from URL
   53:     my (undef,undef,$cdom,$cnum)=split(/\//,$r->uri);
   54: # ------------------------------------------------------------ Get query string
   55:     &Apache::loncommon::get_unprocessed_cgi
   56:                         ($ENV{'QUERY_STRING'},['register','forceedit','todocs',
   57:                                                'folderpath','title','only_body']);
   58: # ----------------------------------------------------- Is this even a course?
   59:     my $homeserver=&Apache::lonnet::homeserver($cnum,$cdom);
   60:     if ($homeserver eq 'no_host') {
   61:         &Apache::loncommon::content_type($r,'text/html');
   62:         $r->send_http_header;
   63:         &Apache::loncommon::simple_error_page($r,'No syllabus available',
   64:                           'No syllabus available');
   65:         return OK;
   66:     } elsif (!&Apache::lonnet::is_course($cdom,$cnum)) {
   67:         &Apache::loncommon::content_type($r,'text/html');
   68:         $r->send_http_header;
   69:         &Apache::loncommon::simple_error_page($r,'No syllabus available',
   70:                           'The course/community for which the syllabus was requested does not exist.');
   71:         return OK;
   72:     }
   73: # ------------------------------------- There is such a course, get environment
   74:     my %courseenv=&Apache::lonnet::dump('environment',$cdom,$cnum);
   75:     my $crstype = &Apache::loncommon::course_type();
   76: 
   77: # --------------------------------------------------------------- Force Student
   78:     my ($forceedit,$forcestudent);
   79:     if ($env{'form.forceedit'}) { $forceedit=1; }
   80:     if (!$forceedit) {
   81:         $forcestudent=1;
   82:     }
   83: 
   84: # --------------------------------------------------------------- Check Privileges
   85:     my $allowed = 0;
   86:     if ($env{'user.environment'}) {
   87: # does this user have privileges to post, etc?
   88:         if ($env{'request.course.id'}
   89:         && $cdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}
   90:         && $cnum eq $env{'course.'.$env{'request.course.id'}.'.num'}) {
   91:             $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
   92:             if ($forcestudent or $target eq 'tex') { $allowed=0; }
   93:         }
   94:     }
   95: 
   96: # -------------------------------------------------- Let's see who handles this
   97:     my $external=$courseenv{'externalsyllabus'};
   98:     my $uploaded=$courseenv{'uploadedsyllabus'};
   99:     my $minimal=$courseenv{'minimalsyllabus'};
  100: 
  101:     if (($minimal =~/\w/) || ($uploaded =~/\w/)) {
  102:         my ($item,$is_pdf);
  103:         if ($minimal =~/\w/) {
  104:             if ($external =~ m{\Q$minimal\E$}) {
  105:                 undef($external);
  106:             }
  107:             $item = $minimal;
  108:         } elsif ($uploaded =~/\w/) {
  109:             if ($external =~ m{\Q$uploaded\E$}) {
  110:                 undef($external);
  111:             }
  112:             $item = $uploaded;
  113:             if ($item =~ /\.pdf$/i) {
  114:                 $is_pdf = 1;
  115:             }
  116:         }
  117:         unless ($allowed && $forceedit) {
  118:             my $file=&Apache::lonnet::filelocation("",$item);
  119:             if ($file =~ /\.(tex|x?html?)$/) {  
  120:                 my $filetype = $1;
  121:                 my $filecontents=&Apache::lonnet::getfile($file);
  122:                 if ($filecontents eq -1) {
  123:                     $r->print(&mt('Syllabus file unavailable'));
  124:                 } elsif ($filetype eq 'tex') {
  125:                     if ($target eq 'tex') {
  126:                         $r->print($filecontents);
  127:                     } else {
  128:                         my $result = &Apache::lontexconvert::converted(\$filecontents,
  129:                                                                        $env{'form.texengine'});
  130:                         my %args;
  131:                         &get_breadcrumbs($cdom,$cnum,$crstype,\%args);
  132:                         if ($env{'form.only_body'}) {
  133:                             $args{'only_body'} = 1;
  134:                         }
  135:                         if ($env{'request.use_absolute'}) {
  136:                             $args{'use_absolute'} = $env{'request.use_absolute'};
  137:                         }
  138:                         $r->print(&Apache::loncommon::start_page("Syllabus",undef,\%args).
  139:                                   $result.
  140:                                   &Apache::loncommon::end_page());
  141:                     }
  142:                 } else {
  143:                     my %mystyle;
  144:                     unless ($target eq 'tex') {
  145:                         $target = 'web';
  146:                     }
  147:                     &Apache::structuretags::reset_problem_globals();
  148:                     my $oldfile = $env{'request.filename'};
  149:                     $env{'request.filename'} = $item;
  150:                     my $result = &Apache::lonxml::xmlparse($r,$target,$filecontents,
  151:                                                            '',%mystyle);
  152:                     &Apache::structuretags::reset_problem_globals();
  153:                     &Apache::lonhomework::finished_parsing();
  154:                     $env{'request.filename'} = $oldfile;
  155:                     &Apache::lonxml::add_messages(\$result);
  156:                     $r->print($result);
  157:                 }
  158:             } else {
  159:                 if ($target eq 'tex') {
  160:                     $r->print(&Apache::lonprintout::print_latex_header($env{'form.latex_type'}).
  161:                               ' \strut \\\\ \textbf{'.&mt('Syllabus').'} \strut \\\\ '.
  162:                               &mt('Unsupported file type.').' \strut \\\\ '.
  163:                               &mt('Print the syllabus directly from your web browser').
  164:                               '\end{document}');
  165:                 } else {
  166:                     $r->print(&Apache::lonwrapper::wrapper($item,undef,$env{'request.use_absolute'},
  167:                                                            undef,$is_pdf,undef,&mt('Syllabus')));
  168:                 }
  169:             }
  170:             return OK;
  171:         }
  172:     } elsif ($external=~/\w/) {
  173:         unless ($allowed && $forceedit) {
  174:             if ($target eq 'tex') {
  175:                 $r->print(&Apache::lonprintout::print_latex_header($env{'form.latex_type'}).
  176:                          ' \strut \\\\ \textbf{'.&mt('Syllabus').'} \strut \\\\ '.$external.' '.
  177:                          ' \strut \\\\ '.&mt('Print the syllabus directly from your web browser').
  178:                          '\end{document}');
  179:             } else {
  180:                 my $is_ext = 1;
  181:                 my $is_pdf;
  182:                 if ($external =~ /\.pdf$/i) {
  183:                     $is_pdf = 1;
  184:                 }
  185:                 $r->print(&Apache::lonwrapper::wrapper($external,undef,$env{'request.use_absolute'},
  186:                                                        $is_ext,$is_pdf,undef,&mt('Syllabus')));
  187:             }
  188:             return OK;
  189:         }
  190:     }
  191: 
  192: # ------------------------------------------------------------ Print the screen
  193: 
  194:     if ($target eq 'tex') {
  195:         $r->print(&Apache::lonprintout::print_latex_header($env{'form.latex_type'}));
  196:     }
  197: 
  198: # ------------------------------ The buck stops here: internal syllabus display
  199: # --------------------------------------------------------- The syllabus fields
  200:     my %syllabusfields=&Apache::lonlocal::texthash(
  201:        'aaa_instructorinfo' => 'Instructor Information',
  202:        'bbb_description'    => 'Course Description',
  203:        'ccc_prereq'         => 'Prerequisites',
  204:        'cdc_classhours'     => 'Class Hours',
  205:        'ddd_officehours'    => 'Office Hours',
  206:        'eee_helproom'       => 'Helproom Hours',
  207:        'efe_projectinfo'    => 'Project Information',
  208:        'fff_examinfo'       => 'Exam Information',
  209:        'fgf_deadlines'      => 'Deadlines',
  210:        'ggg_grading'        => 'Grading Information',
  211:        'hhh_readings'       => 'Readings',
  212:        'iii_coursepack'     => 'Coursepack',
  213:        'jjj_weblinks'       => 'Web Links',
  214:        'kkk_textbook'       => 'Textbook',
  215:        'lll_includeurl'     => 'URLs To Include in Syllabus');
  216: # ---------------------------------------------------------- Load syllabus info
  217:     my %syllabus=&Apache::lonnet::dump('syllabus',$cdom,$cnum);
  218:     my ($output,%displayfields,%noshow);
  219: 
  220: # This handler might be called anonymously ...
  221: # ----------------------------------------------------- Only if not public call
  222:     if ($allowed) {
  223:         if (($env{'form.choice'} =~ /^(template|minimal|url|file)$/) ||
  224:             ($env{'form.phase'} =~ /^(upload|check)_embedded$/)) {
  225:             my $earlyout;
  226:             ($earlyout,$uploaded,$external,$minimal,$output) =
  227:                 &save_changes($cnum,$cdom,$uploaded,$external,$minimal,
  228:                               \%syllabus,\%syllabusfields,\%courseenv);
  229:             if (($env{'form.choice'} eq 'minimal') && 
  230:                 ($minimal eq "/uploaded/$cdom/$cnum/portfolio/syllabus/loncapa.html")) { 
  231:                 delete($env{'form.symb'});
  232:                 delete($env{'request.symb'});
  233:                 $r->internal_redirect("$minimal?editmode=1&forceedit=1");
  234:                 return OK;
  235:             }
  236:             if ($earlyout) {
  237:                 if ($target ne 'tex') {
  238:                     &print_header($r,$cnum,$cdom,$crstype,$allowed,$forceedit,
  239:                                   \%syllabus,\%syllabusfields);
  240:                     $r->print($output.
  241:                               &Apache::loncommon::end_page());
  242:                 }
  243:                 return OK;
  244:             }
  245:         }
  246:     }
  247:     if ($target ne 'tex') {
  248:         &print_header($r,$cnum,$cdom,$crstype,$allowed,$forceedit,\%syllabus,
  249:                       \%syllabusfields);
  250:         $r->print($output);
  251:     }
  252: 
  253: # -------------------------------------------- Determine which fields are shown 
  254: 
  255:     if ($syllabus{'uploaded.fields'}) {
  256:         if ($syllabus{'uploaded.fields'} eq 'none') {
  257:             foreach my $field (keys(%syllabusfields)) {
  258:                 $displayfields{$field} = ' style="display:none;"';
  259:                 $noshow{$field} = 1;
  260:             }
  261:         } else {
  262:             my %included;
  263:             map { $included{$_} = 1; } split(/,/,$syllabus{'uploaded.fields'});
  264:             foreach my $field (keys(%syllabusfields)) {
  265:                 my ($prefix) = split(/_/,$field);
  266:                 if ($included{$prefix}) {
  267:                     $displayfields{$field} = ' style="display:block;"';
  268:                 } else {
  269:                     $displayfields{$field} = ' style="display:none;"';
  270:                     $noshow{$field} = 1;
  271:                 }
  272:             }
  273:         }
  274:     } else {
  275:         foreach my $field (keys(%syllabusfields)) {
  276:             if ($syllabus{$field} ne '') {
  277:                 $displayfields{$field} = ' style="display:block;"';
  278:             } else {
  279:                 $displayfields{$field} = ' style="display:none;"';
  280:             }
  281:         }
  282:     }
  283: 
  284:     if ($allowed) {
  285: #---------------------------------- Print External URL Syllabus Info if editing
  286:         if ($target ne 'tex') {
  287:             my $protocol = $Apache::lonnet::protocol{$homeserver};
  288:             $protocol = 'http' if ($protocol ne 'https');
  289:             my $link = $protocol.'://'.&Apache::lonnet::hostname($homeserver).$r->uri;
  290:             $r->print('<div class="LC_left_float">'
  291:                      .'<span class="LC_help_open_topic LC_info">'
  292:                      .'<span class="LC_info">'
  293:                      .&mt('Public link (no log-in): [_1]','<tt>'.$link.'</tt>')
  294:                      .'&nbsp;</span>'.&Apache::loncommon::help_open_topic('Syllabus_ExtLink')
  295:                      .'</span>'
  296:                      .'</div><div style="padding:0;clear:both;margin:0;border:0"></div>'."\n");
  297:             my $lonhost = $r->dir_config('lonHostID');
  298:             $r->print(&chooser($external,$uploaded,$minimal,$cdom,$cnum,$lonhost,
  299:                                \%syllabusfields,\%syllabus));
  300:         }
  301:     } else {
  302: #--------------------------------------------- Print last update unless editing
  303:         my $lastmod=$syllabus{'uploaded.lastmodified'};
  304:         $lastmod=($lastmod?&Apache::lonlocal::locallocaltime($lastmod):&mt('never'));
  305:         my $who;
  306:         if ($syllabus{'uploaded.lastmodified'}) {
  307:             if (($env{'user.name'} ne 'public') && ($env{'user.domain'} ne 'public')) {
  308:                 $who = &Apache::loncommon::aboutmewrapper(
  309:                        &Apache::loncommon::plainname($syllabus{'uploaded.name'},
  310:                        $syllabus{'uploaded.domain'}),$syllabus{'uploaded.name'},
  311:                        $syllabus{'uploaded.domain'});
  312:             } else {
  313: # Public user?
  314: # Only display name of user, but no link to personal information page
  315:                 $who = &Apache::loncommon::plainname(
  316:                            $syllabus{'uploaded.name'},
  317:                            $syllabus{'uploaded.domain'});
  318:             }
  319:         }
  320:         if ($target ne 'tex') {
  321:             $r->print('<div class="LC_info">'.&mt('Last updated').': '.
  322:                       $lastmod . ' '.
  323:                       ($who ? &mt('by').' '.$who
  324:                            : '' ) .
  325:                       '</div>' );
  326:         } else {
  327:             $r->print('\\\\ '.&mt('Last updated').': '.$lastmod.' '.
  328:                      ($who? &mt('by').'\\\\ '.
  329:                      &Apache::loncommon::plainname($syllabus{'uploaded.name'},$syllabus{'uploaded.domain'})
  330:                      :'')
  331:                     .'\\\\');
  332:         }
  333:     }
  334: 
  335: #-------------------------------------------------------------- Print Headtitle
  336:     if ($target ne 'tex') {
  337:         my $display = 'block';
  338:         if ($external || $uploaded || $minimal) {
  339:             $display = 'none';
  340:         }
  341:         $r->print('<div class="LC_Box" id="template" style="display: '.$display.'">'.
  342:                    '<h2 class="LC_hcell">'.$courseenv{'description'}.'</h2>');
  343:         if ($allowed) {
  344:             $r->print('<div style="margin: 0; float:left;">'.
  345:                       '<h3>'.&Apache::lonnet::domain($cdom,'description').'</h3>'.
  346:                       '</div>');
  347: # Print Help Text if editing at right side of screen
  348:             $r->print('<div style="margin: 0; float:right;">'.
  349:                       &Apache::loncommon::help_open_topic('Uploaded_Templates_TextBoxes',&mt('Help with filling in text boxes')).
  350:                       '</div><br clear="all" />');
  351:         } else {
  352:             $r->print('<h3>'.&Apache::lonnet::domain($cdom,'description').'</h3>');
  353:         }
  354:     } else {
  355:         $r->print('\noindent{\large\textbf{'.$courseenv{'description'}.'}}\\\\\\\\\textbf{'.
  356:         &Apache::lonnet::domain($cdom,'description').'}\\\\');
  357:     }
  358: # -------------------------------------------------------- Get course personnel
  359:     my $hidepersonnel;
  360:     if (($syllabus{'uploaded.fields'}) &&
  361:         (($syllabus{'uploaded.fields'} eq 'none') ||
  362:          ($syllabus{'uploaded.fields'} !~ /000/))) {
  363:         $hidepersonnel = 1;
  364:     }
  365:     if ($target ne 'tex') {
  366:         if ($allowed) {
  367:             my $display = ' style="display:block;"';
  368:             if ($hidepersonnel) {
  369:                 $display = ' style="display:none;"';
  370:             }
  371:             &Apache::lontemplate::print_start_template($r,&mt('Personnel'),'LC_Box',
  372:                                                        'box_000_showpeople',$display);
  373:             $r->print(&get_personnel($r,$target,$cdom,$cnum,$allowed,$crstype,\%syllabus));
  374:             &Apache::lontemplate::print_end_template($r);
  375:         } else {
  376:             unless ($hidepersonnel) {
  377:                 &Apache::lontemplate::print_start_template($r,&mt('Personnel'),'LC_Box');
  378:                 $r->print(&get_personnel($r,$target,$cdom,$cnum,$allowed,$crstype,\%syllabus));  
  379:                 &Apache::lontemplate::print_end_template($r);
  380:             }
  381:         }
  382:     } else {
  383:         unless ($hidepersonnel) {
  384:             $r->print(&get_personnel($r,$target,$cdom,$cnum,$allowed,$crstype,%syllabus));
  385:         }
  386:     }
  387: # -------------------------------------------------------------- Announcements?
  388:     my $day = &Apache::lonannounce::showday(time,2,
  389:              &Apache::lonannounce::readcalendar($cdom.'_'.$cnum));
  390:     my $hidefeeds;
  391:     if (($syllabus{'uploaded.fields'}) &&
  392:         (($syllabus{'uploaded.fields'} eq 'none') ||
  393:          ($syllabus{'uploaded.fields'} !~ /111/))) {
  394:         $hidefeeds = 1;
  395:     }
  396:     if ($target ne 'tex') {
  397:         if ($allowed) {
  398:             my $display = ' style="display:block;"';
  399:             if ($hidefeeds) {
  400:                 $display = ' style="display:none;"';
  401:             }
  402:             &Apache::lontemplate::print_start_template($r,&mt('RSS Feeds and Blogs'),'LC_Box',
  403:                                                        'box_111_showrssfeeds',$display);
  404:             my ($numfeeds,$hiddenfeeds,$rsslinktext);
  405:             my $feeds=&Apache::lonrss::advertisefeeds($cnum,$cdom,$forceedit,\$numfeeds,
  406:                                                       \$hiddenfeeds);
  407:             if ($numfeeds) {
  408:                 $r->print($feeds);
  409:                 $rsslinktext = &mt('New RSS Feed or Blog');
  410:             } else {
  411:                 my $msg = '<br />'.
  412:                           &mt("RSS Feeds and Blogs item is not included in a student's view of the syllabus.");
  413:                 if ($hiddenfeeds) {
  414:                     $r->print('<p class="LC_info">'.
  415:                               &mt('All feeds currently hidden').
  416:                               $msg.
  417:                               '</p>');
  418:                 } else {
  419:                     $r->print('<p class="LC_info">'.
  420:                               &mt('No current feeds').
  421:                               $msg.
  422:                               '</p>');
  423:                 }
  424:                 $rsslinktext = &mt('Manage Course RSS Feeds/Blogs');
  425:                 if ($crstype eq 'Community') {
  426:                     $rsslinktext = &mt('Manage Community RSS Feeds/Blogs');
  427:                 }
  428:             }
  429:             my $editurl= &Apache::lonnet::absolute_url().'/adm/'.$cdom.'/'.$cnum.'/_rss.html';
  430:             $r->print( '<a href="'.$editurl.'">'.$rsslinktext.'</a>');
  431:             &Apache::lontemplate::print_end_template($r);
  432:         } else {
  433:             unless ($hidefeeds) {
  434:                 my $feeds = &Apache::lonrss::advertisefeeds($cnum,$cdom,$forceedit);
  435:                 if ($feeds ne '') {
  436:                     &Apache::lontemplate::print_start_template($r,&mt('RSS Feeds and Blogs'),'LC_Box');
  437:                     $r->print($feeds);
  438:                     &Apache::lontemplate::print_end_template($r);
  439:                 }
  440:             }
  441:         }
  442:     } else {
  443:         $r->print(&Apache::lonxml::xmlparse($r,'tex',$day));
  444:     }
  445: # ---------------------------------------------------------------- Get syllabus
  446:     if (($syllabus{'uploaded.lastmodified'}) || ($allowed)) {
  447: 		my $url_include_handler = sub {
  448: 			my ($r, $field, $message, $group, $data_ref, $fields_ref, $target, $allowed, $display) = @_;
  449: 			my %data = %{$data_ref};
  450: 			my %fields = %{$fields_ref};
  451: 			my $urls=$message;
  452: 			$message='';
  453: 			foreach my $filelink (split(/\n/,$urls)) {
  454: 				my $output='';
  455: 			   # embed style?
  456: 				my ($curfext)=($filelink=~/\.([^\.]+)$/);
  457: 				my $embstyle=&Apache::loncommon::fileembstyle($curfext);
  458: 				if (($embstyle eq 'ssi') || ($curfext=~/\/$/)) {# make ssi call and remove everything but the body contents
  459: 					$output=&Apache::lonnet::ssi_body($filelink);
  460: 				} elsif ($embstyle eq 'img') {# embed as an image
  461: 					$output='<img src="'.$filelink.'" />';
  462: 				}
  463: 				if ($output ne '') {
  464: 					   if ($target ne 'tex') {
  465: 						   $message.='<p>'.$output.'</p>';
  466: 					   } else {
  467: 						   $message.=' '.&Apache::lonxml::xmlparse($r,'tex','<p>'.$output.'</p>').' ';
  468: 					   }
  469: 				}
  470: 			}
  471: 			if ($allowed) {
  472: 				 &Apache::lonfeedback::newline_to_br(\$urls);
  473: 				 &Apache::lontemplate::print_start_template($r,$fields{$field}.
  474: 						  &Apache::loncommon::help_open_topic('Syllabus_URLs'),'LC_Box',
  475:                                                   'box_'.$field,$display);
  476: 				 $r->print($urls);
  477: 				 $r->print("<br /><div>");
  478: 				 &Apache::lontemplate::print_textarea_template($r, $data{$field},
  479: 					$field, Apache::lontemplate->RICH_TEXT_ALWAYS_OFF);
  480: 				 &Apache::lontemplate::print_saveall_template($r);                         
  481: 				 $r->print("</div>");
  482: 				 &Apache::lontemplate::print_end_template($r);
  483: 
  484: 			} else {
  485: 				$r->print($message);
  486: 			}
  487: 		};
  488: 		my %custom_hash = ( 'lll_includeurl' => $url_include_handler );
  489: 		&Apache::lontemplate::print_template_fields($r, \%syllabus, \%syllabusfields, 
  490: 			$target, $allowed, Apache::lontemplate->RICH_TEXT_DETECT_HTML, \%custom_hash,
  491:                         undef,\%displayfields,\%noshow);
  492:         if ($allowed) {
  493:             $r->print('</div></form>'.
  494:             &Apache::lonhtmlcommon::htmlareaselectactive());
  495:         }
  496:     } else {
  497:         if ($target ne 'tex') {$r->print('<p class="LC_info">');} else {$r->print('\par ');}
  498:         $r->print(&mt('No syllabus information provided.'));
  499:         if ($target ne 'tex') {$r->print('</p>');}
  500:     }
  501:     if ($target ne 'tex') {
  502:         if ($env{'form.backto'} eq 'coursecatalog') {
  503:             $r->print('<form name="backtocat" method="post" action="/adm/coursecatalog">'.
  504:                       &Apache::lonhtmlcommon::echo_form_input(['backto','courseid']).
  505:                       '</form>');
  506:         }
  507:         $r->print(&Apache::loncommon::end_page());
  508:     } else {
  509:         $r->print('\end{document}');
  510:     }
  511:     return OK;
  512: }
  513: 
  514: sub print_header {
  515:     my ($r,$cnum,$cdom,$crstype,$allowed,$forceedit,$syllabus,$syllabusfields) = @_;
  516:     return unless ((ref($syllabus) eq 'HASH') || (ref($syllabusfields) eq 'HASH'));
  517: # ----------------------------------------------------------------- Make header
  518:     my $rss_link = &Apache::lonrss::rss_link($cnum,$cdom);
  519:     my $js;
  520:     if ($env{'form.backto'} eq 'coursecatalog') {
  521:         $js .= <<"ENDSCRIPT";
  522: 
  523: <script type="text/javascript">
  524: // <![CDATA[
  525: 
  526: function ToCatalog(caller) {
  527:     numidx = getIndexByName('coursenum');
  528:         if (numidx > -1) {
  529:             if (caller != 'details') {
  530:                 document.backtocat.elements[numidx].value = '';
  531:             }
  532:         }
  533:     document.backtocat.submit();
  534: }
  535: 
  536: function getIndexByName(item) {
  537:     for (var i=0;i<document.backtocat.elements.length;i++) {
  538:         if (document.backtocat.elements[i].name == item) {
  539:             return i;
  540:         }
  541:     }
  542:     return -1;
  543: }
  544: 
  545: // ]]>
  546: </script>
  547: 
  548: ENDSCRIPT
  549:     }
  550:     if ($allowed && $forceedit) {
  551:         my $check_uncheck = &Apache::loncommon::check_uncheck_jscript();
  552:         my @fieldnames = sort(keys(%{$syllabusfields}));
  553:         unshift(@fieldnames,'000_showpeople','111_showrssfeeds');
  554:         my (@checked,@unchecked);
  555:         if ($syllabus->{'uploaded.fields'} eq 'none') {
  556:             my $lastidx = scalar(@fieldnames)-1;
  557:             @unchecked = (0..$lastidx);
  558:         } elsif ($syllabus->{'uploaded.fields'}) {
  559:             my %included;
  560:             map { $included{$_} = 1; } split(/,/,$syllabus->{'uploaded.fields'});
  561:             for (my $i=0; $i<@fieldnames; $i++) {
  562:                 my ($prefix) = split(/_/,$fieldnames[$i]);
  563:                 if ($included{$prefix}) {
  564:                     push(@checked,$i);
  565:                 } else {
  566:                     push(@unchecked,$i);
  567:                 }
  568:             }
  569:         } else {
  570:             @checked = (0,1);
  571:             for (my $i=2; $i<@fieldnames; $i++) {
  572:                 if ($syllabus->{$fieldnames[$i]}) {
  573:                     push(@checked,$i);
  574:                 } else {
  575:                     push(@unchecked,$i);
  576:                 }
  577:             }
  578:         }
  579:         my $fieldstr = "var fields = new Array('".join("','",@fieldnames)."');";
  580:         my $checkedstr = "var include = new Array('".join("','",@checked)."');";
  581:         my $uncheckedstr = "var exclude = new Array('".join("','",@unchecked)."');";
  582:         my $invurl = &mt('Invalid URL');
  583:         &js_escape(\$invurl);
  584:         my $urlregexp = <<'ENDREGEXP';
  585: /^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i
  586: ENDREGEXP
  587: 
  588:         $js .= <<"ENDSCRIPT";
  589: 
  590: <script type="text/javascript">
  591: // <![CDATA[
  592: 
  593: function toggleEditor(pick) {
  594:     var choices = new Array('template','minimal','url','file','templatebox');
  595:     for (var i=0; i<choices.length; i++) {
  596:         if (((choices[i] == 'templatebox') && (pick == 'template')) ||
  597:             (choices[i] == pick)) {
  598:             document.getElementById(choices[i]).style.display='block';
  599:         } else {
  600:             document.getElementById(choices[i]).style.display='none';
  601:         }
  602:     }
  603:     return;
  604: }
  605: 
  606: var regexp = $urlregexp;
  607: 
  608: function extUrlPreview(caller) {
  609:     if (document.getElementById(caller)) {
  610:         var url = document.getElementById(caller).value;
  611:         if (regexp.test(url)) {
  612:             openMyModal(url,500,400,'yes');
  613:         } else {
  614:             alert("$invurl");
  615:         }
  616:     }
  617: }
  618: 
  619: function toggleBox(name,caller) {
  620:     if (name == 'all') {
  621:         if (document.syllabus.showfield.length > 0) {
  622:             for (var i=0; i<document.syllabus.showfield.length; i++) {
  623:                 if (document.syllabus.showfield[i].checked) {
  624:                     if (document.getElementById('box_'+document.syllabus.showfield[i].value)) {
  625:                         document.getElementById('box_'+document.syllabus.showfield[i].value).style.display='block';
  626:                     }
  627:                 } else {
  628:                     if (document.getElementById('box_'+document.syllabus.showfield[i].value)) {
  629:                         document.getElementById('box_'+document.syllabus.showfield[i].value).style.display='none';
  630:                     }
  631:                 }
  632:             }
  633:         }
  634:     } else {
  635:         if (caller.checked) {
  636:             if (document.getElementById('box_'+caller.value)) {
  637:                 document.getElementById('box_'+caller.value).style.display='block';
  638:             }
  639:         } else {
  640:             if (document.getElementById('box_'+caller.value)) {
  641:                 document.getElementById('box_'+caller.value).style.display='none';
  642:             }
  643:         }
  644:     }
  645:     return;
  646: }
  647: 
  648: function setTemplateBoxes() {
  649:     $fieldstr
  650:     $checkedstr
  651:     $uncheckedstr
  652:     if (include.length > 0) {
  653:         for (var i=0; i<include.length; i++) {
  654:             if (document.getElementById('showfield_'+include[i])) {
  655:                 document.getElementById('showfield_'+include[i]).checked = true;
  656:                 if (document.getElementById('box_'+fields[include[i]])) {
  657:                     document.getElementById('box_'+fields[include[i]]).style.display='block';
  658:                 }
  659:             }
  660:         }
  661:     }
  662:     if (exclude.length > 0) {
  663:         for (var i=0; i<exclude.length; i++) {
  664:             if (document.getElementById('showfield_'+exclude[i])) {
  665:                 document.getElementById('showfield_'+exclude[i]).checked = false;
  666:                 if (document.getElementById('box_'+fields[exclude[i]])) {
  667:                     document.getElementById('box_'+fields[exclude[i]]).style.display='none';
  668:                 }
  669:             }
  670:         }
  671:     }
  672:     return;
  673: }
  674: 
  675: $check_uncheck
  676: 
  677: // ]]>
  678: </script>
  679: 
  680: ENDSCRIPT
  681:     }
  682:     my $args = {'function'       => undef,
  683:                 'domain'         => $cdom};
  684:     my $forcereg;
  685:     if ($env{'form.register'}) {
  686:         $forcereg = 1;
  687:         $args->{'force_register'} = $forcereg;
  688:     }
  689:     if ($env{'form.backto'} eq 'coursecatalog') {
  690:         &Apache::lonhtmlcommon::clear_breadcrumbs();
  691:         my $brcrum = [{href=>"javascript:ToCatalog();",
  692:                        text=>&mt('Course/Community Catalog'),
  693:                        no_mt=>1}
  694:                      ];
  695:         if ($env{'form.coursenum'} ne '') {
  696:             push(@{$brcrum},
  697:                   {href=>"javascript:ToCatalog('details')",
  698:                    text=>"Course details"});
  699:         }
  700:         push(@{$brcrum},
  701:               {href=>$r->uri,
  702:                text=>"Course syllabus"});
  703:         $args->{'bread_crumbs'} = $brcrum;
  704:     } else {
  705:         &get_breadcrumbs($cdom,$cnum,$crstype,$args);
  706:     }
  707:     if ($allowed) {
  708:         my %loaditem = (
  709:                          onload => 'setTemplateBoxes();',
  710:                        );
  711:         $args->{'add_entries'} = \%loaditem;
  712:     } else {
  713:         if ($env{'request.use_absolute'}) {
  714:             $args->{'use_absolute'} = $env{'request.use_absolute'};
  715:         }
  716:     }
  717:     if ($env{'form.only_body'}) {
  718:         $args->{'only_body'} = 1;
  719:     }
  720:     my $start_page =
  721:         &Apache::loncommon::start_page("Syllabus", $rss_link.$js,$args);
  722:     if ($start_page) {
  723:         $r->print($start_page);
  724:     }
  725: }
  726: 
  727: sub get_breadcrumbs{
  728:     my ($cdom,$cnum,$crstype,$args) = @_;
  729:     return unless (ref($args) eq 'HASH');
  730:     if ($env{'form.folderpath'} =~ /^supplemental/) {
  731:         my $title = $env{'form.title'};
  732:         if ($title eq '') {
  733:             $title = &mt('Syllabus');
  734:         }
  735:         my $brcrum =
  736:             &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype,undef,$title,1);
  737:         if (ref($brcrum) eq 'ARRAY') {
  738:             $args->{'bread_crumbs'} = $brcrum;
  739:         }
  740:     } else {
  741:         if ((&Apache::lonnet::is_on_map("public/$cdom/$cnum/syllabus"))
  742:                  && (($env{'form.symb'}) || ($env{'form.register'}))) {
  743:             &Apache::lonhtmlcommon::clear_breadcrumbs();
  744:         } else {
  745:             $args->{'bread_crumbs'} = [
  746:                                         {'href' => "/public/$cdom/$cnum/syllabus",
  747:                                          'text' => 'Syllabus'},
  748:                                       ];
  749:         }
  750:     }
  751:     return;
  752: }
  753: 
  754: sub chooser {
  755:     my ($external,$uploaded,$minimal,$cdom,$cnum,$lonhost,$fields,$values) = @_;
  756:     my %lt = &Apache::lonlocal::texthash(
  757:                  'type'          => 'Syllabus Type',
  758:                  'url'           => 'External URL',
  759:                  'file'          => 'Uploaded file',
  760:                  'minimal'       => 'Minimal template',
  761:                  'template'      => 'Standard template',
  762:                  'templateboxes' => 'Choose template items ... ',
  763:                  'curr'          => 'Current:',
  764:                  'rep'           => 'Replace:',
  765:                  'upl'           => 'Upload:',
  766:                  'pr'            => 'Preview',
  767:                  'save'          => 'Save',
  768:                  'sved'          => 'Save and Edit',
  769:                  'chourl'        => 'External URL',
  770:                  'chofile'       => 'Uploaded syllabus file',
  771:                  'parse'         => 'Upload embedded images/multimedia files if HTML file',
  772:     );
  773:     my %checked = (
  774:                     file     => '',
  775:                     minimal  => '',
  776:                     url      => '',
  777:                     template => '',
  778:                   );
  779:     my %display = (
  780:                     file        => 'none',
  781:                     minimal     => 'none',
  782:                     url         => 'none',
  783:                     templatebox => 'none',
  784:                   );
  785:     my $check = ' checked="checked" ';
  786:     if ($uploaded) {
  787:         $checked{'file'} = $check;
  788:         $display{'file'} = 'block';
  789:     } elsif ($external) {
  790:         $checked{'url'}  = $check;
  791:         $display{'url'} = 'block';
  792:     } elsif ($minimal) {
  793:         $checked{'minimal'} = $check;
  794:         $display{'minimal'} = 'block';
  795:     } else {
  796:         $checked{'template'} = $check;
  797:         $checked{'templatebox'} = $check;
  798:         $display{'templatebox'} = 'block';
  799:     }
  800: 
  801:     my $output = 
  802:         '<form name="syllabus" method="post" enctype="multipart/form-data" action="">'."\n".
  803:         '<input type="hidden" name="forceedit" value="1" />'."\n".
  804:         '<div class="LC_left_float"><fieldset><legend>'.$lt{'type'}.'</legend>';
  805:     foreach my $item ('minimal','template','url','file') {
  806:         $output .= '<label><input type="radio" name="choice" value="'.$item.'" '.$checked{$item}.' onclick="toggleEditor('."'$item'".')" />'.
  807:                    $lt{$item}.'</label><br />';
  808:     }
  809:     $output .= '</fieldset></div>'."\n".
  810:                '<div id="url" class="LC_left_float" style="display: '.$display{'url'}.'">'."\n".
  811:                '<fieldset><legend>'.$lt{'chourl'}.'</legend><span class="LC_nobreak">'."\n".
  812:                '<a href="javascript:extUrlPreview('."'syllabusurl'".');">'.$lt{'pr'}.'</a></span>&nbsp;'."\n".
  813:                '<input type="text" id="syllabusurl" name="externalsyllabus" value="'.$external.'" size="55" />'."\n".
  814:                '&nbsp;<input type="submit" name="storeurl" value="'.$lt{'save'}.'" />'."\n".
  815:                '</fieldset></div>'."\n".
  816:                '<div id="minimal" class="LC_left_float" style="display: '.$display{'minimal'}.'">'."\n".
  817:                '<fieldset><legend>'.$lt{'minimal'}.'</legend>';
  818:     if ($minimal) {
  819:         my ($absurl,$filename,$depbutton) = &syllabus_file_info($minimal,$cnum,$cdom,$lonhost,'minimal');
  820:         $output .= '<a href="javascript:extUrlPreview('."'currminimal'".');">'.$lt{'pr'}.'</a>'.
  821:                    '<input type="hidden" name="minimalfile" value="'.&HTML::Entities::encode($absurl).'?inhibitmenu=yes" id="currminimal" />'.
  822:                    $depbutton;
  823:     } else {
  824:         $output .= &mt('Title of Syllabus Page:').'&nbsp;'.
  825:                    '<input type="text" id="minimaltitle" name="syllabustitle" value="'.&mt('Syllabus').'" size="30" />'."\n".
  826:                    '&nbsp;<input type="submit" name="storeminimal" value="'.$lt{'sved'}.'" />'."\n";
  827:     }
  828:     $output .= '</fieldset></div>'."\n".
  829:                '<div id="file" class="LC_left_float" style="display: '.$display{'file'}.'">'."\n".
  830:                '<fieldset><legend>'.$lt{'file'}.'</legend>';
  831:     if ($uploaded) {
  832:         my ($absurl,$filename,$depbutton) = &syllabus_file_info($uploaded,$cnum,$cdom,$lonhost,'file');
  833:         $output .= '<span class="LC_nobreak">'.$lt{'curr'}.'&nbsp;'.
  834:                    '<input type="hidden" name="uploadedfile" value="'.&HTML::Entities::encode($absurl).'?inhibitmenu=yes" id="currfile" />'.
  835:                    '<a href="javascript:extUrlPreview('."'currfile'".');">'.$filename.'</a></span>'.$depbutton.
  836:                    '<br /><br />'.$lt{'rep'};
  837:     } else {
  838:         $output .= $lt{'upl'};
  839:     }
  840:     $output .= '<br />'."\n".
  841:                '<span class="LC_nobreak">'.
  842:                '<input type="file" name="syllabusfile" size="55" />'."\n".
  843:                '&nbsp;<input type="submit" name="storefile" value="'.$lt{'save'}.'" />'.
  844:                '</span><br />'.
  845:                '<label>'.
  846:                '<input type="checkbox" name="parserflag" checked="checked" />'.
  847:                $lt{'parse'}.
  848:                '</label>'.
  849:                '</fieldset></div>'.
  850:                '<div id="templatebox" class="LC_left_float" style="display: '.
  851:                $display{'templatebox'}.';"><fieldset><legend>'.$lt{'templateboxes'}.
  852:                '&nbsp;<input type="button" value="'.&mt('check all').'" '.
  853:                'onclick="javascript:checkAll('."document.syllabus.showfield".');javascript:toggleBox('."'all'".');" />'.
  854:                ('&nbsp;'x2).
  855:                '<input type="button" value="'.&mt('uncheck all').'" '.
  856:                'onclick="javascript:uncheckAll('."document.syllabus.showfield".');javascript:toggleBox('."'all'".');" />'.
  857:                '</legend>'.
  858:                &fields_check_uncheck($fields,$values).
  859:                '</fieldset><br />'.
  860:                '<input type="submit" name="storesyl" value="'.&mt('Save All').'" />'.
  861:                '</div>';
  862:     $output .= '<div style="padding:0;clear:both;margin:0;border:0"></div>';
  863:     return $output;
  864: }
  865: 
  866: sub syllabus_file_info {
  867:     my ($item,$cnum,$cdom,$lonhost,$context) = @_;
  868:     my $protocol = $Apache::lonnet::protocol{$lonhost};
  869:     $protocol = 'http' if ($protocol ne 'https');
  870:     my $absurl = $protocol.'://'.&Apache::lonnet::hostname($lonhost).$item;
  871:     my ($filename) = ($item =~ m{([^/]+)$});
  872:     my $file=&Apache::lonnet::filelocation("",$item);
  873:     my ($depbutton,$filetype,$editable);
  874:     if ($file =~ /\.(xhtml|xml|tex|html|htm)$/) {
  875:         $filetype=$1;
  876:     }
  877:     if ($filetype) {
  878:         unless ($filetype eq 'tex') {
  879:             $filetype='html';
  880:         }
  881:     }
  882:     if ($filetype eq 'html') {
  883:         my $filecontents=&Apache::lonnet::getfile($file);
  884:         unless ($filecontents eq -1) {
  885:             my $mm = new File::MMagic;
  886:             my $mimetype = $mm->checktype_contents($filecontents);
  887:             if ($mimetype eq 'text/html') {
  888:                 my (%codebase,%allfiles);
  889:                 my $parse_result = &Apache::lonnet::extract_embedded_items($item,\%allfiles,
  890:                                                                            \%codebase,\$filecontents);
  891:                 my $actionurl = "/public/$cdom/$cnum/syllabus";
  892:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
  893:                     &Apache::loncommon::ask_for_embedded_content($actionurl,undef,\%allfiles,
  894:                                                                  \%codebase,
  895:                                                                  {'context' => 'rewrites',
  896:                                                                   'ignore_remote_references' => 1,});
  897:                 $editable = 1;
  898:             }
  899:         }
  900:     }
  901:     $depbutton = ('&nbsp;' x 3).
  902:                  &editfile_button($item,$context,$editable).
  903:                  &editbutton_js();
  904:     return ($absurl,$filename,$depbutton);
  905: }
  906: 
  907: sub fields_check_uncheck {
  908:     my ($fields,$values) = @_;
  909:     return unless ((ref($fields) eq 'HASH') && (ref($values) eq 'HASH'));
  910:     my $numinrow = 4;
  911:     my $table;
  912:     my @fieldnames = sort(keys(%{$fields}));
  913:     unshift(@fieldnames,'000_showpeople','111_showrssfeeds'); 
  914:     my $numfields = scalar(@fieldnames);
  915:     my %included;
  916:     if (($values->{'uploaded.fields'}) && ($values->{'uploaded.fields'} ne 'none')) {
  917:         map { $included{$_} = 1; } split(/,/,$values->{'uploaded.fields'});
  918:     }
  919:     for (my $i=0; $i<$numfields; $i++) {
  920:         my ($name,$checked);
  921:         if ($fieldnames[$i] eq '000_showpeople') {
  922:             $name = &mt('Personnel');
  923:         } elsif ($fieldnames[$i] eq '111_showrssfeeds') {
  924:             $name = &mt('RSS Feeds and Blogs');
  925:         } else {
  926:             $name = $fields->{$fieldnames[$i]};
  927:         }
  928:         if ($values->{'uploaded.fields'}) {
  929:             unless ($values->{'uploaded.fields'} eq 'none') {
  930:                 my ($prefix) = split(/_/,$fieldnames[$i]);
  931:                 if ($included{$prefix}) {
  932:                     $checked = ' checked="checked"';
  933:                 }
  934:             }
  935:         } else {
  936:             if ($fieldnames[$i] eq '000_showpeople') {
  937:                 $checked = ' checked="checked"';
  938:             } elsif ($fieldnames[$i] eq '111_showrssfeeds') {
  939:                 $checked = ' checked="checked"';
  940:             } else {
  941:                 if ($values->{$fieldnames[$i]} ne '') {
  942:                     $checked = ' checked="checked"';
  943:                 }
  944:             }
  945:         }
  946:         my $rem = $i%($numinrow);
  947:         if ($rem == 0) {
  948:             if (($i > 0) && ($i < $numfields)) {
  949:                 $table .= '</tr>';
  950:             }
  951:             if ($i < $numfields) {
  952:                 $table .= '<tr>';
  953:             }
  954:         }
  955:         if ($i == $numfields-1) {
  956:             my $rem = $numfields%($numinrow);
  957:             my $colsleft = $numinrow - $rem;
  958:             if ($colsleft > 1) {
  959:                 $table .= '<td colspan="'.$colsleft.'">';
  960:             } else {
  961:                 $table .= '</td>';
  962:             }
  963:         } else {
  964:             $table .= '<td>';
  965:         }
  966:         $table .=
  967:             '<label><input type="checkbox" name="showfield" value="'.$fieldnames[$i].'" '.
  968:             $checked.' id="showfield_'.$i.'" onclick="javascript:toggleBox('."'$fieldnames[$i]',this".');" />'.
  969:             $name.'</label></td>'."\n";
  970:     }
  971:     if ($table ne '') {
  972:         my $rem = $numfields%($numinrow);
  973:         my $colsleft = $numinrow - $rem;
  974:         if ($colsleft > 1 ) {
  975:             $table .= '<td colspan="'.$colsleft.'">&nbsp;</td>';
  976:         } elsif ($colsleft == 1) {
  977:             $table .= '<td>&nbsp;</td>';
  978:         }
  979:         $table = '<table>'.$table.'</tr></table>';
  980:     }
  981:     return $table;
  982: }
  983: 
  984: sub get_personnel {
  985:     my ($r,$target,$cdom,$cnum,$allowed,$crstype,$syllabus) = @_;
  986:     my (%hiddenroles,%hiddenusers);
  987:     if (ref($syllabus) eq 'HASH') {
  988:         if (ref($syllabus->{'personnel'}) eq 'HASH') {
  989:             if ($syllabus->{'personnel'}{'hiderole'}) {
  990:                 map { $hiddenroles{$_} = 1; } split(/,/,$syllabus->{'personnel'}{'hiderole'});
  991:             }
  992:             if ($syllabus->{'personnel'}{'hideuser'}) {
  993:                 map { $hiddenusers{$_} = 1; } split(/,/,$syllabus->{'personnel'}{'hideuser'});
  994:             }
  995:         }
  996:     }
  997:     my $output;
  998:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum,1);
  999:     if ($target ne 'tex') {
 1000:         if ($allowed) {
 1001:             $r->print(&Apache::loncommon::start_data_table().
 1002:                       &Apache::loncommon::start_data_table_header_row().
 1003:                       '<th>'.&mt('Role hidden?').'</th><th>'.&mt('Role').'</th>'.
 1004:                       '<th>'.&mt('Personnel (hidden if checked)').'</th>'.
 1005:                       &Apache::loncommon::end_data_table_header_row());
 1006:         } else {
 1007:             $r->print(&Apache::lonhtmlcommon::start_pick_box());
 1008:         }
 1009:     } else {
 1010:         $r->print('\begin{tabular}{|p{0.45\textwidth}|p{0.45\textwidth}|}\hline');
 1011:     }
 1012:     my @personnel=sort(keys(%coursepersonnel));
 1013:     my $lastpers=$personnel[$#personnel];
 1014:     foreach my $element (@personnel) {
 1015:         unless ($allowed) {
 1016:             next if ($hiddenroles{$element}) 
 1017:         }
 1018:         my ($role,$sec);
 1019:         if ($element =~ /:/) {
 1020:             ($role,$sec) = split(/:/,$element);
 1021:         } else {
 1022:             $role = $element;
 1023:         }
 1024:         my $roletext = &Apache::lonnet::plaintext($role,$crstype);
 1025:         if ($sec) {
 1026:             $roletext .=' ('.&Apache::lonlocal::mt('Section [_1]',$sec).')';
 1027:         }
 1028:         if ($target ne 'tex') {
 1029:             if ($allowed) {
 1030:                 my $checked;
 1031:                 if ($hiddenroles{$element}) {
 1032:                     $checked = ' checked="checked"';
 1033:                 }
 1034:                 $r->print(&Apache::loncommon::start_data_table_row().
 1035:                           '<td>'.
 1036:                           '<input type="checkbox" name="hiderole" value="'.$element.'" '.
 1037:                           $checked.' />'.
 1038:                           '</td><td>'.$roletext.'</td><td>');
 1039:             } else {
 1040:                 $r->print(&Apache::lonhtmlcommon::row_title($roletext));
 1041:             }
 1042:         } else {
 1043:             $r->print(' '.&Apache::lonxml::xmlparse($r,'tex',$roletext).' & ');
 1044:         }
 1045:         my @coursepersonlist;
 1046:         foreach my $user (split(/\,/,$coursepersonnel{$element})) {
 1047:             my ($puname,$pudom)=split(/\:/,$user);
 1048:             if ($target ne 'tex') {
 1049:                 my $courseperson = &Apache::loncommon::plainname($puname,$pudom);
 1050:                 my $checked;
 1051:                 if ($hiddenusers{$element.'&'.$puname.':'.$pudom}) {
 1052:                     $checked = ' checked="checked"';
 1053:                 }
 1054:                 if ($allowed) {
 1055:                     my $item = '<span class="LC_nobreak"><label>'.
 1056:                                '<input type="checkbox" name="hideuser" value="'.$element.'&amp;'.$puname.':'.$pudom.'"'.$checked.' />'.
 1057:                                &Apache::loncommon::aboutmewrapper($courseperson
 1058: ,
 1059:                                                $puname,$pudom).
 1060:                                '</label>'.('&nbsp;'x2).'</span> ';
 1061:                     push(@coursepersonlist,$item);
 1062: 
 1063:                 } else {
 1064:                     next if ($hiddenusers{$element.'&'.$puname.':'.$pudom});
 1065:                     if (($env{'user.name'} eq '') || ($env{'user.name'} eq 'public') ||
 1066:                         ($env{'user.domain'} eq '') || ($env{'user.domain'} eq 'public')) {
 1067:                         push(@coursepersonlist,$courseperson);
 1068:                     } else {
 1069:                         push(@coursepersonlist,&Apache::loncommon::aboutmewrapper($courseperson,
 1070:                                                $puname,$pudom));
 1071:                     }
 1072:                 }
 1073:             } else {
 1074:                 push(@coursepersonlist,&Apache::loncommon::plainname($puname,
 1075:                               $pudom).' ');
 1076:             }
 1077:         }
 1078:         if ($allowed) {
 1079:             $r->print(join('',@coursepersonlist));
 1080:         } else {
 1081:             $r->print(join(', ',@coursepersonlist));
 1082:         }
 1083:         if ($target ne 'tex') {
 1084:             if ($allowed) {
 1085:                 $r->print('</td>'.&Apache::loncommon::end_data_table_row());
 1086:             } else {
 1087:                 my $lastclose=$element eq $lastpers?1:0;
 1088:                 $r->print(&Apache::lonhtmlcommon::row_closure($lastclose));
 1089:             }
 1090:         } else {
 1091:             $r->print('\\\\ \hline');
 1092:         }
 1093:     }
 1094:     if ($target ne 'tex') {
 1095:         if ($allowed) {
 1096:             $r->print(&Apache::loncommon::end_data_table());
 1097:         } else {
 1098:             $r->print(&Apache::lonhtmlcommon::end_pick_box());
 1099:         }
 1100:     } else {
 1101:         $r->print('\end{tabular}\\\\');
 1102:     }
 1103:     return;
 1104: }
 1105: 
 1106: sub save_changes {
 1107:     my ($cnum,$cdom,$uploaded,$external,$minimal,$syllabus,$syllabusfields,$courseenv) = @_;
 1108:     my ($earlyout,$output);
 1109:     unless ((ref($syllabus) eq 'HASH') && (ref($syllabusfields) eq 'HASH') ||
 1110:             (ref($courseenv) eq 'HASH')) {
 1111:         return ($earlyout,$uploaded,$external,$minimal,$output);
 1112:     }
 1113:     if (($env{'form.deleteuploaded_file'}) || ($env{'form.deleteuploaded_minimal'})) {
 1114:         my %storehash;
 1115:         if (($env{'form.choice'} eq 'file') && 
 1116:             ($env{'form.deleteuploaded_file'}) && ($uploaded =~ /\w/)) {
 1117:             if ($courseenv->{'uploadedsyllabus'} =~ m{^\Q/uploaded/$cdom/$cnum/portfolio\E(/syllabus/.+)$}) {
 1118:                 my $filename = $1;
 1119:                 &update_access_permissions($cdom,$cnum,$filename);
 1120:             }
 1121:             &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.uploadedsyllabus');
 1122:             &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.externalsyllabus');
 1123:             $storehash{'uploadedsyllabus'} = '';
 1124:             $storehash{'externalsyllabus'} = '';
 1125:             my $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 1126:             undef($uploaded);
 1127:             undef($external);
 1128:         } elsif (($env{'form.choice'} eq 'minimal') &&
 1129:                  ($env{'form.deleteuploaded_minimal'}) && ($minimal =~ /\w/)) {
 1130:             my $minimalurl = "/uploaded/$cdom/$cnum/portfolio/syllabus/loncapa.html";
 1131:             if ($courseenv->{'minimalsyllabus'} eq "$minimalurl") {
 1132:                 my $filecontents=&Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$minimalurl));
 1133:                 unless ($filecontents eq -1) {
 1134:                     $env{'form.output'} = $filecontents; 
 1135:                     &Apache::lonnet::finishuserfileupload($cnum,$cdom,'output',
 1136:                                                           'portfolio/syllabus/loncapa.html.bak');
 1137:                     $minimalurl = &default_minimal_syllabus($cnum,$cdom);
 1138:                 }
 1139:             }
 1140:             &update_access_permissions($cdom,$cnum,'/syllabus/loncapa.html');
 1141:             &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.externalsyllabus');
 1142:             &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.minimalsyllabus');
 1143:             $storehash{'externalsyllabus'} = '';
 1144:             $storehash{'minimalsyllabus'} = '';
 1145:             my $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 1146:             undef($external);
 1147:             undef($minimal);
 1148:         }
 1149:     } elsif ($env{'form.choice'} eq 'template') {
 1150: #store what the user typed in to the template
 1151:         my @shown = &Apache::loncommon::get_env_multiple('form.showfield');
 1152:         $syllabus->{'uploaded.fields'} = '';
 1153:         if (@shown == 0) {
 1154:             $syllabus->{'uploaded.fields'} = 'none';
 1155:         } else {
 1156:             foreach my $field (sort(@shown)) {
 1157:                 if (($field eq '000_showpeople') ||
 1158:                     ($field eq '111_showrssfeeds') ||
 1159:                     ($syllabusfields->{$field})) {
 1160:                     my ($prefix) = split(/_/,$field);
 1161:                     $syllabus->{'uploaded.fields'} .= $prefix.',';
 1162:                 }
 1163:                 if ($field eq '000_showpeople') {
 1164:                     my @hideusers = &Apache::loncommon::get_env_multiple('form.hideuser');
 1165:                     my @hideroles = &Apache::loncommon::get_env_multiple('form.hiderole');
 1166:                     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum,1);
 1167:                     my %personnel;
 1168:                     foreach my $key (keys(%coursepersonnel)) {
 1169:                         map { $personnel{$key}{$_} = 1; } split(/,/,$coursepersonnel{$key});
 1170:                     }
 1171:                     %{$syllabus->{'personnel'}} = ();
 1172:                     $syllabus->{'personnel'}{'hideuser'} = '';
 1173:                     $syllabus->{'personnel'}{'hiderole'} = '';
 1174:                     foreach my $role (@hideroles) {
 1175:                         if (exists($personnel{$role})) {
 1176:                             $syllabus->{'personnel'}{'hiderole'} .= $role.',';
 1177:                         }
 1178:                     }
 1179:                     foreach my $item (@hideusers) {
 1180:                         my ($role,$user) = split(/\&/,$item);
 1181:                         if (ref($personnel{$role}) eq 'HASH') {
 1182:                             if ($personnel{$role}{$user}) {
 1183:                                 $syllabus->{'personnel'}{'hideuser'} .= $item.',';
 1184:                             }
 1185:                         }
 1186:                     }
 1187:                     $syllabus->{'personnel'}{'hideuser'} =~ s/,$//;
 1188:                     $syllabus->{'personnel'}{'hiderole'} =~ s/,$//;
 1189:                 }
 1190:             }
 1191:             $syllabus->{'uploaded.fields'} =~ s/,$//;
 1192:         }
 1193:         foreach my $syl_field (keys(%{$syllabusfields})) {
 1194:             my $field=$env{'form.'.$syl_field};
 1195:             chomp($field);
 1196:             my $gateway = Apache::lonhtmlgateway->new();
 1197:             $field = $gateway->process_incoming_html($field,1);
 1198:                             #here it will be stored
 1199:             $syllabus->{$syl_field}=$field;
 1200:             if ($syl_field eq 'lll_includeurl') { # clean up included URLs
 1201:                 my $field='';
 1202:                 foreach my $value (split(/\n/,$syllabus->{$syl_field})) {
 1203:                     my $url=$value;
 1204: # get rid of leading and trailing spaces
 1205:                     $url=~s/^\s+//;
 1206:                     $url=~s/\s+$//;
 1207:                     if ($url=~m|^https?\://([^/]+)/(.+)$|) {
 1208:                         my $host = $1;
 1209:                         my $remainder=$2;
 1210: # remove the hostname from internal URLs
 1211:                         my $hostname = &Apache::lonnet::hostname($host);
 1212:                         my %all_hostnames = &Apache::lonnet::all_hostnames();
 1213:                         foreach my $possible_host (keys(%all_hostnames)) {
 1214:                             if ($possible_host =~ /\Q$hostname\E/i) {
 1215:                                 $url=$remainder;
 1216:                             }
 1217:                         }
 1218:                     }
 1219: # norm internal URLs
 1220:                     unless ($url=~/^https?\:/) {
 1221:                         $url=&Apache::lonnet::clutter($url);
 1222:                     }
 1223: # re-assemble field
 1224:                     if ($url) {
 1225:                         $field.=$url."\n";
 1226:                     }
 1227:                 }
 1228:                 $syllabus->{$syl_field}=$field;
 1229:             }
 1230:         }
 1231:         my $now = time;
 1232:         $syllabus->{'uploaded.domain'}=$env{'user.domain'};
 1233:         $syllabus->{'uploaded.name'}=$env{'user.name'};
 1234:         $syllabus->{'uploaded.lastmodified'} = $now;
 1235:         my $putres = &Apache::lonnet::put('syllabus',$syllabus,$cdom,$cnum);
 1236:         if ($putres eq 'ok') {
 1237:             ($uploaded,$minimal,$external) = 
 1238:                 &update_syllabus_env($cdom,$cnum,$courseenv,$env{'form.choice'},$uploaded,
 1239:                                      $minimal,$external);
 1240:             $output = '<div>'.
 1241:                       &Apache::lonhtmlcommon::confirm_success(&mt('Template saved.')).
 1242:                       '</div>';
 1243:         } else {
 1244:             $output = '<div class="LC_error">'.
 1245:                       &mt('An error occurred storing the template: [_1]',$putres).
 1246:                       '</div>';
 1247:         }
 1248:     } elsif ($env{'form.choice'} eq 'url') {
 1249:         if ($env{'form.externalsyllabus'} =~ m{^https?://}) {
 1250:             if ($env{'form.externalsyllabus'} eq $external) {
 1251:                 $output = '<div class="LC_info">'.
 1252:                           &mt('External URL unchanged.').
 1253:                           '</div>';
 1254:                 ($uploaded,$minimal,$external) =
 1255:                     &update_syllabus_env($cdom,$cnum,$courseenv,$env{'form.choice'},$uploaded,
 1256:                                          $minimal,$external);
 1257:             } else {
 1258:                 $external=$env{'form.externalsyllabus'};
 1259:                 $external =~ s/(`)//g;
 1260:                 my $putres =
 1261:                     &Apache::lonnet::put('environment',{externalsyllabus=>$external},
 1262:                                          $cdom,$cnum);
 1263:                 if ($putres eq 'ok') {
 1264:                     &Apache::lonnet::appenv({'course.'.$env{'request.course.id'}.'.externalsyllabus' => $external});
 1265:                     $output = '<div>'.
 1266:                               &Apache::lonhtmlcommon::confirm_success(&mt('External URL saved.')).
 1267:                              '</div>';
 1268:                     ($uploaded,$minimal,$external) =
 1269:                         &update_syllabus_env($cdom,$cnum,$courseenv,$env{'form.choice'},$uploaded,
 1270:                                              $minimal,$external);
 1271:                 } else {
 1272:                     $output = '<div class="LC_error">'.
 1273:                               &mt('An error occurred storing the external URL: [_1]',$putres).
 1274:                               '</div>';
 1275:                 }
 1276:             }
 1277:         } else {
 1278:             $output = '<div class="LC_error">'.
 1279:                       &mt('External URL not saved -- invalid URL.').
 1280:                       '</div>';
 1281:         }
 1282:     } elsif (($env{'form.choice'} eq 'file') || ($env{'form.choice'} eq 'minimal')) {
 1283:         # Process file upload - phase one - upload and parse primary file.
 1284:         my ($upload_result,$uploadphase,$url,$needlink,$error,$errormsg);
 1285:         if ($env{'form.choice'} eq 'file') {
 1286:             if ($env{'form.syllabusfile.filename'}) {
 1287:                 my %allfiles = ();
 1288:                 my %codebase = ();
 1289:                 ($url,$needlink) = &process_upload(\$output,$cnum,$cdom,
 1290:                                                    \%allfiles,\%codebase);
 1291:             } else {
 1292:                 $output = '<div class="LC_info">'.
 1293:                           &mt('No file uploaded').
 1294:                           '</div>';
 1295:             }
 1296:         } elsif ($env{'form.choice'} eq 'minimal') {
 1297:             $url = "/uploaded/$cdom/$cnum/portfolio/syllabus/loncapa.html";
 1298:             my $filecontents=&Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$url));
 1299:             if ($filecontents eq -1) {
 1300:                 $url = &default_minimal_syllabus($cnum,$cdom);
 1301:             }
 1302:         }
 1303:         if ($url =~ m{^/uploaded/\Q$cdom\E/\Q$cnum\E.*/[^/]+$}) {
 1304:             my $exturl = &home_http_host($cdom,$cnum);
 1305:             if ($exturl) {
 1306:                 $exturl .= $url;
 1307:             }
 1308:             my %storehash;
 1309:             if ($env{'form.choice'} eq 'minimal') {
 1310:                 $storehash{'minimalsyllabus'} = $url;
 1311:             } else {
 1312:                 $storehash{'uploadedsyllabus'} = $url;
 1313:             }
 1314:             if ($exturl) {
 1315:                 $storehash{'externalsyllabus'} = $exturl;
 1316:                 if ($exturl =~ /\.(html?|txt|js|css)$/) {
 1317:                     $exturl .= '?inhibitmenu=yes';
 1318:                 }
 1319:             } else {
 1320:                 $storehash{'externalsyllabus'} = '',
 1321:             }
 1322:             my $putres =
 1323:                 &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 1324:             if ($putres eq 'ok') {
 1325:                 &Apache::lonnet::make_public_indefinitely($url);
 1326:                 foreach my $key (keys(%storehash)) {
 1327:                     &Apache::lonnet::appenv({'course.'.$env{'request.course.id'}.'.'.$key => $storehash{$key}});
 1328:                 }
 1329:                 if ($env{'form.choice'} eq 'minimal') {
 1330:                     $minimal = $url;
 1331:                 } else {
 1332:                     $uploaded = $url;
 1333:                 }
 1334:                 if ($needlink) {
 1335:                     $output .= &return_to_editor($cdom,$cnum);
 1336:                     $earlyout = 1;
 1337:                 }
 1338:                 ($uploaded,$minimal,$external) =
 1339:                     &update_syllabus_env($cdom,$cnum,$courseenv,$env{'form.choice'},$uploaded,
 1340:                                          $minimal,$external);
 1341:             } else {
 1342:                 $error = 1;
 1343:                 $errormsg = $putres;
 1344:             }
 1345:         } else {
 1346:             $error = 1;
 1347:         }
 1348:         if ($error) {
 1349:             $output = '<div class="LC_error">';
 1350:             if ($env{'form.choice'} eq 'minimal') {
 1351:                 $output = &mt('An error occurred creating the minimal template file [_1]',$errormsg);
 1352:             } else {
 1353:                 $output = &mt('An error occurred storing the uploaded file [_1]',$errormsg);
 1354:             }
 1355:             $output .= '</div>';
 1356:         }
 1357:     } elsif ($env{'form.phase'} eq 'upload_embedded') {
 1358:         # Process file upload - phase two - upload embedded objects
 1359:         my $uploadphase = 'check_embedded';
 1360:         my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');
 1361:         my $state = &embedded_form_elems($uploadphase,$primaryurl);
 1362:         my $url_root = '/uploaded/'.$cdom.'/'.$cnum;
 1363:         my $actionurl = "/public/$cdom/$cnum/syllabus";
 1364:         my ($result,$flag,$numpathchgs) =
 1365:             &Apache::loncommon::upload_embedded('syllabus','portfolio/syllabus',
 1366:                 $cnum,$cdom,'/userfiles',$url_root,undef,undef,undef,$state,
 1367:                 $actionurl);
 1368:         unless ($numpathchgs) {
 1369:             my $modres =
 1370:                 &Apache::loncommon::modify_html_refs('syllabus','portfolio/syllabus',
 1371:                                                      $cnum,$cdom,
 1372:                                                      '/userfiles',$env{'form.primaryurl'});
 1373:             $result .= $modres;
 1374:         }
 1375:         $output = $result.&return_to_editor($cdom,$cnum);
 1376:         $earlyout = 1;
 1377:     } elsif ($env{'form.phase'} eq 'check_embedded') {
 1378:         # Process file upload - phase three - modify references in HTML file
 1379:         my $uploadphase = 'modified_orightml';
 1380:         my $result =
 1381:             &Apache::loncommon::modify_html_refs('syllabus','portfolio/syllabus',
 1382:                                                  $cnum,$cdom,
 1383:                                                  '/userfiles',$env{'form.primaryurl'});
 1384:         $output = $result.&return_to_editor($cdom,$cnum);
 1385:         $earlyout = 1;
 1386:     }
 1387:     return ($earlyout,$uploaded,$external,$minimal,$output);
 1388: }
 1389: 
 1390: sub default_minimal_syllabus {
 1391:     my ($cnum,$cdom) = @_;
 1392:     my $title;
 1393:     if ($env{'form.syllabustitle'}) {
 1394:         $title = $env{'form.syllabustitle'};
 1395:         $title =~ s{`}{}g;
 1396:         $title=~s/^\s+//;
 1397:         $title=~s/\s+$//;
 1398:     }
 1399:     if ($title eq '') {
 1400:         $title = &mt('Syllabus');
 1401:     }
 1402:     my $initialtext = &mt('Replace with your own content.');
 1403:     my $newhtml = <<END;
 1404: <html>
 1405: <head>
 1406: <title>$title</title>
 1407: </head>
 1408: <body bgcolor="#ffffff">
 1409: <h2>$title</h2>
 1410: $initialtext
 1411: </body>
 1412: </html>
 1413: END
 1414:     $env{'form.output'}=$newhtml;
 1415:     return &Apache::lonnet::finishuserfileupload($cnum,$cdom,'output',
 1416:                                                  'portfolio/syllabus/loncapa.html');
 1417: }
 1418: 
 1419: sub update_syllabus_env {
 1420:     my ($cdom,$cnum,$courseenv,$saved,$uploaded,$minimal,$external) = @_;
 1421:     return ($uploaded,$minimal,$external) unless(ref($courseenv) eq 'HASH');
 1422:     my $now = time;
 1423:     my (@envkeys,%storehash);
 1424:     if ($saved eq 'template') {
 1425:         if ($uploaded || $env{'course.'.$env{'request.course.id'}.'.uploadedsyllabus'}) {
 1426:             push(@envkeys,'uploaded');
 1427:         }
 1428:         if ($minimal || $env{'course.'.$env{'request.course.id'}.'.minimalsyllabus'}) {
 1429:             push(@envkeys,'minimal');
 1430:         }
 1431:         if ($external || $env{'course.'.$env{'request.course.id'}.'.externalsyllabus'}) {
 1432:             push(@envkeys,'external');
 1433:         }
 1434:         $storehash{'updatedsyllabus'} = $now;
 1435:         &Apache::lonnet::appenv({'course.'.$env{'request.course.id'}.'.updatedsyllabus' => $now
 1436: });
 1437:     } elsif ($saved eq 'url') {
 1438:         my $prefix = &home_http_host($cdom,$cnum);
 1439:         if ($external =~ m{^\Q$prefix/uploaded/$cdom/$cnum/portfolio/syllabus/\E(.+)$}) {
 1440:             my $file = $1;
 1441:             if ($file eq 'loncapa.html') {
 1442:                 if ($uploaded || $env{'course.'.$env{'request.course.id'}.'.uploadedsyllabus'}) {
 1443:                     push(@envkeys,'uploaded');
 1444:                 }
 1445:             } elsif ($minimal || $env{'course.'.$env{'request.course.id'}.'.minimalsyllabus'}) {
 1446:                 push(@envkeys,'minimal');
 1447:             }
 1448:         } else {
 1449:             if ($uploaded || $env{'course.'.$env{'request.course.id'}.'.uploadedsyllabus'}) {
 1450:                 push(@envkeys,'uploaded');
 1451:             }
 1452:             if ($minimal || $env{'course.'.$env{'request.course.id'}.'.minimalsyllabus'}) {
 1453:                 push(@envkeys,'minimal');
 1454:             }
 1455:         }
 1456:     } elsif ($saved eq 'file') {
 1457:         if ($minimal || $env{'course.'.$env{'request.course.id'}.'.minimalsyllabus'}) {
 1458:             push(@envkeys,'minimal');
 1459:         }
 1460:     } elsif ($saved eq 'minimal') {
 1461:         if ($uploaded || $env{'course.'.$env{'request.course.id'}.'.uploadedsyllabus'}) {
 1462:             push(@envkeys,'uploaded');
 1463:         }
 1464:     }
 1465:     if (@envkeys > 0) {
 1466:         foreach my $item (@envkeys) {
 1467:             my $key = $item.'syllabus';
 1468:             if ($courseenv->{$key} ne '') {
 1469:                 &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 1470:                 if ($item eq 'minimal') {
 1471:                     &update_access_permissions($cdom,$cnum,'/syllabus/loncapa.html');
 1472:                 } elsif ($item eq 'uploaded') {
 1473:                     if ($courseenv->{$key} =~ m{^\Q/uploaded/$cdom/$cnum/portfolio\E(/syllabus/.+)$}) {
 1474:                         my $filename = $1;
 1475:                         &update_access_permissions($cdom,$cnum,$filename);
 1476:                     }
 1477:                 }
 1478:                 $storehash{$key} = '';
 1479:             } elsif ($env{'course.'.$env{'request.course.id'}.'.'.$key} ne '') {
 1480:                 &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 1481:             }
 1482:             if ($item eq 'uploaded') {
 1483:                 undef($uploaded);
 1484:             }
 1485:             if ($item eq 'external') {
 1486:                 undef($external);
 1487:             }
 1488:             if ($item eq 'minimal') {
 1489:                 undef($minimal);
 1490:             }
 1491:         }
 1492:     }
 1493:     if (keys(%storehash) > 0) {
 1494:         &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 1495:     }
 1496:     return ($uploaded,$minimal,$external);
 1497: }
 1498: 
 1499: sub update_access_permissions {
 1500:     my ($cdom,$cnum,$file_name) = @_;
 1501:     my $current_permissions = &Apache::lonnet::get_portfile_permissions($cdom,$cnum);
 1502:     my %access_controls =
 1503:         &Apache::lonnet::get_access_controls($current_permissions,'',$file_name);
 1504:     if (keys(%access_controls) > 0) {
 1505:         my %changes;
 1506:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 1507:             $changes{'delete'}{$key} = 1;
 1508:         }
 1509:         if (keys(%changes) > 0) {
 1510:             my ($outcome,$deloutcome,$new_values,$translation) =
 1511:                 &Apache::lonnet::modify_access_controls($file_name,\%changes,
 1512:                                                         $cdom,$cnum);
 1513:         }
 1514:     }
 1515:     return; 
 1516: }
 1517: 
 1518: sub home_http_host {
 1519:     my ($cdom,$cnum) = @_;
 1520:     my $home=&Apache::lonnet::homeserver($cnum,$cdom);
 1521:     if ($home ne 'no_host') {
 1522:         my $protocol = $Apache::lonnet::protocol{$home};
 1523:         $protocol = 'http' if ($protocol ne 'https');
 1524:         return $protocol.'://'.&Apache::lonnet::hostname($home);
 1525:     }
 1526:     return;
 1527: }
 1528: 
 1529: sub process_upload {
 1530:     my ($upload_output,$cnum,$cdom,$allfiles,$codebase) = @_;
 1531:     my ($parseaction,$showupload,$mimetype);
 1532:     my $dest = 'portfolio/syllabus';
 1533:     if ($env{'form.parserflag'}) {
 1534:         $parseaction = 'parse';
 1535:     }
 1536:     my $url=&Apache::lonnet::userfileupload('syllabusfile','syllabus',$dest,
 1537:                                             $parseaction,$allfiles,
 1538:                                             $codebase,undef,undef,undef,undef,
 1539:                                             undef,undef,\$mimetype);
 1540:     if ($url =~ m{^/uploaded/\Q$cdom\E/\Q$cnum\E.*/([^/]+)$}) {
 1541:         my $stored = $1;
 1542:         $showupload = '<p>'.&mt('Uploaded [_1]',
 1543:                                 '<span class="LC_filename">'.$stored.'</span>').
 1544:                       '</p>';
 1545:     } else {
 1546:         my ($filename) = ($env{'form.syllabusfile.filename'} =~ m{([^/]+)$});
 1547:         $$upload_output = '<div class="LC_error" id="uploadfileresult">'.
 1548:                           &mt('Unable to save file [_1].',
 1549:                               '<span class="LC_filename">'.$filename.'</span>').
 1550:                           '</div>';
 1551:         return (); 
 1552:     }
 1553:     my $needlink;
 1554:     if (($parseaction eq 'parse') && ($mimetype eq 'text/html')) {
 1555:         $$upload_output = $showupload;
 1556:         my $total_embedded = scalar(keys(%{$allfiles}));
 1557:         if ($total_embedded > 0) {
 1558:             my $uploadphase = 'upload_embedded';
 1559:             my $primaryurl = &HTML::Entities::encode($url,'<>&"');
 1560:             my $state = &embedded_form_elems($uploadphase,$primaryurl);
 1561:             my $actionurl = "/public/$cdom/$cnum/syllabus";
 1562:             my ($embedded,$num,$numpathchanges,$existing);
 1563:             ($embedded,$num,$numpathchanges,$existing) =
 1564:                 &Apache::loncommon::ask_for_embedded_content($actionurl,$state,
 1565:                                                              $allfiles,$codebase,
 1566:                                                             {'error_on_invalid_names'   => 1,
 1567:                                                              'ignore_remote_references' => 1,});
 1568:             if ($embedded) {
 1569:                 $needlink = 1;
 1570:                 if ($num) {
 1571:                     $$upload_output .=
 1572:                         '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
 1573:                 } elsif ($numpathchanges) {
 1574:                     $$upload_output .= $embedded;
 1575:                 } else {
 1576:                     $$upload_output .= $embedded;
 1577:                     &Apache::loncommon::modify_html_refs('syllabus','portfolio/syllabus',
 1578:                                                          $cnum,$cdom,'/userfiles',$url);
 1579:                 }
 1580:             } else {
 1581:                 $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
 1582:                 &Apache::loncommon::modify_html_refs('syllabus','portfolio/syllabus',
 1583:                                                      $cnum,$cdom,'/userfiles',$url);
 1584: 
 1585:             }
 1586:         } else {
 1587:             $$upload_output .= &mt('No embedded items identified').'<br />';
 1588:         }
 1589:         $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
 1590:     }
 1591:     return ($url,$needlink);
 1592: }
 1593: 
 1594: sub embedded_form_elems {
 1595:     my ($phase,$primaryurl) = @_;
 1596:     return <<STATE;
 1597:     <input type="hidden" name="forceedit" value="1" />
 1598:     <input type="hidden" name="cmd" value="upload_embedded" />
 1599:     <input type="hidden" name="phase" value="$phase" />
 1600:     <input type="hidden" name="primaryurl" value="$primaryurl" />
 1601: STATE
 1602: }
 1603: 
 1604: sub return_to_editor {
 1605:     my ($cdom,$cnum) = @_;
 1606:     my $actionurl = "/public/$cdom/$cnum/syllabus";
 1607:     return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'.
 1608:            '<input type="hidden" name="forceedit" value="1" />'."\n".
 1609:            '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
 1610:            '</a></p>';
 1611: }
 1612: 
 1613: sub editfile_button {
 1614:     my ($url,$context,$editable) = @_;
 1615:     my $edittext=&mt('Edit');
 1616:     my $deltext=&mt('Delete');
 1617:     my $output;
 1618:     if ($editable) {
 1619:         $output = '
 1620:                 <input type="button" value="'.$edittext.'" onclick="javascript:gotoeditor('."'$url'".');" name="edit_'.$context.'" />
 1621:                 &nbsp;&nbsp;&nbsp;';
 1622:     }
 1623:     $output .= '
 1624:                 <input type="button" value="'.$deltext.'" onclick="javascript:dodelete('."'$context'".');" name="del_'.$context.'" />
 1625:                 <input type="hidden" value="" name="deleteuploaded_'.$context.'" id="deleteuploaded_'.$context.'" />
 1626:     ';
 1627:     return $output;
 1628: }
 1629: 
 1630: sub editbutton_js {
 1631:     my %js_lt = &Apache::lonlocal::texthash(
 1632:                min    => 'Are you sure you want to delete the contents of the syllabus template?',
 1633:                file   => 'Are you sure you want to delete the uploaded syllabus file?',
 1634:                noundo => 'This action cannot be reversed.'
 1635:              );
 1636:     &js_escape(\%js_lt);
 1637:     return <<ENDJS;
 1638:                 <script type="text/javascript">
 1639:                 // <![CDATA[
 1640:                   function gotoeditor(url) {
 1641:                       document.location.href = url+'?editmode=1&forceedit=1';
 1642:                   }
 1643:                   function dodelete(caller,url) {
 1644:                       if (document.getElementById('deleteuploaded_'+caller)) {
 1645:                           document.getElementById('deleteuploaded_'+caller).value=1;
 1646:                           if (caller == 'minimal') {
 1647:                               if (confirm("$js_lt{'min'}"+"\\n"+"$js_lt{'noundo'}")) {
 1648:                                   document.syllabus.submit();
 1649:                               }
 1650:                           }
 1651:                           if (caller == 'file') {
 1652:                               if (confirm("$js_lt{'file'}"+"\\n"+"$js_lt{'noundo'}")) {
 1653:                                   document.syllabus.submit();
 1654:                               }
 1655:                           }
 1656:                       }
 1657:                       return;   
 1658:                   }
 1659:                 // ]]>
 1660:                 </script>
 1661: ENDJS
 1662: }
 1663: 
 1664: 1;
 1665: __END__

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