Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Reddit{
- var $REDDIT_URL = "http://www.reddit.com";
- var $LISTING_URL = "http://www.reddit.com/%s.json?after=%s&limit=%d"; //1st position is subreddit: empty or "r/something/",
- //2nd position is after_id,
- //3rd position is result count limit
- var $LOGIN_URL = "http://www.reddit.com/api/login/%s"; //1st position is username (redundant and required)
- var $VOTE_URL = "http://www.reddit.com/api/vote";
- var $username = "guest"; //todo: handle this better
- var $modhash = "";
- var $cookie = "";
- function getDataAsJson($url){
- return json_decode(file_get_contents($url));
- }
- function getListings($subreddit="", $after=""){
- if (trim($subreddit) != "" && substr($subreddit, -1) != "/"){
- $subreddit .= "/";
- }
- return $this->getDataAsJson(sprintf($this->LISTING_URL, $subreddit, $after, 100));
- }
- function postData($url, $data){
- $c = curl_init($url);
- curl_setopt($c, CURLOPT_HEADER, 0);
- curl_setopt($c, CURLOPT_POST, true);
- curl_setopt($c, CURLOPT_POSTFIELDS, $data);
- curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($c, CURLOPT_COOKIEJAR, sprintf("cookies/%s.txt", $this->username));
- curl_setopt($c, CURLOPT_COOKIEFILE, sprintf("cookies/%s.txt", $this->username));
- curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
- $data = curl_exec($c);
- curl_close($c);
- $tmp_data = json_decode($data);
- if ($tmp_data != NULL){
- $this->modhash = $tmp_data->json->data->modhash;
- $this->cookie = $tmp_data->json->data->cookie;
- }
- return $data;
- }
- function makeBodyString($data){
- //PHP 5 or better, I will write a 4.0 version later.
- return http_build_query($data);
- }
- function login($username, $password){
- $this->username = $username;
- $data = $this->makeBodyString(array(
- "user"=>$username, //user's username
- "passwd"=>$password, //user's password
- "api_type"=>"json" //required
- ));
- return $this->postData(sprintf($this->LOGIN_URL, $username), $data);
- }
- function submitVote($id, $vote=0){
- $data = $this->makeBodyString(array(
- "id"=>$id, //article id
- "dir"=>$vote, //vote direction. 1=up, 0=none, -1=down
- "uh"=>$this->modhash //modhash
- ));
- return $this->postData($this->VOTE_URL, $data);
- }
- }
Add Comment
Please, Sign In to add comment