DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (3663d7c37d88)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

Components.utils.import("resource:///modules/imServices.jsm");

const EXPORTED_SYMBOLS = [
  "cleanupImMarkup", // used to clean up incoming IMs.
                     // This will use the global ruleset of acceptable stuff
                     // except if another (custom one) is provided
  "createDerivedRuleset", // used to create a ruleset that inherits from the
                          // default one
                          // useful if you want to allow or forbid
                          // an additionnal thing in a specific
                          // conversation but take into account all
                          // the other global settings.
  "addGlobalAllowedTag",
  "removeGlobalAllowedTag",
  "addGlobalAllowedAttribute",
  "removeGlobalAllowedAttribute",
  "addGlobalAllowedStyleRule",
  "removeGlobalAllowedStyleRule"
];

/*
 * Structure of a ruleset:
 * A ruleset is a JS object containing 3 sub-objects: attrs, tags and styles.
 *  - attrs: an object containing a list of attributes allowed for all tags.
 *      example: attrs: { 'style': true }
 *
 *  - tags: an object with the allowed tags. each tag can allow specific attributes.
 *      example: 'a': {'href': true}
 *
 *    each attribute can have a function returning a boolean indicating if
 *    the attribute is accepted.
 *      example: 'href': function(aValue) aValue == 'about:blank'
 *
 *  - styles: an object with the allowed CSS style rule.
 *      example: 'font-size': true
 *    FIXME: make this accept functions to filter the CSS values too.
 *
 *  See the 3 examples of rulesets below.
 */

const kAllowedURLs = function(aValue) /^(https?|ftp|mailto):/.test(aValue);
const kAllowedMozClasses =
  function(aClassName) aClassName == "moz-txt-underscore" ||
                       aClassName == "moz-txt-tag";

// in strict mode, remove all formatings. Keep only links and line breaks.
const kStrictMode = {
  attrs: { },

  tags: {
    'a': {
      'title': true,
      'href': kAllowedURLs
    },
    'br': true,
    'p': true
  },

  styles: { }
};

// standard mode allows basic formattings (bold, italic, underlined)
const kStandardMode = {
  attrs: {
    'style': true
  },

  tags: {
    'div': true,
    'a': {
      'title': true,
      'href': kAllowedURLs
    },
    'em': true,
    'strong': true,
    'b': true,
    'i': true,
    'u': true,
    'span': {
      'class': kAllowedMozClasses
    },
    'br': true,
    'code': true,
    'ul': true,
    'li': true,
    'ol': true,
    'cite': true,
    'blockquote': true,
    'p': true
  },

  styles: {
    'font-style': true,
    'font-weight': true,
    'text-decoration': true
  }
};

// permissive mode allows about anything that isn't going to mess up the chat window
const kPermissiveMode = {
  attrs: {
    'style': true
  },

  tags : {
    'div': true,
    'a': {
      'title': true,
      'href': kAllowedURLs
    },
    'font': {
      'face': true,
      'color': true,
      'size': true
    },
    'em': true,
    'strong': true,
    'b': true,
    'i': true,
    'u': true,
    'span': {
      'class': kAllowedMozClasses
    },
    'br': true,
    'hr': true,
    'code': true,
    'ul': true,
    'li': true,
    'ol': true,
    'cite': true,
    'blockquote': true,
    'p': true
  },

  // FIXME: should be possible to use functions to filter values
  styles : {
    'color': true,
    'font': true,
    'font-family': true,
    'font-size': true,
    'font-style': true,
    'font-weight': true,
    'text-decoration': true
  }
};

const kModePref = "messenger.options.filterMode";
const kModes = [kStrictMode, kStandardMode, kPermissiveMode];

var gGlobalRuleset = null;

function initGlobalRuleset()
{
  gGlobalRuleset = newRuleset();

  Services.prefs.addObserver(kModePref, styleObserver, false);
}

var styleObserver = {
  observe: function so_observe(aObject, aTopic, aMsg) {
    if (aTopic != "nsPref:changed" || aMsg != kModePref)
      throw "bad notification";

    if (!gGlobalRuleset)
      throw "gGlobalRuleset not initialized";

    setBaseRuleset(getModePref(), gGlobalRuleset);
  }
};

function getModePref()
{
  let baseNum = Services.prefs.getIntPref(kModePref);
  if (baseNum < 0 || baseNum > 2)
    baseNum = 1;

  return kModes[baseNum];
}

function setBaseRuleset(aBase, aResult)
{
  aResult.tags.__proto__ = aBase.tags;
  aResult.attrs.__proto__ = aBase.attrs;
  aResult.styles.__proto__ = aBase.styles;
}

function newRuleset(aBase)
{
  if (!aBase)
    aBase = getModePref();

  let result = {};
  result.tags = {};
  result.attrs = {};
  result.styles = {};
  setBaseRuleset(aBase, result);
  return result;
}

function createDerivedRuleset()
{
  if (!gGlobalRuleset)
    initGlobalRuleset();
  return newRuleset(gGlobalRuleset);
}

function addGlobalAllowedTag(aTag, aAttrs)
{
  gGlobalRuleset.tags[aTag] = aAttrs || true;
}
function removeGlobalAllowedTag(aTag)
{
  delete gGlobalRuleset.tags[aTag];
}

function addGlobalAllowedAttribute(aAttr, aRule)
{
  gGlobalRuleset.attrs[aAttr] = aRule || true;
}
function removeGlobalAllowedAttribute(aAttr)
{
  delete gGlobalRuleset.attrs[aAttr];
}

function addGlobalAllowedStyleRule(aStyle, aRule)
{
  gGlobalRuleset.styles[aStyle] = aRule || true;
}
function removeGlobalAllowedStyleRule(aStyle)
{
  delete gGlobalRuleset.styles[aStyle];
}

function cleanupNode(aNode, aRules, aTextModifiers)
{
  for (let i = 0; i < aNode.childNodes.length; ++i) {
    let node = aNode.childNodes[i];
    if (node instanceof Components.interfaces.nsIDOMHTMLElement) {
      // check if node allowed
      let nodeName = node.localName.toLowerCase();
      if (!(nodeName in aRules.tags)) {
        // this node is not allowed, replace it with its children
        while (node.hasChildNodes())
          aNode.insertBefore(node.removeChild(node.firstChild), node);
        aNode.removeChild(node);
        // We want to process again the node at the index i which is
        // now the first child of the node we removed
        --i;
        continue;
      }

      // we are going to keep this child node, clean up its children
      cleanupNode(node, aRules, aTextModifiers);

      // cleanup attributes
      let attrs = node.attributes;
      let acceptFunction = function(aAttrRules, aAttr) {
        // an attribute is always accepted if its rule is true, or conditionnaly
        // accepted if its rule is a function that evaluates to true
        // if its rule does not exist, it is refused
          let localName = aAttr.localName;
          let rule = localName in aAttrRules && aAttrRules[localName];
          return (rule === true ||
                  (rule instanceof Function && rule(aAttr.value)));
      };
      for (let j = 0; j < attrs.length; ++j) {
        let attr = attrs[j];
        // we check both the list of accepted attributes for all tags
        // and the list of accepted attributes for this specific tag.
        if (!(acceptFunction(aRules.attrs, attr) ||
              (aRules.tags[nodeName] instanceof Object) &&
              acceptFunction(aRules.tags[nodeName], attr))) {
          node.removeAttribute(attr.name);
          --j;
        }
      }

      // cleanup style
      let style = node.style;
      for (let j = 0; j < style.length; ++j) {
        if (!(style[j] in aRules.styles)) {
          style.removeProperty(style[j]);
          --j;
        }
      }
    }
    else {
      // We are on a text node, we need to apply the functions
      // provided in the aTextModifiers array.

      // Each of these function should return the number of nodes added:
      //  * -1 if the current textnode was deleted
      //  * 0 if the node count is unchanged
      //  * positive value if nodes were added.
      //     For instance, adding an <img> tag for a smiley adds 2 nodes:
      //      - the img tag
      //      - the new text node after the img tag.

      // This is the number of nodes we need to process. If new nodes
      // are created, the next text modifier functions have more nodes
      // to process.
      let textNodeCount = 1;
      for each (let modifier in aTextModifiers)
        for (let n = 0; n < textNodeCount; ++n) {
          let textNode = aNode.childNodes[i + n];

          // If we are processing nodes created by one of the previous
          // text modifier function, some of the nodes are likely not
          // text node, skip them.
          if (!(textNode instanceof Components.interfaces.nsIDOMText))
            continue;

          let result = modifier(textNode);
          textNodeCount += result;
          n += result;
        }

      // newly created nodes should not be filtered, be sure we skip them!
      i += textNodeCount - 1;
    }
  }
}

function cleanupImMarkup(aDocument, aText, aRuleset, aTextModifiers)
{
  if (!aDocument)
    throw "providing an HTML document is required";

  if (!gGlobalRuleset)
    initGlobalRuleset();

  let parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
                         .createInstance(Components.interfaces.nsIDOMParser);
  let doc = parser.parseFromString(aText, "text/html");
  let div = doc.getElementsByTagName("body")[0];
  cleanupNode(div, aRuleset || gGlobalRuleset, aTextModifiers || []);
  return div.innerHTML;
}