File:  [LON-CAPA] / loncom / interface / lonsyllabus.pm
Revision 1.121: download - view: text, annotated - select for diffs
Thu May 9 05:43:30 2013 UTC (11 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Syllabus.
  - code migrated from handler() to new subroutines to facilitate reuse.
  - &save_changes() - used to process and store changes to syllabus made
    by CC.
  - &print_header() - used to call start_page etc., after any updates have
    been stored by &save_changes
  - &get_personnel() - used to build display of course personnel.
- Templated syllabus page
  - checkboxes for fields can be used to hide fields which currently contain
    entries (note these fields will still be viewable on pre-LON-CAPA 2.11
    servers).

    1: # The LearningOnline Network
    2: # Syllabus
    3: #
    4: # $Id: lonsyllabus.pm,v 1.121 2013/05/09 05:43:30 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::lonannounce;
   39: use Apache::lonlocal;
   40: use Apache::lonhtmlcommon;
   41: use Apache::lonspeller();
   42: use HTML::Entities();
   43: 
   44: sub handler {
   45:     my $r = shift;
   46:     &Apache::loncommon::content_type($r,'text/html');
   47:     $r->send_http_header;
   48:     return OK if $r->header_only;
   49: 
   50:     my $target=$env{'form.grade_target'};
   51: # --------------------------------------------------- Get course info from URL
   52:     my (undef,undef,$cdom,$cnum)=split(/\//,$r->uri);
   53: # ------------------------------------------------------------ Get query string
   54:     &Apache::loncommon::get_unprocessed_cgi
   55:                         ($ENV{'QUERY_STRING'},['register','forceedit','todocs',
   56:                                                'folderpath','title']);
   57: # ----------------------------------------------------- Is this even a course?
   58:     my $homeserver=&Apache::lonnet::homeserver($cnum,$cdom);
   59:     if ($homeserver eq 'no_host') {
   60:         &Apache::loncommon::content_type($r,'text/html');
   61:         $r->send_http_header;
   62:         &Apache::loncommon::simple_error_page($r,'No syllabus available',
   63:                           'No syllabus available');
   64:         return OK;
   65:     } elsif (!&Apache::lonnet::is_course($cdom,$cnum)) {
   66:         &Apache::loncommon::content_type($r,'text/html');
   67:         $r->send_http_header;
   68:         &Apache::loncommon::simple_error_page($r,'No syllabus available',
   69:                           'The course/community for which the syllabus was requested does not exist.');
   70:         return OK;
   71:     }
   72: # ------------------------------------- There is such a course, get environment
   73:     my %courseenv=&Apache::lonnet::dump('environment',$cdom,$cnum);
   74: 
   75: # ------------------------------------------------------------ Print the screen
   76: 
   77:     if ($target eq 'tex') {
   78:         $r->print(&Apache::lonprintout::print_latex_header($env{'form.latex_type'}));
   79:     }
   80: 
   81: # --------------------------------------------------------------- Force Student
   82:     my ($forceedit,$forcestudent);
   83:     if ($env{'form.forceedit'}) { $forceedit=1; }
   84:     if (!$forceedit) {
   85:         $forcestudent=1;
   86:     }
   87: 
   88: # --------------------------------------------------------------- Check Privileges
   89:     my $allowed = 0;
   90:     if ($env{'user.environment'}) {
   91: # does this user have privileges to post, etc?
   92:         if ($env{'request.course.id'}
   93:         && $cdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}
   94:         && $cnum eq $env{'course.'.$env{'request.course.id'}.'.num'}) {
   95:             $allowed=&Apache::lonnet::allowed('mdc',$env{'request.course.id'});
   96:             if ($forcestudent or $target eq 'tex') { $allowed=0; }
   97:         }
   98:     }
   99: 
  100: # -------------------------------------------------- Let's see who handles this
  101:     my $external=$courseenv{'externalsyllabus'};
  102:     my $uploaded=$courseenv{'uploadedsyllabus'};
  103: 
  104:     if ($uploaded =~/\w/) {
  105:         if ($external =~ m{\Q$uploaded\E$}) {
  106:             undef($external);
  107:         }
  108:         unless ($allowed && $forceedit) {
  109:             my $file=&Apache::lonnet::filelocation("",$uploaded);
  110:             if ($file =~ /\.(sty|css|js|txt|tex|html?)$/) {  
  111:                 my $filetype;
  112:                 if ($file =~ /\.(sty|css|js|txt|tex)$/) {
  113:                     $filetype=$1;
  114:                 } else {
  115:                     $filetype='html';
  116:                 }
  117:                 my $result = '';
  118:                 my $filecontents=&Apache::lonnet::getfile($file);
  119:                 if ($filecontents eq -1) {
  120:                     $r->print(&mt('Syllabus file unavailable'));
  121:                 } elsif ($filetype eq 'html') {
  122:                     my %mystyle;
  123:                     &Apache::structuretags::reset_problem_globals();
  124:                     my $oldfile = $env{'request.filename'};
  125:                     $env{'request.filename'} = $uploaded;
  126:                     $result = &Apache::lonxml::xmlparse($r,'web',$filecontents,
  127:                                                         '',%mystyle);
  128:                     &Apache::structuretags::reset_problem_globals();
  129:                     &Apache::lonhomework::finished_parsing();
  130:                     $env{'request.filename'} = $oldfile;
  131:                     &Apache::lonxml::add_messages(\$result);
  132:                     $r->print($result);
  133:                 }
  134:             } else {
  135:                 $r->print(&Apache::lonwrapper::wrapper($uploaded));
  136:             }
  137:             return OK;
  138:         }
  139:     } elsif ($external=~/\w/) {
  140:         unless ($allowed && $forceedit) {
  141:             $r->print(&Apache::lonwrapper::wrapper($external));
  142:             return OK;
  143:         }
  144:     }
  145: 
  146:     my $crstype = &Apache::loncommon::course_type();
  147: 
  148: # ------------------------------ The buck stops here: internal syllabus display
  149: # --------------------------------------------------------- The syllabus fields
  150:     my %syllabusfields=&Apache::lonlocal::texthash(
  151:        'aaa_instructorinfo' => 'Instructor Information',
  152:        'bbb_description'    => 'Course Description',
  153:        'ccc_prereq'         => 'Prerequisites',
  154:        'cdc_classhours'     => 'Class Hours',
  155:        'ddd_officehours'    => 'Office Hours',
  156:        'eee_helproom'       => 'Helproom Hours',
  157:        'efe_projectinfo'    => 'Project Information',
  158:        'fff_examinfo'       => 'Exam Information',
  159:        'fgf_deadlines'      => 'Deadlines',
  160:        'ggg_grading'        => 'Grading Information',
  161:        'hhh_readings'       => 'Readings',
  162:        'iii_coursepack'     => 'Coursepack',
  163:        'jjj_weblinks'       => 'Web Links',
  164:        'kkk_textbook'       => 'Textbook',
  165:        'lll_includeurl'     => 'URLs To Include in Syllabus');
  166: # ---------------------------------------------------------- Load syllabus info
  167:     my %syllabus=&Apache::lonnet::dump('syllabus',$cdom,$cnum);
  168:     my ($output,%displayfields,%noshow);
  169: 
  170: # This handler might be called anonymously ...
  171: # ----------------------------------------------------- Only if not public call
  172:     if ($allowed) {
  173:         if (($env{'form.choice'} =~ /^(template|url|file)$/) ||
  174:             ($env{'form.phase'} =~ /^(upload|check)_embedded$/)) {
  175:             my $earlyout;
  176:             ($earlyout,$uploaded,$external,$output) =
  177:                 &save_changes($cnum,$cdom,$uploaded,$external,\%syllabus,
  178:                               \%syllabusfields,\%courseenv);
  179:             if ($earlyout) {
  180:                 if ($target ne 'tex') {
  181:                     &print_header($r,$cnum,$cdom,$crstype,$allowed,$forceedit,
  182:                                   \%syllabus,\%syllabusfields);
  183:                     $r->print($output);
  184:                 }
  185:                 return OK;
  186:             }
  187:         }
  188:     }
  189:     if ($target ne 'tex') {
  190:         &print_header($r,$cnum,$cdom,$crstype,$allowed,$forceedit,\%syllabus,
  191:                       \%syllabusfields);
  192:         $r->print($output);
  193:     }
  194: 
  195: # -------------------------------------------- Determine which fields are shown 
  196: 
  197:     if ($syllabus{'uploaded.fields'}) {
  198:         if ($syllabus{'uploaded.fields'} eq 'none') {
  199:             foreach my $field (keys(%syllabusfields)) {
  200:                 $displayfields{$field} = ' style="display:none;"';
  201:                 $noshow{$field} = 1;
  202:             }
  203:         } else {
  204:             my %included;
  205:             map { $included{$_} = 1; } split(/,/,$syllabus{'uploaded.fields'});
  206:             foreach my $field (keys(%syllabusfields)) {
  207:                 my ($prefix) = split(/_/,$field);
  208:                 if ($included{$prefix}) {
  209:                     $displayfields{$field} = ' style="display:block;"';
  210:                 } else {
  211:                     $displayfields{$field} = ' style="display:none;"';
  212:                     $noshow{$field} = 1;
  213:                 }
  214:             }
  215:         }
  216:     } else {
  217:         foreach my $field (keys(%syllabusfields)) {
  218:             if ($syllabus{$field} ne '') {
  219:                 $displayfields{$field} = ' style="display:block;"';
  220:             } else {
  221:                 $displayfields{$field} = ' style="display:none;"';
  222:             }
  223:         }
  224:     }
  225: 
  226:     if ($allowed) {
  227: #---------------------------------- Print External URL Syllabus Info if editing
  228:         if ($target ne 'tex') {
  229:             my $protocol = $Apache::lonnet::protocol{$homeserver};
  230:             $protocol = 'http' if ($protocol ne 'https');
  231:             my $link = $protocol.'://'.&Apache::lonnet::hostname($homeserver).$r->uri;
  232:             $r->print('<div class="LC_left_float">'
  233:                      .'<span class="LC_help_open_topic LC_info">'
  234:                      .'<span class="LC_info">'
  235:                      .&mt('Public link (no log-in): [_1]','<tt>'.$link.'</tt>')
  236:                      .'&nbsp;</span>'.&Apache::loncommon::help_open_topic('Syllabus_ExtLink')
  237:                      .'</span>'
  238:                      .'</div><div style="padding:0;clear:both;margin:0;border:0"></div>'."\n");
  239:             my $lonhost = $r->dir_config('lonHostID');
  240:             $r->print(&chooser($external,$uploaded,$cdom,$cnum,$lonhost,\%syllabusfields,
  241:                                \%syllabus));
  242:         }
  243:     } else {
  244: #--------------------------------------------- Print last update unless editing
  245:         my $lastmod=$syllabus{'uploaded.lastmodified'};
  246:         $lastmod=($lastmod?&Apache::lonlocal::locallocaltime($lastmod):&mt('never'));
  247:         my $who;
  248:         if ($syllabus{'uploaded.lastmodified'}) {
  249:             if (($env{'user.name'} ne 'public') && ($env{'user.domain'} ne 'public')) {
  250:                 $who = &Apache::loncommon::aboutmewrapper(
  251:                        &Apache::loncommon::plainname($syllabus{'uploaded.name'},
  252:                        $syllabus{'uploaded.domain'}),$syllabus{'uploaded.name'},
  253:                        $syllabus{'uploaded.domain'});
  254:             } else {
  255: # Public user?
  256: # Only display name of user, but no link to personal information page
  257:                 $who = &Apache::loncommon::plainname(
  258:                            $syllabus{'uploaded.name'},
  259:                            $syllabus{'uploaded.domain'});
  260:             }
  261:         }
  262:         if ($target ne 'tex') {
  263:             $r->print('<div class="LC_info">'.&mt('Last updated').': '.
  264:                       $lastmod . ' '.
  265:                       ($who ? &mt('by').' '.$who
  266:                            : '' ) .
  267:                       '</div>' );
  268:         } else {
  269:             $r->print('\\\\ '.&mt('Last updated').': '.$lastmod.' '.
  270:                      ($who? &mt('by').'\\\\ '.
  271:                      &Apache::loncommon::plainname($syllabus{'uploaded.name'},$syllabus{'uploaded.domain'})
  272:                      :'')
  273:                     .'\\\\');
  274:         }
  275:     }
  276: 
  277: #-------------------------------------------------------------- Print Headtitle
  278:     if ($target ne 'tex') {
  279:         my $display = 'block';
  280:         if ($external || $uploaded) {
  281:             $display = 'none';
  282:         }
  283:         $r->print('<div class="LC_Box" id="template" style="display: '.$display.'">'.
  284:                    '<h2 class="LC_hcell">'.$courseenv{'description'}.'</h2>');
  285:         if ($allowed) {
  286:             $r->print('<div style="margin: 0; float:left;">'.
  287:                       '<h3>'.&Apache::lonnet::domain($cdom,'description').'</h3>'.
  288:                       '</div>');
  289: # Print Help Text if editing at right side of screen
  290:             $r->print('<div style="margin: 0; float:right;">'.
  291:                       &Apache::loncommon::help_open_topic('Uploaded_Templates_TextBoxes',&mt('Help with filling in text boxes')).
  292:                       '</div><br clear="all" />');
  293:         } else {
  294:             $r->print('<h3>'.&Apache::lonnet::domain($cdom,'description').'</h3>');
  295:         }
  296:     } else {
  297:         $r->print('\noindent{\large\textbf{'.$courseenv{'description'}.'}}\\\\\\\\\textbf{'.
  298:         &Apache::lonnet::domain($cdom,'description').'}\\\\');
  299:     }
  300: # -------------------------------------------------------- Get course personnel
  301:     my $hidepersonnel;
  302:     if (($syllabus{'uploaded.fields'}) &&
  303:         (($syllabus{'uploaded.fields'} eq 'none') ||
  304:          ($syllabus{'uploaded.fields'} !~ /000/))) {
  305:         $hidepersonnel = 1;
  306:     }
  307:     if ($target ne 'tex') {
  308:         if ($allowed) {
  309:             my $display = ' style="display:block;"';
  310:             if ($hidepersonnel) {
  311:                 $display = ' style="display:none;"';
  312:             }
  313:             &Apache::lontemplate::print_start_template($r,&mt('Personnel'),'LC_Box',
  314:                                                        'box_000_showpeople',$display);
  315:             $r->print(&get_personnel($r,$target,$cdom,$cnum,$allowed));
  316:             &Apache::lontemplate::print_end_template($r);
  317:         } else {
  318:             unless ($hidepersonnel) {
  319:                 &Apache::lontemplate::print_start_template($r,&mt('Personnel'),'LC_Box');
  320:                 $r->print(&get_personnel($r,$target,$cdom,$cnum,$allowed));  
  321:                 &Apache::lontemplate::print_end_template($r);
  322:             }
  323:         }
  324:     } else {
  325:         unless ($hidepersonnel) {
  326:             $r->print(&get_personnel($r,$target,$cdom,$cnum,$allowed));
  327:         }
  328:     }
  329: # -------------------------------------------------------------- Announcements?
  330:     my $day = &Apache::lonannounce::showday(time,2,
  331:              &Apache::lonannounce::readcalendar($cdom.'_'.$cnum));
  332:     my $hidefeeds;
  333:     if (($syllabus{'uploaded.fields'}) &&
  334:         (($syllabus{'uploaded.fields'} eq 'none') ||
  335:          ($syllabus{'uploaded.fields'} !~ /111/))) {
  336:         $hidefeeds = 1;
  337:     }
  338:     if ($target ne 'tex') {
  339:         if ($allowed) {
  340:             my $display = ' style="display:block;"';
  341:             if ($hidefeeds) {
  342:                 $display = ' style="display:none;"';
  343:             }
  344:             &Apache::lontemplate::print_start_template($r,&mt('RSS Feeds and Blogs'),'LC_Box',
  345:                                                        'box_111_showrssfeeds',$display);
  346:             my ($numfeeds,$hiddenfeeds,$rsslinktext);
  347:             my $feeds=&Apache::lonrss::advertisefeeds($cnum,$cdom,$forceedit,\$numfeeds,
  348:                                                       \$hiddenfeeds);
  349:             if ($numfeeds) {
  350:                 $r->print($feeds);
  351:                 $rsslinktext = &mt('New RSS Feed or Blog');
  352:             } else {
  353:                 my $msg = '<br />'.
  354:                           &mt("RSS Feeds and Blogs item is not included in a student's view of the syllabus.");
  355:                 if ($hiddenfeeds) {
  356:                     $r->print('<p class="LC_info">'.
  357:                               &mt('All feeds currently hidden').
  358:                               $msg.
  359:                               '</p>');
  360:                 } else {
  361:                     $r->print('<p class="LC_info">'.
  362:                               &mt('No current feeds').
  363:                               $msg.
  364:                               '</p>');
  365:                 }
  366:                 $rsslinktext = &mt('Manage Course RSS Feeds/Blogs');
  367:                 if ($crstype eq 'Community') {
  368:                     $rsslinktext = &mt('Manage Communiity RSS Feeds/Blogs');
  369:                 }
  370:             }
  371:             my $editurl= &Apache::lonnet::absolute_url().'/adm/'.$cdom.'/'.$cnum.'/_rss.html';
  372:             $r->print( '<a href="'.$editurl.'">'.$rsslinktext.'</a>');
  373:             &Apache::lontemplate::print_end_template($r);
  374:         } else {
  375:             unless ($hidefeeds) {
  376:                 my $feeds = &Apache::lonrss::advertisefeeds($cnum,$cdom,$forceedit);
  377:                 if ($feeds ne '') {
  378:                     &Apache::lontemplate::print_start_template($r,&mt('RSS Feeds and Blogs'),'LC_Box');
  379:                     $r->print($feeds);
  380:                     &Apache::lontemplate::print_end_template($r);
  381:                 }
  382:             }
  383:         }
  384:     } else {
  385:         $r->print(&Apache::lonxml::xmlparse($r,'tex',$day));
  386:     }
  387: # ---------------------------------------------------------------- Get syllabus
  388:     if (($syllabus{'uploaded.lastmodified'}) || ($allowed)) {
  389:         if ($allowed) {
  390:             $r->print('<form method="post" action="">');
  391:         }
  392: 
  393: 		my $url_include_handler = sub {
  394: 			my ($r, $field, $message, $group, $data_ref, $fields_ref, $target, $allowed, $display) = @_;
  395: 			my %data = %{$data_ref};
  396: 			my %fields = %{$fields_ref};
  397: 			my $urls=$message;
  398: 			$message='';
  399: 			foreach my $filelink (split(/\n/,$urls)) {
  400: 				my $output='';
  401: 			   # embed style?
  402: 				my ($curfext)=($filelink=~/\.([^\.]+)$/);
  403: 				my $embstyle=&Apache::loncommon::fileembstyle($curfext);
  404: 				if (($embstyle eq 'ssi') || ($curfext=~/\/$/)) {# make ssi call and remove everything but the body contents
  405: 					$output=&Apache::lonnet::ssi_body($filelink);
  406: 				} elsif ($embstyle eq 'img') {# embed as an image
  407: 					$output='<img src="'.$filelink.'" />';
  408: 				}
  409: 				if ($output ne '') {
  410: 					   if ($target ne 'tex') {
  411: 						   $message.='<p>'.$output.'</p>';
  412: 					   } else {
  413: 						   $message.=' '.&Apache::lonxml::xmlparse($r,'tex','<p>'.$output.'</p>').' ';
  414: 					   }
  415: 				}
  416: 			}
  417: 			if ($allowed) {
  418: 				 &Apache::lonfeedback::newline_to_br(\$urls);
  419: 				 &Apache::lontemplate::print_start_template($r,$fields{$field}.
  420: 						  &Apache::loncommon::help_open_topic('Syllabus_URLs'),'LC_Box',
  421:                                                   'box_'.$field,$display);
  422: 				 $r->print($urls);
  423: 				 $r->print("<br /><div>");
  424: 				 &Apache::lontemplate::print_textarea_template($r, $data{$field},
  425: 					$field, Apache::lontemplate->RICH_TEXT_ALWAYS_OFF);
  426: 				 &Apache::lontemplate::print_saveall_template($r);                         
  427: 				 $r->print("</div>");
  428: 				 &Apache::lontemplate::print_end_template($r);
  429: 
  430: 			} else {
  431: 				$r->print($message);
  432: 			}
  433: 		};
  434: 		my %custom_hash = ( 'lll_includeurl' => $url_include_handler );
  435: 		&Apache::lontemplate::print_template_fields($r, \%syllabus, \%syllabusfields, 
  436: 			$target, $allowed, Apache::lontemplate->RICH_TEXT_DETECT_HTML, \%custom_hash,
  437:                         undef,\%displayfields,\%noshow);
  438:         if ($allowed) {
  439:             $r->print('</form>'.
  440:             &Apache::lonhtmlcommon::htmlareaselectactive());
  441:         }
  442:     } else {
  443:         if ($target ne 'tex') {$r->print('<p class="LC_info">');} else {$r->print('\par ');}
  444:         $r->print(&mt('No syllabus information provided.'));
  445:         if ($target ne 'tex') {$r->print('</p>');}
  446:     }
  447:     if ($target ne 'tex') {
  448:         if ($env{'form.backto'} eq 'coursecatalog') {
  449:             $r->print('<form name="backtocat" method="post" action="/adm/coursecatalog">'.
  450:                       &Apache::lonhtmlcommon::echo_form_input(['backto','courseid']).
  451:                       '</form>');
  452:         }
  453:         $r->print(&Apache::loncommon::end_page());
  454:     } else {
  455:         $r->print('\end{document}');
  456:     }
  457:     return OK;
  458: }
  459: 
  460: sub print_header {
  461:     my ($r,$cnum,$cdom,$crstype,$allowed,$forceedit,$syllabus,$syllabusfields) = @_;
  462:     return unless ((ref($syllabus) eq 'HASH') || (ref($syllabusfields) eq 'HASH'));
  463: # ----------------------------------------------------------------- Make header
  464:     my $rss_link = &Apache::lonrss::rss_link($cnum,$cdom);
  465:     my $js;
  466:     if ($env{'form.backto'} eq 'coursecatalog') {
  467:         $js .= <<"ENDSCRIPT";
  468: 
  469: <script type="text/javascript">
  470: // <![CDATA[
  471: 
  472: function ToCatalog(caller) {
  473:     numidx = getIndexByName('coursenum');
  474:         if (numidx > -1) {
  475:             if (caller != 'details') {
  476:                 document.backtocat.elements[numidx].value = '';
  477:             }
  478:         }
  479:     document.backtocat.submit();
  480: }
  481: 
  482: function getIndexByName(item) {
  483:     for (var i=0;i<document.backtocat.elements.length;i++) {
  484:         if (document.backtocat.elements[i].name == item) {
  485:             return i;
  486:         }
  487:     }
  488:     return -1;
  489: }
  490: 
  491: // ]]>
  492: </script>
  493: 
  494: ENDSCRIPT
  495:     }
  496:     if ($allowed && $forceedit) {
  497:         my $check_uncheck = &Apache::loncommon::check_uncheck_jscript();
  498:         my @fieldnames = sort(keys(%{$syllabusfields}));
  499:         unshift(@fieldnames,'000_showpeople','111_showrssfeeds');
  500:         my (@checked,@unchecked);
  501:         if ($syllabus->{'uploaded.fields'} eq 'none') {
  502:             my $lastidx = scalar(@fieldnames)-1;
  503:             @unchecked = (0..$lastidx);
  504:         } elsif ($syllabus->{'uploaded.fields'}) {
  505:             my %included;
  506:             map { $included{$_} = 1; } split(/,/,$syllabus->{'uploaded.fields'});
  507:             for (my $i=0; $i<@fieldnames; $i++) {
  508:                 my ($prefix) = split(/_/,$fieldnames[$i]);
  509:                 if ($included{$prefix}) {
  510:                     push(@checked,$i);
  511:                 } else {
  512:                     push(@unchecked,$i);
  513:                 }
  514:             }
  515:         } else {
  516:             @checked = (0,1);
  517:             for (my $i=2; $i<@fieldnames; $i++) {
  518:                 if ($syllabus->{$fieldnames[$i]}) {
  519:                     push(@checked,$i);
  520:                 } else {
  521:                     push(@unchecked,$i);
  522:                 }
  523:             }
  524:         }
  525:         my $fieldstr = "var fields = new Array('".join("','",@fieldnames)."');";
  526:         my $checkedstr = "var include = new Array('".join("','",@checked)."');";
  527:         my $uncheckedstr = "var exclude = new Array('".join("','",@unchecked)."');";
  528:         my $invurl = &mt('Invalid URL');
  529:         my $urlregexp = <<'ENDREGEXP';
  530: /^([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
  531: ENDREGEXP
  532: 
  533:         $js .= <<"ENDSCRIPT";
  534: 
  535: <script type="text/javascript">
  536: // <![CDATA[
  537: 
  538: function toggleEditor(pick) {
  539:     var choices = new Array('template','url','file','templatebox');
  540:     for (var i=0; i<choices.length; i++) {
  541:         if (((choices[i] == 'templatebox') && (pick == 'template')) ||
  542:             (choices[i] == pick)) {
  543:             document.getElementById(choices[i]).style.display='block';
  544:         } else {
  545:             document.getElementById(choices[i]).style.display='none';
  546:         }
  547:     }
  548:     return;
  549: }
  550: 
  551: var regexp = $urlregexp;
  552: 
  553: function extUrlPreview(caller) {
  554:     if (document.getElementById(caller)) {
  555:         var url = document.getElementById(caller).value;
  556:         if (regexp.test(url)) {
  557:             openMyModal(url,500,400,'yes');
  558:         } else {
  559:             alert("$invurl");
  560:         }
  561:     }
  562: }
  563: 
  564: function toggleBox(name,caller) {
  565:     if (name == 'all') {
  566:         if (document.syllabus.showfield.length > 0) {
  567:             for (var i=0; i<document.syllabus.showfield.length; i++) {
  568:                 if (document.syllabus.showfield[i].checked) {
  569:                     if (document.getElementById('box_'+document.syllabus.showfield[i].value)) {
  570:                         document.getElementById('box_'+document.syllabus.showfield[i].value).style.display='block';
  571:                     }
  572:                 } else {
  573:                     if (document.getElementById('box_'+document.syllabus.showfield[i].value)) {
  574:                         document.getElementById('box_'+document.syllabus.showfield[i].value).style.display='none';
  575:                     }
  576:                 }
  577:             }
  578:         }
  579:     } else {
  580:         if (caller.checked) {
  581:             if (document.getElementById('box_'+caller.value)) {
  582:                 document.getElementById('box_'+caller.value).style.display='block';
  583:             }
  584:         } else {
  585:             if (document.getElementById('box_'+caller.value)) {
  586:                 document.getElementById('box_'+caller.value).style.display='none';
  587:             }
  588:         }
  589:     }
  590:     return;
  591: }
  592: 
  593: function setTemplateBoxes() {
  594:     $fieldstr
  595:     $checkedstr
  596:     $uncheckedstr
  597:     if (include.length > 0) {
  598:         for (var i=0; i<include.length; i++) {
  599:             if (document.getElementById('showfield_'+include[i])) {
  600:                 document.getElementById('showfield_'+include[i]).checked = true;
  601:                 if (document.getElementById('box_'+fields[include[i]])) {
  602:                     document.getElementById('box_'+fields[include[i]]).style.display='block';
  603:                 }
  604:             }
  605:         }
  606:     }
  607:     if (exclude.length > 0) {
  608:         for (var i=0; i<exclude.length; i++) {
  609:             if (document.getElementById('showfield_'+exclude[i])) {
  610:                 document.getElementById('showfield_'+exclude[i]).checked = false;
  611:                 if (document.getElementById('box_'+fields[exclude[i]])) {
  612:                     document.getElementById('box_'+fields[exclude[i]]).style.display='none';
  613:                 }
  614:             }
  615:         }
  616:     }
  617:     return;
  618: }
  619: 
  620: $check_uncheck
  621: 
  622: // ]]>
  623: </script>
  624: 
  625: ENDSCRIPT
  626:     }
  627:     my $args = {'function'       => undef,
  628:                 'domain'         => $cdom};
  629:     my $forcereg;
  630:     if ($env{'form.register'}) {
  631:         $forcereg = 1;
  632:         $args->{'force_register'} = $forcereg;
  633:     }
  634:     if ($env{'form.backto'} eq 'coursecatalog') {
  635:         &Apache::lonhtmlcommon::clear_breadcrumbs();
  636:         my $brcrum = [{href=>"javascript:ToCatalog();",
  637:                        text=>&mt('Course/Community Catalog'),
  638:                        no_mt=>1}
  639:                      ];
  640:         if ($env{'form.coursenum'} ne '') {
  641:             push(@{$brcrum},
  642:                   {href=>"javascript:ToCatalog('details')",
  643:                    text=>"Course details"});
  644:         }
  645:         push(@{$brcrum},
  646:               {href=>$r->uri,
  647:                text=>"Course syllabus"});
  648:         $args->{'bread_crumbs'} = $brcrum;
  649:     } elsif ($env{'form.folderpath'} =~ /^supplemental/) {
  650:         my $title = $env{'form.title'};
  651:         if ($title eq '') {
  652:             $title = &mt('Syllabus');
  653:         }
  654:         my $brcrum =
  655:             &Apache::lonhtmlcommon::docs_breadcrumbs(undef,$crstype,undef,$title,1);
  656:         if (ref($brcrum) eq 'ARRAY') {
  657:             $args->{'bread_crumbs'} = $brcrum;
  658:         }
  659:     } else {
  660:         if ((&Apache::lonnet::is_on_map("public/$cdom/$cnum/syllabus"))
  661:                  && (($env{'form.symb'}) || ($env{'form.register'}))) {
  662:             &Apache::lonhtmlcommon::clear_breadcrumbs();
  663:         } else {
  664:             $args->{'bread_crumbs'} = [
  665:                                         {'href' => "/public/$cdom/$cnum/syllabus",
  666:                                          'text' => 'Syllabus'},
  667:                                       ];
  668:         }
  669:     }
  670:     if ($allowed) {
  671:         my %loaditem = (
  672:                          onload => 'setTemplateBoxes();',
  673:                        );
  674:         $args->{'add_entries'} = \%loaditem;
  675:     }
  676:     my $start_page =
  677:         &Apache::loncommon::start_page("Syllabus", $rss_link.$js,$args);
  678:     $r->print($start_page);
  679: }
  680: 
  681: sub chooser {
  682:     my ($external,$uploaded,$cdom,$cnum,$lonhost,$fields,$values) = @_;
  683:     my %lt = &Apache::lonlocal::texthash(
  684:                  'type'          => 'Syllabus Type',
  685:                  'url'           => 'External URL',
  686:                  'file'          => 'Uploaded File',
  687:                  'template'      => 'Syllabus Template',
  688:                  'templateboxes' => 'Choose template items ... ',
  689:                  'curr'          => 'Current:',
  690:                  'rep'           => 'Replace:',
  691:                  'upl'           => 'Upload:',
  692:                  'pr'            => 'Preview',
  693:                  'save'          => 'Save',
  694:                  'chourl'        => 'Choose external URL',
  695:                  'chofile'       => 'Uploaded syllabus file',
  696:                  'parse'         => 'Upload embedded images/multimedia files if HTML file',
  697:     );
  698:     my %checked = (
  699:                     file     => '',
  700:                     url      => '',
  701:                     template => '',
  702:                   );
  703:     my %display = (
  704:                     file        => 'none',
  705:                     url         => 'none',
  706:                     templatebox => 'none',
  707:                   );
  708:     my $check = ' checked="checked" ';
  709:     if ($uploaded) {
  710:         $checked{'file'} = $check;
  711:         $display{'file'} = 'block';
  712:     } elsif ($external) {
  713:         $checked{'url'}  = $check;
  714:         $display{'url'} = 'block';
  715:     } else {
  716:         $checked{'template'} = $check;
  717:         $checked{'templatebox'} = $check;
  718:         $display{'templatebox'} = 'block';
  719:     }
  720: 
  721:     my $output = 
  722:         '<form name="syllabus" method="post" enctype="multipart/form-data" action="">'."\n".
  723:         '<input type="hidden" name="forceedit" value="1" />'."\n".
  724:         '<div class="LC_left_float"><fieldset><legend>'.$lt{'type'}.'</legend>';
  725:     foreach my $item ('template','url','file') {
  726:         $output .= '<label><input type="radio" name="choice" value="'.$item.'" '.$checked{$item}.' onclick="toggleEditor('."'$item'".')" />'.
  727:                    $lt{$item}.'</label><br />';
  728:     }
  729:     $output .= '</fieldset></div>'."\n".
  730:                '<div id="url" class="LC_left_float" style="display: '.$display{'url'}.'">'."\n".
  731:                '<fieldset><legend>'.$lt{'chourl'}.'</legend><span class="LC_nobreak">'."\n".
  732:                '<a href="javascript:extUrlPreview('."'syllabusurl'".');">'.$lt{'pr'}.'</a></span>&nbsp;'."\n".
  733:                '<input type="text" id="syllabusurl" name="externalsyllabus" value="'.$external.'" size="55" />'."\n".
  734:                '&nbsp;<input type="submit" name="storeurl" value="'.$lt{'save'}.'" />'."\n".
  735:                '</fieldset></div>'."\n".
  736:                '<div id="file" class="LC_left_float" style="display: '.$display{'file'}.'"><fieldset><legend>'.$lt{'file'}.'</legend>';
  737:     if ($uploaded) {
  738:         my $protocol = $Apache::lonnet::protocol{$lonhost};
  739:         $protocol = 'http' if ($protocol ne 'https');
  740:         my $absurl = $protocol.'://'.&Apache::lonnet::hostname($lonhost).$uploaded;
  741:         my ($filename) = ($uploaded =~ m{([^/]+)$});
  742:         my $file=&Apache::lonnet::filelocation("",$uploaded);
  743:         my $depbutton;
  744:         if ($file =~ /\.html?$/) {
  745:             my $filecontents=&Apache::lonnet::getfile($file);
  746:             unless ($filecontents eq -1) {
  747:                 my $mm = new File::MMagic;
  748:                 my $mimetype = $mm->checktype_contents($filecontents);
  749:                 if ($mimetype eq 'text/html') {
  750:                     my (%codebase,%allfiles);
  751:                     my $parse_result = &Apache::lonnet::extract_embedded_items($uploaded,\%allfiles,
  752:                                                                                \%codebase,\$filecontents);
  753:                     my $actionurl = "/public/$cdom/$cnum/syllabus";
  754:                     my ($ignore,$num,$numpathchanges,$existing,$mapping) =
  755:                         &Apache::loncommon::ask_for_embedded_content($actionurl,undef,\%allfiles,
  756:                                                                      \%codebase,
  757:                                                                      {'context' => 'rewrites',
  758:                                                                       'ignore_remote_references' => 1,});
  759:                     if (keys(%allfiles)) {
  760:                         $depbutton = ('&nbsp;' x 3).
  761:                                      &editfile_button().
  762:                                      &editbutton_js($uploaded);
  763:                     }
  764:                 }
  765:             }
  766:         }
  767: 
  768:         $output .= '<span class="LC_nobreak">'.$lt{'curr'}.'&nbsp;'.
  769:                    '<input type="hidden" name="uploadedfile" value="'.&HTML::Entities::encode($absurl).'?inhibitmenu=yes" id="currfile" />'.
  770:                    '<a href="javascript:extUrlPreview('."'currfile'".');">'.$filename.'</a></span>'.$depbutton.
  771:                    '<br /><br />'.$lt{'rep'};
  772:     } else {
  773:         $output .= $lt{'upl'};
  774:     }
  775: 
  776:     $output .= '<br />'."\n".
  777:                '<span class="LC_nobreak">'.
  778:                '<input type="file" name="syllabusfile" size="55" />'."\n".
  779:                '&nbsp;<input type="submit" name="storefile" value="'.$lt{'save'}.'" />'.
  780:                '</span><br />'.
  781:                '<label>'.
  782:                '<input type="checkbox" name="parserflag" checked="checked" />'.
  783:                $lt{'parse'}.
  784:                '</label>'.
  785:                '</fieldset></div>'.
  786:                '<div id="templatebox" class="LC_left_float" style="display: '.
  787:                $display{'templatebox'}.';"><fieldset><legend>'.$lt{'templateboxes'}.
  788:                '&nbsp;<input type="button" value="'.&mt('check all').'" '.
  789:                'onclick="javascript:checkAll('."document.syllabus.showfield".');javascript:toggleBox('."'all'".');" />'.
  790:                ('&nbsp;'x2).
  791:                '<input type="button" value="'.&mt('uncheck all').'" '.
  792:                'onclick="javascript:uncheckAll('."document.syllabus.showfield".');javascript:toggleBox('."'all'".');" />'.
  793:                '</legend>'.
  794:                &fields_check_uncheck($fields,$values).
  795:                '</fieldset><br />'.
  796:                '<input type="submit" name="storesyl" value="'.&mt('Save All').'" />'.
  797:                '</div>';
  798:     $output .= '<div style="padding:0;clear:both;margin:0;border:0"></div>';
  799:     return $output;
  800: }
  801: 
  802: sub fields_check_uncheck {
  803:     my ($fields,$values) = @_;
  804:     return unless ((ref($fields) eq 'HASH') && (ref($values) eq 'HASH'));
  805:     my $numinrow = 4;
  806:     my $table;
  807:     my @fieldnames = sort(keys(%{$fields}));
  808:     unshift(@fieldnames,'000_showpeople','111_showrssfeeds'); 
  809:     my $numfields = scalar(@fieldnames);
  810:     my %included;
  811:     if (($values->{'uploaded.fields'}) && ($values->{'uploaded.fields'} ne 'none')) {
  812:         map { $included{$_} = 1; } split(/,/,$values->{'uploaded.fields'});
  813:     }
  814:     for (my $i=0; $i<$numfields; $i++) {
  815:         my ($name,$checked);
  816:         if ($fieldnames[$i] eq '000_showpeople') {
  817:             $name = &mt('Personnel');
  818:         } elsif ($fieldnames[$i] eq '111_showrssfeeds') {
  819:             $name = &mt('RSS Feeds and Blogs');
  820:         } else {
  821:             $name = $fields->{$fieldnames[$i]};
  822:         }
  823:         if ($values->{'uploaded.fields'}) {
  824:             unless ($values->{'uploaded.fields'} eq 'none') {
  825:                 my ($prefix) = split(/_/,$fieldnames[$i]);
  826:                 if ($included{$prefix}) {
  827:                     $checked = ' checked="checked"';
  828:                 }
  829:             }
  830:         } else {
  831:             if ($fieldnames[$i] eq '000_showpeople') {
  832:                 $checked = ' checked="checked"';
  833:             } elsif ($fieldnames[$i] eq '111_showrssfeeds') {
  834:                 $checked = ' checked="checked"';
  835:             } else {
  836:                 if ($values->{$fieldnames[$i]} ne '') {
  837:                     $checked = ' checked="checked"';
  838:                 }
  839:             }
  840:         }
  841:         my $rem = $i%($numinrow);
  842:         if ($rem == 0) {
  843:             if (($i > 0) && ($i < $numfields)) {
  844:                 $table .= '</tr>';
  845:             }
  846:             if ($i < $numfields) {
  847:                 $table .= '<tr>';
  848:             }
  849:         }
  850:         if ($i == $numfields-1) {
  851:             my $rem = $numfields%($numinrow);
  852:             my $colsleft = $numinrow - $rem;
  853:             if ($colsleft > 1) {
  854:                 $table .= '<td colspan="'.$colsleft.'">';
  855:             } else {
  856:                 $table .= '</td>';
  857:             }
  858:         } else {
  859:             $table .= '<td>';
  860:         }
  861:         $table .=
  862:             '<label><input type="checkbox" name="showfield" value="'.$fieldnames[$i].'" '.
  863:             $checked.' id="showfield_'.$i.'" onclick="javascript:toggleBox('."'$fieldnames[$i]',this".');" />'.
  864:             $name.'</label></td>'."\n";
  865:     }
  866:     if ($table ne '') {
  867:         my $rem = $numfields%($numinrow);
  868:         my $colsleft = $numinrow - $rem;
  869:         if ($colsleft > 1 ) {
  870:             $table .= '<td colspan="'.$colsleft.'">&nbsp;</td>';
  871:         } elsif ($colsleft == 1) {
  872:             $table .= '<td>&nbsp;</td>';
  873:         }
  874:         $table = '<table>'.$table.'</tr></table>';
  875:     }
  876:     return $table;
  877: }
  878: 
  879: sub get_personnel {
  880:     my ($r,$target,$cdom,$cnum,$allowed) = @_;
  881:     my $output;
  882:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
  883:     if ($target ne 'tex') {
  884:         $r->print(&Apache::lonhtmlcommon::start_pick_box());
  885:     } else {
  886:         $r->print('\begin{tabular}{|p{0.45\textwidth}|p{0.45\textwidth}|}\hline');
  887:     }
  888:     my @personnel=sort(keys(%coursepersonnel));
  889:     my $lastpers=$personnel[$#personnel];
  890:     foreach my $element (@personnel) {
  891:         if ($target ne 'tex') {
  892:             $r->print(&Apache::lonhtmlcommon::row_title($element));
  893:         } else {
  894:             $r->print(' '.&Apache::lonxml::xmlparse($r,'tex',$element).' & ');
  895:         }
  896:         my @coursepersonlist;
  897:         foreach my $user (split(/\,/,$coursepersonnel{$element})) {
  898:             my ($puname,$pudom)=split(/\:/,$user);
  899:             if ($target ne 'tex') {
  900:                 my $courseperson = &Apache::loncommon::plainname($puname,$pudom);
  901:                 if (($env{'user.name'} eq '') || ($env{'user.name'} eq 'public') ||
  902:                     ($env{'user.domain'} eq '') || ($env{'user.domain'} eq 'public')) {
  903:                     push(@coursepersonlist,$courseperson);
  904:                 } else {
  905:                     push(@coursepersonlist,&Apache::loncommon::aboutmewrapper($courseperson,
  906:                               $puname,$pudom));
  907:                 }
  908:             } else {
  909:                 push(@coursepersonlist,&Apache::loncommon::plainname($puname,
  910:                               $pudom).' ');
  911:             }
  912:         }
  913:         $r->print(join(", ",@coursepersonlist));
  914:         if ($target ne 'tex') {
  915:             my $lastclose=$element eq $lastpers?1:0;
  916:             $r->print(&Apache::lonhtmlcommon::row_closure($lastclose));
  917:         } else {
  918:             $r->print('\\\\ \hline');
  919:         }
  920:     }
  921:     if ($target ne 'tex') {
  922:         $r->print(&Apache::lonhtmlcommon::end_pick_box());
  923:     } else {
  924:         $r->print('\end{tabular}\\\\');
  925:     }
  926:     return;
  927: }
  928: 
  929: sub save_changes {
  930:     my ($cnum,$cdom,$uploaded,$external,$syllabus,$syllabusfields,$courseenv) = @_;
  931:     my ($earlyout,$output);
  932:     unless ((ref($syllabus) eq 'HASH') && (ref($syllabusfields) eq 'HASH')) {
  933:         return ($earlyout,$uploaded,$external,$output);
  934:     }
  935: #store what the user typed in to the template
  936:     if ($env{'form.choice'} eq 'template') {
  937:         my @shown = &Apache::loncommon::get_env_multiple('form.showfield');
  938:         $syllabus->{'uploaded.fields'} = '';
  939:         if (@shown == 0) {
  940:             $syllabus->{'uploaded.fields'} = 'none';
  941:         } else {
  942:             foreach my $field (sort(@shown)) {
  943:                 if (($field eq '000_showpeople') ||
  944:                     ($field eq '111_showrssfeeds') ||
  945:                     ($syllabusfields->{$field})) {
  946:                     my ($prefix) = split(/_/,$field);
  947:                     $syllabus->{'uploaded.fields'} .= $prefix.',';
  948:                 }
  949:             }
  950:             $syllabus->{'uploaded.fields'} =~ s/,$//;
  951:         }
  952:         foreach my $syl_field (keys(%{$syllabusfields})) {
  953:             my $field=$env{'form.'.$syl_field};
  954:             chomp($field);
  955:             $field=~s/\s+$//s;
  956:             $field=~s/^\s+//s;
  957:             $field=~s/\<br\s*\/*\>$//s;
  958:             $field=&Apache::lonfeedback::clear_out_html($field,1);
  959:                             #here it will be stored
  960:             $syllabus->{$syl_field}=$field;
  961:             if ($syl_field eq 'lll_includeurl') { # clean up included URLs
  962:                 my $field='';
  963:                 foreach my $value (split(/\n/,$syllabus->{$syl_field})) {
  964:                     my $url=$value;
  965: # get rid of leading and trailing spaces
  966:                     $url=~s/^\s+//;
  967:                     $url=~s/\s+$//;
  968:                     if ($url=~m|^https?\://([^/]+)/(.+)$|) {
  969:                         my $host = $1;
  970:                         my $remainder=$2;
  971: # remove the hostname from internal URLs
  972:                         my $hostname = &Apache::lonnet::hostname($host);
  973:                         my %all_hostnames = &Apache::lonnet::all_hostnames();
  974:                         foreach my $possible_host (keys(%all_hostnames)) {
  975:                             if ($possible_host =~ /\Q$hostname\E/i) {
  976:                                 $url=$remainder;
  977:                             }
  978:                         }
  979:                     }
  980: # norm internal URLs
  981:                     unless ($url=~/^https?\:/) {
  982:                         $url=&Apache::lonnet::clutter($url);
  983:                     }
  984: # re-assemble field
  985:                     if ($url) {
  986:                         $field.=$url."\n";
  987:                     }
  988:                 }
  989:                 $syllabus->{$syl_field}=$field;
  990:             }
  991:         }
  992:         my $now = time;
  993:         $syllabus->{'uploaded.domain'}=$env{'user.domain'};
  994:         $syllabus->{'uploaded.name'}=$env{'user.name'};
  995:         $syllabus->{'uploaded.lastmodified'} = $now;
  996:         my $putres = &Apache::lonnet::put('syllabus',$syllabus,$cdom,$cnum);
  997:         if ($putres eq 'ok') {
  998:             my %storehash;
  999:             if ($courseenv->{'uploadedsyllabus'}) {
 1000:                 &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.uploadedsyllabus');
 1001:                 $storehash{'uploadedsyllabus'} = '';
 1002:             }
 1003:             if ($courseenv->{'externalsyllabus'}) {
 1004:                 &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.externalsyllabus');
 1005:                 $storehash{'externalsyllabus'} = '';
 1006:             }
 1007:             $storehash{'updatedsyllabus'} = $now;
 1008:             &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 1009:             &Apache::lonnet::appenv({'course.'.$env{'request.course.id'}.'.updatedsyllabus' => $now});
 1010:             if ($courseenv->{'externalsyllabus'} || $courseenv->{'uploadedsyllabus'}) {
 1011:                 undef($uploaded);
 1012:                 undef($external);
 1013:             }
 1014:             $output = '<div>'.
 1015:                       &Apache::lonhtmlcommon::confirm_success(&mt('Template saved.')).
 1016:                       '</div>';
 1017:         } else {
 1018:             $output = '<div class="LC_error">'.
 1019:                       &mt('An error occurred storing the template: [_1]',$putres).
 1020:                       '</div>';
 1021:         }
 1022:     } elsif ($env{'form.choice'} eq 'url') {
 1023:         if ($env{'form.externalsyllabus'} =~ m{^https?://}) {
 1024:             if ($env{'form.externalsyllabus'} eq $external) {
 1025:                 $output = '<div class="LC_info">'.
 1026:                           &mt('External URL unchanged.').
 1027:                           '</div>';
 1028:                 if ($uploaded) {
 1029:                     my $prefix;
 1030:                     my $home=&Apache::lonnet::homeserver($cnum,$cdom);
 1031:                     if ($home ne 'no_host') {
 1032:                         my $protocol = $Apache::lonnet::protocol{$home};
 1033:                         $protocol = 'http' if ($protocol ne 'https');
 1034:                         $prefix = $protocol.'://'.&Apache::lonnet::hostname($home);
 1035:                     }
 1036:                     unless ($external =~ m{^\Q$prefix/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
 1037:                         &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.uploadedsyllabus');
 1038:                         &Apache::lonnet::put('environment',{uploadedsyllabus => ''},
 1039:                                              $cdom,$cnum);
 1040:                         undef($uploaded);
 1041:                         $earlyout = 1;
 1042:                     }
 1043:                 }
 1044:             } else {
 1045:                 $external=$env{'form.externalsyllabus'};
 1046:                 $external =~ s/(`)//g;
 1047:                 my $putres =
 1048:                     &Apache::lonnet::put('environment',{externalsyllabus=>$external},
 1049:                                          $cdom,$cnum);
 1050:                 if ($putres eq 'ok') {
 1051:                     &Apache::lonnet::appenv({'course.'.$env{'request.course.id'}.'.externalsyllabus' => $external});
 1052:                     $output = '<div>'.
 1053:                               &Apache::lonhtmlcommon::confirm_success(&mt('External URL saved.')).
 1054:                              '</div>';
 1055:                     if ($uploaded) {
 1056:                         my $prefix;
 1057:                         my $home=&Apache::lonnet::homeserver($cnum,$cdom);
 1058:                         if ($home ne 'no_host') {
 1059:                             my $protocol = $Apache::lonnet::protocol{$home};
 1060:                             $protocol = 'http' if ($protocol ne 'https');
 1061:                             $prefix = $protocol.'://'.&Apache::lonnet::hostname($home);
 1062:                         }
 1063:                         unless ($external =~ m{^\Q$prefix/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
 1064:                             &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.uploadedsyllabus');
 1065:                             &Apache::lonnet::put('environment',{uploadedsyllabus => ''},
 1066:                                                  $cdom,$cnum);
 1067:                             undef($uploaded);
 1068:                         }
 1069:                     }
 1070:                 } else {
 1071:                     $output = '<div class="LC_error">'.
 1072:                               &mt('An error occurred storing the external URL: [_1]',$putres).
 1073:                               '</div>';
 1074:                 }
 1075:             }
 1076:         } else {
 1077:             $output = '<div class="LC_error">'.
 1078:                       &mt('External URL not saved -- invalid URL.').
 1079:                       '</div>';
 1080:         }
 1081:     } elsif ($env{'form.choice'} eq 'file') {
 1082:         # Process file upload - phase one - upload and parse primary file.
 1083:         my %allfiles = ();
 1084:         my %codebase = ();
 1085:         my ($upload_result,$uploadphase);
 1086:         if ($env{'form.syllabusfile.filename'}) {
 1087:             my ($url,$needlink) = &process_upload(\$output,$cnum,$cdom,
 1088:                                                   \%allfiles,\%codebase);
 1089:             if ($url =~ m{^/uploaded/\Q$cdom\E/\Q$cnum\E.*/[^/]+$}) {
 1090:                 my $exturl;
 1091:                 my $home=&Apache::lonnet::homeserver($cnum,$cdom);
 1092:                 if ($home ne 'no_host') {
 1093:                     my $protocol = $Apache::lonnet::protocol{$home};
 1094:                     $protocol = 'http' if ($protocol ne 'https');
 1095:                     $exturl = $protocol.'://'.&Apache::lonnet::hostname($home).$url;
 1096:                 }
 1097:                 my %storehash = (
 1098:                                    uploadedsyllabus => $url,
 1099:                                 );
 1100:                 if ($exturl) {
 1101:                     $storehash{'externalsyllabus'} = $exturl;
 1102:                     if ($exturl =~ /\.(html?|txt|js|css)$/) {
 1103:                         $exturl .= '?inhibitmenu=yes';
 1104:                     }
 1105:                 } else {
 1106:                     $storehash{'externalsyllabus'} = '',
 1107:                 }
 1108:                 my $putres =
 1109:                     &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 1110:                 if ($putres eq 'ok') {
 1111:                     &Apache::lonnet::make_public_indefinitely($url);
 1112:                     foreach my $key (keys(%storehash)) {
 1113:                         &Apache::lonnet::appenv({'course.'.$env{'request.course.id'}.'.'.$key => $storehash{$key}});
 1114:                     }
 1115:                     $uploaded = $url;
 1116:                     if ($needlink) {
 1117:                         $output .= &return_to_editor($cdom,$cnum).
 1118:                                    &Apache::loncommon::end_page();
 1119:                         $earlyout = 1;
 1120:                     }
 1121:                 }
 1122:             }
 1123:         }
 1124:     } elsif ($env{'form.phase'} eq 'upload_embedded') {
 1125:         # Process file upload - phase two - upload embedded objects
 1126:         my $uploadphase = 'check_embedded';
 1127:         my $primaryurl = &HTML::Entities::encode($env{'form.primaryurl'},'<>&"');
 1128:         my $state = &embedded_form_elems($uploadphase,$primaryurl);
 1129:         my $url_root = '/uploaded/'.$cdom.'/'.$cnum;
 1130:         my $actionurl = "/public/$cdom/$cnum/syllabus";
 1131:         my ($result,$flag,$numpathchgs) =
 1132:             &Apache::loncommon::upload_embedded('syllabus','portfolio/syllabus',
 1133:                 $cnum,$cdom,'/userfiles',$url_root,undef,undef,undef,$state,
 1134:                 $actionurl);
 1135:         unless ($numpathchgs) {
 1136:             my $modres =
 1137:                 &Apache::loncommon::modify_html_refs('syllabus','portfolio/syllabus',
 1138:                                                      $cnum,$cdom,
 1139:                                                      '/userfiles',$env{'form.primaryurl'});
 1140:             $result .= $modres;
 1141:         }
 1142:         $output = $result.&return_to_editor($cdom,$cnum).
 1143:                   &Apache::loncommon::end_page();
 1144:         $earlyout = 1;
 1145:     } elsif ($env{'form.phase'} eq 'check_embedded') {
 1146:         # Process file upload - phase three - modify references in HTML file
 1147:         my $uploadphase = 'modified_orightml';
 1148:         my $result =
 1149:             &Apache::loncommon::modify_html_refs('syllabus','portfolio/syllabus',
 1150:                                                  $cnum,$cdom,
 1151:                                                  '/userfiles',$env{'form.primaryurl'});
 1152:         $output = $result.&return_to_editor($cdom,$cnum).
 1153:                   &Apache::loncommon::end_page();
 1154:         $earlyout = 1;
 1155:     }
 1156:     return ($earlyout,$uploaded,$external,$output);
 1157: }
 1158: 
 1159: sub process_upload {
 1160:     my ($upload_output,$cnum,$cdom,$allfiles,$codebase) = @_;
 1161:     my ($parseaction,$showupload,$mimetype);
 1162:     my $dest = 'portfolio/syllabus';
 1163:     if ($env{'form.parserflag'}) {
 1164:         $parseaction = 'parse';
 1165:     }
 1166:     my $url=&Apache::lonnet::userfileupload('syllabusfile','syllabus',$dest,
 1167:                                             $parseaction,$allfiles,
 1168:                                             $codebase,undef,undef,undef,undef,
 1169:                                             undef,undef,\$mimetype);
 1170:     if ($url =~ m{^/uploaded/\Q$cdom\E/\Q$cnum\E.*/([^/]+)$}) {
 1171:         my $stored = $1;
 1172:         $showupload = '<p>'.&mt('Uploaded [_1]',
 1173:                                 '<span class="LC_filename">'.$stored.'</span>').
 1174:                       '</p>';
 1175:     } else {
 1176:         my ($filename) = ($env{'form.syllabusfile.filename'} =~ m{([^/]+)$});
 1177:         $$upload_output = '<div class="LC_error" id="uploadfileresult">'.
 1178:                           &mt('Unable to save file [_1].',
 1179:                               '<span class="LC_filename">'.$filename.'</span>').
 1180:                           '</div>';
 1181:         return (); 
 1182:     }
 1183:     my $needlink;
 1184:     if (($parseaction eq 'parse') && ($mimetype eq 'text/html')) {
 1185:         $$upload_output = $showupload;
 1186:         my $total_embedded = scalar(keys(%{$allfiles}));
 1187:         if ($total_embedded > 0) {
 1188:             my $uploadphase = 'upload_embedded';
 1189:             my $primaryurl = &HTML::Entities::encode($url,'<>&"');
 1190:             my $state = &embedded_form_elems($uploadphase,$primaryurl);
 1191:             my $actionurl = "/public/$cdom/$cnum/syllabus";
 1192:             my ($embedded,$num,$numpathchanges,$existing);
 1193:             ($embedded,$num,$numpathchanges,$existing) =
 1194:                 &Apache::loncommon::ask_for_embedded_content($actionurl,$state,
 1195:                                                              $allfiles,$codebase,
 1196:                                                             {'error_on_invalid_names'   => 1,
 1197:                                                              'ignore_remote_references' => 1,});
 1198:             if ($embedded) {
 1199:                 $needlink = 1;
 1200:                 if ($num) {
 1201:                     $$upload_output .=
 1202:                         '<p>'.&mt('This file contains embedded multimedia objects, which need to be uploaded.').'</p>'.$embedded;
 1203:                 } elsif ($numpathchanges) {
 1204:                     $$upload_output .= $embedded;
 1205:                 } else {
 1206:                     $$upload_output .= $embedded;
 1207:                     &Apache::loncommon::modify_html_refs('syllabus','portfolio/syllabus',
 1208:                                                          $cnum,$cdom,'/userfiles',$url);
 1209:                 }
 1210:             } else {
 1211:                 $$upload_output .= &mt('Embedded item(s) already present, so no additional upload(s) required').'<br />';
 1212:                 &Apache::loncommon::modify_html_refs('syllabus','portfolio/syllabus',
 1213:                                                      $cnum,$cdom,'/userfiles',$url);
 1214: 
 1215:             }
 1216:         } else {
 1217:             $$upload_output .= &mt('No embedded items identified').'<br />';
 1218:         }
 1219:         $$upload_output = '<div id="uploadfileresult">'.$$upload_output.'</div>';
 1220:     }
 1221:     return ($url,$needlink);
 1222: }
 1223: 
 1224: sub embedded_form_elems {
 1225:     my ($phase,$primaryurl) = @_;
 1226:     return <<STATE;
 1227:     <input type="hidden" name="forceedit" value="1" />
 1228:     <input type="hidden" name="cmd" value="upload_embedded" />
 1229:     <input type="hidden" name="phase" value="$phase" />
 1230:     <input type="hidden" name="primaryurl" value="$primaryurl" />
 1231: STATE
 1232: }
 1233: 
 1234: sub return_to_editor {
 1235:     my ($cdom,$cnum) = @_;
 1236:     my $actionurl = "/public/$cdom/$cnum/syllabus";
 1237:     return '<p><form name="backtoeditor" method="post" action="'.$actionurl.'" />'.
 1238:            '<input type="hidden" name="forceedit" value="1" />'."\n".
 1239:            '<a href="javascript:document.backtoeditor.submit();">'.&mt('Return to Editor').
 1240:            '</a></p>';
 1241: }
 1242: 
 1243: sub editfile_button {
 1244:     my $buttontext=&mt('Edit');
 1245:     return <<"END";
 1246:                 <input type="button" value="$buttontext" onclick="javascript:gotoeditor();" />
 1247: END
 1248: }
 1249: 
 1250: sub editbutton_js {
 1251:     my ($url) = @_;
 1252:     return <<ENDJS;
 1253:                 <script type="text/javascript">
 1254:                 // <![CDATA[
 1255:                   function gotoeditor() {
 1256:                       document.location.href = '$url?forceedit=1';
 1257:                   }
 1258:                 // ]]>
 1259:                 </script>
 1260: ENDJS
 1261: }
 1262: 
 1263: 1;
 1264: __END__

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