CSS styling and loading threads
[Anonymous-Twitter-Board.git] / class / twitter-connection.php
blobdd040b62d60b03171eb2550a16649ebc6e3e7e7d
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";
27 private $oembed_api = "https://publish.twitter.com/oembed";
28 private $default_status_string = "https://twitter.com/:USERNAME/status/";
30 function __construct(){
31 $this->oauth_data = $this->getIniFile("settings/keys.ini");
32 $this->user_info = $this->getIniFile("settings/userinfo.ini");
33 $this->post_properties = $this->getIniFile("settings/postproperties.ini");
34 $this->buildStatusString();
38 function buildStatusString(){
39 $this->default_status_string = str_replace(":USERNAME", $this->user_info["User-Name"], $this->default_status_string);
42 function getIniFile($path){
43 $path_string = fopen($path,"r");
44 $return_array = array();
45 while(!feof($path_string)){
46 $line = fgets($path_string);
47 $key = substr($line,0,strpos($line, "="));
48 //eat last character
49 $value = trim(substr($line, strpos($line, "=")+1));
51 $return_array[$key] = $value;
53 return $return_array;
56 function getEmbededTweet($post_id){
57 $query_string = "url=" . rawurlencode($this->default_status_string . "$post_id");
58 $curl = curl_init($this->oembed_api . "?$query_string");
59 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
60 $content = curl_exec($curl);
62 return json_decode($content,true);
65 function retrieveTimeline(){
66 $highest_post_id = -1;
68 $timeline_arr = $this->getUserTimeline($this->post_properties["TopPostNo"]);
69 $timeline_database_arr = array();
71 if($timeline_arr["errors"][0]["code"] == null && sizeof($timeline_arr) != 0){
72 foreach ($timeline_arr as $timeline_item){
73 $post_id = $timeline_item["id"];
74 $post_text = $timeline_item["text"];
75 $post_image_string = $this->grabTwitterImage($timeline_item);
76 array_push($timeline_database_arr, [$post_id, $post_text, $post_image_string]);
78 $highest_post_id = $post_id > $highest_post_id ? $post_id : $highest_post_id;
81 else echo $timeline_arr["errors"][0]["code"] . "Tim<br/>";
83 echo "<hr>"; //From the post ID try and find any replies
85 $reply_arr = $this->getTweetReplies($this->post_properties["TopPostNo"]);
86 $reply_arr_container = array();
88 if($reply_arr["errors"][0]["code"] == null && sizeof($reply_arr) != 0){
89 $reply_id = 0;
90 foreach($reply_arr as $reply_item){
91 $reply_id = $reply_item["id"];
92 $reply_text = $reply_item["text"];
93 $reply_image_string = $this->grabTwitterImage($reply_item);
94 $responding_to_id = $reply_item['in_reply_to_status_id'];
95 echo "$lowest_post_id -- $responding_to_id<hr/>";
96 array_push($reply_arr_container, [$reply_id, $reply_text, $reply_image_string, $responding_to_id]);
98 $highest_post_id = $reply_id > $highest_post_id ? $reply_id : $highest_post_id;
101 else echo $reply_arr["errors"][0]["code"] . "Rep<br/>";
103 if(sizeof($timeline_database_arr) + sizeof($reply_arr_container) == 0){
104 echo "No Updates<hr/>";
105 return;
107 else{
108 $postfile = fopen("settings/postproperties.ini", "w");
109 echo "TopPostNo=$highest_post_id<br/>";
110 fwrite($postfile, "TopPostNo=$highest_post_id");
113 $combined_database_arr = array_merge ($timeline_database_arr, $reply_arr_container);
114 $database_connection = new QueueDatabaseConstruction(true);
116 echo "<hr>";
118 $this->recursiveEchoJson($combined_database_arr,0);
119 echo "<pre>";
120 if(sizeof($timeline_database_arr) != 0){
121 $this->addTimelineTweetsToDatabase($combined_database_arr, $database_connection);
123 echo "</pre>";
125 $database_connection = null;
128 function deleteExpiredEntries(){
129 $database_connection = new QueueDatabaseConstruction(true);
131 $threads = $database_connection->getThreads();
132 $thread_count = 0;
133 foreach($threads as $thread){
134 $thread_count++;
135 if($thread_count > 7){
136 var_dump ($thread);
137 $database_connection->deleteFromUnprocessedImageString($thread["ImageURL"]);
138 $database_connection->recursiveDeleteResponses($thread[0]);
139 $database_connection->deleteThread("Tweet", $thread[0]);//0 is the most relevant PostID
142 $database_connection = null;
146 function endConnection(){
147 $this->database_connection = null;
150 function grabTwitterImage($tweet_array){
151 $first_join = false;
152 $image_url_string = null;
153 echo "<hr/>";
154 if($tweet_array["extended_entities"] != null){
155 foreach($tweet_array["extended_entities"] ["media"] as $entity){
156 $filename_url ="";
157 if(isset($entity["video_info"])){
158 $filename_url = $entity["video_info"]["variants"][0]["url"];
159 $extention = pathinfo($filename_url, PATHINFO_EXTENSION );
160 echo "$filename_url $extention";
162 else{
163 $filename_url = $entity["media_url_https"];
164 $extention = pathinfo($filename_url , PATHINFO_EXTENSION );
167 $filename = "images/" . (microtime(true) * 10000) . (rand(0,10000)) . ".$extention";
168 $this->uploadMedia($filename, $filename_url);
169 if(!$first_join){
170 $first_join = true;
171 $image_url_string = rawurlencode($filename);
173 else $image_url_string .= "," . rawurlencode($filename);
177 return $image_url_string;
180 function recursiveEchoJson($json, $indents){
181 echo "<pre>";
182 foreach($json as $key => $attribute){
183 if(is_array ($attribute)){
184 $this->makeIndents($indents);
185 echo "$key {\n";
187 $this->recursiveEchoJson($attribute, ++$indents);
189 $this->makeIndents(--$indents);
190 echo "}\n";
192 else{
193 $this->makeIndents($indents);
194 echo "$key = $attribute \n";
197 echo "</pre>";
198 if($indents == 1) echo "<hr/>";
201 function makeIndents($indent_count){
202 for ($i = 0; $i < $indent_count ; $i++){ echo "\t"; }
205 function addTimelineTweetsToDatabase($timeline_database_arr, $database_connection){
206 var_dump($timeline_database_arr);
207 foreach($timeline_database_arr as $key => $timeline_item){
208 $database_connection->addToTable("Tweet", array("PostID"=>$timeline_item[0],
209 "PostText"=> $timeline_item[1], "ImageURL"=> $timeline_item[2]));
210 if($timeline_item[3] !== null)
211 $database_connection->addToTable("Response", array("PostID"=>$timeline_item[0], "RepliesTo"=>$timeline_item[3]));
214 function uploadMedia($filename,$url){
215 file_put_contents($filename, fopen($url, 'r'));
218 function getUserTimeline($since_id = 976628662446551043, $count = 100){
220 $random_value = OauthRandom::randomAlphaNumet(32);
221 $method = "HMAC-SHA1";
222 $oauth_version = "1.0";
223 $timestamp = time();
224 $reply_exclude = "false";
226 echo $this->user_info["User-ID"];
228 $get_fields = "since_id=" . $since_id . "&count=" . $count . "&include_rts=false&exclude_replies=$reply_exclude&user_id=" . $this->user_info["User-ID"];
229 //$msg_len = (strlen($this->user_timeline_api . "?$get_fields")); //GET REQUESTS HAVE NO DYNAMIC LENGTH
231 $param_array = array( "user_id" => $this->user_info["User-ID"],
232 "since_id" => "$since_id",
233 "exclude_replies"=>"$reply_exclude",
234 "count" => "$count",
235 "include_rts" => "false",
236 "oauth_version" => "$oauth_version",
237 "oauth_nonce"=>"$random_value",
238 "oauth_token"=> $this->oauth_data["oauth_token"],
239 "oauth_timestamp" => "$timestamp",
240 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
241 "oauth_signature_method" => "$method"
244 $signature = rawurlencode($this->generateSignature(array(
245 "base_url" => $this->user_timeline_api,
246 "request_method" => "GET"),
247 $param_array,
248 array(
249 "consumer_secret" => $this->oauth_data["consumer_secret"],
250 "oauth_secret" => $this->oauth_data["oauth_secret"]
254 $param_array["oauth_signature"] = $signature;
255 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
256 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", "Host: api.twitter.com",
257 $this->buildAuthorizationString($param_array));
259 //request
260 echo "<hr/>";
261 $curl = curl_init($this->user_timeline_api . "?$get_fields");
262 curl_setopt($curl, CURLOPT_HTTPGET, 1);
263 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
264 curl_setopt($curl, CURLOPT_HEADER, false);
265 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
266 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER , false);
268 echo "<br/>-- Fin -- <hr/>";
269 $content = curl_exec($curl);
270 return json_decode(($content), true);
275 function getTweetReplies($current_post_id, $max_post_id = -1){
276 $random_value = OauthRandom::randomAlphaNumet(32);
277 $method = "HMAC-SHA1";
278 $oauth_version = "1.0";
279 $timestamp = time();
282 $get_fields = "since_id=" . $current_post_id;
283 $param_array = array(
284 "since_id" => "$current_post_id",
285 "oauth_version" => "$oauth_version",
286 "oauth_nonce"=>"$random_value",
287 "oauth_token"=> $this->oauth_data["oauth_token"],
288 "oauth_timestamp" => "$timestamp",
289 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
290 "oauth_signature_method" => "$method"
292 if($max_post_id > 0){
293 $get_fields .= $max_post_id > 0 ? "&max_id=" . $max_post_id : "";
294 $param_array["max_id"] = "$max_post_id";
297 $signature = rawurlencode($this->generateSignature(array(
298 "base_url" => $this->mention_timeline_api,
299 "request_method" => "GET"),
300 $param_array,
301 array(
302 "consumer_secret" => $this->oauth_data["consumer_secret"],
303 "oauth_secret" => $this->oauth_data["oauth_secret"]
306 $param_array["oauth_signature"] = $signature;
307 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
308 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", "Host: api.twitter.com",
309 $this->buildAuthorizationString($param_array));
311 //request
312 $curl = curl_init($this->mention_timeline_api . "?$get_fields");
313 curl_setopt($curl, CURLOPT_HTTPGET, 1);
314 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
315 curl_setopt($curl, CURLOPT_HEADER, false);
316 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
317 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER , false);
318 $content = curl_exec($curl);
319 return json_decode(($content), true);
325 function buildAuthorizationString($parameters){
326 $authorization_string = 'Authorization: OAuth ';
328 ksort($parameters);
329 $is_first_join = false;
330 foreach($parameters as $key => $value){
331 if(!$is_first_join){
332 $is_first_join = true;
333 $authorization_string .= $key . '="' . $value . '"';
335 else{
336 $authorization_string .= "," . $key . '="' . $value . '"';
339 return $authorization_string;
342 function makeTweet($comment, $file_arr){
343 $image_string = $this->addTweetMedia($file_arr);
345 //access info
346 $request_method = "POST";
348 //message info
349 $encode_tweet_msg = rawurlencode($comment);
350 $include_entities = "true";
352 //append to postfield_string the media code via media_ids=$media_id
353 $postfield_string = "include_entities=$include_entities&status=$encode_tweet_msg&media_ids=$image_string";
354 $msg_len = (strlen($postfield_string));
356 $random_value = OauthRandom::randomAlphaNumet(32);
357 $method = "HMAC-SHA1";
358 $oauth_version = "1.0";
359 $timestamp = time();
361 $param_array = array("include_entities" => "$include_entities",
362 "status" => "$encode_tweet_msg",
363 "media_ids" => "$image_string",
364 "oauth_version" => "$oauth_version",
365 "oauth_nonce"=>"$random_value",
366 "oauth_token"=> $this->oauth_data["oauth_token"],
367 "oauth_timestamp" => "$timestamp",
368 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
369 "oauth_signature_method" => "$method"
372 //add media id to the signature
373 $signature = rawurlencode($this->generateSignature(array(
374 "base_url" => $this->status_api,
375 "request_method" => $request_method),
376 $param_array,
377 array(
378 "consumer_secret" => $this->oauth_data["consumer_secret"],
379 "oauth_secret" => $this->oauth_data["oauth_secret"]
383 $param_array["oauth_signature"] = $signature;
384 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,
385 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
386 "Content-Length: $msg_len", "Host: api.twitter.com",
387 $this->buildAuthorizationString($param_array));
389 //request
390 echo "<hr/>";
391 $curl = curl_init($this->status_api);
392 curl_setopt($curl, CURLOPT_POST, 1);
393 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
394 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
395 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
396 echo "<br/>-- Fin -- <hr/>";
397 $content = curl_exec($curl);
398 var_dump (json_decode($content, true));
399 return json_decode($content, true);
402 function addTweetMedia($file_arr){
404 //image info
405 $image_string = "";//delimited by ',' commas
406 for($file = 0 ; $file < count($file_arr) ; $file++){
407 if($file_arr[$file] != ""){
408 //create data in binary/b64
409 $mime_type = pathinfo($file_arr[$file], PATHINFO_EXTENSION);
410 $file_arr[$file] = urldecode($file_arr[$file]);
411 $binary = file_get_contents($file_arr[$file]);
413 $base64 = base64_encode($binary);
415 //upload file to twitter and get id for use in files
416 $size = filesize($file_arr[$file]);
417 if($file == 0)
418 $image_string = $this->getMediaID($base64, $size, 'image/' . $mime_type);
419 else
420 $image_string .= "," . $this->getMediaID($base64, $size, 'image/' . $mime_type);
423 return rawurlencode($image_string);
426 function getMediaID($base64, $size, $mime_type){
427 $random_value = OAuthRandom::randomAlphaNumet(32);
428 $timestamp = time();
430 echo "<br/><br/>";
431 /////////////MAKE INIT////////////
432 //post data
433 $media_id = $this->mediaInit($size, $mime_type, $random_value, $timestamp);
435 echo "<br/><br/>";
437 /////////////MAKE APPEND////////////
438 //post data
439 $this->mediaAppend($base64, $media_id, $random_value, $timestamp);
441 echo "<br/><br/>";
443 /////////////MAKE FINAL/
444 $this->makeFinal($media_id, $random_value, $timestamp);
445 echo "<br/><br/>";
447 return $media_id ;
450 function mediaInit($size, $mime, $random_value, $timestamp){
451 $command = "INIT";
452 $method = "HMAC-SHA1";
453 $oauth_version = "1.0";
455 $postfield_string = "command=$command&total_bytes=$size&media_type=$mime";
457 $msg_len = (strlen($postfield_string));
458 //header data
459 // BUILD SIGNATURE
460 $signature = rawurlencode($this->generateSignature(array(
461 "base_url" => $this->media_api,
462 "request_method" => "POST"),
463 array(
464 "command" => "$command",
465 "total_bytes" => "$size",
466 "media_type" => "$mime",
467 "oauth_version" => "$oauth_version",
468 "oauth_nonce"=>"$random_value",
469 "oauth_token"=> $this->oauth_data["oauth_token"],
470 "oauth_timestamp" => "$timestamp",
471 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
472 "oauth_signature_method" => "$method",
474 array(
475 "consumer_secret" => $this->oauth_data["consumer_secret"],
476 "oauth_secret" => $this->oauth_data["oauth_secret"]
482 $header_data = array("Accept: */*", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
483 "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
484 "Content-Length: $msg_len", "Host: upload.twitter.com",
485 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
486 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
489 //request
490 $curl = curl_init($this->media_api);
491 curl_setopt($curl, CURLOPT_POST, 1);
492 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
493 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
494 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
495 $media_id_arr = json_decode(curl_exec($curl), true);
496 print_r ($media_id_arr);
497 return $media_id_arr["media_id_string"];
500 function mediaAppend(&$binary_file, $media_id, $random_value, $timestamp){
501 $command = "APPEND";
502 $method = "HMAC-SHA1";
503 $oauth_version = "1.0";
505 $segment_index = 0;
507 //header data
508 // BUILD SIGNATURE
509 $signature = rawurlencode($this->generateSignature(array(
510 "base_url" => $this->media_api,
511 "request_method" => "POST"),
512 array(
513 "command" => "$command",
514 "media" => "$binary_file",
515 "media_id"=>"$media_id",
516 "segment_index"=>"$segment_index",
517 "oauth_version" => "$oauth_version",
518 "oauth_nonce"=>"$random_value",
519 "oauth_token"=> $this->oauth_data["oauth_token"],
520 "oauth_timestamp" => "$timestamp",
521 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
522 "oauth_signature_method" => "$method",
524 array(
525 "consumer_secret" => $this->oauth_data["consumer_secret"],
526 "oauth_secret" => $this->oauth_data["oauth_secret"]
531 $postfield_string = "media=" . rawurlencode($binary_file) . "&command=$command&media_id=$media_id&segment_index=$segment_index" ;
532 $msg_len = (strlen($postfield_string));
533 $header_data = array("Except:", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
534 "Content-Type: application/x-www-form-urlencoded",
535 "Content-Length: $msg_len", "Host: upload.twitter.com",
536 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
537 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
539 //request
540 $curl = curl_init($this->media_api);
541 curl_setopt($curl, CURLOPT_POST, 1);
542 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
543 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
544 curl_setopt($curl, CURLOPT_HEADER , true);
545 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
546 $http_response = curl_exec($curl);
547 echo $http_response;
550 function makeFinal($media_id, $random_value, $timestamp){
551 $command = "FINALIZE";
552 $method = "HMAC-SHA1";
553 $oauth_version = "1.0";
555 $signature = rawurlencode($this->generateSignature(array(
556 "base_url" => $this->media_api,
557 "request_method" => "POST"),
558 array(
559 "command" => "$command",
560 "media_id"=>"$media_id",
561 "oauth_version" => "$oauth_version",
562 "oauth_nonce"=>"$random_value",
563 "oauth_token"=> $this->oauth_data["oauth_token"],
564 "oauth_timestamp" => "$timestamp",
565 "oauth_consumer_key" => $this->oauth_data["oauth_consumer_key"],
566 "oauth_signature_method" => "$method",
568 array(
569 "consumer_secret" => $this->oauth_data["consumer_secret"],
570 "oauth_secret" => $this->oauth_data["oauth_secret"]
573 $postfield_string = "command=$command&media_id=$media_id" ;
574 $msg_len = (strlen($postfield_string));
575 $header_data = array("Except:", "Connection: close","User-Agent: VerniyXYZ-CURL" ,"Content-Transfer-Encoding: binary",
576 "Content-Type: application/x-www-form-urlencoded",
577 "Content-Length: $msg_len", "Host: upload.twitter.com",
578 'Authorization: OAuth oauth_consumer_key="' . $this->oauth_data["oauth_consumer_key"] .'",oauth_nonce="' . $random_value . '",oauth_signature="' .
579 $signature . '",oauth_signature_method="' .$method . '"' . ',oauth_timestamp="' . $timestamp . '",oauth_token="' . $this->oauth_data["oauth_token"] . '",oauth_version="' . $oauth_version . '"'
581 //request
582 $curl = curl_init($this->media_api);
583 curl_setopt($curl, CURLOPT_POST, 1);
584 curl_setopt($curl, CURLOPT_HTTPHEADER, $header_data);
585 curl_setopt($curl, CURLOPT_POSTFIELDS, $postfield_string);
586 curl_setopt($curl, CURLOPT_HEADER , true);
587 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
588 $http_response = curl_exec($curl);
589 echo $http_response;
592 function generateSignature($request_arr, $paramater_arr, $secret_arr){
593 // BUILD SIGNATURE
594 $request_method = strtoupper($request_arr["request_method"]);
595 $base_url = rawurlencode($request_arr["base_url"]);
597 ksort($paramater_arr);
598 if(isset($paramater_arr["media"])) $paramater_arr["media"] = rawurlencode($paramater_arr["media"]);
599 $paramter_string = $this->buildOAuthParamaterString($paramater_arr);
601 $base_string = ($request_method . "&" . $base_url . "&" . $paramter_string);
602 $secret_string = $secret_arr["consumer_secret"] . "&" . $secret_arr["oauth_secret"];
603 $signature = (base64_encode(hash_hmac("SHA1",$base_string, $secret_string, true)));
605 return $signature;
608 function buildOAuthParamaterString($paramater_arr){
609 $param_string = "";
610 $join_param_by_amphersand = false;
611 foreach($paramater_arr as $key => $param){
612 if(!$join_param_by_amphersand){
613 $join_param_by_amphersand=true;
615 else{
616 $param_string .= rawurlencode("&");
618 $param_string .= rawurlencode($key . "=" . $param);
620 return $param_string;
625 echo"run script from externals<br/>";