All Database adding and Tweet retrieving functions
[Anonymous-Twitter-Board.git] / class / twitter-connection.php
blob75bb327247b86a09dd5e8bc492d60cfe44203546
1 <?php
3 /*
4 A NOTE ON TWITTER ERRORS:
5 ERROR 215 TYPICALLY MEANS YOU GOT THE AUTHENTICATION STRING FORAMT WRONG
6 ERROR 32 MEANS YOU GOT THE VALUES WRONG
7 */
9 function removeExtraSymbols($string){
10 $string = str_replace(".", "a", $string);
11 $string = str_replace("%", "b", $string);
12 $string = str_replace("/", "c", $string);
13 return $string;
16 require("class/oauth-random.php");
17 require("class/queue-database-construction.php");
18 class TwitterConnection{
19 private $oauth_data = array();
20 private $user_info = array();
21 private $post_properties = array();
23 private $media_api = "https://upload.twitter.com/1.1/media/upload.json";
24 private $status_api = "https://api.twitter.com/1.1/statuses/update.json";
25 private $user_timeline_api = "https://api.twitter.com/1.1/statuses/user_timeline.json";
26 private $mention_timeline_api = "https://api.twitter.com/1.1/statuses/mentions_timeline.json";
28 function __construct(){
29 $this->oauth_data = $this->getIniFile("settings/keys.ini");
30 $this->user_info = $this->getIniFile("settings/userinfo.ini");
31 $this->post_properties = $this->getIniFile("settings/postproperties.ini");
34 function getIniFile($path){
35 $path_string = fopen($path,"r");
36 $return_array = array();
37 while(!feof($path_string)){
38 $line = fgets($path_string);
39 $key = substr($line,0,strpos($line, "="));
40 //eat last character
41 $value = trim(substr($line, strpos($line, "=")+1));
43 $return_array[$key] = $value;
45 return $return_array;
48 function retrieveTimeline(){
49 $highest_post_id = -1;
51 $timeline_arr = $this->getUserTimeline($this->post_properties["TopPostNo"]);
52 $timeline_database_arr = array();
54 if($timeline_arr["errors"][0]["code"] == null && sizeof($timeline_arr) != 0){
55 foreach ($timeline_arr as $timeline_item){
56 $post_id = $timeline_item["id"];
57 $post_text = $timeline_item["text"];
58 $post_image_string = $this->grabTwitterImage($timeline_item);
59 array_push($timeline_database_arr, [$post_id, $post_text, $post_image_string]);
61 $highest_post_id = $post_id > $highest_post_id ? $post_id : $highest_post_id;
64 else echo $timeline_arr["errors"][0]["code"] . "Tim<br/>";
66 echo "<hr>"; //From the post ID try and find any replies
68 $reply_arr = $this->getTweetReplies($this->post_properties["TopPostNo"]);
69 $reply_arr_container = array();
71 if($reply_arr["errors"][0]["code"] == null && sizeof($reply_arr) != 0){
72 $reply_id = 0;
73 foreach($reply_arr as $reply_item){
74 $reply_id = $reply_item["id"];
75 $reply_text = $reply_item["text"];
76 $reply_image_string = $this->grabTwitterImage($reply_item);
77 $responding_to_id = $reply_item['in_reply_to_status_id'];
78 echo "$lowest_post_id -- $responding_to_id<hr/>";
79 array_push($reply_arr_container, [$reply_id, $reply_text, $reply_image_string, $responding_to_id]);
81 $highest_post_id = $reply_id > $highest_post_id ? $reply_id : $highest_post_id;
84 else echo $reply_arr["errors"][0]["code"] . "Rep<br/>";
86 if(sizeof($timeline_database_arr) + sizeof($reply_arr_container) == 0){
87 echo "No Updates<hr/>";
88 return;
90 else{
91 $postfile = fopen("settings/postproperties.ini", "w");
92 echo "TopPostNo=$highest_post_id<br/>";
93 fwrite($postfile, "TopPostNo=$highest_post_id");
96 $combined_database_arr = array_merge ($timeline_database_arr, $reply_arr_container);
97 $database_connection = new QueueDatabaseConstruction(true);
99 echo "<hr>";
101 $this->recursiveEchoJson($combined_database_arr,0);
102 echo "<pre>";
103 if(sizeof($timeline_database_arr) != 0){
104 $this->addTimelineTweetsToDatabase($combined_database_arr, $database_connection);
106 echo "</pre>";
108 $database_connection = null;
111 function endConnection(){
112 $this->database_connection = null;
115 function grabTwitterImage($tweet_array){
116 $first_join = false;
117 $image_url_string = null;
118 echo "<hr/>";
119 if($tweet_array["extended_entities"] != null){
120 foreach($tweet_array["extended_entities"] ["media"] as $entity){
121 $filename = "images/" . (microtime(true) * 10000) . (rand(0,1000))
122 . removeExtraSymbols($entity["media_url_https"][rawurlencode(rand(0, strlen($entity["media_url_https"])))]) . ".jpg";
123 $this->uploadMedia($filename, $entity["media_url_https"]);
124 if(!$first_join){
125 $first_join = true;
126 $image_url_string = $filename;
128 else $image_url_string .= "," . rawurlencode($filename);
132 return $image_url_string;
135 function recursiveEchoJson($json, $indents){
136 echo "<pre>";
137 foreach($json as $key => $attribute){
138 if(is_array ($attribute)){
139 $this->makeIndents($indents);
140 echo "$key {\n";
142 $this->recursiveEchoJson($attribute, ++$indents);
144 $this->makeIndents(--$indents);
145 echo "}\n";
147 else{
148 $this->makeIndents($indents);
149 echo "$key = $attribute \n";
152 echo "</pre>";
153 if($indents == 1) echo "<hr/>";
156 function makeIndents($indent_count){
157 for ($i = 0; $i < $indent_count ; $i++){ echo "\t"; }
160 function addTimelineTweetsToDatabase($timeline_database_arr, $database_connection){
161 var_dump($timeline_database_arr);
162 foreach($timeline_database_arr as $key => $timeline_item){
163 echo $timeline_item[0] . "--1<br/>";
164 $database_connection->addToTable("Tweet", array("PostID"=>$timeline_item[0],
165 "PostText"=> $timeline_item[1], "ImageURL"=> $timeline_item[2]));
166 if($timeline_item[3] !== null)
167 $database_connection->addToTable("Response", array("PostID"=>$timeline_item[0], "RepliesTo"=>$timeline_item[3]));
170 function uploadMedia($filename,$url){
171 file_put_contents($filename, fopen($url, 'r'));
174 function getUserTimeline($since_id = 976628662446551043, $count = 100){
176 $random_value = OauthRandom::randomAlphaNumet(32);
177 $method = "HMAC-SHA1";
178 $oauth_version = "1.0";
179 $timestamp = time();
180 $reply_exclude = "false";
182 $get_fields = "since_id=" . $since_id . "&count=" . $count . "&include_rts=false&exclude_replies=$reply_exclude&user_id=" . $this->user_info["User-ID"];
183 //$msg_len = (strlen($this->user_timeline_api . "?$get_fields")); //GET REQUESTS HAVE NO DYNAMIC LENGTH
185 $param_array = array( "user_id" => $this->user_info["User-ID"],
186 "since_id" => "$since_id",
187 "exclude_replies"=>"$reply_exclude",
188 "count" => "$count",
189 "include_rts" => "false",
190 "oauth_version" => "$oauth_version",
191 "oauth_nonce"=>"$random_value",
192 "oauth_token"=> $this->oauth_data["oauth_token"],
193 "oauth_timestamp" => "$timestamp",
194 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
195 "oauth_signature_method" => "$method"
198 $signature = rawurlencode($this->generateSignature(array(
199 "base_url" => $this->user_timeline_api,
200 "request_method" => "GET"),
201 $param_array,
202 array(
203 "consumer_secret" => $this->oauth_data["consumer_secret"],
204 "oauth_secret" => $this->oauth_data["oauth_secret"]
208 $param_array["oauth_signature"] = $signature;
209 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
210 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", "Host: api.twitter.com",
211 $this->buildAuthorizationString($param_array));
213 //request
214 echo "<hr/>";
215 $curl = curl_init($this->user_timeline_api . "?$get_fields");
216 curl_setopt($curl, CURLOPT_HTTPGET, 1);
217 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
218 curl_setopt($curl, CURLOPT_HEADER, false);
219 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
220 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER , false);
222 echo "<br/>-- Fin -- <hr/>";
223 $content = curl_exec($curl);
224 return json_decode(($content), true);
229 function getTweetReplies($current_post_id, $max_post_id = -1){
230 $random_value = OauthRandom::randomAlphaNumet(32);
231 $method = "HMAC-SHA1";
232 $oauth_version = "1.0";
233 $timestamp = time();
236 $get_fields = "since_id=" . $current_post_id;
237 $param_array = array(
238 "since_id" => "$current_post_id",
239 "oauth_version" => "$oauth_version",
240 "oauth_nonce"=>"$random_value",
241 "oauth_token"=> $this->oauth_data["oauth_token"],
242 "oauth_timestamp" => "$timestamp",
243 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
244 "oauth_signature_method" => "$method"
246 if($max_post_id > 0){
247 $get_fields .= $max_post_id > 0 ? "&max_id=" . $max_post_id : "";
248 $param_array["max_id"] = "$max_post_id";
251 $signature = rawurlencode($this->generateSignature(array(
252 "base_url" => $this->mention_timeline_api,
253 "request_method" => "GET"),
254 $param_array,
255 array(
256 "consumer_secret" => $this->oauth_data["consumer_secret"],
257 "oauth_secret" => $this->oauth_data["oauth_secret"]
260 $param_array["oauth_signature"] = $signature;
261 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
262 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", "Host: api.twitter.com",
263 $this->buildAuthorizationString($param_array));
265 //request
266 $curl = curl_init($this->mention_timeline_api . "?$get_fields");
267 curl_setopt($curl, CURLOPT_HTTPGET, 1);
268 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
269 curl_setopt($curl, CURLOPT_HEADER, false);
270 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
271 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER , false);
272 $content = curl_exec($curl);
273 return json_decode(($content), true);
279 function buildAuthorizationString($parameters){
280 $authorization_string = 'Authorization: OAuth ';
282 ksort($parameters);
283 $is_first_join = false;
284 foreach($parameters as $key => $value){
285 if(!$is_first_join){
286 $is_first_join = true;
287 $authorization_string .= $key . '="' . $value . '"';
289 else{
290 $authorization_string .= "," . $key . '="' . $value . '"';
293 return $authorization_string;
296 function makeTweet($comment, $file_arr){
297 $image_string = $this->addTweetMedia($file_arr);
299 //access info
300 $request_method = "POST";
302 //message info
303 $encode_tweet_msg = rawurlencode($comment);
304 $include_entities = "true";
306 //append to postfield_string the media code via media_ids=$media_id
307 $postfield_string = "include_entities=$include_entities&status=$encode_tweet_msg&media_ids=$image_string";
308 $msg_len = (strlen($postfield_string));
310 $random_value = OauthRandom::randomAlphaNumet(32);
311 $method = "HMAC-SHA1";
312 $oauth_version = "1.0";
313 $timestamp = time();
315 $param_array = array("include_entities" => "$include_entities",
316 "status" => "$encode_tweet_msg",
317 "media_ids" => "$image_string",
318 "oauth_version" => "$oauth_version",
319 "oauth_nonce"=>"$random_value",
320 "oauth_token"=> $this->oauth_data["oauth_token"],
321 "oauth_timestamp" => "$timestamp",
322 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
323 "oauth_signature_method" => "$method"
326 //add media id to the signature
327 $signature = rawurlencode($this->generateSignature(array(
328 "base_url" => $this->status_api,
329 "request_method" => $request_method),
330 $param_array,
331 array(
332 "consumer_secret" => $this->oauth_data["consumer_secret"],
333 "oauth_secret" => $this->oauth_data["oauth_secret"]
337 $param_array["oauth_signature"] = $signature;
338 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
339 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
340 "Content-Length: $msg_len", "Host: api.twitter.com",
341 $this->buildAuthorizationString($param_array));
343 //request
344 echo "<hr/>";
345 $curl = curl_init($this->status_api);
346 curl_setopt($curl, CURLOPT_POST, 1);
347 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
348 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
349 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
350 echo "<br/>-- Fin -- <hr/>";
351 $content = curl_exec($curl);
352 echo $content;
355 function addTweetMedia($file_arr){
357 //image info
358 $image_string = "";//delimited by ',' commas
359 for($file = 0 ; $file < count($file_arr) ; $file++){
360 if($file_arr[$file] != ""){
361 //create data in binary/b64
362 $mime_type = pathinfo($file_arr[$file], PATHINFO_EXTENSION);
363 $file_arr[$file] = urldecode($file_arr[$file]);
364 $binary = file_get_contents($file_arr[$file]);
366 $base64 = base64_encode($binary);
368 //upload file to twitter and get id for use in files
369 $size = filesize($file_arr[$file]);
370 if($file == 0)
371 $image_string = $this->getMediaID($base64, $size, 'image/' . $mime_type);
372 else
373 $image_string .= "," . $this->getMediaID($base64, $size, 'image/' . $mime_type);
376 return rawurlencode($image_string);
379 function getMediaID($base64, $size, $mime_type){
380 $random_value = OAuthRandom::randomAlphaNumet(32);
381 $timestamp = time();
383 echo "<br/><br/>";
384 /////////////MAKE INIT////////////
385 //post data
386 $media_id = $this->mediaInit($size, $mime_type, $random_value, $timestamp);
388 echo "<br/><br/>";
390 /////////////MAKE APPEND////////////
391 //post data
392 $this->mediaAppend($base64, $media_id, $random_value, $timestamp);
394 echo "<br/><br/>";
396 /////////////MAKE FINAL/
397 $this->makeFinal($media_id, $random_value, $timestamp);
398 echo "<br/><br/>";
400 return $media_id ;
403 function mediaInit($size, $mime, $random_value, $timestamp){
404 $command = "INIT";
405 $method = "HMAC-SHA1";
406 $oauth_version = "1.0";
408 $postfield_string = "command=$command&total_bytes=$size&media_type=$mime";
410 $msg_len = (strlen($postfield_string));
411 //header data
412 // BUILD SIGNATURE
413 $signature = rawurlencode($this->generateSignature(array(
414 "base_url" => $this->media_api,
415 "request_method" => "POST"),
416 array(
417 "command" => "$command",
418 "total_bytes" => "$size",
419 "media_type" => "$mime",
420 "oauth_version" => "$oauth_version",
421 "oauth_nonce"=>"$random_value",
422 "oauth_token"=> $this->oauth_data["oauth_token"],
423 "oauth_timestamp" => "$timestamp",
424 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
425 "oauth_signature_method" => "$method",
427 array(
428 "consumer_secret" => $this->oauth_data["consumer_secret"],
429 "oauth_secret" => $this->oauth_data["oauth_secret"]
435 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
436 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
437 "Content-Length: $msg_len", "Host: upload.twitter.com",
438 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
439 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
442 //request
443 $curl = curl_init($this->media_api);
444 curl_setopt($curl, CURLOPT_POST, 1);
445 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
446 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
447 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
448 $media_id_arr = json_decode(curl_exec($curl), true);
449 print_r ($media_id_arr);
450 return $media_id_arr["media_id_string"];
453 function mediaAppend(&$binary_file, $media_id, $random_value, $timestamp){
454 $command = "APPEND";
455 $method = "HMAC-SHA1";
456 $oauth_version = "1.0";
458 $segment_index = 0;
460 //header data
461 // BUILD SIGNATURE
462 $signature = rawurlencode($this->generateSignature(array(
463 "base_url" => $this->media_api,
464 "request_method" => "POST"),
465 array(
466 "command" => "$command",
467 "media" => "$binary_file",
468 "media_id"=>"$media_id",
469 "segment_index"=>"$segment_index",
470 "oauth_version" => "$oauth_version",
471 "oauth_nonce"=>"$random_value",
472 "oauth_token"=> $this->oauth_data["oauth_token"],
473 "oauth_timestamp" => "$timestamp",
474 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
475 "oauth_signature_method" => "$method",
477 array(
478 "consumer_secret" => $this->oauth_data["consumer_secret"],
479 "oauth_secret" => $this->oauth_data["oauth_secret"]
484 $postfield_string = "media=" . rawurlencode($binary_file) . "&command=$command&media_id=$media_id&segment_index=$segment_index" ;
485 $msg_len = (strlen($postfield_string));
486 $header_data = array("Except:", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
487 "Content-Type: application/x-www-form-urlencoded",
488 "Content-Length: $msg_len", "Host: upload.twitter.com",
489 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
490 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
492 //request
493 $curl = curl_init($this->media_api);
494 curl_setopt($curl, CURLOPT_POST, 1);
495 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
496 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
497 curl_setopt($curl, CURLOPT_HEADER , true);
498 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
499 $http_response = curl_exec($curl);
500 echo $http_response;
503 function makeFinal($media_id, $random_value, $timestamp){
504 $command = "FINALIZE";
505 $method = "HMAC-SHA1";
506 $oauth_version = "1.0";
508 $signature = rawurlencode($this->generateSignature(array(
509 "base_url" => $this->media_api,
510 "request_method" => "POST"),
511 array(
512 "command" => "$command",
513 "media_id"=>"$media_id",
514 "oauth_version" => "$oauth_version",
515 "oauth_nonce"=>"$random_value",
516 "oauth_token"=> $this->oauth_data["oauth_token"],
517 "oauth_timestamp" => "$timestamp",
518 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
519 "oauth_signature_method" => "$method",
521 array(
522 "consumer_secret" => $this->oauth_data["consumer_secret"],
523 "oauth_secret" => $this->oauth_data["oauth_secret"]
526 $postfield_string = "command=$command&media_id=$media_id" ;
527 $msg_len = (strlen($postfield_string));
528 $header_data = array("Except:", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
529 "Content-Type: application/x-www-form-urlencoded",
530 "Content-Length: $msg_len", "Host: upload.twitter.com",
531 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
532 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
534 //request
535 $curl = curl_init($this->media_api);
536 curl_setopt($curl, CURLOPT_POST, 1);
537 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
538 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
539 curl_setopt($curl, CURLOPT_HEADER , true);
540 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
541 $http_response = curl_exec($curl);
542 echo $http_response;
545 function generateSignature($request_arr, $paramater_arr, $secret_arr){
546 // BUILD SIGNATURE
547 $request_method = strtoupper($request_arr["request_method"]);
548 $base_url = rawurlencode($request_arr["base_url"]);
550 ksort($paramater_arr);
551 if(isset($paramater_arr["media"])) $paramater_arr["media"] = rawurlencode($paramater_arr["media"]);
552 $paramter_string = $this->buildOAuthParamaterString($paramater_arr);
554 $base_string = ($request_method . "&" . $base_url . "&" . $paramter_string);
555 $secret_string = $secret_arr["consumer_secret"] . "&" . $secret_arr["oauth_secret"];
556 $signature = (base64_encode(hash_hmac("SHA1",$base_string, $secret_string, true)));
558 return $signature;
561 function buildOAuthParamaterString($paramater_arr){
562 $param_string = "";
563 $join_param_by_amphersand = false;
564 foreach($paramater_arr as $key => $param){
565 if(!$join_param_by_amphersand){
566 $join_param_by_amphersand=true;
568 else{
569 $param_string .= rawurlencode("&");
571 $param_string .= rawurlencode($key . "=" . $param);
573 return $param_string;
578 echo"run script from externals<br/>";