PageRenderTime 56ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/controllers/components/akismet.php

https://github.com/markomavric/croogo
PHP | 391 lines | 157 code | 43 blank | 191 comment | 15 complexity | ffe6e8a2bd48607d92ed75ab2a720fbd MD5 | raw file
  1. <?php
  2. /**
  3. * Akismet anti-comment spam service
  4. *
  5. * The class in this package allows use of the {@link http://akismet.com Akismet} anti-comment spam service in any PHP5 application.
  6. *
  7. * This service performs a number of checks on submitted data and returns whether or not the data is likely to be spam.
  8. *
  9. * Please note that in order to use this class, you must have a vaild {@link http://wordpress.com/api-keys/ WordPress API key}. They are free for non/small-profit types and getting one will only take a couple of minutes.
  10. *
  11. * For commercial use, please {@link http://akismet.com/commercial/ visit the Akismet commercial licensing page}.
  12. *
  13. * Please be aware that this class is PHP5 only. Attempts to run it under PHP4 will most likely fail.
  14. *
  15. * See the Akismet class documentation page linked to below for usage information.
  16. *
  17. * @package akismet
  18. * @author Alex Potsides, {@link http://www.achingbrain.net http://www.achingbrain.net}
  19. * @version 0.4
  20. * @copyright Alex Potsides, {@link http://www.achingbrain.net http://www.achingbrain.net}
  21. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  22. */
  23. /**
  24. * The Akismet PHP5 Class
  25. *
  26. * This class takes the functionality from the Akismet WordPress plugin written by {@link http://photomatt.net/ Matt Mullenweg} and allows it to be integrated into any PHP5 application or website.
  27. *
  28. * The original plugin is {@link http://akismet.com/download/ available on the Akismet website}.
  29. *
  30. * <b>Usage:</b>
  31. * <code>
  32. * $akismet = new Akismet('http://www.example.com/blog/', 'aoeu1aoue');
  33. * $akismet->setCommentAuthor($name);
  34. * $akismet->setCommentAuthorEmail($email);
  35. * $akismet->setCommentAuthorURL($url);
  36. * $akismet->setCommentContent($comment);
  37. * $akismet->setPermalink('http://www.example.com/blog/alex/someurl/');
  38. * if($akismet->isCommentSpam())
  39. * // store the comment but mark it as spam (in case of a mis-diagnosis)
  40. * else
  41. * // store the comment normally
  42. * </code>
  43. *
  44. * Optionally you may wish to check if your WordPress API key is valid as in the example below.
  45. *
  46. * <code>
  47. * $akismet = new Akismet('http://www.example.com/blog/', 'aoeu1aoue');
  48. *
  49. * if($akismet->isKeyValid()) {
  50. * // api key is okay
  51. * } else {
  52. * // api key is invalid
  53. * }
  54. * </code>
  55. *
  56. * @package akismet
  57. * @name Akismet
  58. * @version 0.4
  59. * @author Alex Potsides
  60. * @link http://www.achingbrain.net/
  61. */
  62. class AkismetComponent extends Object
  63. {
  64. private $version = '0.4';
  65. private $wordPressAPIKey;
  66. private $blogURL;
  67. private $comment;
  68. private $apiPort;
  69. private $akismetServer;
  70. private $akismetVersion;
  71. // This prevents some potentially sensitive information from being sent accross the wire.
  72. private $ignore = array('HTTP_COOKIE',
  73. 'HTTP_X_FORWARDED_FOR',
  74. 'HTTP_X_FORWARDED_HOST',
  75. 'HTTP_MAX_FORWARDS',
  76. 'HTTP_X_FORWARDED_SERVER',
  77. 'REDIRECT_STATUS',
  78. 'SERVER_PORT',
  79. 'PATH',
  80. 'DOCUMENT_ROOT',
  81. 'SERVER_ADMIN',
  82. 'QUERY_STRING',
  83. 'PHP_SELF' );
  84. /**
  85. * @param string $blogURL The URL of your blog.
  86. * @param string $wordPressAPIKey WordPress API key.
  87. */
  88. public function startup() {
  89. $this->blogURL = Configure::read('Service.akismet_url');
  90. $this->wordPressAPIKey = Configure::read('Service.akismet_key');
  91. // Set some default values
  92. $this->apiPort = 80;
  93. $this->akismetServer = 'rest.akismet.com';
  94. $this->akismetVersion = '1.1';
  95. // Start to populate the comment data
  96. $this->comment['blog'] = $this->blogURL;
  97. $this->comment['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
  98. if(isset($_SERVER['HTTP_REFERER'])) {
  99. $this->comment['referrer'] = $_SERVER['HTTP_REFERER'];
  100. }
  101. /*
  102. * This is necessary if the server PHP5 is running on has been set up to run PHP4 and
  103. * PHP5 concurently and is actually running through a separate proxy al a these instructions:
  104. * http://www.schlitt.info/applications/blog/archives/83_How_to_run_PHP4_and_PHP_5_parallel.html
  105. * and http://wiki.coggeshall.org/37.html
  106. * Otherwise the user_ip appears as the IP address of the PHP4 server passing the requests to the
  107. * PHP5 one...
  108. */
  109. $this->comment['user_ip'] = $_SERVER['REMOTE_ADDR'] != getenv('SERVER_ADDR') ? $_SERVER['REMOTE_ADDR'] : getenv('HTTP_X_FORWARDED_FOR');
  110. }
  111. /**
  112. * Makes a request to the Akismet service to see if the API key passed to the constructor is valid.
  113. *
  114. * Use this method if you suspect your API key is invalid.
  115. *
  116. * @return bool True is if the key is valid, false if not.
  117. */
  118. public function isKeyValid() {
  119. // Check to see if the key is valid
  120. $response = $this->sendRequest('key=' . $this->wordPressAPIKey . '&blog=' . $this->blogURL, $this->akismetServer, '/' . $this->akismetVersion . '/verify-key');
  121. return $response[1] == 'valid';
  122. }
  123. // makes a request to the Akismet service
  124. private function sendRequest($request, $host, $path) {
  125. $http_request = "POST " . $path . " HTTP/1.0\r\n";
  126. $http_request .= "Host: " . $host . "\r\n";
  127. $http_request .= "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n";
  128. $http_request .= "Content-Length: " . strlen($request) . "\r\n";
  129. $http_request .= "User-Agent: Akismet PHP5 Class " . $this->version . " | Akismet/1.11\r\n";
  130. $http_request .= "\r\n";
  131. $http_request .= $request;
  132. $socketWriteRead = new SocketWriteRead($host, $this->apiPort, $http_request);
  133. $socketWriteRead->send();
  134. return explode("\r\n\r\n", $socketWriteRead->getResponse(), 2);
  135. }
  136. // Formats the data for transmission
  137. private function getQueryString() {
  138. foreach($_SERVER as $key => $value) {
  139. if(!in_array($key, $this->ignore)) {
  140. if($key == 'REMOTE_ADDR') {
  141. $this->comment[$key] = $this->comment['user_ip'];
  142. } else {
  143. $this->comment[$key] = $value;
  144. }
  145. }
  146. }
  147. $query_string = '';
  148. foreach($this->comment as $key => $data) {
  149. if(!is_array($data)) {
  150. $query_string .= $key . '=' . urlencode(stripslashes($data)) . '&';
  151. }
  152. }
  153. return $query_string;
  154. }
  155. /**
  156. * Tests for spam.
  157. *
  158. * Uses the web service provided by {@link http://www.akismet.com Akismet} to see whether or not the submitted comment is spam. Returns a boolean value.
  159. *
  160. * @return bool True if the comment is spam, false if not
  161. * @throws Will throw an exception if the API key passed to the constructor is invalid.
  162. */
  163. public function isCommentSpam() {
  164. $response = $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.rest.akismet.com', '/' . $this->akismetVersion . '/comment-check');
  165. if($response[1] == 'invalid' && !$this->isKeyValid()) {
  166. throw new exception('The Wordpress API key passed to the Akismet constructor is invalid. Please obtain a valid one from http://wordpress.com/api-keys/');
  167. }
  168. return ($response[1] == 'true');
  169. }
  170. /**
  171. * Submit spam that is incorrectly tagged as ham.
  172. *
  173. * Using this function will make you a good citizen as it helps Akismet to learn from its mistakes. This will improve the service for everybody.
  174. */
  175. public function submitSpam() {
  176. $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.' . $this->akismetServer, '/' . $this->akismetVersion . '/submit-spam');
  177. }
  178. /**
  179. * Submit ham that is incorrectly tagged as spam.
  180. *
  181. * Using this function will make you a good citizen as it helps Akismet to learn from its mistakes. This will improve the service for everybody.
  182. */
  183. public function submitHam() {
  184. $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.' . $this->akismetServer, '/' . $this->akismetVersion . '/submit-ham');
  185. }
  186. /**
  187. * To override the user IP address when submitting spam/ham later on
  188. *
  189. * @param string $userip An IP address. Optional.
  190. */
  191. public function setUserIP($userip) {
  192. $this->comment['user_ip'] = $userip;
  193. }
  194. /**
  195. * To override the referring page when submitting spam/ham later on
  196. *
  197. * @param string $referrer The referring page. Optional.
  198. */
  199. public function setReferrer($referrer) {
  200. $this->comment['referrer'] = $referrer;
  201. }
  202. /**
  203. * A permanent URL referencing the blog post the comment was submitted to.
  204. *
  205. * @param string $permalink The URL. Optional.
  206. */
  207. public function setPermalink($permalink) {
  208. $this->comment['permalink'] = $permalink;
  209. }
  210. /**
  211. * The type of comment being submitted.
  212. *
  213. * May be blank, comment, trackback, pingback, or a made up value like "registration" or "wiki".
  214. */
  215. public function setCommentType($commentType) {
  216. $this->comment['comment_type'] = $commentType;
  217. }
  218. /**
  219. * The name that the author submitted with the comment.
  220. */
  221. public function setCommentAuthor($commentAuthor) {
  222. $this->comment['comment_author'] = $commentAuthor;
  223. }
  224. /**
  225. * The email address that the author submitted with the comment.
  226. *
  227. * The address is assumed to be valid.
  228. */
  229. public function setCommentAuthorEmail($authorEmail) {
  230. $this->comment['comment_author_email'] = $authorEmail;
  231. }
  232. /**
  233. * The URL that the author submitted with the comment.
  234. */
  235. public function setCommentAuthorURL($authorURL) {
  236. $this->comment['comment_author_url'] = $authorURL;
  237. }
  238. /**
  239. * The comment's body text.
  240. */
  241. public function setCommentContent($commentBody) {
  242. $this->comment['comment_content'] = $commentBody;
  243. }
  244. /**
  245. * Defaults to 80
  246. */
  247. public function setAPIPort($apiPort) {
  248. $this->apiPort = $apiPort;
  249. }
  250. /**
  251. * Defaults to rest.akismet.com
  252. */
  253. public function setAkismetServer($akismetServer) {
  254. $this->akismetServer = $akismetServer;
  255. }
  256. /**
  257. * Defaults to '1.1'
  258. */
  259. public function setAkismetVersion($akismetVersion) {
  260. $this->akismetVersion = $akismetVersion;
  261. }
  262. }
  263. /**
  264. * Utility class used by Akismet
  265. *
  266. * This class is used by Akismet to do the actual sending and receiving of data. It opens a connection to a remote host, sends some data and the reads the response and makes it available to the calling program.
  267. *
  268. * The code that makes up this class originates in the Akismet WordPress plugin, which is {@link http://akismet.com/download/ available on the Akismet website}.
  269. *
  270. * N.B. It is not necessary to call this class directly to use the Akismet class. This is included here mainly out of a sense of completeness.
  271. *
  272. * @package akismet
  273. * @name SocketWriteRead
  274. * @version 0.1
  275. * @author Alex Potsides
  276. * @link http://www.achingbrain.net/
  277. */
  278. class SocketWriteRead {
  279. private $host;
  280. private $port;
  281. private $request;
  282. private $response;
  283. private $responseLength;
  284. private $errorNumber;
  285. private $errorString;
  286. /**
  287. * @param string $host The host to send/receive data.
  288. * @param int $port The port on the remote host.
  289. * @param string $request The data to send.
  290. * @param int $responseLength The amount of data to read. Defaults to 1160 bytes.
  291. */
  292. public function __construct($host, $port, $request, $responseLength = 1160) {
  293. $this->host = $host;
  294. $this->port = $port;
  295. $this->request = $request;
  296. $this->responseLength = $responseLength;
  297. $this->errorNumber = 0;
  298. $this->errorString = '';
  299. }
  300. /**
  301. * Sends the data to the remote host.
  302. *
  303. * @throws An exception is thrown if a connection cannot be made to the remote host.
  304. */
  305. public function send() {
  306. $this->response = '';
  307. $fs = fsockopen($this->host, $this->port, $this->errorNumber, $this->errorString, 3);
  308. if($this->errorNumber != 0) {
  309. throw new Exception('Error connecting to host: ' . $this->host . ' Error number: ' . $this->errorNumber . ' Error message: ' . $this->errorString);
  310. }
  311. if($fs !== false) {
  312. @fwrite($fs, $this->request);
  313. while(!feof($fs)) {
  314. $this->response .= fgets($fs, $this->responseLength);
  315. }
  316. fclose($fs);
  317. }
  318. }
  319. /**
  320. * Returns the server response text
  321. *
  322. * @return string
  323. */
  324. public function getResponse() {
  325. return $this->response;
  326. }
  327. /**
  328. * Returns the error number
  329. *
  330. * If there was no error, 0 will be returned.
  331. *
  332. * @return int
  333. */
  334. public function getErrorNumner() {
  335. return $this->errorNumber;
  336. }
  337. /**
  338. * Returns the error string
  339. *
  340. * If there was no error, an empty string will be returned.
  341. *
  342. * @return string
  343. */
  344. public function getErrorString() {
  345. return $this->errorString;
  346. }
  347. }
  348. ?>