expiration functions
[Anonymous-Twitter-Board.git] / class / twitter-connection.php
blob3ce3a516c249a0e6b5cef3772c51bea0fe43f42d
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_once("class/oauth-random.php");
17 require_once("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 deleteExpiredEntries(){
112 $database_connection = new QueueDatabaseConstruction(true);
114 $threads = $database_connection->getThreads();
115 $thread_count = 0;
116 foreach($threads as $thread){
117 $thread_count++;
118 if($thread_count > 7){
119 var_dump ($thread);
120 $database_connection->deleteFromUnprocessedImageString($thread["ImageURL"]);
121 $database_connection->recursiveDeleteResponses($thread[0]);
122 $database_connection->deleteThread("Tweet", $thread[0]);//0 is the most relevant PostID
125 $database_connection = null;
129 function endConnection(){
130 $this->database_connection = null;
133 function grabTwitterImage($tweet_array){
134 $first_join = false;
135 $image_url_string = null;
136 echo "<hr/>";
137 if($tweet_array["extended_entities"] != null){
138 foreach($tweet_array["extended_entities"] ["media"] as $entity){
139 $filename = "images/" . (microtime(true) * 10000) . (rand(0,1000))
140 . removeExtraSymbols($entity["media_url_https"][rawurlencode(rand(0, strlen($entity["media_url_https"])))]) . ".jpg";
141 $this->uploadMedia($filename, $entity["media_url_https"]);
142 if(!$first_join){
143 $first_join = true;
144 $image_url_string = rawurlencode($filename);
146 else $image_url_string .= "," . rawurlencode($filename);
150 return $image_url_string;
153 function recursiveEchoJson($json, $indents){
154 echo "<pre>";
155 foreach($json as $key => $attribute){
156 if(is_array ($attribute)){
157 $this->makeIndents($indents);
158 echo "$key {\n";
160 $this->recursiveEchoJson($attribute, ++$indents);
162 $this->makeIndents(--$indents);
163 echo "}\n";
165 else{
166 $this->makeIndents($indents);
167 echo "$key = $attribute \n";
170 echo "</pre>";
171 if($indents == 1) echo "<hr/>";
174 function makeIndents($indent_count){
175 for ($i = 0; $i < $indent_count ; $i++){ echo "\t"; }
178 function addTimelineTweetsToDatabase($timeline_database_arr, $database_connection){
179 var_dump($timeline_database_arr);
180 foreach($timeline_database_arr as $key => $timeline_item){
181 $database_connection->addToTable("Tweet", array("PostID"=>$timeline_item[0],
182 "PostText"=> $timeline_item[1], "ImageURL"=> $timeline_item[2]));
183 if($timeline_item[3] !== null)
184 $database_connection->addToTable("Response", array("PostID"=>$timeline_item[0], "RepliesTo"=>$timeline_item[3]));
187 function uploadMedia($filename,$url){
188 file_put_contents($filename, fopen($url, 'r'));
191 function getUserTimeline($since_id = 976628662446551043, $count = 100){
193 $random_value = OauthRandom::randomAlphaNumet(32);
194 $method = "HMAC-SHA1";
195 $oauth_version = "1.0";
196 $timestamp = time();
197 $reply_exclude = "false";
199 $get_fields = "since_id=" . $since_id . "&count=" . $count . "&include_rts=false&exclude_replies=$reply_exclude&user_id=" . $this->user_info["User-ID"];
200 //$msg_len = (strlen($this->user_timeline_api . "?$get_fields")); //GET REQUESTS HAVE NO DYNAMIC LENGTH
202 $param_array = array( "user_id" => $this->user_info["User-ID"],
203 "since_id" => "$since_id",
204 "exclude_replies"=>"$reply_exclude",
205 "count" => "$count",
206 "include_rts" => "false",
207 "oauth_version" => "$oauth_version",
208 "oauth_nonce"=>"$random_value",
209 "oauth_token"=> $this->oauth_data["oauth_token"],
210 "oauth_timestamp" => "$timestamp",
211 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
212 "oauth_signature_method" => "$method"
215 $signature = rawurlencode($this->generateSignature(array(
216 "base_url" => $this->user_timeline_api,
217 "request_method" => "GET"),
218 $param_array,
219 array(
220 "consumer_secret" => $this->oauth_data["consumer_secret"],
221 "oauth_secret" => $this->oauth_data["oauth_secret"]
225 $param_array["oauth_signature"] = $signature;
226 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
227 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", "Host: api.twitter.com",
228 $this->buildAuthorizationString($param_array));
230 //request
231 echo "<hr/>";
232 $curl = curl_init($this->user_timeline_api . "?$get_fields");
233 curl_setopt($curl, CURLOPT_HTTPGET, 1);
234 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
235 curl_setopt($curl, CURLOPT_HEADER, false);
236 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
237 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER , false);
239 echo "<br/>-- Fin -- <hr/>";
240 $content = curl_exec($curl);
241 return json_decode(($content), true);
246 function getTweetReplies($current_post_id, $max_post_id = -1){
247 $random_value = OauthRandom::randomAlphaNumet(32);
248 $method = "HMAC-SHA1";
249 $oauth_version = "1.0";
250 $timestamp = time();
253 $get_fields = "since_id=" . $current_post_id;
254 $param_array = array(
255 "since_id" => "$current_post_id",
256 "oauth_version" => "$oauth_version",
257 "oauth_nonce"=>"$random_value",
258 "oauth_token"=> $this->oauth_data["oauth_token"],
259 "oauth_timestamp" => "$timestamp",
260 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
261 "oauth_signature_method" => "$method"
263 if($max_post_id > 0){
264 $get_fields .= $max_post_id > 0 ? "&max_id=" . $max_post_id : "";
265 $param_array["max_id"] = "$max_post_id";
268 $signature = rawurlencode($this->generateSignature(array(
269 "base_url" => $this->mention_timeline_api,
270 "request_method" => "GET"),
271 $param_array,
272 array(
273 "consumer_secret" => $this->oauth_data["consumer_secret"],
274 "oauth_secret" => $this->oauth_data["oauth_secret"]
277 $param_array["oauth_signature"] = $signature;
278 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
279 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", "Host: api.twitter.com",
280 $this->buildAuthorizationString($param_array));
282 //request
283 $curl = curl_init($this->mention_timeline_api . "?$get_fields");
284 curl_setopt($curl, CURLOPT_HTTPGET, 1);
285 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
286 curl_setopt($curl, CURLOPT_HEADER, false);
287 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
288 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER , false);
289 $content = curl_exec($curl);
290 return json_decode(($content), true);
296 function buildAuthorizationString($parameters){
297 $authorization_string = 'Authorization: OAuth ';
299 ksort($parameters);
300 $is_first_join = false;
301 foreach($parameters as $key => $value){
302 if(!$is_first_join){
303 $is_first_join = true;
304 $authorization_string .= $key . '="' . $value . '"';
306 else{
307 $authorization_string .= "," . $key . '="' . $value . '"';
310 return $authorization_string;
313 function makeTweet($comment, $file_arr){
314 $image_string = $this->addTweetMedia($file_arr);
316 //access info
317 $request_method = "POST";
319 //message info
320 $encode_tweet_msg = rawurlencode($comment);
321 $include_entities = "true";
323 //append to postfield_string the media code via media_ids=$media_id
324 $postfield_string = "include_entities=$include_entities&status=$encode_tweet_msg&media_ids=$image_string";
325 $msg_len = (strlen($postfield_string));
327 $random_value = OauthRandom::randomAlphaNumet(32);
328 $method = "HMAC-SHA1";
329 $oauth_version = "1.0";
330 $timestamp = time();
332 $param_array = array("include_entities" => "$include_entities",
333 "status" => "$encode_tweet_msg",
334 "media_ids" => "$image_string",
335 "oauth_version" => "$oauth_version",
336 "oauth_nonce"=>"$random_value",
337 "oauth_token"=> $this->oauth_data["oauth_token"],
338 "oauth_timestamp" => "$timestamp",
339 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
340 "oauth_signature_method" => "$method"
343 //add media id to the signature
344 $signature = rawurlencode($this->generateSignature(array(
345 "base_url" => $this->status_api,
346 "request_method" => $request_method),
347 $param_array,
348 array(
349 "consumer_secret" => $this->oauth_data["consumer_secret"],
350 "oauth_secret" => $this->oauth_data["oauth_secret"]
354 $param_array["oauth_signature"] = $signature;
355 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
356 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
357 "Content-Length: $msg_len", "Host: api.twitter.com",
358 $this->buildAuthorizationString($param_array));
360 //request
361 echo "<hr/>";
362 $curl = curl_init($this->status_api);
363 curl_setopt($curl, CURLOPT_POST, 1);
364 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
365 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
366 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
367 echo "<br/>-- Fin -- <hr/>";
368 $content = curl_exec($curl);
369 var_dump (json_decode($content, true));
370 return json_decode($content, true);
373 function addTweetMedia($file_arr){
375 //image info
376 $image_string = "";//delimited by ',' commas
377 for($file = 0 ; $file < count($file_arr) ; $file++){
378 if($file_arr[$file] != ""){
379 //create data in binary/b64
380 $mime_type = pathinfo($file_arr[$file], PATHINFO_EXTENSION);
381 $file_arr[$file] = urldecode($file_arr[$file]);
382 $binary = file_get_contents($file_arr[$file]);
384 $base64 = base64_encode($binary);
386 //upload file to twitter and get id for use in files
387 $size = filesize($file_arr[$file]);
388 if($file == 0)
389 $image_string = $this->getMediaID($base64, $size, 'image/' . $mime_type);
390 else
391 $image_string .= "," . $this->getMediaID($base64, $size, 'image/' . $mime_type);
394 return rawurlencode($image_string);
397 function getMediaID($base64, $size, $mime_type){
398 $random_value = OAuthRandom::randomAlphaNumet(32);
399 $timestamp = time();
401 echo "<br/><br/>";
402 /////////////MAKE INIT////////////
403 //post data
404 $media_id = $this->mediaInit($size, $mime_type, $random_value, $timestamp);
406 echo "<br/><br/>";
408 /////////////MAKE APPEND////////////
409 //post data
410 $this->mediaAppend($base64, $media_id, $random_value, $timestamp);
412 echo "<br/><br/>";
414 /////////////MAKE FINAL/
415 $this->makeFinal($media_id, $random_value, $timestamp);
416 echo "<br/><br/>";
418 return $media_id ;
421 function mediaInit($size, $mime, $random_value, $timestamp){
422 $command = "INIT";
423 $method = "HMAC-SHA1";
424 $oauth_version = "1.0";
426 $postfield_string = "command=$command&total_bytes=$size&media_type=$mime";
428 $msg_len = (strlen($postfield_string));
429 //header data
430 // BUILD SIGNATURE
431 $signature = rawurlencode($this->generateSignature(array(
432 "base_url" => $this->media_api,
433 "request_method" => "POST"),
434 array(
435 "command" => "$command",
436 "total_bytes" => "$size",
437 "media_type" => "$mime",
438 "oauth_version" => "$oauth_version",
439 "oauth_nonce"=>"$random_value",
440 "oauth_token"=> $this->oauth_data["oauth_token"],
441 "oauth_timestamp" => "$timestamp",
442 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
443 "oauth_signature_method" => "$method",
445 array(
446 "consumer_secret" => $this->oauth_data["consumer_secret"],
447 "oauth_secret" => $this->oauth_data["oauth_secret"]
453 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
454 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
455 "Content-Length: $msg_len", "Host: upload.twitter.com",
456 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
457 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
460 //request
461 $curl = curl_init($this->media_api);
462 curl_setopt($curl, CURLOPT_POST, 1);
463 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
464 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
465 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
466 $media_id_arr = json_decode(curl_exec($curl), true);
467 print_r ($media_id_arr);
468 return $media_id_arr["media_id_string"];
471 function mediaAppend(&$binary_file, $media_id, $random_value, $timestamp){
472 $command = "APPEND";
473 $method = "HMAC-SHA1";
474 $oauth_version = "1.0";
476 $segment_index = 0;
478 //header data
479 // BUILD SIGNATURE
480 $signature = rawurlencode($this->generateSignature(array(
481 "base_url" => $this->media_api,
482 "request_method" => "POST"),
483 array(
484 "command" => "$command",
485 "media" => "$binary_file",
486 "media_id"=>"$media_id",
487 "segment_index"=>"$segment_index",
488 "oauth_version" => "$oauth_version",
489 "oauth_nonce"=>"$random_value",
490 "oauth_token"=> $this->oauth_data["oauth_token"],
491 "oauth_timestamp" => "$timestamp",
492 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
493 "oauth_signature_method" => "$method",
495 array(
496 "consumer_secret" => $this->oauth_data["consumer_secret"],
497 "oauth_secret" => $this->oauth_data["oauth_secret"]
502 $postfield_string = "media=" . rawurlencode($binary_file) . "&command=$command&media_id=$media_id&segment_index=$segment_index" ;
503 $msg_len = (strlen($postfield_string));
504 $header_data = array("Except:", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
505 "Content-Type: application/x-www-form-urlencoded",
506 "Content-Length: $msg_len", "Host: upload.twitter.com",
507 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
508 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
510 //request
511 $curl = curl_init($this->media_api);
512 curl_setopt($curl, CURLOPT_POST, 1);
513 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
514 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
515 curl_setopt($curl, CURLOPT_HEADER , true);
516 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
517 $http_response = curl_exec($curl);
518 echo $http_response;
521 function makeFinal($media_id, $random_value, $timestamp){
522 $command = "FINALIZE";
523 $method = "HMAC-SHA1";
524 $oauth_version = "1.0";
526 $signature = rawurlencode($this->generateSignature(array(
527 "base_url" => $this->media_api,
528 "request_method" => "POST"),
529 array(
530 "command" => "$command",
531 "media_id"=>"$media_id",
532 "oauth_version" => "$oauth_version",
533 "oauth_nonce"=>"$random_value",
534 "oauth_token"=> $this->oauth_data["oauth_token"],
535 "oauth_timestamp" => "$timestamp",
536 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
537 "oauth_signature_method" => "$method",
539 array(
540 "consumer_secret" => $this->oauth_data["consumer_secret"],
541 "oauth_secret" => $this->oauth_data["oauth_secret"]
544 $postfield_string = "command=$command&media_id=$media_id" ;
545 $msg_len = (strlen($postfield_string));
546 $header_data = array("Except:", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
547 "Content-Type: application/x-www-form-urlencoded",
548 "Content-Length: $msg_len", "Host: upload.twitter.com",
549 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
550 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
552 //request
553 $curl = curl_init($this->media_api);
554 curl_setopt($curl, CURLOPT_POST, 1);
555 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
556 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
557 curl_setopt($curl, CURLOPT_HEADER , true);
558 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
559 $http_response = curl_exec($curl);
560 echo $http_response;
563 function generateSignature($request_arr, $paramater_arr, $secret_arr){
564 // BUILD SIGNATURE
565 $request_method = strtoupper($request_arr["request_method"]);
566 $base_url = rawurlencode($request_arr["base_url"]);
568 ksort($paramater_arr);
569 if(isset($paramater_arr["media"])) $paramater_arr["media"] = rawurlencode($paramater_arr["media"]);
570 $paramter_string = $this->buildOAuthParamaterString($paramater_arr);
572 $base_string = ($request_method . "&" . $base_url . "&" . $paramter_string);
573 $secret_string = $secret_arr["consumer_secret"] . "&" . $secret_arr["oauth_secret"];
574 $signature = (base64_encode(hash_hmac("SHA1",$base_string, $secret_string, true)));
576 return $signature;
579 function buildOAuthParamaterString($paramater_arr){
580 $param_string = "";
581 $join_param_by_amphersand = false;
582 foreach($paramater_arr as $key => $param){
583 if(!$join_param_by_amphersand){
584 $join_param_by_amphersand=true;
586 else{
587 $param_string .= rawurlencode("&");
589 $param_string .= rawurlencode($key . "=" . $param);
591 return $param_string;
596 echo"run script from externals<br/>";