| 16 | | $this->setValidators(array('url' => new sfValidatorUrl(array('required' => true, 'max_length' => 1024)))); |
| | 16 | |
| | 17 | // "And" is correct, these are really progressive filters improving the URL |
| | 18 | |
| | 19 | $this->setValidators(array('url' => new sfValidatorAnd(array( |
| | 20 | // @foo => correct twitter RSS feed URL for that person (requires querying Twitter API) |
| | 21 | new sfValidatorCallback(array('callback' => array($this, 'validateTwitterHandle'))), |
| | 22 | // www.foo.bar => http://www.foo.bar |
| | 23 | new sfValidatorCallback(array('callback' => array($this, 'validateLazyUrl'))), |
| | 24 | // Must be a valid URL to go past this stage |
| | 25 | new sfValidatorUrl(array('required' => true, 'max_length' => 1024)), |
| | 26 | // If the URL is a plain old page get the first RSS feed 'link'ed in it |
| | 27 | new sfValidatorCallback(array('callback' => array($this, 'validateFeed'))))))); |
| | 35 | |
| | 36 | // Convert Twitter handles to RSS feed URLs. Leave anything else alone |
| | 37 | public function validateTwitterHandle($validator, $value) |
| | 38 | { |
| | 39 | if (preg_match('/^@(\w+)$/', $value, $matches)) |
| | 40 | { |
| | 41 | $handle = $matches[1]; |
| | 42 | $info = json_decode(file_get_contents('http://api.twitter.com/1/users/show.json?' . http_build_query(array('screen_name' => $handle))), true); |
| | 43 | if (isset($info['id'])) |
| | 44 | { |
| | 45 | return 'http://twitter.com/statuses/user_timeline/' . $info['id'] . '.rss'; |
| | 46 | } |
| | 47 | } |
| | 48 | return $value; |
| | 49 | } |
| | 50 | |
| | 51 | // If it smells like HTML and contains a suitable link tag, extract the first feed URL, |
| | 52 | // which is probably what they meant. Otherwise leave it alone |
| | 53 | public function validateFeed($validator, $value) |
| | 54 | { |
| | 55 | $content = @file_get_contents($value); |
| | 56 | if ($content) |
| | 57 | { |
| | 58 | $html = new DOMDocument(); |
| | 59 | // Incredibly noisy on typical markup |
| | 60 | @$html->loadHTML($content); |
| | 61 | $xpath = new DOMXPath($html); |
| | 62 | $arts = $xpath->query('//link[@rel="alternate" and @type="application/rss+xml"]'); |
| | 63 | if (isset($arts->length) && $arts->length) |
| | 64 | { |
| | 65 | return $arts->item(0)->getAttribute('href'); |
| | 66 | } |
| | 67 | } |
| | 68 | return $value; |
| | 69 | } |
| | 70 | // Add missing http:// |
| | 71 | public function validateLazyUrl($validator, $value) |
| | 72 | { |
| | 73 | if (preg_match('/^[\w\+-]+\./', $value)) |
| | 74 | { |
| | 75 | return 'http://' . $value; |
| | 76 | } |
| | 77 | return $value; |
| | 78 | } |