File indexing completed on 2024-05-12 06:02:04

0001 <?php
0002 
0003 /**
0004  * Validates the HTML attribute lang, effectively a language code.
0005  * @note Built according to RFC 3066, which obsoleted RFC 1766
0006  */
0007 class HTMLPurifier_AttrDef_Lang extends HTMLPurifier_AttrDef
0008 {
0009 
0010     /**
0011      * @param string $string
0012      * @param HTMLPurifier_Config $config
0013      * @param HTMLPurifier_Context $context
0014      * @return bool|string
0015      */
0016     public function validate($string, $config, $context)
0017     {
0018         $string = trim($string);
0019         if (!$string) {
0020             return false;
0021         }
0022 
0023         $subtags = explode('-', $string);
0024         $num_subtags = count($subtags);
0025 
0026         if ($num_subtags == 0) { // sanity check
0027             return false;
0028         }
0029 
0030         // process primary subtag : $subtags[0]
0031         $length = strlen($subtags[0]);
0032         switch ($length) {
0033             case 0:
0034                 return false;
0035             case 1:
0036                 if (!($subtags[0] == 'x' || $subtags[0] == 'i')) {
0037                     return false;
0038                 }
0039                 break;
0040             case 2:
0041             case 3:
0042                 if (!ctype_alpha($subtags[0])) {
0043                     return false;
0044                 } elseif (!ctype_lower($subtags[0])) {
0045                     $subtags[0] = strtolower($subtags[0]);
0046                 }
0047                 break;
0048             default:
0049                 return false;
0050         }
0051 
0052         $new_string = $subtags[0];
0053         if ($num_subtags == 1) {
0054             return $new_string;
0055         }
0056 
0057         // process second subtag : $subtags[1]
0058         $length = strlen($subtags[1]);
0059         if ($length == 0 || ($length == 1 && $subtags[1] != 'x') || $length > 8 || !ctype_alnum($subtags[1])) {
0060             return $new_string;
0061         }
0062         if (!ctype_lower($subtags[1])) {
0063             $subtags[1] = strtolower($subtags[1]);
0064         }
0065 
0066         $new_string .= '-' . $subtags[1];
0067         if ($num_subtags == 2) {
0068             return $new_string;
0069         }
0070 
0071         // process all other subtags, index 2 and up
0072         for ($i = 2; $i < $num_subtags; $i++) {
0073             $length = strlen($subtags[$i]);
0074             if ($length == 0 || $length > 8 || !ctype_alnum($subtags[$i])) {
0075                 return $new_string;
0076             }
0077             if (!ctype_lower($subtags[$i])) {
0078                 $subtags[$i] = strtolower($subtags[$i]);
0079             }
0080             $new_string .= '-' . $subtags[$i];
0081         }
0082         return $new_string;
0083     }
0084 }
0085 
0086 // vim: et sw=4 sts=4