Annotation of modules/damieng/clean_xml/post_xml.pm, revision 1.1
1.1 ! damieng 1: #!/usr/bin/perl
! 2:
! 3: package post_xml;
! 4:
! 5: use strict;
! 6: use utf8;
! 7: use warnings;
! 8:
! 9: use File::Basename;
! 10: use File::Temp qw/ tempfile /;
! 11: use Cwd 'abs_path';
! 12: use XML::LibXML;
! 13: use HTML::TokeParser; # used to parse sty files
! 14: use Tie::IxHash; # for ordered hashes
! 15:
! 16: use Env qw(RES_DIR); # path of res directory parent (without the / at the end)
! 17:
! 18: no warnings 'recursion'; # yes, fix_paragraph is using heavy recursion, I know
! 19:
! 20: # these are constants
! 21: my @block_elements = ('parameter','location','answer','foil','image','polygon','rectangle','text','conceptgroup','itemgroup','item','label','data','function','array','unit','answergroup','functionplotresponse','functionplotruleset','functionplotelements','functionplotcustomrule','essayresponse','hintpart','formulahint','numericalhint','reactionhint','organichint','optionhint','radiobuttonhint','stringhint','customhint','mathhint','formulahintcondition','numericalhintcondition','reactionhintcondition','organichintcondition','optionhintcondition','radiobuttonhintcondition','stringhintcondition','customhintcondition','mathhintcondition','imageresponse','foilgroup','datasubmission','textfield','hiddensubmission','radiobuttonresponse','rankresponse','matchresponse','import','style','script','window','block','library','notsolved','part','postanswerdate','preduedate','problem','problemtype','randomlabel','bgimg','labelgroup','randomlist','solved','while','tex','print','web','gnuplot','curve','Task','IntroParagraph','ClosingParagraph','Question','QuestionText','Setup','Instance','InstanceText','Criteria','CriteriaText','GraderNote','languageblock','translated','lang','instructorcomment','dataresponse','togglebox','standalone','comment','drawimage','allow','displayduedate','displaytitle','responseparam','organicstructure','scriptlib','parserlib','drawoptionlist','spline','backgroundplot','plotobject','plotvector','drawvectorsum','functionplotrule','functionplotvectorrule','functionplotvectorsumrule','axis','key','xtics','ytics','title','xlabel','ylabel','hiddenline','dtm');
! 22: my @inline_like_block = ('stringresponse','optionresponse','numericalresponse','formularesponse','mathresponse','organicresponse','reactionresponse','customresponse','externalresponse', 'hint', 'hintgroup'); # inline elements treated like blocks for pretty print and some other things
! 23: my @responses = ('stringresponse','optionresponse','numericalresponse','formularesponse','mathresponse','organicresponse','reactionresponse','customresponse','externalresponse','essayresponse','radiobuttonresponse','matchresponse','rankresponse','imageresponse','functionplotresponse');
! 24: my @block_html = ('html','head','body','section','h1','h2','h3','h4','h5','h6','div','p','ul','ol','li','table','tbody','tr','td','th','dl','dt','dd','pre','noscript','hr','address','blockquote','object','applet','embed','map','form','fieldset','iframe','center','frameset');
! 25: my @no_newline_inside = ('import','parserlib','scriptlib','data','function','label','xlabel','ylabel','tic','text','rectangle','image','title','h1','h2','h3','h4','h5','h6','li','td','p');
! 26: my @preserve_elements = ('script','answer','pre');
! 27: my @accepting_style = ('section','h1','h2','h3','h4','h5','h6','div','p','li','td','th','dt','dd','pre','blockquote');
! 28: my @latex_math = ('\alpha', '\theta', '\omicron', '\tau', '\beta', '\vartheta', '\pi', '\upsilon', '\gamma', '\gamma', '\varpi', '\phi', '\delta', '\kappa', '\rho', '\varphi', '\epsilon', '\lambda', '\varrho', '\chi', '\varepsilon', '\mu', '\sigma', '\psi', '\zeta', '\nu', '\varsigma', '\omega', '\eta', '\xi',
! 29: '\Gamma', '\Lambda', '\Sigma', '\Psi', '\Delta', '\Xi', '\Upsilon', '\Omega', '\Theta', '\Pi', '\Phi',
! 30: '\pm', '\cap', '\diamond', '\oplus', '\mp', '\cup', '\bigtriangleup', '\ominus', '\times', '\uplus', '\bigtriangledown', '\otimes', '\div', '\sqcap', '\triangleleft', '\oslash', '\ast', '\sqcup', '\triangleright', '\odot', '\star', '\vee', '\lhd$', '\bigcirc', '\circ', '\wedge', '\rhd$', '\dagger', '\bullet', '\setminus', '\unlhd$', '\ddagger', '\cdot', '\wr', '\unrhd$', '\amalg', '+', '-',
! 31: '\leq', '\geq', '\equiv', '\models', '\prec', '\succ', '\sim', '\perp', '\preceq', '\succeq', '\simeq', '\mid', '\ll', '\gg', '\asymp', '\parallel', '\subset', '\supset', '\approx', '\bowtie', '\subseteq', '\supseteq', '\cong', '\Join$', '\sqsubset$', '\sqsupset$', '\neq', '\smile', '\sqsubseteq', '\sqsupseteq', '\doteq', '\frown', '\in', '\ni', '\propto', '\vdash', '\dashv',
! 32: '\colon', '\ldotp', '\cdotp',
! 33: '\leftarrow', '\longleftarrow', '\uparrow', '\Leftarrow', '\Longleftarrow', '\Uparrow', '\rightarrow', '\longrightarrow', '\downarrow', '\Rightarrow', '\Longrightarrow', '\Downarrow', '\leftrightarrow', '\longleftrightarrow', '\updownarrow', '\Leftrightarrow', '\Longleftrightarrow', '\Updownarrow', '\mapsto', '\longmapsto', '\nearrow', '\hookleftarrow', '\hookrightarrow', '\searrow', '\leftharpoonup', '\rightharpoonup', '\swarrow', '\leftharpoondown', '\rightharpoondown', '\nwarrow', '\rightleftharpoons', '\leadsto$',
! 34: '\ldots', '\cdots', '\vdots', '\ddots', '\aleph', '\prime', '\forall', '\infty', '\hbar', '\emptyset', '\exists', '\Box$', '\imath', '\nabla', '\neg', '\Diamond$', '\jmath', '\surd', '\flat', '\triangle', '\ell', '\top', '\natural', '\clubsuit', '\wp', '\bot', '\sharp', '\diamondsuit', '\Re', '\|', '\backslash', '\heartsuit', '\Im', '\angle', '\partial', '\spadesuit', '\mho$',
! 35: '\sum', '\bigcap', '\bigodot', '\prod', '\bigcup', '\bigotimes', '\coprod', '\bigsqcup', '\bigoplus', '\int', '\bigvee', '\biguplus', '\oint', '\bigwedge',
! 36: '\arccos', '\cos', '\csc', '\exp', '\ker', '\limsup', '\min', '\sinh', '\arcsin', '\cosh', '\deg', '\gcd', '\lg', '\ln', '\Pr', '\sup', '\arctan', '\cot', '\det', '\hom', '\lim', '\log', '\sec', '\tan', '\arg', '\coth', '\dim', '\inf', '\liminf', '\max', '\sin', '\tanh',
! 37: '\uparrow', '\Uparrow', '\downarrow', '\Downarrow', '\updownarrow', '\Updownarrow', '\lfloor', '\rfloor', '\lceil', '\rceil', '\langle', '\rangle', '\backslash',
! 38: '\rmoustache', '\lmoustache', '\rgroup', '\lgroup', '\arrowvert', '\Arrowvert', '\bracevert',
! 39: '\hat{', '\acute{', '\bar{', '\dot{', '\breve{', '\check{', '\grave{', '\vec{', '\ddot{', '\tilde{',
! 40: '\widetilde{', '\widehat{', '\overleftarrow{', '\overrightarrow{', '\overline{', '\underline{', '\overbrace{', '\underbrace{', '\sqrt{', '\sqrt[', '\frac{'
! 41: );
! 42: # list of elements that can contain style elements:
! 43: my @containing_styles = ('library','problem',@responses,'foil','item','text','hintgroup','hintpart','label','part','preduedate','postanswerdate','solved','notsolved','block','while','web','standalone','problemtype','languageblock','translated','lang','window','windowlink','togglebox','instructorcomment','body','section','div','p','li','dd','td','th','blockquote','object','applet','video','audio','canvas','fieldset','button',
! 44: 'span','strong','em','b','i','sup','sub','code','kbd','samp','tt','ins','del','var','small','big','u','font');
! 45: my @html_styles = ('span', 'strong', 'em' , 'b', 'i', 'sup', 'sub', 'tt', 'var', 'small', 'big', 'u');
! 46:
! 47:
! 48: # Parses the XML document and fixes many things to turn it into a LON-CAPA 3 document
! 49: # Returns the text of the document.
! 50: sub post_xml {
! 51: my ($textref, $new_path) = @_;
! 52:
! 53: my $dom_doc = XML::LibXML->load_xml(string => $textref);
! 54:
! 55: my $root = fix_structure($dom_doc);
! 56:
! 57: remove_elements($root, ['startouttext','startoutext','startottext','startouttex','startouttect','atartouttext','starouttext','starttextout','starttext','starttextarea','endouttext','endoutext','endoutttext','endouttxt','endouutext','ednouttext','endouttex','endoouttext','endouttest','endtextout','endtextarea','startpartmarker','endpartmarker','basefont','x-claris-tagview','x-claris-window','x-sas-window']);
! 58:
! 59: remove_empty_attributes($root);
! 60:
! 61: fix_attribute_case($root);
! 62:
! 63: my $fix_by_hand = replace_m($root);
! 64:
! 65: my @all_block = (@block_elements, @block_html);
! 66: add_sty_blocks($new_path, $root, \@all_block); # must come before the subs using @all_block
! 67:
! 68: fix_block_styles($root, \@all_block);
! 69: $root->normalize();
! 70:
! 71: fix_fonts($root, \@all_block);
! 72:
! 73: replace_u($root);
! 74:
! 75: remove_bad_cdata_sections($root);
! 76:
! 77: add_cdata_sections($root);
! 78:
! 79: fix_style_element($root);
! 80:
! 81: fix_tables($root);
! 82:
! 83: fix_lists($root);
! 84:
! 85: fix_wrong_name_for_img($root); # should be before replace_deprecated_attributes_by_css
! 86:
! 87: replace_deprecated_attributes_by_css($root);
! 88:
! 89: replace_center($root, \@all_block); # must come after replace_deprecated_attributes_by_css
! 90:
! 91: replace_nobr($root);
! 92:
! 93: remove_useless_notsolved($root);
! 94:
! 95: fix_paragraphs_inside($root, \@all_block);
! 96:
! 97: remove_empty_style($root);
! 98:
! 99: fix_empty_lc_elements($root);
! 100:
! 101: lowercase_attribute_values($root);
! 102:
! 103: replace_numericalresponse_unit_attribute($root);
! 104:
! 105: replace_functions_by_elements($root);
! 106:
! 107: pretty($root, \@all_block);
! 108:
! 109: replace_tm_dtm($root);
! 110:
! 111: open my $out, '>', $new_path;
! 112: print $out $dom_doc->toString(); # byte string !
! 113: close $out;
! 114:
! 115: if ($fix_by_hand) {
! 116: die "The file has been converted but it should be fixed by hand.";
! 117: }
! 118: }
! 119:
! 120: sub fix_structure {
! 121: my ($doc) = @_;
! 122: # the 'loncapa' root element has already been added in pre_xml
! 123: my $root = $doc->documentElement;
! 124: # inside the root, replace html, problem and library elements by their content
! 125: my @toreplace = ('html','problem','library');
! 126: foreach my $name (@toreplace) {
! 127: my @elements = $root->getElementsByTagName($name);
! 128: foreach my $element (@elements) {
! 129: replace_by_children($element);
! 130: }
! 131: }
! 132: # insert all link and style elements inside a new head element
! 133: my $current_node = undef;
! 134: my @heads = $doc->getElementsByTagName('head');
! 135: my @links = $doc->getElementsByTagName('link');
! 136: my @styles = $doc->getElementsByTagName('style');
! 137: my @titles = $doc->getElementsByTagName('title');
! 138: if (scalar(@titles) > 0) {
! 139: # NOTE: there is a title element in gnuplot, not to be confused with the one inside HTML head
! 140: for (my $i=0; $i<scalar(@titles); $i++) {
! 141: my $title = $titles[$i];
! 142: my $found_gnuplot = 0;
! 143: my $ancestor = $title->parentNode;
! 144: while (defined $ancestor) {
! 145: if ($ancestor->nodeName eq 'gnuplot') {
! 146: $found_gnuplot = 1;
! 147: last;
! 148: }
! 149: $ancestor = $ancestor->parentNode;
! 150: }
! 151: if ($found_gnuplot) {
! 152: splice(@titles, $i, 1);
! 153: $i--;
! 154: }
! 155: }
! 156: }
! 157: if (scalar(@heads) > 0 || scalar(@titles) > 0 || scalar(@links) > 0 || scalar(@styles) > 0) {
! 158: my $htmlhead = $doc->createElement('head');
! 159: foreach my $head (@heads) {
! 160: my $next;
! 161: for (my $child=$head->firstChild; defined $child; $child=$next) {
! 162: $next = $child->nextSibling;
! 163: $head->removeChild($child);
! 164: if ($child->nodeType != XML_ELEMENT_NODE ||
! 165: string_in_array(['title','script','style','meta','link','import','base'], $child->nodeName)) {
! 166: $htmlhead->appendChild($child);
! 167: } else {
! 168: # this should not be in head
! 169: insert_after_or_first($root, $child, $current_node);
! 170: }
! 171: }
! 172: $head->parentNode->removeChild($head);
! 173: }
! 174: foreach my $child (@titles, @links, @styles) {
! 175: $child->parentNode->removeChild($child);
! 176: $htmlhead->appendChild($child);
! 177: }
! 178: insert_after_or_first($root, $htmlhead, $current_node);
! 179: $current_node = $htmlhead;
! 180: }
! 181: # body
! 182: my $htmlbody = undef;
! 183: my @bodies = $doc->getElementsByTagName('body');
! 184: if (scalar(@bodies) > 0) {
! 185: # TODO: fix content and position of body elements
! 186: if ($root->nodeName eq 'problem') {
! 187: foreach my $body (@bodies) {
! 188: replace_by_children($body);
! 189: }
! 190: }
! 191: }
! 192: # add all the meta elements afterwards when they are LON-CAPA meta. Remove all HTML meta.
! 193: my @meta_names = ('abstract','author','authorspace','avetries','avetries_list','clear','comefrom','comefrom_list','copyright','correct','count','course','course_list','courserestricted','creationdate','dependencies','depth','difficulty','difficulty_list','disc','disc_list','domain','end','field','firstname','generation','goto','goto_list','groupname','helpful','highestgradelevel','hostname','id','keynum','keywords','language','lastname','lastrevisiondate','lowestgradelevel','middlename','mime','modifyinguser','notes','owner','permanentemail','scope','sequsage','sequsage_list','standards','start','stdno','stdno_list','subject','technical','title','url','username','value','version');
! 194: my @metas = $doc->getElementsByTagName('meta');
! 195: foreach my $meta (@metas) {
! 196: $meta->parentNode->removeChild($meta);
! 197: my $name = $meta->getAttribute('name');
! 198: my $content = $meta->getAttribute('content');
! 199: if (defined $name && defined $content && string_in_array(\@meta_names, lc($name))) {
! 200: my $lcmeta = $doc->createElement('meta');
! 201: $lcmeta->setAttribute('name', lc($name));
! 202: $lcmeta->setAttribute('content', $content);
! 203: insert_after_or_first($root, $lcmeta, $current_node);
! 204: $current_node = $lcmeta;
! 205: }
! 206: }
! 207: return($root);
! 208: }
! 209:
! 210: # insert the new child under parent after the reference child, or as the first child if the reference child is not defined
! 211: sub insert_after_or_first {
! 212: my ($parent, $newchild, $refchild) = @_;
! 213: if (defined $refchild) {
! 214: $parent->insertAfter($newchild, $refchild);
! 215: } elsif (defined $parent->firstChild) {
! 216: $parent->insertBefore($newchild, $parent->firstChild);
! 217: } else {
! 218: $parent->appendChild($newchild);
! 219: }
! 220: }
! 221:
! 222: # removes all elements with given names inside the node, but keep the content
! 223: sub remove_elements {
! 224: my ($node, $to_remove) = @_;
! 225: my $nextChild;
! 226: for (my $child=$node->firstChild; defined $child; $child=$nextChild) {
! 227: $nextChild = $child->nextSibling;
! 228: my $type = $node->nodeType;
! 229: if ($type == XML_ELEMENT_NODE) {
! 230: if (string_in_array($to_remove, $child->nodeName)) {
! 231: my $first_non_white = $child->firstChild;
! 232: if (defined $first_non_white && $first_non_white->nodeType == XML_TEXT_NODE &&
! 233: $first_non_white->nodeValue =~ /^\s*$/) {
! 234: $first_non_white = $first_non_white->nextSibling;
! 235: }
! 236: if (defined $first_non_white) {
! 237: $nextChild = $first_non_white;
! 238: replace_by_children($child);
! 239: } else {
! 240: $node->removeChild($child);
! 241: }
! 242: } else {
! 243: remove_elements($child, $to_remove);
! 244: }
! 245: }
! 246: }
! 247: }
! 248:
! 249: # removes some attributes that have an invalid empty value
! 250: sub remove_empty_attributes {
! 251: my ($root) = @_;
! 252: my $doc = $root->ownerDocument;
! 253: # this list is based on validation errors in the MSU subset (it could be more complete if it was based on the schema)
! 254: my @attributes = (
! 255: ['curve', ['pointsize']],
! 256: ['foil', ['location']],
! 257: ['foilgroup', ['checkboxoptions', 'options', 'texoptions']],
! 258: ['gnuplot', ['pattern', 'texwidth']],
! 259: ['img', ['height', 'texheight', 'texwidth', 'texwrap', 'width']],
! 260: ['import', ['importmode']],
! 261: ['optionresponse', ['max']],
! 262: ['organicstructure', ['options']],
! 263: ['radiobuttonresponse', ['max']],
! 264: ['randomlabel', ['height', 'texwidth', 'width']],
! 265: ['stringresponse', ['type']],
! 266: ['textline', ['size']],
! 267: );
! 268: foreach my $element_attributes (@attributes) {
! 269: my $element_name = $element_attributes->[0];
! 270: my $attribute_names = $element_attributes->[1];
! 271: my @elements = $doc->getElementsByTagName($element_name);
! 272: foreach my $element (@elements) {
! 273: foreach my $attribute_name (@$attribute_names) {
! 274: my $value = $element->getAttribute($attribute_name);
! 275: if (defined $value && $value =~ /^\s*$/) {
! 276: $element->removeAttribute($attribute_name);
! 277: }
! 278: }
! 279: }
! 280: }
! 281: }
! 282:
! 283: # fixes the case for a few attributes that are not all lowercase
! 284: # (the HTML parser used in html_to_xml turns everything lowercase, which is a good thing in general)
! 285: sub fix_attribute_case {
! 286: my ($root) = @_;
! 287: my $doc = $root->ownerDocument;
! 288: my @attributes = (
! 289: ['labelgroup', ['TeXsize']],
! 290: ['h1', ['TeXsize']],
! 291: ['h2', ['TeXsize']],
! 292: ['h3', ['TeXsize']],
! 293: ['h4', ['TeXsize']],
! 294: ['h5', ['TeXsize']],
! 295: ['h6', ['TeXsize']],
! 296: # font and basefont have a TeXsize but will be removed
! 297: ['optionresponse', ['TeXlayout']],
! 298: ['itemgroup', ['TeXitemgroupwidth']],
! 299: ['Task', ['OptionalRequired']],
! 300: ['Question', ['OptionalRequired','Mandatory']],
! 301: ['Instance', ['OptionalRequired','Disabled']],
! 302: ['Criteria', ['Mandatory']],
! 303: ['table', ['TeXwidth','TeXtheme']],
! 304: ['td', ['TeXwidth']],
! 305: ['th', ['TeXwidth']],
! 306: ['img', ['TeXwidth','TeXheight','TeXwrap']],
! 307: );
! 308: foreach my $element_attributes (@attributes) {
! 309: my $element_name = $element_attributes->[0];
! 310: my $attribute_names = $element_attributes->[1];
! 311: my @elements = $doc->getElementsByTagName($element_name);
! 312: foreach my $element (@elements) {
! 313: foreach my $attribute_name (@$attribute_names) {
! 314: my $value = $element->getAttribute(lc($attribute_name));
! 315: if (defined $value) {
! 316: $element->removeAttribute(lc($attribute_name));
! 317: $element->setAttribute($attribute_name, $value);
! 318: }
! 319: }
! 320: }
! 321: }
! 322: }
! 323:
! 324: # Replaces m by HTML, tm and/or dtm (which will be replaced by <m> later, but they are useful
! 325: # to know if the element is a block element or not).
! 326: # m might contain non-math LaTeX, while tm and dtm may only contain math.
! 327: # Returns 1 if the file should be fixed by hand, 0 otherwise.
! 328: sub replace_m {
! 329: my ($root) = @_;
! 330: my $doc = $root->ownerDocument;
! 331: my $fix_by_hand = 0;
! 332: # search for variable declarations
! 333: my @variables = ();
! 334: my @scripts = $root->getElementsByTagName('script');
! 335: foreach my $script (@scripts) {
! 336: my $type = $script->getAttribute('type');
! 337: if (defined $type && $type eq 'loncapa/perl') {
! 338: if (defined $script->firstChild && $script->firstChild->nodeType == XML_TEXT_NODE) {
! 339: my $text = $script->firstChild->nodeValue;
! 340: # NOTE: we are not interested in replacing "@value", only "$value"
! 341: # this regexp is for " $a = ..." and " $a[...] = ..."
! 342: while ($text =~ /^[ \t]*\$([a-zA-Z_0-9]+)(?:\[[^\]]+\])?[ \t]*=/gm) {
! 343: if (!string_in_array(\@variables, $1)) {
! 344: push(@variables, $1);
! 345: }
! 346: }
! 347: # this regexp is for "...; $a = ..." and "...; $a[...] = ..."
! 348: while ($text =~ /^[^'"\/;]+;[ \t]*\$([a-zA-Z_0-9]+)(?:\[[^\]]+\])?[ \t]*=/gm) {
! 349: if (!string_in_array(\@variables, $1)) {
! 350: push(@variables, $1);
! 351: }
! 352: }
! 353: # this regexp is for " ($a, $b, $c) = ..."
! 354: my @matches = ($text =~ /^[ \t]*\([ \t]*\$([a-zA-Z_0-9]+)(?:[ \t]*,[ \t]*\$([a-zA-Z_0-9]+))*[ \t]*\)[ \t]*=/gm);
! 355: foreach my $match (@matches) {
! 356: if (!defined $match) {
! 357: next; # not sure why it happens, but it does
! 358: }
! 359: if (!string_in_array(\@variables, $match)) {
! 360: push(@variables, $match);
! 361: }
! 362: }
! 363: # and this one is for "push @a"
! 364: while ($text =~ /^[ \t]*push @([a-zA-Z_0-9]+)[ \t,]*/gm) {
! 365: if (!string_in_array(\@variables, $1)) {
! 366: push(@variables, $1);
! 367: }
! 368: }
! 369: # use the opportunity to report usage of <m> in Perl scripts
! 370: if ($text =~ /^[^#].*<m[ >]/m) {
! 371: print "WARNING: <m> is used in a script, it should be converted by hand\n";
! 372: $fix_by_hand = 1;
! 373: }
! 374: }
! 375: }
! 376: }
! 377: my @ms = $root->getElementsByTagName('m');
! 378: foreach my $m (@ms) {
! 379: if (!defined $m->firstChild) {
! 380: $m->parentNode->removeChild($m);
! 381: next;
! 382: }
! 383: if (defined $m->firstChild->nextSibling || $m->firstChild->nodeType != XML_TEXT_NODE) {
! 384: print "WARNING: m value is not simple text\n";
! 385: $fix_by_hand = 1;
! 386: next;
! 387: }
! 388: my $text = $m->firstChild->nodeValue;
! 389: my $text_before_variable_replacement = $text;
! 390: my $var_key1 = 'dfhg3df54hg65hg4';
! 391: my $var_key2 = 'dfhg654d6f5g4h5f';
! 392: my $eval = defined $m->getAttribute('eval') && $m->getAttribute('eval') eq 'on';
! 393: if ($eval) {
! 394: # replace variables
! 395: foreach my $variable (@variables) {
! 396: my $replacement = $var_key1.$variable.$var_key2;
! 397: $text =~ s/\$$variable(?![a-zA-Z])/$replacement/ge;
! 398: $text =~ s/\$\{$variable\}/$replacement/ge;
! 399: }
! 400: }
! 401: # check if the expression is enclosed in math separators: $ $$ \( \) \[ \]
! 402: # if so, replace the whole node by dtm or tm
! 403: my $new_text;
! 404: my $new_node_name;
! 405: if ($text =~ /^\s*\$\$([^\$]*)\$\$\s*$/) {
! 406: $new_node_name = 'dtm';
! 407: $new_text = $1;
! 408: } elsif ($text =~ /^\s*\\\[(.*)\\\]\s*$/s) {
! 409: $new_node_name = 'dtm';
! 410: $new_text = $1;
! 411: } elsif ($text =~ /^\s*\$([^\$]*)\$\s*$/) {
! 412: $new_node_name = 'tm';
! 413: $new_text = $1;
! 414: } elsif ($text =~ /^\s*\\\((.*)\\\)\s*$/s) {
! 415: $new_node_name = 'tm';
! 416: $new_text = $1;
! 417: }
! 418: if (defined $new_node_name) {
! 419: if ($eval) {
! 420: foreach my $variable (@variables) {
! 421: my $replacement = $var_key1.$variable.$var_key2;
! 422: $new_text =~ s/$replacement([a-zA-Z])/\${$variable}$1/g;
! 423: $new_text =~ s/$replacement/\$$variable/g;
! 424: }
! 425: }
! 426: my $new_node = $doc->createElement($new_node_name);
! 427: if ($eval) {
! 428: $new_node->setAttribute('eval', 'on');
! 429: }
! 430: $new_node->appendChild($doc->createTextNode($new_text));
! 431: $m->parentNode->replaceChild($new_node, $m);
! 432: next;
! 433: }
! 434: if ($text !~ /\$|\\\(|\\\)|\\\[|\\\]/) {
! 435: # there are no math separators inside
! 436: # try to guess if this is meant as math
! 437: my $found_math = 0;
! 438: foreach my $symbol (@latex_math) {
! 439: if (index($text, $symbol) != -1) {
! 440: $found_math = 1;
! 441: last;
! 442: }
! 443: }
! 444: if ($found_math) {
! 445: # interpret the whole text as LaTeX inline math
! 446: my $new_node = $doc->createElement('tm');
! 447: if ($eval) {
! 448: $new_node->setAttribute('eval', 'on');
! 449: }
! 450: $new_node->appendChild($doc->createTextNode($text_before_variable_replacement));
! 451: $m->parentNode->replaceChild($new_node, $m);
! 452: next;
! 453: }
! 454: # no math symbol found, we will convert the text with tth
! 455: }
! 456:
! 457: # there are math separators inside, even after hiding variables, or there was no math symbol
! 458:
! 459: # hide math parts inside before running tth
! 460: my $math_key1 = '#ghjgdh5hg45gf';
! 461: my $math_key2 = '#';
! 462: my @maths = ();
! 463: my @separators = (['$$','$$'], ['\\(','\\)'], ['\\[','\\]'], ['$','$']);
! 464: foreach my $seps (@separators) {
! 465: my $sep1 = $seps->[0];
! 466: my $sep2 = $seps->[1];
! 467: my $pos1 = index($text, $sep1);
! 468: if ($pos1 == -1) {
! 469: next;
! 470: }
! 471: my $pos2 = index($text, $sep2, $pos1+length($sep1));
! 472: while ($pos1 != -1 && $pos2 != -1) {
! 473: my $replace = substr($text, $pos1, $pos2+length($sep2)-$pos1);
! 474: push(@maths, $replace);
! 475: my $by = $math_key1.scalar(@maths).$math_key2;
! 476: $text = substr($text, 0, $pos1).$by.substr($text, $pos2+length($sep2));
! 477: $pos1 = index($text, $sep1);
! 478: if ($pos1 != -1) {
! 479: $pos2 = index($text, $sep2, $pos1+length($sep1));
! 480: }
! 481: }
! 482: }
! 483: # get HTML as text from tth
! 484: my $html_text = tth($text);
! 485: # replace math by replacements
! 486: for (my $i=0; $i < scalar(@maths); $i++) {
! 487: my $math = $maths[$i];
! 488: $math =~ s/&/&/g;
! 489: $math =~ s/</</g;
! 490: $math =~ s/>/>/g;
! 491: if ($math =~ /^\$\$(.*)\$\$$/s) {
! 492: $math = '<dtm>'.$1.'</dtm>';
! 493: } elsif ($math =~ /^\\\[(.*)\\\]$/s) {
! 494: $math = '<dtm>'.$1.'</dtm>';
! 495: } elsif ($math =~ /^\\\((.*)\\\)$/s) {
! 496: $math = '<tm>'.$1.'</tm>';
! 497: } elsif ($math =~ /^\$(.*)\$$/s) {
! 498: $math = '<tm>'.$1.'</tm>';
! 499: }
! 500: my $replace = $math_key1.($i+1).$math_key2;
! 501: $html_text =~ s/$replace/$math/;
! 502: }
! 503: # replace variables if necessary
! 504: if ($eval) {
! 505: foreach my $variable (@variables) {
! 506: my $replacement = $var_key1.$variable.$var_key2;
! 507: $html_text =~ s/$replacement([a-zA-Z])/\${$variable}$1/g;
! 508: $html_text =~ s/$replacement/\$$variable/g;
! 509: }
! 510: }
! 511: my $fragment = html_to_dom($html_text);
! 512: $doc->adoptNode($fragment);
! 513: $m->parentNode->replaceChild($fragment, $m);
! 514:
! 515: }
! 516: return $fix_by_hand;
! 517: }
! 518:
! 519: # Returns the HTML equivalent of LaTeX input, using tth
! 520: sub tth {
! 521: my ($text) = @_;
! 522: my ($fh, $tmp_path) = tempfile();
! 523: binmode($fh, ':utf8');
! 524: print $fh $text;
! 525: close $fh;
! 526: my $output = `tth -r -w2 -u -y0 < $tmp_path 2>/dev/null`;
! 527: # hopefully the temp file will not be removed before this point (otherwise we should use unlink_on_destroy 0)
! 528: $output =~ s/^\s*|\s*$//;
! 529: $output =~ s/<div class="p"><!----><\/div>/<br\/>/; # why is tth using such ugly markup for \newline ?
! 530: return $output;
! 531: }
! 532:
! 533: # transform simple HTML into a DOM fragment (which will need to be adopted by the document)
! 534: sub html_to_dom {
! 535: my ($text) = @_;
! 536: $text = '<root>'.$text.'</root>';
! 537: my $textref = html_to_xml::html_to_xml(\$text);
! 538: utf8::upgrade($$textref); # otherwise the XML parser fails when the HTML parser turns into a character
! 539: my $dom_doc = XML::LibXML->load_xml(string => $textref);
! 540: my $root = $dom_doc->documentElement;
! 541: remove_empty_style($root);
! 542: my $fragment = $dom_doc->createDocumentFragment();
! 543: my $next;
! 544: for (my $n=$root->firstChild; defined $n; $n=$next) {
! 545: $next = $n->nextSibling;
! 546: $root->removeChild($n);
! 547: $fragment->appendChild($n);
! 548: }
! 549: return($fragment);
! 550: }
! 551:
! 552: # Use the linked sty files to guess which newly defined elements should be considered blocks.
! 553: # Also adds to @containing_styles the sty elements that contain styles.
! 554: # @param {string} fn - the .lc file path (we only extract the directory path from it)
! 555: sub add_sty_blocks {
! 556: my ($fn, $root, $all_block) = @_;
! 557: my $doc = $root->ownerDocument;
! 558: my @parserlibs = $doc->getElementsByTagName('parserlib');
! 559: my @libs = ();
! 560: foreach my $parserlib (@parserlibs) {
! 561: if (defined $parserlib->firstChild && $parserlib->firstChild->nodeType == XML_TEXT_NODE) {
! 562: my $value = $parserlib->firstChild->nodeValue;
! 563: $value =~ s/^\s+|\s+$//g;
! 564: if ($value ne '') {
! 565: push(@libs, $value);
! 566: }
! 567: }
! 568: }
! 569: my ($name, $path, $suffix) = fileparse($fn);
! 570: foreach my $sty (@libs) {
! 571: if (substr($sty, 0, 1) eq '/') {
! 572: $sty = $RES_DIR.$sty;
! 573: } else {
! 574: $sty = $path.$sty;
! 575: }
! 576: my $new_elements = parse_sty($sty, $all_block);
! 577: better_guess($root, $new_elements, $all_block);
! 578: my $new_blocks = $new_elements->{'block'};
! 579: my $new_inlines = $new_elements->{'inline'};
! 580: push(@$all_block, @{$new_blocks});
! 581: #push(@inlines, @{$new_inlines}); # we are not using a list of inline elements at this point
! 582: }
! 583: }
! 584:
! 585: ##
! 586: # Parses a sty file and returns lists of block and inline elements.
! 587: # @param {string} fn - the file path
! 588: ##
! 589: sub parse_sty {
! 590: my ($fn, $all_block) = @_;
! 591: my @blocks = ();
! 592: my @inlines = ();
! 593: my $p = HTML::TokeParser->new($fn);
! 594: if (! $p) {
! 595: die "post_xml.pl: parse_sty: Error reading $fn\n";
! 596: }
! 597: $p->empty_element_tags(1);
! 598: my $in_definetag = 0;
! 599: my $in_render = 0;
! 600: my %newtags = ();
! 601: my $newtag = '';
! 602: my $is_block = 0;
! 603: while (my $token = $p->get_token) {
! 604: if ($token->[0] eq 'S') {
! 605: my $tag = lc($token->[1]);
! 606: if ($tag eq 'definetag') {
! 607: $in_definetag = 1;
! 608: $is_block = 0;
! 609: my $attributes = $token->[2];
! 610: $newtag = $attributes->{'name'};
! 611: if (substr($newtag, 0, 1) eq '/') {
! 612: $newtag = substr($newtag, 1);
! 613: }
! 614: } elsif ($in_definetag && $tag eq 'render') {
! 615: $in_render = 1;
! 616: $is_block = 0;
! 617: } elsif ($in_render) {
! 618: if (string_in_array($all_block, $tag)) {
! 619: $is_block = 1;
! 620: }
! 621: }
! 622: } elsif ($token->[0] eq 'E') {
! 623: my $tag = lc($token->[1]);
! 624: if ($tag eq 'definetag') {
! 625: $in_definetag = 0;
! 626: if (defined $newtags{$newtag}) {
! 627: $newtags{$newtag} = $newtags{$newtag} || $is_block;
! 628: } else {
! 629: $newtags{$newtag} = $is_block;
! 630: }
! 631: } elsif ($in_definetag && $tag eq 'render') {
! 632: $in_render = 0;
! 633: }
! 634: }
! 635: }
! 636: foreach $newtag (keys(%newtags)) {
! 637: if ($newtags{$newtag} == 1) {
! 638: push(@blocks, $newtag);
! 639: } else {
! 640: push(@inlines, $newtag);
! 641: }
! 642: }
! 643: return {'block'=>\@blocks, 'inline'=>\@inlines};
! 644: }
! 645:
! 646: ##
! 647: # Marks as block the elements that contain block elements in the input file.
! 648: # Also adds to @containing_styles the sty elements that contain styles.
! 649: # @param {string} fn - the file path
! 650: # @param {Hash<string,Array>} new_elements - contains arrays in 'block' and 'inline'
! 651: ##
! 652: sub better_guess {
! 653: my ($root, $new_elements, $all_block) = @_;
! 654: my $new_blocks = $new_elements->{'block'};
! 655: my $new_inlines = $new_elements->{'inline'};
! 656:
! 657: my @change = (); # change these elements from inline to block
! 658: foreach my $tag (@{$new_inlines}) {
! 659: my @nodes = $root->getElementsByTagName($tag);
! 660: NODE_LOOP: foreach my $node (@nodes) {
! 661: for (my $child=$node->firstChild; defined $child; $child=$child->nextSibling) {
! 662: if ($child->nodeType == XML_ELEMENT_NODE) {
! 663: if (string_in_array($all_block, $child->nodeName) || string_in_array($new_blocks, $child->nodeName)) {
! 664: push(@change, $tag);
! 665: last NODE_LOOP;
! 666: }
! 667: }
! 668: }
! 669: }
! 670: }
! 671: foreach my $inline (@change) {
! 672: my $index = 0;
! 673: $index++ until $new_inlines->[$index] eq $inline;
! 674: splice(@{$new_inlines}, $index, 1);
! 675: push(@{$new_blocks}, $inline);
! 676: }
! 677: # add to @containing_styles when a style is used inside
! 678: # NOTE: some sty elements will be added even though they should not, but if we don't do that
! 679: # all style will be removed in the sty elements.
! 680: foreach my $tag ((@{$new_blocks}, @{$new_inlines})) {
! 681: my @nodes = $root->getElementsByTagName($tag);
! 682: NODE_LOOP: foreach my $node (@nodes) {
! 683: for (my $child=$node->firstChild; defined $child; $child=$child->nextSibling) {
! 684: if ($child->nodeType == XML_ELEMENT_NODE) {
! 685: if (string_in_array(\@html_styles, $child->nodeName)) {
! 686: push(@containing_styles, $tag);
! 687: last NODE_LOOP;
! 688: }
! 689: }
! 690: }
! 691: }
! 692: }
! 693: }
! 694:
! 695: # When a style element contains a block, move the style inside the block where it is allowed.
! 696: # style/block/other -> block/style/other
! 697: # When a style is used where it is not allowed, move it inside its children or remove it (unless it contains only text)
! 698: # element_not_containing_styles/style/other -> element_not_containing_styles/other/style (except if other is a style)
! 699: # The fix is not perfect in the case of element_not_containing_styles/style1/style2/block/text (style1 will be lost):
! 700: # element_not_containing_styles/style1/style2/block/text -> element_not_containing_styles/block/style2/text
! 701: # (a solution to this problem would be to merge the styles in a span)
! 702: # NOTE: .sty defined elements might have been added to @containing_styles by better_guess().
! 703: sub fix_block_styles {
! 704: my ($element, $all_block) = @_;
! 705: my $doc = $element->ownerDocument;
! 706: if (string_in_array(\@html_styles, $element->nodeName)) {
! 707: # move spaces out of the style element
! 708: if (defined $element->firstChild && $element->firstChild->nodeType == XML_TEXT_NODE) {
! 709: my $child = $element->firstChild;
! 710: if ($child->nodeValue =~ /^(\s+)(\S.*)$/s) {
! 711: $element->parentNode->insertBefore($doc->createTextNode($1), $element);
! 712: $child->setData($2);
! 713: }
! 714: }
! 715: if (defined $element->lastChild && $element->lastChild->nodeType == XML_TEXT_NODE) {
! 716: my $child = $element->lastChild;
! 717: if ($child->nodeValue =~ /^(.*\S)(\s+)$/s) {
! 718: $element->parentNode->insertAfter($doc->createTextNode($2), $element);
! 719: $child->setData($1);
! 720: }
! 721: }
! 722:
! 723: my $found_block = 0;
! 724: for (my $child=$element->firstChild; defined $child; $child=$child->nextSibling) {
! 725: if ($child->nodeType == XML_ELEMENT_NODE && string_in_array($all_block, $child->nodeName)) {
! 726: $found_block = 1;
! 727: last;
! 728: }
! 729: }
! 730: my $no_style_here = !string_in_array(\@containing_styles, $element->parentNode->nodeName);
! 731: if ($found_block || $no_style_here) {
! 732: # there is a block or the style is not allowed here,
! 733: # the style element has to be replaced by its modified children
! 734: my $s; # a clone of the style
! 735: my $next;
! 736: for (my $child=$element->firstChild; defined $child; $child=$next) {
! 737: $next = $child->nextSibling;
! 738: if ($child->nodeType == XML_ELEMENT_NODE && (string_in_array($all_block, $child->nodeName) ||
! 739: $child->nodeName eq 'br' || $no_style_here)) {
! 740: # avoid inverting a style with a style with $no_style_here (that would cause endless recursion)
! 741: if (!$no_style_here || (!string_in_array(\@html_styles, $child->nodeName) &&
! 742: string_in_array(\@containing_styles, $child->nodeName))) {
! 743: # block node or inline node when the style is not allowed:
! 744: # move all children inside the style, and make the style the only child
! 745: $s = $element->cloneNode();
! 746: my $next2;
! 747: for (my $child2=$child->firstChild; defined $child2; $child2=$next2) {
! 748: $next2 = $child2->nextSibling;
! 749: $child->removeChild($child2);
! 750: $s->appendChild($child2);
! 751: }
! 752: $child->appendChild($s);
! 753: }
! 754: $s = undef;
! 755: } elsif (($child->nodeType == XML_TEXT_NODE && $child->nodeValue !~ /^\s*$/) ||
! 756: $child->nodeType == XML_ELEMENT_NODE) {
! 757: # if the style is allowed, move text and inline nodes inside the style
! 758: if (!$no_style_here) {
! 759: if (!defined $s) {
! 760: $s = $element->cloneNode();
! 761: $element->insertBefore($s, $child);
! 762: }
! 763: $element->removeChild($child);
! 764: $s->appendChild($child);
! 765: }
! 766: } else {
! 767: # do not put other nodes inside the style
! 768: $s = undef;
! 769: }
! 770: }
! 771: # now replace by children and fix them
! 772: my $parent = $element->parentNode;
! 773: for (my $child=$element->firstChild; defined $child; $child=$next) {
! 774: $next = $child->nextSibling;
! 775: $element->removeChild($child);
! 776: $parent->insertBefore($child, $element);
! 777: if ($child->nodeType == XML_ELEMENT_NODE) {
! 778: fix_block_styles($child, $all_block);
! 779: }
! 780: }
! 781: $parent->removeChild($element);
! 782: return;
! 783: }
! 784: }
! 785: # otherwise fix all children
! 786: my $next;
! 787: for (my $child=$element->firstChild; defined $child; $child=$next) {
! 788: $next = $child->nextSibling;
! 789: if ($child->nodeType == XML_ELEMENT_NODE) {
! 790: fix_block_styles($child, $all_block);
! 791: }
! 792: }
! 793: }
! 794:
! 795: # removes empty font elements and font elements that contain at least one block element
! 796: # replaces other font elements by equivalent span
! 797: sub fix_fonts {
! 798: my ($root, $all_block) = @_;
! 799: my $doc = $root->ownerDocument;
! 800: my @fonts = $root->getElementsByTagName('font');
! 801: @fonts = reverse(@fonts); # to deal with the ancestor last in the case of font/font
! 802: foreach my $font (@fonts) {
! 803: my $block = 0;
! 804: for (my $child=$font->firstChild; defined $child; $child=$child->nextSibling) {
! 805: if (string_in_array($all_block, $child->nodeName) || string_in_array(\@inline_like_block, $child->nodeName)) {
! 806: $block = 1;
! 807: last;
! 808: }
! 809: }
! 810: if (!defined $font->firstChild || $block) {
! 811: # empty font or font containing block elements
! 812: # replace this node by its content
! 813: replace_by_children($font);
! 814: } else {
! 815: # replace by equivalent span
! 816: my $color = get_non_empty_attribute($font, 'color');
! 817: my $size = get_non_empty_attribute($font, 'size');
! 818: my $face = get_non_empty_attribute($font, 'face');
! 819: if (defined $face) {
! 820: $face =~ s/^,|,$//;
! 821: }
! 822: if (!defined $color && !defined $size && !defined $face) {
! 823: # useless font element: replace this node by its content
! 824: replace_by_children($font);
! 825: next;
! 826: }
! 827: my $replacement;
! 828: tie (my %properties, 'Tie::IxHash', ());
! 829: if (!defined $color && !defined $size && defined $face && lc($face) eq 'symbol') {
! 830: $replacement = $doc->createDocumentFragment();
! 831: } else {
! 832: $replacement = $doc->createElement('span');
! 833: my $css = '';
! 834: if (defined $color) {
! 835: $color =~ s/^x//;
! 836: $properties{'color'} = $color;
! 837: }
! 838: if (defined $size) {
! 839: my %hash = (
! 840: '1' => 'x-small',
! 841: '2' => 'small',
! 842: '3' => 'medium',
! 843: '4' => 'large',
! 844: '5' => 'x-large',
! 845: '6' => 'xx-large',
! 846: '7' => '300%',
! 847: '-1' => 'small',
! 848: '-2' => 'x-small',
! 849: '+1' => 'large',
! 850: '+2' => 'x-large',
! 851: '+3' => 'xx-large',
! 852: '+4' => '300%',
! 853: );
! 854: my $value = $hash{$size};
! 855: if (!defined $value) {
! 856: $value = 'medium';
! 857: }
! 858: $properties{'font-size'} = $value;
! 859: }
! 860: if (defined $face) {
! 861: if (lc($face) ne 'symbol' && lc($face) ne 'bold') {
! 862: $properties{'font-family'} = $face;
! 863: }
! 864: }
! 865: set_css_properties($replacement, \%properties);
! 866: }
! 867: if (defined $face && lc($face) eq 'symbol') {
! 868: # convert all content to unicode
! 869: my $next;
! 870: for (my $child=$font->firstChild; defined $child; $child=$next) {
! 871: $next = $child->nextSibling;
! 872: if ($child->nodeType == XML_TEXT_NODE) {
! 873: my $value = $child->nodeValue;
! 874: $value =~ tr/ABGDEZHQIKLMNXOPRSTUFCYWabgdezhqiklmnxoprVstufcywJjv¡«¬®/ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρςστυφχψωϑϕϖϒ↔←→/;
! 875: $child->setData($value);
! 876: }
! 877: }
! 878: }
! 879: # replace the font node
! 880: if ($replacement->nodeType == XML_ELEMENT_NODE && !defined $font->previousSibling &&
! 881: !defined $font->nextSibling && string_in_array(\@accepting_style, $font->parentNode->nodeName)) {
! 882: # use CSS on the parent block and replace font by its children instead of using a new element
! 883: set_css_properties($font->parentNode, \%properties);
! 884: replace_by_children($font);
! 885: } else {
! 886: # move all font children inside the replacement (span or fragment)
! 887: my $next;
! 888: for (my $child=$font->firstChild; defined $child; $child=$next) {
! 889: $next = $child->nextSibling;
! 890: $font->removeChild($child);
! 891: $replacement->appendChild($child);
! 892: }
! 893: # replace font
! 894: $font->parentNode->replaceChild($replacement, $font);
! 895: }
! 896: }
! 897: }
! 898: $root->normalize();
! 899: }
! 900:
! 901: # replaces u by <span style="text-decoration: underline">
! 902: sub replace_u {
! 903: my ($root) = @_;
! 904: my $doc = $root->ownerDocument;
! 905: my @us = $root->getElementsByTagName('u');
! 906: foreach my $u (@us) {
! 907: my $span = $doc->createElement('span');
! 908: $span->setAttribute('style', 'text-decoration: underline');
! 909: my $next;
! 910: for (my $child=$u->firstChild; defined $child; $child=$next) {
! 911: $next = $child->nextSibling;
! 912: $u->removeChild($child);
! 913: $span->appendChild($child);
! 914: }
! 915: $u->parentNode->replaceChild($span, $u);
! 916: }
! 917: }
! 918:
! 919: # removes CDATA sections tags that have not been parsed correcty by the HTML parser
! 920: # also removes bad comments in script elements
! 921: sub remove_bad_cdata_sections {
! 922: my ($root) = @_;
! 923: my $doc = $root->ownerDocument;
! 924: foreach my $name (@preserve_elements) {
! 925: my @nodes = $root->getElementsByTagName($name);
! 926: foreach my $node (@nodes) {
! 927: if (defined $node->firstChild && $node->firstChild->nodeType == XML_TEXT_NODE) {
! 928: my $value = $node->firstChild->nodeValue;
! 929: if ($name eq 'script' && (!defined $node->getAttribute('type') || $node->getAttribute('type') ne 'loncapa/perl') &&
! 930: !defined $node->firstChild->nextSibling && $value =~ /^(\s*)<!--(.*)-->(\s*)$/) {
! 931: # web browsers interpret that as a real comment when it is on 1 line, but the Perl HTML parser thinks it is the script
! 932: # -> turning it back into a comment
! 933: # (this is only true for Javascript script elements, since LON-CAPA does not parse loncapa/perl scripts in the same way)
! 934: $node->removeChild($node->firstChild);
! 935: $node->appendChild($doc->createComment($2));
! 936: next;
! 937: }
! 938: # at the beginning:
! 939: $value =~ s/^(\s*)<!\[CDATA\[/$1/; # <![CDATA[
! 940: $value =~ s/^(\s*)\/\*\s*<!\[CDATA\[\s*\*\//$1/; # /* <![CDATA[ */
! 941: $value =~ s/^(\s*)\/\/\s*<!\[CDATA\[/$1/; # // <![CDATA[
! 942: $value =~ s/^(\s*)(\/\/)?\s*<!--/$1/; # // <!--
! 943: # at the end:
! 944: $value =~ s/\/\/\s*\]\]>(\s*)$/$1/; # // ]]>
! 945: $value =~ s/\]\]>(\s*)$/$1/; # ]]>
! 946: $value =~ s/(\/\/)?\s*-->(\s*)$/$2/; # // -->
! 947: $value =~ s/\/\*\s*\]\]>\s*\*\/(\s*)$/$1/; # /* ]]> */
! 948:
! 949: $value = "\n".$value."\n";
! 950: $value =~ s/\s*(\n[ \t]*)/$1/;
! 951: $value =~ s/\s+$/\n/;
! 952: $node->firstChild->setData($value);
! 953: }
! 954: }
! 955: }
! 956: }
! 957:
! 958: # adds CDATA sections to scripts
! 959: sub add_cdata_sections {
! 960: my ($root) = @_;
! 961: my $doc = $root->ownerDocument;
! 962: my @scripts = $root->getElementsByTagName('script');
! 963: my @answers = $root->getElementsByTagName('answer');
! 964: foreach my $answer (@answers) {
! 965: my $ancestor = $answer->parentNode;
! 966: my $found_capa_response = 0;
! 967: while (defined $ancestor) {
! 968: if ($ancestor->nodeName eq 'numericalresponse' || $ancestor->nodeName eq 'formularesponse') {
! 969: $found_capa_response = 1;
! 970: last;
! 971: }
! 972: $ancestor = $ancestor->parentNode;
! 973: }
! 974: if (!$found_capa_response) {
! 975: push(@scripts, $answer);
! 976: }
! 977: }
! 978: foreach my $script (@scripts) {
! 979: # use a CDATA section in the normal situation, for any script
! 980: my $first = $script->firstChild;
! 981: if (defined $first && $first->nodeType == XML_TEXT_NODE && !defined $first->nextSibling) {
! 982: my $cdata = $doc->createCDATASection($first->nodeValue);
! 983: $script->replaceChild($cdata, $first);
! 984: }
! 985: }
! 986: }
! 987:
! 988: # removes "<!--" and "-->" at the beginning and end of style elements
! 989: sub fix_style_element {
! 990: my ($root) = @_;
! 991: my @styles = $root->getElementsByTagName('style');
! 992: foreach my $style (@styles) {
! 993: if (defined $style->firstChild && $style->firstChild->nodeType == XML_TEXT_NODE &&
! 994: !defined $style->firstChild->nextSibling) {
! 995: my $text = $style->firstChild->nodeValue;
! 996: if ($text =~ /^\s*<!--(.*)-->\s*$/s) {
! 997: $style->firstChild->setData($1);
! 998: }
! 999: }
! 1000: }
! 1001: }
! 1002:
! 1003: # create missing cells at the end of table rows
! 1004: sub fix_tables {
! 1005: my ($root) = @_;
! 1006: my @tables = $root->getElementsByTagName('table');
! 1007: foreach my $table (@tables) {
! 1008: fix_cells($table);
! 1009: foreach my $tbody ($table->getChildrenByTagName('tbody')) {
! 1010: fix_cells($tbody);
! 1011: }
! 1012: foreach my $thead ($table->getChildrenByTagName('thead')) {
! 1013: fix_cells($thead);
! 1014: }
! 1015: foreach my $tfoot ($table->getChildrenByTagName('tfoot')) {
! 1016: fix_cells($tfoot);
! 1017: }
! 1018: }
! 1019: }
! 1020:
! 1021: # create missing cells at the end of table rows
! 1022: sub fix_cells {
! 1023: my ($table) = @_; # could actually be table, tbody, thead or tfoot
! 1024: my $doc = $table->ownerDocument;
! 1025: my @nb_cells = ();
! 1026: my $max_nb_cells = 0;
! 1027: my @rowspans = ();
! 1028: my @trs = $table->getChildrenByTagName('tr');
! 1029: foreach my $tr (@trs) {
! 1030: my $nb_cells;
! 1031: if (defined $rowspans[0]) {
! 1032: $nb_cells = shift(@rowspans);
! 1033: } else {
! 1034: $nb_cells = 0;
! 1035: }
! 1036: for (my $cell=$tr->firstChild; defined $cell; $cell=$cell->nextSibling) {
! 1037: if ($cell->nodeName eq 'td' || $cell->nodeName eq 'th') {
! 1038: my $colspan = $cell->getAttribute('colspan');
! 1039: if (defined $colspan && $colspan =~ /^\s*[0-9]+\s*$/) {
! 1040: $nb_cells += $colspan;
! 1041: } else {
! 1042: $nb_cells++;
! 1043: }
! 1044: my $rowspan = $cell->getAttribute('rowspan');
! 1045: if (defined $rowspan && $rowspan =~ /^\s*[0-9]+\s*$/) {
! 1046: for (my $i=0; $i < $rowspan-1; $i++) {
! 1047: if (!defined $rowspans[$i]) {
! 1048: $rowspans[$i] = 1;
! 1049: } else {
! 1050: $rowspans[$i]++;
! 1051: }
! 1052: }
! 1053: }
! 1054: }
! 1055: }
! 1056: push(@nb_cells, $nb_cells);
! 1057: if ($nb_cells > $max_nb_cells) {
! 1058: $max_nb_cells = $nb_cells;
! 1059: }
! 1060: }
! 1061: foreach my $tr (@trs) {
! 1062: my $nb_cells = shift(@nb_cells);
! 1063: if ($nb_cells < $max_nb_cells) {
! 1064: for (1..($max_nb_cells - $nb_cells)) {
! 1065: $tr->appendChild($doc->createElement('td'));
! 1066: }
! 1067: }
! 1068: }
! 1069: }
! 1070:
! 1071: # replaces ul/ul by ul/li/ul and the same for ol (using the previous li if possible)
! 1072: # also adds a ul element when a li has no ul/ol ancestor
! 1073: sub fix_lists {
! 1074: my ($root) = @_;
! 1075: my $doc = $root->ownerDocument;
! 1076: my @uls = $root->getElementsByTagName('ul');
! 1077: my @ols = $root->getElementsByTagName('ol');
! 1078: my @lists = (@uls, @ols);
! 1079: foreach my $list (@lists) {
! 1080: my $next;
! 1081: for (my $child=$list->firstChild; defined $child; $child=$next) {
! 1082: $next = $child->nextSibling;
! 1083: if ($child->nodeType == XML_ELEMENT_NODE && string_in_array(['ul','ol'], $child->nodeName)) {
! 1084: my $previous = $child->previousNonBlankSibling(); # note: non-DOM method
! 1085: $list->removeChild($child);
! 1086: if (defined $previous && $previous->nodeType == XML_ELEMENT_NODE && $previous->nodeName eq 'li') {
! 1087: $previous->appendChild($child);
! 1088: } else {
! 1089: my $li = $doc->createElement('li');
! 1090: $li->appendChild($child);
! 1091: if (!defined $next) {
! 1092: $list->appendChild($li);
! 1093: } else {
! 1094: $list->insertBefore($li, $next);
! 1095: }
! 1096: }
! 1097: }
! 1098: }
! 1099: }
! 1100: my @lis = $root->getElementsByTagName('li');
! 1101: foreach my $li (@lis) {
! 1102: my $found_list_ancestor = 0;
! 1103: my $ancestor = $li->parentNode;
! 1104: while (defined $ancestor) {
! 1105: if ($ancestor->nodeName eq 'ul' || $ancestor->nodeName eq 'ol') {
! 1106: $found_list_ancestor = 1;
! 1107: last;
! 1108: }
! 1109: $ancestor = $ancestor->parentNode;
! 1110: }
! 1111: if (!$found_list_ancestor) {
! 1112: # replace li by ul and add li under ul
! 1113: my $ul = $doc->createElement('ul');
! 1114: $li->parentNode->insertBefore($ul, $li);
! 1115: $li->parentNode->removeChild($li);
! 1116: $ul->appendChild($li);
! 1117: # add all other li afterwards inside ul (there might be text nodes in-between)
! 1118: my $next = $ul->nextSibling;
! 1119: while (defined $next) {
! 1120: my $next_next = $next->nextSibling;
! 1121: if ($next->nodeType == XML_TEXT_NODE && $next->nodeValue =~ /^\s*$/ &&
! 1122: defined $next_next && $next_next->nodeType == XML_ELEMENT_NODE && $next_next->nodeName eq 'li') {
! 1123: $next->parentNode->removeChild($next);
! 1124: $ul->appendChild($next);
! 1125: $next = $next_next;
! 1126: $next_next = $next_next->nextSibling;
! 1127: }
! 1128: if ($next->nodeType == XML_ELEMENT_NODE && $next->nodeName eq 'li') {
! 1129: $next->parentNode->removeChild($next);
! 1130: $ul->appendChild($next);
! 1131: } else {
! 1132: last;
! 1133: }
! 1134: $next = $next_next;
! 1135: }
! 1136: }
! 1137: }
! 1138: }
! 1139:
! 1140: # Some "image" elements are actually img element with a wrong name. This renames them.
! 1141: # Amazingly enough, "<image src=..." displays an image in some browsers
! 1142: # ("image" has existed at some point as an experimental HTML element).
! 1143: sub fix_wrong_name_for_img {
! 1144: my ($root) = @_;
! 1145: my @images = $root->getElementsByTagName('image');
! 1146: foreach my $image (@images) {
! 1147: if (!defined $image->getAttribute('src')) {
! 1148: next;
! 1149: }
! 1150: my $found_correct_ancestor = 0;
! 1151: my $ancestor = $image->parentNode;
! 1152: while (defined $ancestor) {
! 1153: if ($ancestor->nodeName eq 'drawimage' || $ancestor->nodeName eq 'imageresponse') {
! 1154: $found_correct_ancestor = 1;
! 1155: last;
! 1156: }
! 1157: $ancestor = $ancestor->parentNode;
! 1158: }
! 1159: if ($found_correct_ancestor) {
! 1160: next;
! 1161: }
! 1162: # this really has to be renamed "img"
! 1163: $image->setNodeName('img');
! 1164: }
! 1165: }
! 1166:
! 1167: # Replaces many deprecated attributes and replaces them by equivalent CSS when possible
! 1168: sub replace_deprecated_attributes_by_css {
! 1169: my ($root) = @_;
! 1170:
! 1171: fix_deprecated_in_tables($root);
! 1172:
! 1173: fix_deprecated_in_table_rows($root);
! 1174:
! 1175: fix_deprecated_in_table_cells($root);
! 1176:
! 1177: fix_deprecated_in_lists($root);
! 1178:
! 1179: fix_deprecated_in_list_items($root);
! 1180:
! 1181: fix_deprecated_in_hr($root);
! 1182:
! 1183: fix_deprecated_in_img($root);
! 1184:
! 1185: fix_deprecated_in_body($root);
! 1186:
! 1187: fix_align_attribute($root);
! 1188: }
! 1189:
! 1190: # Replaces deprecated attributes in tables
! 1191: sub fix_deprecated_in_tables {
! 1192: my ($root) = @_;
! 1193: my @tables = $root->getElementsByTagName('table');
! 1194: foreach my $table (@tables) {
! 1195: tie (my %new_properties, 'Tie::IxHash', ());
! 1196: my $align = $table->getAttribute('align');
! 1197: if (defined $align) {
! 1198: $table->removeAttribute('align');
! 1199: $align = lc(trim($align));
! 1200: }
! 1201: if ($table->parentNode->nodeName eq 'center' || (defined $align && $align eq 'center') ||
! 1202: (defined $table->parentNode->getAttribute('align') && $table->parentNode->getAttribute('align') eq 'center')) {
! 1203: $new_properties{'margin-left'} = 'auto';
! 1204: $new_properties{'margin-right'} = 'auto';
! 1205: }
! 1206: if (defined $align && ($align eq 'left' || $align eq 'right')) {
! 1207: $new_properties{'float'} = $align;
! 1208: }
! 1209: my $width = $table->getAttribute('width');
! 1210: if (defined $width) {
! 1211: $table->removeAttribute('width');
! 1212: $width = trim($width);
! 1213: if ($width =~ /^[0-9]+$/) {
! 1214: $width .= 'px';
! 1215: }
! 1216: if ($width ne '') {
! 1217: $new_properties{'width'} = $width;
! 1218: }
! 1219: }
! 1220: my $height = $table->getAttribute('height');
! 1221: if (defined $height) {
! 1222: $table->removeAttribute('height');
! 1223: # no replacement for table height
! 1224: }
! 1225: my $bgcolor = $table->getAttribute('bgcolor');
! 1226: if (defined $bgcolor) {
! 1227: $table->removeAttribute('bgcolor');
! 1228: $bgcolor = trim($bgcolor);
! 1229: $bgcolor =~ s/^x\s*//;
! 1230: if ($bgcolor ne '') {
! 1231: $new_properties{'background-color'} = $bgcolor;
! 1232: }
! 1233: }
! 1234: my $frame = $table->getAttribute('frame');
! 1235: if (defined $frame) {
! 1236: $table->removeAttribute('frame');
! 1237: $frame = lc(trim($frame));
! 1238: if ($frame eq 'void') {
! 1239: $new_properties{'border'} = 'none';
! 1240: } elsif ($frame eq 'above') {
! 1241: $new_properties{'border-top'} = '1px solid black';
! 1242: } elsif ($frame eq 'below') {
! 1243: $new_properties{'border-bottom'} = '1px solid black';
! 1244: } elsif ($frame eq 'hsides') {
! 1245: $new_properties{'border-top'} = '1px solid black';
! 1246: $new_properties{'border-bottom'} = '1px solid black';
! 1247: } elsif ($frame eq 'vsides') {
! 1248: $new_properties{'border-left'} = '1px solid black';
! 1249: $new_properties{'border-right'} = '1px solid black';
! 1250: } elsif ($frame eq 'lhs') {
! 1251: $new_properties{'border-left'} = '1px solid black';
! 1252: } elsif ($frame eq 'rhs') {
! 1253: $new_properties{'border-right'} = '1px solid black';
! 1254: } elsif ($frame eq 'box') {
! 1255: $new_properties{'border'} = '1px solid black';
! 1256: } elsif ($frame eq 'border') {
! 1257: $new_properties{'border'} = '1px solid black';
! 1258: }
! 1259: }
! 1260: if (scalar(keys %new_properties) > 0) {
! 1261: set_css_properties($table, \%new_properties);
! 1262: }
! 1263: # we can't replace the border attribute without creating a style block, but we can improve things like border="BORDER"
! 1264: my $border = $table->getAttribute('border');
! 1265: if (defined $border) {
! 1266: $border = trim($border);
! 1267: if ($border !~ /^\s*[0-9]+\s*(px)?\s*$/) {
! 1268: $table->setAttribute('border', '1');
! 1269: }
! 1270: }
! 1271: }
! 1272:
! 1273: }
! 1274:
! 1275: # Replaces deprecated attributes in tr elements
! 1276: sub fix_deprecated_in_table_rows {
! 1277: my ($root) = @_;
! 1278: my @trs = $root->getElementsByTagName('tr');
! 1279: foreach my $tr (@trs) {
! 1280: my $old_properties = get_css_properties($tr);
! 1281: tie (my %new_properties, 'Tie::IxHash', ());
! 1282: my $bgcolor = $tr->getAttribute('bgcolor');
! 1283: if (defined $bgcolor) {
! 1284: $tr->removeAttribute('bgcolor');
! 1285: if (!defined $old_properties->{'background-color'}) {
! 1286: $bgcolor = trim($bgcolor);
! 1287: $bgcolor =~ s/^x\s*//;
! 1288: if ($bgcolor ne '') {
! 1289: $new_properties{'background-color'} = $bgcolor;
! 1290: }
! 1291: }
! 1292: }
! 1293: my $align = $tr->getAttribute('align');
! 1294: if (defined $align && $align !~ /\s*char\s*/i) {
! 1295: $tr->removeAttribute('align');
! 1296: if (!defined $old_properties->{'text-align'}) {
! 1297: $align = lc(trim($align));
! 1298: if ($align ne '') {
! 1299: $new_properties{'text-align'} = $align;
! 1300: }
! 1301: }
! 1302: }
! 1303: my $valign = $tr->getAttribute('valign');
! 1304: if (defined $valign) {
! 1305: $tr->removeAttribute('valign');
! 1306: if (!defined $old_properties->{'vertical-align'}) {
! 1307: $valign = lc(trim($valign));
! 1308: if ($valign ne '') {
! 1309: $new_properties{'vertical-align'} = $valign;
! 1310: }
! 1311: }
! 1312: }
! 1313: if (scalar(keys %new_properties) > 0) {
! 1314: set_css_properties($tr, \%new_properties);
! 1315: }
! 1316: }
! 1317: }
! 1318:
! 1319: # Replaces deprecated attributes in table cells (td and th)
! 1320: sub fix_deprecated_in_table_cells {
! 1321: my ($root) = @_;
! 1322: my @tds = $root->getElementsByTagName('td');
! 1323: my @ths = $root->getElementsByTagName('th');
! 1324: my @cells = (@tds, @ths);
! 1325: foreach my $cell (@cells) {
! 1326: my $old_properties = get_css_properties($cell);
! 1327: tie (my %new_properties, 'Tie::IxHash', ());
! 1328: my $width = $cell->getAttribute('width');
! 1329: if (defined $width) {
! 1330: $cell->removeAttribute('width');
! 1331: if (!defined $old_properties->{'width'}) {
! 1332: $width = trim($width);
! 1333: if ($width =~ /^[0-9]+$/) {
! 1334: $width .= 'px';
! 1335: }
! 1336: if ($width ne '') {
! 1337: $new_properties{'width'} = $width;
! 1338: }
! 1339: }
! 1340: }
! 1341: my $height = $cell->getAttribute('height');
! 1342: if (defined $height) {
! 1343: $cell->removeAttribute('height');
! 1344: if (!defined $old_properties->{'height'}) {
! 1345: $height = trim($height);
! 1346: if ($height =~ /^[0-9]+$/) {
! 1347: $height .= 'px';
! 1348: }
! 1349: if ($height ne '') {
! 1350: $new_properties{'height'} = $height;
! 1351: }
! 1352: }
! 1353: }
! 1354: my $bgcolor = $cell->getAttribute('bgcolor');
! 1355: if (defined $bgcolor) {
! 1356: $cell->removeAttribute('bgcolor');
! 1357: if (!defined $old_properties->{'background-color'}) {
! 1358: $bgcolor = trim($bgcolor);
! 1359: $bgcolor =~ s/^x\s*//;
! 1360: if ($bgcolor ne '') {
! 1361: $new_properties{'background-color'} = $bgcolor;
! 1362: }
! 1363: }
! 1364: }
! 1365: my $align = $cell->getAttribute('align');
! 1366: if (defined $align && $align !~ /\s*char\s*/i) {
! 1367: $cell->removeAttribute('align');
! 1368: if (!defined $old_properties->{'text-align'}) {
! 1369: $align = lc(trim($align));
! 1370: if ($align ne '') {
! 1371: $new_properties{'text-align'} = $align;
! 1372: }
! 1373: }
! 1374: }
! 1375: my $valign = $cell->getAttribute('valign');
! 1376: if (defined $valign) {
! 1377: $cell->removeAttribute('valign');
! 1378: if (!defined $old_properties->{'vertical-align'}) {
! 1379: $valign = lc(trim($valign));
! 1380: if ($valign ne '') {
! 1381: $new_properties{'vertical-align'} = $valign;
! 1382: }
! 1383: }
! 1384: }
! 1385: if (scalar(keys %new_properties) > 0) {
! 1386: set_css_properties($cell, \%new_properties);
! 1387: }
! 1388: }
! 1389: }
! 1390:
! 1391: # Replaces deprecated attributes in lists (ul and ol)
! 1392: sub fix_deprecated_in_lists {
! 1393: my ($root) = @_;
! 1394: my @uls = $root->getElementsByTagName('ul');
! 1395: my @ols = $root->getElementsByTagName('ol');
! 1396: my @lists = (@uls, @ols);
! 1397: foreach my $list (@lists) {
! 1398: my $type = $list->getAttribute('type');
! 1399: if (defined $type) {
! 1400: my $lst = list_style_type($type);
! 1401: if (defined $lst) {
! 1402: $list->removeAttribute('type');
! 1403: if (!defined get_css_property($list, 'list-style-type')) {
! 1404: set_css_property($list, 'list-style-type', $lst);
! 1405: }
! 1406: }
! 1407: }
! 1408: }
! 1409: }
! 1410:
! 1411: # Replaces deprecated attributes in list items (li)
! 1412: sub fix_deprecated_in_list_items {
! 1413: my ($root) = @_;
! 1414: my @lis = $root->getElementsByTagName('li');
! 1415: foreach my $li (@lis) {
! 1416: my $type = $li->getAttribute('type');
! 1417: if (defined $type) {
! 1418: my $lst = list_style_type($type);
! 1419: if (defined $lst) {
! 1420: $li->removeAttribute('type');
! 1421: if (!defined get_css_property($li, 'list-style-type')) {
! 1422: set_css_property($li, 'list-style-type', $lst);
! 1423: }
! 1424: }
! 1425: }
! 1426: }
! 1427: }
! 1428:
! 1429: # returns the CSS list-style-type value equivalent to the given type attribute for a list or list item
! 1430: sub list_style_type {
! 1431: my ($type) = @_;
! 1432: my $value;
! 1433: $type = trim($type);
! 1434: if (lc($type) eq 'circle') {
! 1435: $value = 'circle';
! 1436: } elsif (lc($type) eq 'disc') {
! 1437: $value = 'disc';
! 1438: } elsif (lc($type) eq 'square') {
! 1439: $value = 'square';
! 1440: } elsif ($type eq 'a') {
! 1441: $value = 'lower-latin';
! 1442: } elsif ($type eq 'A') {
! 1443: $value = 'upper-latin';
! 1444: } elsif ($type eq 'i') {
! 1445: $value = 'lower-roman';
! 1446: } elsif ($type eq 'I') {
! 1447: $value = 'upper-roman';
! 1448: } elsif ($type eq '1') {
! 1449: $value = 'decimal';
! 1450: }
! 1451: return $value;
! 1452: }
! 1453:
! 1454: # Replaces deprecated attributes in hr
! 1455: sub fix_deprecated_in_hr {
! 1456: my ($root) = @_;
! 1457: my @hrs = $root->getElementsByTagName('hr');
! 1458: foreach my $hr (@hrs) {
! 1459: tie (my %new_properties, 'Tie::IxHash', ());
! 1460: my $align = $hr->getAttribute('align');
! 1461: if (defined $align) {
! 1462: $align = lc(trim($align));
! 1463: if ($align eq 'left') {
! 1464: $new_properties{'text-align'} = 'left';
! 1465: $new_properties{'margin-left'} = '0';
! 1466: } elsif ($align eq 'right') {
! 1467: $new_properties{'text-align'} = 'right';
! 1468: $new_properties{'margin-right'} = '0';
! 1469: }
! 1470: $hr->removeAttribute('align');
! 1471: }
! 1472: my $color = $hr->getAttribute('color');
! 1473: if (defined $color) {
! 1474: $color = trim($color);
! 1475: $color =~ s/^x\s*//;
! 1476: if ($color ne '') {
! 1477: $new_properties{'color'} = $color;
! 1478: $new_properties{'background-color'} = $color;
! 1479: }
! 1480: $hr->removeAttribute('color');
! 1481: }
! 1482: my $noshade = $hr->getAttribute('noshade');
! 1483: my $size = $hr->getAttribute('size');
! 1484: if (defined $noshade) {
! 1485: $new_properties{'border-width'} = '0';
! 1486: if (!defined $color) {
! 1487: $new_properties{'color'} = 'gray';
! 1488: $new_properties{'background-color'} = 'gray';
! 1489: }
! 1490: if (!defined $size) {
! 1491: $size = '2';
! 1492: }
! 1493: $hr->removeAttribute('noshade');
! 1494: }
! 1495: if (defined $size) {
! 1496: $size = trim($size);
! 1497: if ($size ne '') {
! 1498: $new_properties{'height'} = $size.'px';
! 1499: }
! 1500: if (defined $hr->getAttribute('size')) {
! 1501: $hr->removeAttribute('size');
! 1502: }
! 1503: }
! 1504: my $width = $hr->getAttribute('width');
! 1505: if (defined $width) {
! 1506: $width = trim($width);
! 1507: if ($width ne '') {
! 1508: if ($width !~ /\%$/) {
! 1509: $width .= 'px';
! 1510: }
! 1511: $new_properties{'width'} = $width;
! 1512: }
! 1513: $hr->removeAttribute('width');
! 1514: }
! 1515: if (scalar(keys %new_properties) > 0) {
! 1516: set_css_properties($hr, \%new_properties);
! 1517: }
! 1518: }
! 1519: }
! 1520:
! 1521: # Replaces deprecated attributes in img
! 1522: sub fix_deprecated_in_img {
! 1523: my ($root) = @_;
! 1524: my @imgs = $root->getElementsByTagName('img');
! 1525: foreach my $img (@imgs) {
! 1526: my $old_properties = get_css_properties($img);
! 1527: tie (my %new_properties, 'Tie::IxHash', ());
! 1528: my $align = $img->getAttribute('align');
! 1529: if (defined $align) {
! 1530: $align = lc(trim($align));
! 1531: if ($align eq 'middle' || $align eq 'top' || $align eq 'bottom') {
! 1532: $img->removeAttribute('align');
! 1533: if (!defined $old_properties->{'vertical-align'}) {
! 1534: $new_properties{'vertical-align'} = $align;
! 1535: }
! 1536: } elsif ($align eq 'left' || $align eq 'right') {
! 1537: $img->removeAttribute('align');
! 1538: if (!defined $old_properties->{'float'}) {
! 1539: $new_properties{'float'} = $align;
! 1540: }
! 1541: } elsif ($align eq 'center' || $align eq '') {
! 1542: $img->removeAttribute('align');
! 1543: }
! 1544: }
! 1545: my $border = $img->getAttribute('border');
! 1546: if (defined $border) {
! 1547: $border = lc(trim($border));
! 1548: if ($border =~ /^[0-9]+\s*(px)?$/) {
! 1549: $img->removeAttribute('border');
! 1550: if (!defined $old_properties->{'border'}) {
! 1551: if ($border !~ /px$/) {
! 1552: $border .= 'px';
! 1553: }
! 1554: $new_properties{'border'} = $border.' solid black';
! 1555: }
! 1556: }
! 1557: }
! 1558: my $hspace = $img->getAttribute('hspace');
! 1559: if (defined $hspace) {
! 1560: $hspace = lc(trim($hspace));
! 1561: if ($hspace =~ /^[0-9]+\s*(px)?$/) {
! 1562: $img->removeAttribute('hspace');
! 1563: if (!defined $old_properties->{'margin-left'} || !defined $old_properties->{'margin-right'}) {
! 1564: if ($hspace !~ /px$/) {
! 1565: $hspace .= 'px';
! 1566: }
! 1567: $new_properties{'margin-left'} = $hspace;
! 1568: $new_properties{'margin-right'} = $hspace;
! 1569: }
! 1570: }
! 1571: }
! 1572: if (scalar(keys %new_properties) > 0) {
! 1573: set_css_properties($img, \%new_properties);
! 1574: }
! 1575: }
! 1576: }
! 1577:
! 1578: # Replaces deprecated attributes in htmlbody (the style attribute could be used in a div for output)
! 1579: sub fix_deprecated_in_body {
! 1580: my ($root) = @_;
! 1581: my $doc = $root->ownerDocument;
! 1582: my @bodies = $root->getElementsByTagName('htmlbody');
! 1583: foreach my $body (@bodies) {
! 1584: my $old_properties = get_css_properties($body);
! 1585: tie (my %new_properties, 'Tie::IxHash', ());
! 1586: my $bgcolor = $body->getAttribute('bgcolor');
! 1587: if (defined $bgcolor) {
! 1588: $body->removeAttribute('bgcolor');
! 1589: if (!defined $old_properties->{'background-color'}) {
! 1590: $bgcolor = trim($bgcolor);
! 1591: $bgcolor =~ s/^x\s*//;
! 1592: if ($bgcolor ne '') {
! 1593: $new_properties{'background-color'} = $bgcolor;
! 1594: }
! 1595: }
! 1596: }
! 1597: my $color = $body->getAttribute('text');
! 1598: if (defined $color) {
! 1599: $body->removeAttribute('text');
! 1600: if (!defined $old_properties->{'color'}) {
! 1601: $color = trim($color);
! 1602: $color =~ s/^x\s*//;
! 1603: if ($color ne '') {
! 1604: $new_properties{'color'} = $color;
! 1605: }
! 1606: }
! 1607: }
! 1608: my $background = $body->getAttribute('background');
! 1609: if (defined $background && ($background =~ /\.jpe?g$|\.gif|\.png/i)) {
! 1610: $body->removeAttribute('background');
! 1611: if (!defined $old_properties->{'background-image'}) {
! 1612: $background = trim($background);
! 1613: if ($background ne '') {
! 1614: $new_properties{'background-image'} = 'url('.$background.')';
! 1615: }
! 1616: }
! 1617: }
! 1618: # NOTE: these attributes have never been standard and are better removed with no replacement
! 1619: foreach my $bad ('bottommargin', 'leftmargin', 'rightmargin', 'topmargin', 'marginheight', 'marginwidth') {
! 1620: if ($body->hasAttribute($bad)) {
! 1621: $body->removeAttribute($bad);
! 1622: }
! 1623: }
! 1624: # NOTE: link alink and vlink require a <style> block to be converted
! 1625: my $link = $body->getAttribute('link');
! 1626: my $alink = $body->getAttribute('alink');
! 1627: my $vlink = $body->getAttribute('vlink');
! 1628: if (defined $link || defined $alink || defined $vlink) {
! 1629: my $head;
! 1630: my @heads = $root->getElementsByTagName('htmlhead');
! 1631: if (scalar(@heads) > 0) {
! 1632: $head = $heads[0];
! 1633: } else {
! 1634: $head = $doc->createElement('htmlhead');
! 1635: $root->insertBefore($head, $root->firstChild);
! 1636: }
! 1637: my $style = $doc->createElement('style');
! 1638: $head->appendChild($style);
! 1639: my $css = "\n";
! 1640: if (defined $link) {
! 1641: $body->removeAttribute('link');
! 1642: $link = trim($link);
! 1643: $link =~ s/^x\s*//;
! 1644: $css .= ' a:link { color:'.$link.' }';
! 1645: $css .= "\n";
! 1646: }
! 1647: if (defined $alink) {
! 1648: $body->removeAttribute('alink');
! 1649: $alink = trim($alink);
! 1650: $alink =~ s/^x\s*//;
! 1651: $css .= ' a:active { color:'.$alink.' }';
! 1652: $css .= "\n";
! 1653: }
! 1654: if (defined $vlink) {
! 1655: $body->removeAttribute('vlink');
! 1656: $vlink = trim($vlink);
! 1657: $vlink =~ s/^x\s*//;
! 1658: $css .= ' a:visited { color:'.$vlink.' }';
! 1659: $css .= "\n";
! 1660: }
! 1661: $css .= ' ';
! 1662: $style->appendChild($doc->createTextNode($css));
! 1663: }
! 1664: if (scalar(keys %new_properties) > 0) {
! 1665: set_css_properties($body, \%new_properties);
! 1666: } elsif (!$body->hasAttributes) {
! 1667: $body->parentNode->removeChild($body);
! 1668: }
! 1669: }
! 1670: }
! 1671:
! 1672: # replaces <div align="center"> by <div style="text-align:center;">
! 1673: # also for p and h1..h6
! 1674: sub fix_align_attribute {
! 1675: my ($root) = @_;
! 1676: my @nodes = $root->getElementsByTagName('div');
! 1677: push(@nodes, $root->getElementsByTagName('p'));
! 1678: for (my $i=1; $i<=6; $i++) {
! 1679: push(@nodes, $root->getElementsByTagName('h'.$i));
! 1680: }
! 1681: foreach my $node (@nodes) {
! 1682: my $align = $node->getAttribute('align');
! 1683: if (defined $align) {
! 1684: $node->removeAttribute('align');
! 1685: $align = trim($align);
! 1686: if ($align ne '' && !defined get_css_property($node, 'text-align')) {
! 1687: set_css_property($node, 'text-align', lc($align));
! 1688: }
! 1689: }
! 1690: }
! 1691: }
! 1692:
! 1693: # replace center by a div or remove it if there is a table inside
! 1694: sub replace_center {
! 1695: my ($root, $all_block) = @_;
! 1696: my $doc = $root->ownerDocument;
! 1697: my @centers = $root->getElementsByTagName('center');
! 1698: foreach my $center (@centers) {
! 1699: if ($center->getChildrenByTagName('table')->size() > 0) { # note: getChildrenByTagName is not DOM (LibXML specific)
! 1700: replace_by_children($center);
! 1701: } else {
! 1702: if ((!defined $center->previousSibling ||
! 1703: ($center->previousSibling->nodeType == XML_TEXT_NODE && $center->previousSibling->nodeValue =~ /^\s*$/ && !defined $center->previousSibling->previousSibling)) &&
! 1704: (!defined $center->nextSibling ||
! 1705: ($center->nextSibling->nodeType == XML_TEXT_NODE && $center->nextSibling->nodeValue =~ /^\s*$/ && !defined $center->nextSibling->nextSibling)) &&
! 1706: string_in_array(\@accepting_style, $center->parentNode->nodeName)) {
! 1707: # use CSS on the parent block and replace center by its children
! 1708: set_css_property($center->parentNode, 'text-align', 'center');
! 1709: replace_by_children($center);
! 1710: } else {
! 1711: # use p or div ? check if there is a block inside
! 1712: my $found_block = 0;
! 1713: for (my $child=$center->firstChild; defined $child; $child=$child->nextSibling) {
! 1714: if ($child->nodeType == XML_ELEMENT_NODE && string_in_array($all_block, $child->nodeName)) {
! 1715: $found_block = 1;
! 1716: last;
! 1717: }
! 1718: }
! 1719: my $new_node;
! 1720: if ($found_block) {
! 1721: $new_node = $doc->createElement('div');
! 1722: $new_node->setAttribute('style', 'text-align: center; margin: 0 auto');
! 1723: } else {
! 1724: $new_node = $doc->createElement('p');
! 1725: $new_node->setAttribute('style', 'text-align: center');
! 1726: }
! 1727: my $next;
! 1728: for (my $child=$center->firstChild; defined $child; $child=$next) {
! 1729: $next = $child->nextSibling;
! 1730: $center->removeChild($child);
! 1731: $new_node->appendChild($child);
! 1732: }
! 1733: $center->parentNode->replaceChild($new_node, $center);
! 1734: }
! 1735: }
! 1736: }
! 1737: }
! 1738:
! 1739: # replaces <nobr> by <span style="white-space:nowrap">
! 1740: sub replace_nobr {
! 1741: my ($root) = @_;
! 1742: my @nobrs = $root->getElementsByTagName('nobr');
! 1743: foreach my $nobr (@nobrs) {
! 1744: if (!defined $nobr->previousSibling && !defined $nobr->nextSibling &&
! 1745: string_in_array(\@accepting_style, $nobr->parentNode->nodeName)) {
! 1746: # use CSS on the parent block
! 1747: set_css_property($nobr->parentNode, 'white-space', 'nowrap');
! 1748: replace_by_children($nobr);
! 1749: } else {
! 1750: $nobr->setNodeName('span');
! 1751: $nobr->setAttribute('style', 'white-space:nowrap');
! 1752: }
! 1753: }
! 1754: }
! 1755:
! 1756: # removes notsolved tags in the case <hintgroup showoncorrect="no"><notsolved>...</notsolved></hintgroup>
! 1757: # and in the case <notsolved><hintgroup showoncorrect="no">...</hintgroup></notsolved>
! 1758: sub remove_useless_notsolved {
! 1759: my ($root) = @_;
! 1760: my @hintgroups = $root->getElementsByTagName('hintgroup');
! 1761: foreach my $hintgroup (@hintgroups) {
! 1762: my $showoncorrect = get_non_empty_attribute($hintgroup, 'showoncorrect');
! 1763: if (!defined $showoncorrect || $showoncorrect eq 'no') {
! 1764: my @notsolveds = $hintgroup->getElementsByTagName('notsolved');
! 1765: foreach my $notsolved (@notsolveds) {
! 1766: replace_by_children($notsolved);
! 1767: }
! 1768: }
! 1769: my $parent = $hintgroup->parentNode;
! 1770: if ($parent->nodeName eq 'notsolved' && scalar(@{$parent->nonBlankChildNodes()}) == 1) {
! 1771: replace_by_children($parent);
! 1772: }
! 1773: }
! 1774: }
! 1775:
! 1776: # adds a paragraph inside if needed and calls fix_paragraph for all paragraphs (including new ones)
! 1777: sub fix_paragraphs_inside {
! 1778: my ($node, $all_block) = @_;
! 1779: # blocks in which paragrahs will be added:
! 1780: my @blocks_with_p = ('loncapa','library','problem','part','problemtype','window','block','while','postanswerdate','preduedate','solved','notsolved','languageblock','translated','lang','instructorcomment','togglebox','standalone','form');
! 1781: my @fix_p_if_br_or_p = (@responses,'foil','item','text','label','hintgroup','hintpart','hint','web','windowlink','div','li','dd','td','th','blockquote');
! 1782: if ((string_in_array(\@blocks_with_p, $node->nodeName) && paragraph_needed($node)) ||
! 1783: (string_in_array(\@fix_p_if_br_or_p, $node->nodeName) && paragraph_inside($node))) {
! 1784: # if non-empty, add paragraphs where needed between all br and remove br
! 1785: # (it would be easier to just put everything in a p and fix it afterwards, but there are performance issues
! 1786: # when a paragraph has many blocks directly inside)
! 1787: my $doc = $node->ownerDocument;
! 1788: my $p = undef;
! 1789: my @new_children = ();
! 1790: my $next;
! 1791: for (my $child=$node->firstChild; defined $child; $child=$next) {
! 1792: $next = $child->nextSibling;
! 1793: $node->removeChild($child);
! 1794: if ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName eq 'br') {
! 1795: if (defined $p) {
! 1796: push(@new_children, $p);
! 1797: } else {
! 1798: push(@new_children, $doc->createElement('p'));
! 1799: }
! 1800: $p = undef;
! 1801: } elsif ($child->nodeType == XML_ELEMENT_NODE && string_in_array(\@inline_like_block, $child->nodeName)) {
! 1802: # inline_like_block: use the paragraph if there is one, otherwise do not create one
! 1803: if (defined $p) {
! 1804: $p->appendChild($child);
! 1805: } else {
! 1806: push(@new_children, $child);
! 1807: }
! 1808: } elsif ($child->nodeType == XML_ELEMENT_NODE && string_in_array($all_block, $child->nodeName)) {
! 1809: # these children are blocks and should not be in a paragraph
! 1810: if (defined $p) {
! 1811: push(@new_children, $p);
! 1812: $p = undef;
! 1813: }
! 1814: push(@new_children, $child);
! 1815: } elsif ($child->nodeType == XML_TEXT_NODE && $child->nodeValue =~ /^[ \t\f\n\r]*$/) {
! 1816: # blank text: add to paragraph if there is one and there is a next node, otherwise keep out of the paragraph
! 1817: if (defined $p) {
! 1818: if (defined $next) {
! 1819: $p->appendChild($child);
! 1820: } else {
! 1821: push(@new_children, $p);
! 1822: $p = undef;
! 1823: push(@new_children, $child);
! 1824: }
! 1825: } else {
! 1826: push(@new_children, $child);
! 1827: }
! 1828: } elsif ($child->nodeType == XML_TEXT_NODE ||
! 1829: $child->nodeType == XML_ELEMENT_NODE || $child->nodeType == XML_CDATA_SECTION_NODE ||
! 1830: $child->nodeType == XML_ENTITY_NODE || $child->nodeType == XML_ENTITY_REF_NODE) {
! 1831: # these children require a paragraph
! 1832: if (!defined $p) {
! 1833: $p = $doc->createElement('p');
! 1834: }
! 1835: $p->appendChild($child);
! 1836: } else {
! 1837: # these children do not require a paragraph (XML comments, PI)
! 1838: # -> do not move them in a new paragraph
! 1839: if (defined $p) {
! 1840: push(@new_children, $p);
! 1841: $p = undef;
! 1842: }
! 1843: push(@new_children, $child);
! 1844: }
! 1845: }
! 1846: if (defined $p) {
! 1847: push(@new_children, $p);
! 1848: }
! 1849: foreach my $child (@new_children) {
! 1850: $node->appendChild($child);
! 1851: }
! 1852: }
! 1853: # now fix the paragraphs everywhere, so that all inline nodes are inside a paragraph, and block nodes are outside
! 1854: my $next;
! 1855: for (my $child=$node->firstChild; defined $child; $child=$next) {
! 1856: $next = $child->nextSibling;
! 1857: if ($child->nodeType == XML_ELEMENT_NODE && defined $child->firstChild) {
! 1858: if ($child->nodeName eq 'p') {
! 1859: fix_paragraph($child, $all_block);
! 1860: } else {
! 1861: fix_paragraphs_inside($child, $all_block);
! 1862: }
! 1863: }
! 1864: }
! 1865: }
! 1866:
! 1867: # returns 1 if a paragraph is needed inside this node (assuming the parent can have paragraphs)
! 1868: sub paragraph_needed {
! 1869: my ($node) = @_;
! 1870: for (my $child=$node->firstChild; defined $child; $child=$child->nextSibling) {
! 1871: if (($child->nodeType == XML_TEXT_NODE && $child->nodeValue !~ /^\s*$/) ||
! 1872: ($child->nodeType == XML_ELEMENT_NODE && !string_in_array(\@inline_like_block, $child->nodeName)) ||
! 1873: $child->nodeType == XML_CDATA_SECTION_NODE ||
! 1874: $child->nodeType == XML_ENTITY_NODE || $child->nodeType == XML_ENTITY_REF_NODE) {
! 1875: return(1);
! 1876: }
! 1877: }
! 1878: return(0);
! 1879: }
! 1880:
! 1881: # returns 1 if there is a paragraph or br in a child of this node, or inside an inline child
! 1882: sub paragraph_inside {
! 1883: my ($node) = @_;
! 1884: # inline elements that can be split in half if there is a paragraph inside (currently all HTML):
! 1885: # (also used in first_block below)
! 1886: my @splitable_inline = ('span', 'a', 'strong', 'em' , 'b', 'i', 'sup', 'sub', 'code', 'kbd', 'samp', 'tt', 'ins', 'del', 'var', 'small', 'big', 'font', 'u');
! 1887: for (my $child=$node->firstChild; defined $child; $child=$child->nextSibling) {
! 1888: if ($child->nodeType == XML_ELEMENT_NODE) {
! 1889: my $name = $child->nodeName;
! 1890: if ($name eq 'p' || $name eq 'br') {
! 1891: return(1);
! 1892: } elsif (string_in_array(\@splitable_inline, $name)) {
! 1893: if (paragraph_inside($child)) {
! 1894: return(1);
! 1895: }
! 1896: }
! 1897: }
! 1898: }
! 1899: return(0);
! 1900: }
! 1901:
! 1902: # fixes paragraphs inside paragraphs (without a block in-between)
! 1903: sub fix_paragraph {
! 1904: my ($p, $all_block) = @_;
! 1905: my $loop_right = 1; # this loops is to avoid out of memory errors with recurse, see below
! 1906: while ($loop_right) {
! 1907: $loop_right = 0;
! 1908: my $block = find_first_block($p, $all_block);
! 1909: if (defined $block) {
! 1910: my $trees = clone_ancestor_around_node($p, $block);
! 1911: my $doc = $p->ownerDocument;
! 1912: my $replacement = $doc->createDocumentFragment();
! 1913: my $left = $trees->{'left'};
! 1914: my $middle = $trees->{'middle'};
! 1915: my $right = $trees->{'right'};
! 1916: my $left_needs_p = 0; # 1 if it needs a paragraph (used to replace br later)
! 1917:
! 1918: if (defined $left) {
! 1919: # fix paragraphs inside, in case one of the descendants can have paragraphs inside (like numericalresponse/hintgroup):
! 1920: for (my $child=$left->firstChild; defined $child; $child=$child->nextSibling) {
! 1921: if ($child->nodeType == XML_ELEMENT_NODE) {
! 1922: fix_paragraphs_inside($child, $all_block);
! 1923: }
! 1924: }
! 1925: if (!paragraph_needed($left)) {
! 1926: # this was just blank text, comments or inline responses, it should not create a new paragraph
! 1927: my $next;
! 1928: for (my $child=$left->firstChild; defined $child; $child=$next) {
! 1929: $next = $child->nextSibling;
! 1930: $left->removeChild($child);
! 1931: $replacement->appendChild($child);
! 1932: }
! 1933: } else {
! 1934: $left_needs_p = 1;
! 1935: $replacement->appendChild($left);
! 1936: }
! 1937: }
! 1938:
! 1939: my $n = $middle->firstChild;
! 1940: while (defined $n) {
! 1941: if ($n->nodeType == XML_ELEMENT_NODE && (string_in_array($all_block, $n->nodeName) || $n->nodeName eq 'br')) {
! 1942: if ($n->nodeName eq 'p') {
! 1943: my $parent = $n->parentNode;
! 1944: # first apply recursion
! 1945: fix_paragraph($n, $all_block);
! 1946: # now the p might have been replaced by several nodes, which should replace the initial p
! 1947: my $next_block;
! 1948: for (my $block=$parent->firstChild; defined $block; $block=$next_block) {
! 1949: $next_block = $block->nextSibling;
! 1950: if ($block->nodeName eq 'p') {
! 1951: $parent->removeChild($block);
! 1952: # for each parent before $middle, clone in-between the p and its children (to preserve the styles)
! 1953: if (defined $block->firstChild) {
! 1954: for (my $p=$parent; $p!=$middle; $p=$p->parentNode) {
! 1955: my $newp = $p->cloneNode(0);
! 1956: my $next;
! 1957: for (my $child=$block->firstChild; defined $child; $child=$next) {
! 1958: $next = $child->nextSibling;
! 1959: $block->removeChild($child);
! 1960: $newp->appendChild($child);
! 1961: }
! 1962: $block->appendChild($newp);
! 1963: }
! 1964: }
! 1965: }
! 1966: $replacement->appendChild($block);
! 1967: }
! 1968: } else {
! 1969: # replace the whole p by this block, forgetting about intermediate inline elements
! 1970: $n->parentNode->removeChild($n);
! 1971: if ($n->nodeName eq 'br') {
! 1972: # replace a br by a paragraph if there was nothing before in the paragraph,
! 1973: # otherwise remove it because it already broke the paragraph in half
! 1974: if (!defined $left || !$left_needs_p) {
! 1975: $replacement->appendChild($middle);
! 1976: }
! 1977: } else {
! 1978: fix_paragraphs_inside($n, $all_block);
! 1979: $replacement->appendChild($n);
! 1980: }
! 1981: }
! 1982: last;
! 1983: }
! 1984: $n = $n->firstChild;
! 1985: if (defined $n && defined $n->nextSibling) {
! 1986: die "Error in post_xml.fix_paragraph: block not found";
! 1987: }
! 1988: }
! 1989:
! 1990: if (defined $right) {
! 1991: if ($block->nodeName eq 'p') {
! 1992: # remove attributes on the right paragraph
! 1993: my @attributelist = $right->attributes();
! 1994: foreach my $att (@attributelist) {
! 1995: $right->removeAttribute($att->nodeName);
! 1996: }
! 1997: }
! 1998: if ($right->firstChild->nodeType == XML_TEXT_NODE && $right->firstChild->nodeValue =~ /^[ \t\f\n\r]*$/) {
! 1999: # remove the first text node with whitespace only from the p, it should not trigger the creation of a p
! 2000: # (but take nbsp into account, so we should not use \s here)
! 2001: my $first = $right->firstChild;
! 2002: $right->removeChild($first);
! 2003: $replacement->appendChild($first);
! 2004: }
! 2005: if (defined $right->firstChild) {
! 2006: if (paragraph_needed($right)) {
! 2007: $replacement->appendChild($right);
! 2008: #fix_paragraph($right, $all_block); This is taking way too much memory for blocks with many children
! 2009: # -> loop instead of recurse
! 2010: $loop_right = 1;
! 2011: } else {
! 2012: # this was just blank text, comments or inline responses, it should not create a new paragraph
! 2013: my $next;
! 2014: for (my $child=$right->firstChild; defined $child; $child=$next) {
! 2015: $next = $child->nextSibling;
! 2016: $right->removeChild($child);
! 2017: $replacement->appendChild($child);
! 2018: # fix paragraphs inside, in case one of the descendants can have paragraphs inside (like numericalresponse/hintgroup):
! 2019: if ($child->nodeType == XML_ELEMENT_NODE) {
! 2020: fix_paragraphs_inside($child, $all_block);
! 2021: }
! 2022: }
! 2023: }
! 2024: }
! 2025: }
! 2026:
! 2027: $p->parentNode->replaceChild($replacement, $p);
! 2028:
! 2029: if ($loop_right) {
! 2030: $p = $right;
! 2031: }
! 2032:
! 2033: } else {
! 2034: # fix paragraphs inside, in case one of the descendants can have paragraphs inside (like numericalresponse/hintgroup):
! 2035: my $next;
! 2036: for (my $child=$p->firstChild; defined $child; $child=$next) {
! 2037: $next = $child->nextSibling;
! 2038: if ($child->nodeType == XML_ELEMENT_NODE) {
! 2039: fix_paragraphs_inside($child, $all_block);
! 2040: }
! 2041: }
! 2042: }
! 2043: }
! 2044: }
! 2045:
! 2046: sub find_first_block {
! 2047: my ($node, $all_block) = @_;
! 2048: # inline elements that can be split in half if there is a paragraph inside (currently all HTML):
! 2049: my @splitable_inline = ('span', 'a', 'strong', 'em' , 'b', 'i', 'sup', 'sub', 'code', 'kbd', 'samp', 'tt', 'ins', 'del', 'var', 'small', 'big', 'font', 'u');
! 2050: for (my $child=$node->firstChild; defined $child; $child=$child->nextSibling) {
! 2051: if ($child->nodeType == XML_ELEMENT_NODE) {
! 2052: if (string_in_array($all_block, $child->nodeName) || $child->nodeName eq 'br') {
! 2053: return($child);
! 2054: }
! 2055: if (string_in_array(\@splitable_inline, $child->nodeName)) {
! 2056: my $block = find_first_block($child, $all_block);
! 2057: if (defined $block) {
! 2058: return($block);
! 2059: }
! 2060: }
! 2061: }
! 2062: }
! 2063: return(undef);
! 2064: }
! 2065:
! 2066: # Creates clones of the ancestor containing the descendants before the node, at the node, and after the node.
! 2067: # returns a hash with: left, middle, right (left and right can be undef)
! 2068: sub clone_ancestor_around_node {
! 2069: my ($ancestor, $node) = @_;
! 2070: my $middle_node;
! 2071: my ($left, $middle, $right);
! 2072: for (my $child=$ancestor->firstChild; defined $child; $child=$child->nextSibling) {
! 2073: if ($child == $node || is_ancestor_of($child, $node)) {
! 2074: $middle_node = $child;
! 2075: last;
! 2076: }
! 2077: }
! 2078: if (!defined $middle_node) {
! 2079: die "error in split_ancestor_around_node: middle not found";
! 2080: }
! 2081: if (defined $middle_node->previousSibling) {
! 2082: $left = $ancestor->cloneNode(0);
! 2083: for (my $child=$ancestor->firstChild; $child != $middle_node; $child=$child->nextSibling) {
! 2084: $left->appendChild($child->cloneNode(1));
! 2085: }
! 2086: }
! 2087: $middle = $ancestor->cloneNode(0);
! 2088: if ($middle_node == $node) {
! 2089: $middle->appendChild($middle_node->cloneNode(1));
! 2090: } else {
! 2091: my $subres = clone_ancestor_around_node($middle_node, $node);
! 2092: my $subleft = $subres->{'left'};
! 2093: if (defined $subleft) {
! 2094: if (!defined $left) {
! 2095: $left = $ancestor->cloneNode(0);
! 2096: }
! 2097: $left->appendChild($subleft);
! 2098: }
! 2099: $middle->appendChild($subres->{'middle'});
! 2100: my $subright = $subres->{'right'};
! 2101: if (defined $subright) {
! 2102: $right = $ancestor->cloneNode(0);
! 2103: $right->appendChild($subright);
! 2104: }
! 2105: }
! 2106: if (defined $middle_node->nextSibling) {
! 2107: if (!defined $right) {
! 2108: $right = $ancestor->cloneNode(0);
! 2109: }
! 2110: for (my $child=$middle_node->nextSibling; defined $child; $child=$child->nextSibling) {
! 2111: $right->appendChild($child->cloneNode(1));
! 2112: }
! 2113: }
! 2114: my %result = ();
! 2115: $result{'left'} = $left;
! 2116: $result{'middle'} = $middle;
! 2117: $result{'right'} = $right;
! 2118: return(\%result);
! 2119: }
! 2120:
! 2121: sub is_ancestor_of {
! 2122: my ($n1, $n2) = @_;
! 2123: my $n = $n2->parentNode;
! 2124: while (defined $n) {
! 2125: if ($n == $n1) {
! 2126: return(1);
! 2127: }
! 2128: $n = $n->parentNode;
! 2129: }
! 2130: return(0);
! 2131: }
! 2132:
! 2133: # removes empty style elements and replaces the ones with only whitespaces inside by their content
! 2134: # also remove hints that have become empty after empty style removal.
! 2135: sub remove_empty_style {
! 2136: my ($root) = @_;
! 2137: # actually, preserve some elements like ins when they have whitespace, only remove if they are empty
! 2138: my @remove_if_empty = ('span', 'strong', 'em' , 'b', 'i', 'sup', 'sub', 'code', 'kbd', 'samp', 'tt', 'ins', 'del', 'var', 'small', 'big', 'font', 'u', 'hint');
! 2139: my @remove_if_blank = ('span', 'strong', 'em' , 'b', 'i', 'sup', 'sub', 'tt', 'var', 'small', 'big', 'font', 'u', 'hint');
! 2140: foreach my $name (@remove_if_empty) {
! 2141: my @nodes = $root->getElementsByTagName($name);
! 2142: while (scalar(@nodes) > 0) {
! 2143: my $node = pop(@nodes);
! 2144: if (!defined $node->firstChild) {
! 2145: my $parent = $node->parentNode;
! 2146: if (defined $node->previousSibling && $node->previousSibling->nodeType == XML_TEXT_NODE &&
! 2147: $node->previousSibling->nodeValue =~ /\$\S*$/) {
! 2148: # case $a<sup></sup>x
! 2149: my $value = $node->previousSibling->nodeValue;
! 2150: $value =~ s/\$(\S*)$/\$\{$1\}/;
! 2151: $node->previousSibling->setData($value);
! 2152: }
! 2153: $parent->removeChild($node);
! 2154: $parent->normalize();
! 2155: # now that we removed the node, check if the parent has become an empty style, and so on
! 2156: while (defined $parent && string_in_array(\@remove_if_empty, $parent->nodeName) && !defined $parent->firstChild) {
! 2157: my $grandparent = $parent->parentNode;
! 2158: $grandparent->removeChild($parent);
! 2159: remove_reference_from_array(\@nodes, $parent);
! 2160: $parent = $grandparent;
! 2161: }
! 2162: }
! 2163: }
! 2164: }
! 2165: foreach my $name (@remove_if_blank) {
! 2166: my @nodes = $root->getElementsByTagName($name);
! 2167: while (scalar(@nodes) > 0) {
! 2168: my $node = pop(@nodes);
! 2169: if (defined $node->firstChild && !defined $node->firstChild->nextSibling && $node->firstChild->nodeType == XML_TEXT_NODE) {
! 2170: # NOTE: careful, with UTF-8, \s matches non-breaking spaces and we want to preserve these
! 2171: if ($node->firstChild->nodeValue =~ /^[\t\n\f\r ]*$/) {
! 2172: my $parent = $node->parentNode;
! 2173: replace_by_children($node);
! 2174: $parent->normalize();
! 2175: # now that we removed the node, check if the parent has become a style with only whitespace, and so on
! 2176: while (defined $parent && string_in_array(\@remove_if_blank, $parent->nodeName) &&
! 2177: (!defined $parent->firstChild ||
! 2178: (!defined $parent->firstChild->nextSibling && $parent->firstChild->nodeType == XML_TEXT_NODE &&
! 2179: $parent->firstChild->nodeValue =~ /^^[\t\n\f\r ]*$/))) {
! 2180: my $grandparent = $parent->parentNode;
! 2181: replace_by_children($parent);
! 2182: remove_reference_from_array(\@nodes, $parent);
! 2183: $parent = $grandparent;
! 2184: }
! 2185: }
! 2186: }
! 2187: }
! 2188: }
! 2189: }
! 2190:
! 2191: # remove whitespace inside LON-CAPA elements that have an empty content-model (HTML ones are handled by html_to_xml)
! 2192: sub fix_empty_lc_elements {
! 2193: my ($node) = @_;
! 2194: my @lcempty = ('arc','axis','backgroundplot','drawoptionlist','drawvectorsum','fill','functionplotrule','functionplotvectorrule','functionplotvectorsumrule','hiddenline','hiddensubmission','key','line','location','organicstructure','parameter','plotobject','plotvector','responseparam','spline','textline');
! 2195: if (string_in_array(\@lcempty, $node->nodeName)) {
! 2196: if (defined $node->firstChild && !defined $node->firstChild->nextSibling &&
! 2197: $node->firstChild->nodeType == XML_TEXT_NODE && $node->firstChild->nodeValue =~ /^\s*$/) {
! 2198: $node->removeChild($node->firstChild);
! 2199: }
! 2200: if (defined $node->firstChild) {
! 2201: print "Warning: a ".$node->nodeName." has something inside\n";
! 2202: }
! 2203: return;
! 2204: }
! 2205: for (my $child=$node->firstChild; defined $child; $child=$child->nextSibling) {
! 2206: if ($child->nodeType == XML_ELEMENT_NODE) {
! 2207: fix_empty_lc_elements($child);
! 2208: }
! 2209: }
! 2210: }
! 2211:
! 2212: # turn some attribute values into lowercase when they should be
! 2213: sub lowercase_attribute_values {
! 2214: my ($root) = @_;
! 2215: my @with_yesno = (['radiobuttonresponse', ['randomize']],
! 2216: ['optionresponse', ['randomize']],
! 2217: ['matchresponse', ['randomize']],
! 2218: ['itemgroup', ['randomize']],
! 2219: ['rankresponse', ['randomize']],
! 2220: ['functionplotresponse', ['xaxisvisible', 'yaxisvisible', 'gridvisible']],
! 2221: ['backgroundplot', ['fixed']],
! 2222: ['drawvectorsum', ['showvalue']],
! 2223: ['textline', ['readonly']],
! 2224: ['hint', ['showoncorrect']],
! 2225: ['body', ['dir']],
! 2226: ['img', ['encrypturl']],
! 2227: ['form', ['method']],
! 2228: ['input', ['type']]
! 2229: );
! 2230: foreach my $el_attributes (@with_yesno) {
! 2231: my $el_name = $el_attributes->[0];
! 2232: my @elements = $root->getElementsByTagName($el_name);
! 2233: foreach my $element (@elements) {
! 2234: my $att_list = $el_attributes->[1];
! 2235: foreach my $att_name (@$att_list) {
! 2236: my $att_value = $element->getAttribute($att_name);
! 2237: if (!defined $att_value) {
! 2238: next;
! 2239: }
! 2240: if ($att_value eq 'yes' || $att_value eq 'no') {
! 2241: next;
! 2242: }
! 2243: if ($att_value =~ /\s*yes\s*/i) {
! 2244: $element->setAttribute($att_name, 'yes');
! 2245: } elsif ($att_value =~ /\s*no\s*/i) {
! 2246: $element->setAttribute($att_name, 'no');
! 2247: }
! 2248: }
! 2249: }
! 2250: }
! 2251: }
! 2252:
! 2253: # fixes spelling mistakes for numericalresponse/@unit
! 2254: sub replace_numericalresponse_unit_attribute {
! 2255: my ($root) = @_;
! 2256: my @numericalresponses = $root->getElementsByTagName('numericalresponse');
! 2257: foreach my $numericalresponse (@numericalresponses) {
! 2258: if (defined $numericalresponse->getAttribute('units') && !defined $numericalresponse->getAttribute('unit')) {
! 2259: $numericalresponse->setAttribute('unit', $numericalresponse->getAttribute('units'));
! 2260: $numericalresponse->removeAttribute('units');
! 2261: }
! 2262: }
! 2263:
! 2264: }
! 2265:
! 2266: # Replaces &format and &prettyprint by <num> whenever possible.
! 2267: # Also replaces &chemparse by <chem>.
! 2268: # If the function call is enclosed in <display>, the <display> element is removed.
! 2269: sub replace_functions_by_elements {
! 2270: my ($root) = @_;
! 2271: my $doc = $root->ownerDocument;
! 2272: my @preserve = ('script','answer','parse','m','tm','dtm','numericalhintscript'); # display is handled later
! 2273: my @all = $root->getElementsByTagName('*');
! 2274: foreach my $element (@all) {
! 2275: if (string_in_array(\@preserve, $element->nodeName)) {
! 2276: next;
! 2277: }
! 2278: my $changed = 0;
! 2279: my $next;
! 2280: for (my $child=$element->firstChild; defined $child; $child=$next) {
! 2281: $next = $child->nextSibling;
! 2282: if ($child->nodeType == XML_TEXT_NODE) {
! 2283: my $value = $child->nodeValue;
! 2284: if ($value =~ /^(.*)&(?:format|prettyprint)\((\$\{?[a-zA-Z0-9]*\}?(?:\[[^\]]*\])?|[0-9.]+)\s?,\s?(["'][,.\$]?[0-9][eEfFgGsS]["']|\$[a-zA-Z0-9]*)\)(.*)$/s) {
! 2285: # NOTE: we don't check for &prettyprint's 3rd argument (target), but it has not been seen outside of script elements.
! 2286: # NOTE: the format options ',' and '$' are not supported by &format in current LON-CAPA since rev 1.81 of default_homework.lcpm,
! 2287: # but are supported by &prettyprint;
! 2288: # if we use (like current LON-CAPA) &prettyprint for <num> implementation, it will change a few resulting documents
! 2289: # (by making them display something they were probably intended to display, but which did not).
! 2290: # Usage of <num> with &prettyprint instead of &format might also change the display when there is an exponent.
! 2291: my $before = $1;
! 2292: my $number = $2;
! 2293: my $format = $3;
! 2294: my $after = $4;
! 2295: $format =~ s/^['"]|['"]$//g;
! 2296: # do not change this if the parent is <display> and there are other things before or after &format
! 2297: if ($element->nodeName eq 'display' && (defined $child->previousSibling || defined $next ||
! 2298: $before !~ /^\s*$/ || $after !~ /^\s*$/)) {
! 2299: last;
! 2300: }
! 2301: my $replacement = $doc->createDocumentFragment();
! 2302: my $num = $doc->createElement('num');
! 2303: $num->setAttribute('format', $format);
! 2304: $num->appendChild($doc->createTextNode($number));
! 2305: if (length($before) > 0) {
! 2306: $replacement->appendChild($doc->createTextNode($before));
! 2307: }
! 2308: $replacement->appendChild($num);
! 2309: if (length($after) > 0) {
! 2310: $replacement->appendChild($doc->createTextNode($after));
! 2311: }
! 2312: $element->replaceChild($replacement, $child);
! 2313: $changed = 1;
! 2314: $next = $element->firstChild; # start over, there might be another &format in the same text node
! 2315: } elsif ($value =~ /^(.*)&chemparse\(([^'"()]*|'[^']*'|"[^"]*")\)(.*)$/s) {
! 2316: my $before = $1;
! 2317: my $reaction = $2;
! 2318: my $after = $3;
! 2319: $reaction =~ s/^'(.*)'$/$1/;
! 2320: $reaction =~ s/^"(.*)"$/$1/;
! 2321: if ($element->nodeName eq 'display' && (defined $child->previousSibling || defined $next ||
! 2322: $before !~ /^\s*$/ || $after !~ /^\s*$/)) {
! 2323: last;
! 2324: }
! 2325: my $replacement = $doc->createDocumentFragment();
! 2326: my $chem = $doc->createElement('chem');
! 2327: $chem->appendChild($doc->createTextNode($reaction));
! 2328: if (length($before) > 0) {
! 2329: $replacement->appendChild($doc->createTextNode($before));
! 2330: }
! 2331: $replacement->appendChild($chem);
! 2332: if (length($after) > 0) {
! 2333: $replacement->appendChild($doc->createTextNode($after));
! 2334: }
! 2335: $element->replaceChild($replacement, $child);
! 2336: $changed = 1;
! 2337: $next = $element->firstChild;
! 2338: }
! 2339: }
! 2340: }
! 2341: if ($changed && $element->nodeName eq 'display') {
! 2342: my $first = $element->firstChild;
! 2343: if ($first->nodeType == XML_ELEMENT_NODE && string_in_array(['num','chem'], $first->nodeName) &&
! 2344: !defined $first->nextSibling) {
! 2345: # remove useless display element
! 2346: replace_by_children($element);
! 2347: }
! 2348: }
! 2349: }
! 2350: }
! 2351:
! 2352: # pretty-print using im-memory DOM tree
! 2353: sub pretty {
! 2354: my ($node, $all_block, $indent_level) = @_;
! 2355: my $doc = $node->ownerDocument;
! 2356: $indent_level ||= 0;
! 2357: my $type = $node->nodeType;
! 2358: if ($type == XML_ELEMENT_NODE) {
! 2359: my $name = $node->nodeName;
! 2360: if ((string_in_array($all_block, $name) || string_in_array(\@inline_like_block, $name)) &&
! 2361: !string_in_array(\@preserve_elements, $name)) {
! 2362: # make sure there is a newline at the beginning and at the end if there is anything inside
! 2363: if (defined $node->firstChild && !string_in_array(\@no_newline_inside, $name)) {
! 2364: my $first = $node->firstChild;
! 2365: if ($first->nodeType == XML_TEXT_NODE) {
! 2366: my $text = $first->nodeValue;
! 2367: if ($text !~ /^ *\n/) {
! 2368: $first->setData("\n" . $text);
! 2369: }
! 2370: } else {
! 2371: $node->insertBefore($doc->createTextNode("\n"), $first);
! 2372: }
! 2373: my $last = $node->lastChild;
! 2374: if ($last->nodeType == XML_TEXT_NODE) {
! 2375: my $text = $last->nodeValue;
! 2376: if ($text !~ /\n *$/) {
! 2377: $last->setData($text . "\n");
! 2378: }
! 2379: } else {
! 2380: $node->appendChild($doc->createTextNode("\n"));
! 2381: }
! 2382: }
! 2383:
! 2384: # indent and make sure there is a newline before and after a block element
! 2385: my $newline_indent = "\n".(' ' x (2*($indent_level + 1)));
! 2386: my $newline_indent_last = "\n".(' ' x (2*$indent_level));
! 2387: my $next;
! 2388: for (my $child=$node->firstChild; defined $child; $child=$next) {
! 2389: $next = $child->nextSibling;
! 2390: if ($child->nodeType == XML_ELEMENT_NODE) {
! 2391: if (string_in_array($all_block, $child->nodeName) || string_in_array(\@inline_like_block, $child->nodeName)) {
! 2392: # make sure there is a newline before and after a block element
! 2393: if (defined $child->previousSibling && $child->previousSibling->nodeType == XML_TEXT_NODE) {
! 2394: my $prev = $child->previousSibling;
! 2395: my $text = $prev->nodeValue;
! 2396: if ($text !~ /\n *$/) {
! 2397: $prev->setData($text . $newline_indent);
! 2398: }
! 2399: } else {
! 2400: $node->insertBefore($doc->createTextNode($newline_indent), $child);
! 2401: }
! 2402: if (defined $next && $next->nodeType == XML_TEXT_NODE) {
! 2403: my $text = $next->nodeValue;
! 2404: if ($text !~ /^ *\n/) {
! 2405: $next->setData($newline_indent . $text);
! 2406: }
! 2407: } else {
! 2408: $node->insertAfter($doc->createTextNode($newline_indent), $child);
! 2409: }
! 2410: }
! 2411: pretty($child, $all_block, $indent_level+1);
! 2412: } elsif ($child->nodeType == XML_TEXT_NODE) {
! 2413: my $text = $child->nodeValue;
! 2414: # collapse newlines
! 2415: $text =~ s/\n([\t ]*\n)+/\n/g;
! 2416: # indent and remove spaces and tabs before newlines
! 2417: if (defined $next) {
! 2418: $text =~ s/[\t ]*\n[\t ]*/$newline_indent/ge;
! 2419: } else {
! 2420: $text =~ s/[\t ]*\n[\t ]*/$newline_indent/ge;
! 2421: $text =~ s/[\t ]*\n[\t ]*$/$newline_indent_last/e;
! 2422: }
! 2423: $child->setData($text);
! 2424: }
! 2425: }
! 2426:
! 2427: # removes whitespace at the beginning and end of p td, th and li (except for nbsp at the beginning)
! 2428: my @to_trim = ('p','td','th','li');
! 2429: if (string_in_array(\@to_trim, $name) && defined $node->firstChild && $node->firstChild->nodeType == XML_TEXT_NODE) {
! 2430: my $text = $node->firstChild->nodeValue;
! 2431: $text =~ s/^[ \t\f\n\r]*//;
! 2432: if ($text eq '') {
! 2433: $node->removeChild($node->firstChild);
! 2434: } else {
! 2435: $node->firstChild->setData($text);
! 2436: }
! 2437: }
! 2438: if (string_in_array(\@to_trim, $name) && defined $node->lastChild && $node->lastChild->nodeType == XML_TEXT_NODE) {
! 2439: my $text = $node->lastChild->nodeValue;
! 2440: $text =~ s/\s*$//;
! 2441: if ($text eq '') {
! 2442: $node->removeChild($node->lastChild);
! 2443: } else {
! 2444: $node->lastChild->setData($text);
! 2445: }
! 2446: }
! 2447: } elsif (string_in_array(\@preserve_elements, $name)) {
! 2448: # collapse newlines at the beginning and the end of scripts
! 2449: if (defined $node->firstChild && $node->firstChild->nodeType == XML_TEXT_NODE) {
! 2450: my $text = $node->firstChild->nodeValue;
! 2451: $text =~ s/^\n( *\n)+/\n/;
! 2452: if ($text eq '') {
! 2453: $node->removeChild($node->firstChild);
! 2454: } else {
! 2455: $node->firstChild->setData($text);
! 2456: }
! 2457: }
! 2458: if (defined $node->lastChild && $node->lastChild->nodeType == XML_TEXT_NODE) {
! 2459: my $text = $node->lastChild->nodeValue;
! 2460: $text =~ s/\n( *\n)+$/\n/;
! 2461: if ($text eq '') {
! 2462: $node->removeChild($node->lastChild);
! 2463: } else {
! 2464: $node->lastChild->setData($text);
! 2465: }
! 2466: }
! 2467: }
! 2468: }
! 2469: }
! 2470:
! 2471: sub replace_tm_dtm {
! 2472: my ($root) = @_;
! 2473: my $doc = $root->ownerDocument;
! 2474: my @elements = $root->getElementsByTagName('tm');
! 2475: push(@elements, $root->getElementsByTagName('dtm'));
! 2476: foreach my $element (@elements) {
! 2477: my $first = $element->firstChild;
! 2478: if (defined $first && $first->nodeType == XML_TEXT_NODE) {
! 2479: my $text = $first->nodeValue;
! 2480: if ($element->nodeName eq 'tm') {
! 2481: $first->setData('$'.$text.'$');
! 2482: } else {
! 2483: $first->setData('$$'.$text.'$$');
! 2484: }
! 2485: }
! 2486: $element->setNodeName('m');
! 2487: }
! 2488: }
! 2489:
! 2490:
! 2491: ######## utilities ########
! 2492:
! 2493: ##
! 2494: # Trims a string (really, this should be built-in in Perl, this is ridiculous, ugly and slow)
! 2495: # @param {string} s - the string to trim
! 2496: # @returns the trimmed string
! 2497: ##
! 2498: sub trim {
! 2499: my ($s) = @_;
! 2500: $s =~ s/^\s+//;
! 2501: $s =~ s/\s+$//;
! 2502: return($s);
! 2503: }
! 2504:
! 2505: ##
! 2506: # Tests if a string is in an array (using eq) (to avoid Smartmatch warnings with $value ~~ @array)
! 2507: # @param {Array<string>} array - reference to the array of strings
! 2508: # @param {string} value - the string to look for
! 2509: # @returns 1 if found, 0 otherwise
! 2510: ##
! 2511: sub string_in_array {
! 2512: my ($array, $value) = @_;
! 2513: foreach my $v (@{$array}) {
! 2514: if ($v eq $value) {
! 2515: return 1;
! 2516: }
! 2517: }
! 2518: return 0;
! 2519: }
! 2520:
! 2521: ##
! 2522: # Tests if an object is in an array (using ==)
! 2523: # @param {Array<Object>} array - reference to the array of references
! 2524: # @param {Object} ref - the reference to look for
! 2525: # @returns 1 if found, 0 otherwise
! 2526: ##
! 2527: sub reference_in_array {
! 2528: my ($array, $ref) = @_;
! 2529: foreach my $v (@{$array}) {
! 2530: if ($v == $ref) {
! 2531: return 1;
! 2532: }
! 2533: }
! 2534: return 0;
! 2535: }
! 2536:
! 2537: ##
! 2538: # returns the index of a string in an array
! 2539: # @param {Array<Object>} array - reference to the array of strings
! 2540: # @param {string} s - the string to look for (using eq)
! 2541: # @returns the index if found, -1 otherwise
! 2542: ##
! 2543: sub index_of_string {
! 2544: my ($array, $s) = @_;
! 2545: for (my $i=0; $i<scalar(@{$array}); $i++) {
! 2546: if ($array->[$i] eq $s) {
! 2547: return $i;
! 2548: }
! 2549: }
! 2550: return -1;
! 2551: }
! 2552:
! 2553: ##
! 2554: # returns the index of a reference in an array
! 2555: # @param {Array<Object>} array - reference to the array of references
! 2556: # @param {Object} ref - the reference to look for
! 2557: # @returns the index if found, -1 otherwise
! 2558: ##
! 2559: sub index_of_reference {
! 2560: my ($array, $ref) = @_;
! 2561: for (my $i=0; $i<scalar(@{$array}); $i++) {
! 2562: if ($array->[$i] == $ref) {
! 2563: return $i;
! 2564: }
! 2565: }
! 2566: return -1;
! 2567: }
! 2568:
! 2569: ##
! 2570: # if found, removes a string from an array, otherwise do nothing
! 2571: # @param {Array<string>} array - reference to the array of string
! 2572: # @param {string} s - the string to look for (using eq)
! 2573: ##
! 2574: sub remove_string_from_array {
! 2575: my ($array, $s) = @_;
! 2576: my $index = index_of_string($array, $s);
! 2577: if ($index != -1) {
! 2578: splice(@$array, $index, 1);
! 2579: }
! 2580: }
! 2581:
! 2582: ##
! 2583: # if found, removes a reference from an array, otherwise do nothing
! 2584: # @param {Array<Object>} array - reference to the array of references
! 2585: # @param {Object} ref - the reference to look for
! 2586: ##
! 2587: sub remove_reference_from_array {
! 2588: my ($array, $ref) = @_;
! 2589: my $index = index_of_reference($array, $ref);
! 2590: if ($index != -1) {
! 2591: splice(@$array, $index, 1);
! 2592: }
! 2593: }
! 2594:
! 2595: ##
! 2596: # replaces a node by its children
! 2597: # @param {Node} node - the DOM node
! 2598: ##
! 2599: sub replace_by_children {
! 2600: my ($node) = @_;
! 2601: my $parent = $node->parentNode;
! 2602: my $next;
! 2603: my $previous;
! 2604: for (my $child=$node->firstChild; defined $child; $child=$next) {
! 2605: $next = $child->nextSibling;
! 2606: if ((!defined $previous || !defined $next) &&
! 2607: $child->nodeType == XML_TEXT_NODE && $child->nodeValue =~ /^\s*$/) {
! 2608: next; # do not keep first and last whitespace nodes
! 2609: } else {
! 2610: if (!defined $previous && $child->nodeType == XML_TEXT_NODE) {
! 2611: # remove whitespace at the beginning
! 2612: my $value = $child->nodeValue;
! 2613: $value =~ s/^\s+//;
! 2614: $child->setData($value);
! 2615: }
! 2616: if (!defined $next && $child->nodeType == XML_TEXT_NODE) {
! 2617: # and at the end
! 2618: my $value = $child->nodeValue;
! 2619: $value =~ s/\s+$//;
! 2620: $child->setData($value);
! 2621: }
! 2622: }
! 2623: $node->removeChild($child);
! 2624: $parent->insertBefore($child, $node);
! 2625: $previous = $child;
! 2626: }
! 2627: $parent->removeChild($node);
! 2628: }
! 2629:
! 2630: ##
! 2631: # returns the trimmed attribute value if the attribute exists and is not blank, undef otherwise
! 2632: # @param {Node} node - the DOM node
! 2633: # @param {string} attribute_name - the attribute name
! 2634: ##
! 2635: sub get_non_empty_attribute {
! 2636: my ($node, $attribute_name) = @_;
! 2637: my $value = $node->getAttribute($attribute_name);
! 2638: if (defined $value && $value !~ /^\s*$/) {
! 2639: $value = trim($value);
! 2640: return($value);
! 2641: }
! 2642: return(undef);
! 2643: }
! 2644:
! 2645: ##
! 2646: # Returns a CSS property value from the style attribute of the element, or undef if not defined
! 2647: # @param {Element} el - the DOM element
! 2648: # @param {string} property_name - the CSS property name
! 2649: ##
! 2650: sub get_css_property {
! 2651: my ($el, $property_name) = @_;
! 2652: my $style = $el->getAttribute('style');
! 2653: if (defined $style) {
! 2654: $style =~ s/^\s*;\s*//;
! 2655: $style =~ s/\s*;\s*$//;
! 2656: } else {
! 2657: $style = '';
! 2658: }
! 2659: my @pairs = split(';', $style);
! 2660: foreach my $pair (@pairs) {
! 2661: my @name_value = split(':', $pair);
! 2662: if (scalar(@name_value) != 2) {
! 2663: next;
! 2664: }
! 2665: my $name = trim($name_value[0]);
! 2666: my $value = trim($name_value[1]);
! 2667: if (lc($name) eq $property_name) {
! 2668: return($value); # return the first one found
! 2669: }
! 2670: }
! 2671: return(undef);
! 2672: }
! 2673:
! 2674: ##
! 2675: # Returns the reference to a hash CSS property name => value from the style attribute of the element.
! 2676: # Returns an empty list if the style attribute is not defined,
! 2677: # @param {Element} el - the DOM element
! 2678: # @return {Hash<string, string>} reference to the hash property name => property value
! 2679: ##
! 2680: sub get_css_properties {
! 2681: my ($el) = @_;
! 2682: my $style = $el->getAttribute('style');
! 2683: if (defined $style) {
! 2684: $style =~ s/^\s*;\s*//;
! 2685: $style =~ s/\s*;\s*$//;
! 2686: } else {
! 2687: $style = '';
! 2688: }
! 2689: my @pairs = split(';', $style);
! 2690: tie (my %hash, 'Tie::IxHash', ());
! 2691: foreach my $pair (@pairs) {
! 2692: my @name_value = split(':', $pair);
! 2693: if (scalar(@name_value) != 2) {
! 2694: next;
! 2695: }
! 2696: my $name = trim($name_value[0]);
! 2697: my $value = trim($name_value[1]);
! 2698: if (defined $hash{$name}) {
! 2699: # duplicate property in the style attribute: keep only the last one
! 2700: delete $hash{$name};
! 2701: }
! 2702: $hash{$name} = $value;
! 2703: }
! 2704: return(\%hash);
! 2705: }
! 2706:
! 2707: ##
! 2708: # Sets a CSS property in the style attribute of an element
! 2709: # @param {Element} el - the DOM element
! 2710: # @param {string} property_name - the CSS property name
! 2711: # @param {string} property_value - the CSS property value
! 2712: ##
! 2713: sub set_css_property {
! 2714: my ($el, $property_name, $property_value) = @_;
! 2715: my $hash_ref = { $property_name => $property_value };
! 2716: set_css_properties($el, $hash_ref);
! 2717: }
! 2718:
! 2719: ##
! 2720: # Sets several CSS properties in the style attribute of an element
! 2721: # @param {Element} el - the DOM element
! 2722: # @param {Hash<string, string>} properties - reference to the hash property name => property value
! 2723: ##
! 2724: sub set_css_properties {
! 2725: my ($el, $properties) = @_;
! 2726: my $hash = get_css_properties($el);
! 2727: foreach my $property_name (keys %$properties) {
! 2728: my $property_value = $properties->{$property_name};
! 2729: if (defined $hash->{$property_name}) {
! 2730: delete $hash->{$property_name}; # to add the new one at the end
! 2731: }
! 2732: $hash->{$property_name} = $property_value;
! 2733: }
! 2734: my $style = '';
! 2735: foreach my $key (keys %$hash) {
! 2736: $style .= $key.':'.$hash->{$key}.'; ';
! 2737: }
! 2738: $style =~ s/; $//;
! 2739: $el->setAttribute('style', $style);
! 2740: }
! 2741:
! 2742: 1;
! 2743: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>