ID.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Validates the HTML attribute ID.
  4. * @warning Even though this is the id processor, it
  5. * will ignore the directive Attr:IDBlacklist, since it will only
  6. * go according to the ID accumulator. Since the accumulator is
  7. * automatically generated, it will have already absorbed the
  8. * blacklist. If you're hacking around, make sure you use load()!
  9. */
  10. class HTMLPurifier_AttrDef_HTML_ID extends HTMLPurifier_AttrDef
  11. {
  12. // selector is NOT a valid thing to use for IDREFs, because IDREFs
  13. // *must* target IDs that exist, whereas selector #ids do not.
  14. /**
  15. * Determines whether or not we're validating an ID in a CSS
  16. * selector context.
  17. */
  18. protected $selector;
  19. public function __construct($selector = false) {
  20. $this->selector = $selector;
  21. }
  22. public function validate($id, $config, $context) {
  23. if (!$this->selector && !$config->get('Attr.EnableID')) return false;
  24. $id = trim($id); // trim it first
  25. if ($id === '') return false;
  26. $prefix = $config->get('Attr.IDPrefix');
  27. if ($prefix !== '') {
  28. $prefix .= $config->get('Attr.IDPrefixLocal');
  29. // prevent re-appending the prefix
  30. if (strpos($id, $prefix) !== 0) $id = $prefix . $id;
  31. } elseif ($config->get('Attr.IDPrefixLocal') !== '') {
  32. trigger_error('%Attr.IDPrefixLocal cannot be used unless '.
  33. '%Attr.IDPrefix is set', E_USER_WARNING);
  34. }
  35. if (!$this->selector) {
  36. $id_accumulator =& $context->get('IDAccumulator');
  37. if (isset($id_accumulator->ids[$id])) return false;
  38. }
  39. // we purposely avoid using regex, hopefully this is faster
  40. if (ctype_alpha($id)) {
  41. $result = true;
  42. } else {
  43. if (!ctype_alpha(@$id[0])) return false;
  44. $trim = trim( // primitive style of regexps, I suppose
  45. $id,
  46. 'A..Za..z0..9:-._'
  47. );
  48. $result = ($trim === '');
  49. }
  50. $regexp = $config->get('Attr.IDBlacklistRegexp');
  51. if ($regexp && preg_match($regexp, $id)) {
  52. return false;
  53. }
  54. if (!$this->selector && $result) $id_accumulator->add($id);
  55. // if no change was made to the ID, return the result
  56. // else, return the new id if stripping whitespace made it
  57. // valid, or return false.
  58. return $result ? $id : false;
  59. }
  60. }
  61. // vim: et sw=4 sts=4