StringUtil.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * String utility
  4. *
  5. * This class is mainly used to implement the 'text-match' filter, used by both
  6. * the CalDAV calendar-query REPORT, and CardDAV addressbook-query REPORT.
  7. * Because they both need it, it was decided to put it in Sabre_DAV instead.
  8. *
  9. * @package Sabre
  10. * @subpackage DAV
  11. * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
  12. * @author Evert Pot (http://www.rooftopsolutions.nl/)
  13. * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
  14. */
  15. class Sabre_DAV_StringUtil {
  16. /**
  17. * Checks if a needle occurs in a haystack ;)
  18. *
  19. * @param string $haystack
  20. * @param string $needle
  21. * @param string $collation
  22. * @param string $matchType
  23. * @return bool
  24. */
  25. static public function textMatch($haystack, $needle, $collation, $matchType = 'contains') {
  26. switch($collation) {
  27. case 'i;ascii-casemap' :
  28. // default strtolower takes locale into consideration
  29. // we don't want this.
  30. $haystack = str_replace(range('a','z'), range('A','Z'), $haystack);
  31. $needle = str_replace(range('a','z'), range('A','Z'), $needle);
  32. break;
  33. case 'i;octet' :
  34. // Do nothing
  35. break;
  36. case 'i;unicode-casemap' :
  37. $haystack = mb_strtoupper($haystack, 'UTF-8');
  38. $needle = mb_strtoupper($needle, 'UTF-8');
  39. break;
  40. default :
  41. throw new Sabre_DAV_Exception_BadRequest('Collation type: ' . $collation . ' is not supported');
  42. }
  43. switch($matchType) {
  44. case 'contains' :
  45. return strpos($haystack, $needle)!==false;
  46. case 'equals' :
  47. return $haystack === $needle;
  48. case 'starts-with' :
  49. return strpos($haystack, $needle)===0;
  50. case 'ends-with' :
  51. return strrpos($haystack, $needle)===strlen($haystack)-strlen($needle);
  52. default :
  53. throw new Sabre_DAV_Exception_BadRequest('Match-type: ' . $matchType . ' is not supported');
  54. }
  55. }
  56. /**
  57. * This method takes an input string, checks if it's not valid UTF-8 and
  58. * attempts to convert it to UTF-8 if it's not.
  59. *
  60. * Note that currently this can only convert ISO-8559-1 to UTF-8 (latin-1),
  61. * anything else will likely fail.
  62. *
  63. * @param string $input
  64. * @return string
  65. */
  66. static public function ensureUTF8($input) {
  67. $encoding = mb_detect_encoding($input , array('UTF-8','ISO-8859-1'), true);
  68. if ($encoding === 'ISO-8859-1') {
  69. return utf8_encode($input);
  70. } else {
  71. return $input;
  72. }
  73. }
  74. }