<?php

use Abraham\TwitterOAuth\TwitterOAuth;

// Twitter OAuth Settings:
/* TOPISTO */
define('CONSUMER_KEY', 'HBInbm93bM80z86XVJ34rtjxO');
define('CONSUMER_SECRET', 'zpdSp8yv9R2VODgPRA0RZbiO7VE8vSPNLVNg9zI0HjWnJKADO8');
define('ACCESS_TOKEN', '315679287-EjINhav5VbJPscb4h9pw3WwveeeX0ShpnIjcawDe');
define('ACCESS_TOKEN_SECRET', 'SIFKfPYEoIdlAyeQKVS3y067uNFuLpy013wRycJ8VxNcd');

/* R. Topisto 
define('CONSUMER_KEY', '9Ie6CjwM5eZSQu5Xnbel4PBqm');
define('CONSUMER_SECRET', 'pI4ha5gW7Lft6Lg5xP7nH49Yqbm8PwLn1EP8D1qKg1q0SYd5t2');
define('ACCESS_TOKEN', '840479603143630849-c3xFLJFvo77ubP1njoXHpFu9LQqKLR8');
define('ACCESS_TOKEN_SECRET', 'EW4Zi10cQnNfoOunnEF1svJ3omz223U57G6KuYo5ZZ2Ls');
*/

define('TWITTER_WIDTH', 880);
define('TWITTER_HEIGHT', 440);

class twitter
{
  public static function tweet($message, $media='')
  {
    $twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    $content = $twitter->get('account/verify_credentials');
    if ($twitter->getLastHttpCode() !== 200) return FALSE;

    $parameters = array("status" => $message);

    if (($media != NULL)&&($media != ''))
    {
      $imageMedia = $twitter->upload('media/upload', array('media' => $media));
      if ($twitter->getLastHttpCode() !== 200) return FALSE;

      $parameters = array(
        "status" => $message,
        "media_ids" => $imageMedia->media_id_string);
    }

    $statuses = $twitter->post("statuses/update", $parameters);
    if ($twitter->getLastHttpCode() !== 200) return FALSE;

    return TRUE;
  }

  public static function thanksRetweet()
  {
    $twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    $content = $twitter->get('account/verify_credentials');
    if ($twitter->getLastHttpCode() !== 200) return FALSE;

    $results = $twitter->get('statuses/retweets_of_me');
    if ($twitter->getLastHttpCode() !== 200) return FALSE;

    /* TO DO */

    return TRUE;
  }

  public static function thanksFollowers()
  {
    $twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    $content = $twitter->get('account/verify_credentials');
    if ($twitter->getLastHttpCode() !== 200) return FALSE;

    $results = $twitter->get('followers/list');
    if ($twitter->getLastHttpCode() !== 200) return FALSE;

    $followers = json_decode(file_get_contents('followers.json'));
    foreach($results->users as $user)
      if (!in_array($user->screen_name, $followers))
      {
        $parameters = array("status" => '@'.$user->screen_name.' thanks following me !');
        $followers[] = $user->screen_name;
        $statuses = $twitter->post("statuses/update", $parameters);
        if ($twitter->getLastHttpCode() !== 200) return FALSE;
        break; // Un à la fois ...
      }
    file_put_contents('followers.json', json_encode($followers));

    return TRUE;
  }

}

?>
