Beispiel #1
1
<?php

require 'API/TwitterAPIExchange.php';
$settings = array('oauth_access_token' => 'Your Access App Token', 'oauth_access_token_secret' => 'Your Access Secret App Token', 'consumer_key' => 'Your consumer_key', 'consumer_secret' => 'Tu Consumer_Secret');
$url = "https://api.twitter.com/1.1/statuses/update.json";
$requestMethod = 'POST';
//
$postfields = array('status' => 'Hola este es mi segundo Tweet, Gracias a todos #AprendanPHP');
// Crear la instancia de conexion con twitter
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
Beispiel #2
0
function postTwitter()
{
    $url = 'https://upload.twitter.com/1.1/media/upload.json';
    $requestMethod = 'POST';
    $settings = array('consumer_key' => "yyDZQ8MvKof6NKHjh15jrFu8I", 'consumer_secret' => "aY2RJcTyM7HVyyUXMIedrGEW3OVVwE1F4f4gnSMB0yrjZJnKMg", 'oauth_access_token' => "711228384077074432-zQwT4Xlvy1cuxBM6rtyUxJdPafrtDQh", 'oauth_access_token_secret' => "ZgSXDRYwXAPlS81HuRvJlouh5zWJJMK4niFzeLzAa7YAL");
    $postfields = array('media_data' => base64_encode(file_get_contents(getCaminhoImagem(getConnection()))));
    try {
        $twitter = new TwitterAPIExchange($settings);
        echo "Enviando imagem...\n";
        $retorno = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(true);
        echo $retorno . "\n";
        $retorno = json_decode($retorno);
        if (isset($retorno->error) && $retorno->error != "") {
            return false;
        }
        $url = 'https://api.twitter.com/1.1/statuses/update.json';
        $requestMethod = 'POST';
        /** POST fields required by the URL above. See relevant docs as above **/
        $postfields = array('status' => 'If you like SEXY GIRLS visit http://sluttyfeed.com/ - The best P**N on internet! - #p**n #adult #hot #xxx', 'media_ids' => $retorno->media_id_string);
        echo "\nPostando no twitter...\n";
        $retorno = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
        echo $retorno . "\n";
        $retorno = json_decode($retorno);
        if (isset($retorno->errors)) {
            return false;
        }
        echo "Postado!\n";
        return true;
    } catch (Exception $ex) {
        echo $ex->getMessage();
        return false;
    }
}
Beispiel #3
0
 /**
  * request method for accessing twitter endpoints
  * 
  * 
  * @param string $url
  * @param string $method
  * @param array $fields
  * @return string
  * @throws Exception
  */
 public function request($url, $method = 'POST', $fields = array())
 {
     if (!isset($url)) {
         throw new Exception('SERVER: Unable to submit request to an empty URL.');
     }
     if ($method == 'GET') {
         if (!empty($fields)) {
             $queryStr = http_build_query($fields);
             return $this->twitterAPIExchange->setGetfield($queryStr)->buildOauth($url, $method)->performRequest();
         }
     }
     if ($method == 'POST') {
         return $this->twitterAPIExchange->buildOauth($url, $method)->setPostfields($fields)->performRequest();
     }
 }
 private function postRequest($url, $params = array())
 {
     $postFields = array();
     foreach ($params as $key => $value) {
         $postFields[$key] = $value;
     }
     $twitter = new TwitterAPIExchange($this->creds['oauth']);
     $response = $twitter->buildOauth($url, 'POST')->setPostfields($postFields)->performRequest();
     return $response;
 }
function follow($usuario)
{
    ini_set('display_errors', 1);
    require_once 'plugins/twitter-api-exchange/TwitterAPIExchange.php';
    $settings = array('oauth_access_token' => get_option("access_token"), 'oauth_access_token_secret' => get_option("access_token_secret"), 'consumer_key' => get_option("consumer_key"), 'consumer_secret' => get_option("consumer_secret"));
    $url = 'https://api.twitter.com/1.1/friendships/create.json';
    $requestMethod = 'POST';
    $postfields = array('screen_name' => $usuario, 'follow' => "true");
    $twitter = new TwitterAPIExchange($settings);
    return $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
}
Beispiel #6
0
 /**
  * Загрузка изображений
  * $file - путь к загружаемому файлу
  */
 public function uploadImg($file)
 {
     $file = file_get_contents(MODX_BASE_PATH . $file);
     $data = base64_encode($file);
     $url = 'https://upload.twitter.com/1.1/media/upload.json';
     $requestMethod = 'POST';
     $postfields = array('media_data' => $data);
     $twitter = new TwitterAPIExchange($this->twKeys);
     $request = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
     $response = json_decode($request);
     return $response;
 }
 /**
  * @param string $level
  * @param string $message
  * @param array  $context
  */
 public function log($level, $message, array $context = [])
 {
     $message = '[' . strtoupper($level) . '] ' . $message;
     // Set access tokens here - see: https://apps.twitter.com/
     $settings = ['oauth_access_token' => $this->oAuthAccessToken, 'oauth_access_token_secret' => $this->oAuthAccessTokenSecret, 'consumer_key' => $this->consumerKey, 'consumer_secret' => $this->consumerKeySecret];
     // URL for REST request, see: https://dev.twitter.com/rest/public
     $url = 'https://api.twitter.com/1.1/direct_messages/new.json';
     $requestMethod = 'POST';
     // POST fields required by the URL above. See relevant docs as above
     $postfields = ['screen_name' => $this->receiverScreenName, 'text' => $message];
     // Perform the request and echo the response
     $twitter = new \TwitterAPIExchange($settings);
     $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(false);
 }
Beispiel #8
0
/**
 * send @a message with @a picture to twitter.
 * Supported image formats are PNG, JPG and GIF (Animated GIFs are not supported).
 */
function twitter_pic2twitter($message, $picture)
{
    // Documentation see:
    // https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
    $url = 'https://api.twitter.com/1.1/statuses/update_with_media.json ';
    $requestMethod = 'POST';
    // POST fields
    $postfields = array('status' => $txt, 'media' => array(), 'lat' => '41.02', 'long' => '28.97', 'display_coordinates' => false);
    // Perform a POST request and echo the response
    $twitter = new TwitterAPIExchange($settings);
    $result = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
    if (get_debug()) {
        echo $result;
    }
}
function twitter_is_user_following($twitterUser)
{
    global $twitterAuth;
    global $twitterApiUrls;
    $twitter = new TwitterAPIExchange($twitterAuth);
    $twitter->buildOauth($twitterApiUrls["get_followers_list"], "GET");
    $followers = json_decode($twitter->performRequest());
    $following = false;
    //die (print_r($followers->users, true));
    foreach ($followers->users as $follower) {
        if ($follower->screen_name == $twitterUser) {
            $following = true;
            break;
        }
    }
    return $following;
}
 public function actionSendtwitterblast()
 {
     ini_set('display_errors', 1);
     $message = $_POST['message'];
     $settings = array('oauth_access_token' => "408895167-RW2Sd8IZddrzViscHqGHYysS414Hj92KqOPnEb4l", 'oauth_access_token_secret' => "10c2ZXjIOgAvcMAWgfp8qc87tbgrQIVorrQ7J6h5dTl7m", 'consumer_key' => "nvUS5zpy2CSYAwJ1vvtYbdmK6", 'consumer_secret' => "tZDsbHSFLCwGnt197ISN3OmK3fn1EdtQyYhMg9fpXU6P92sDJv");
     $url = 'https://api.twitter.com/1.1/direct_messages/new.json';
     $requestMethod = 'POST';
     $connect = Yii::$app->db;
     $account = $connect->createCommand("SELECT ACCOUNT FROM TEST_TWITTER WHERE ROWNUM <= 5")->queryAll();
     foreach ($account as $rows) {
         $akun = $rows['ACCOUNT'];
         // array_push($postfields, array('screen_name' => $akun));
         $postfields = array('text' => $message, 'screen_name' => 'Jutaan SME Telkom');
         $twitter = new TwitterAPIExchange($settings);
         echo $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
     }
 }
Beispiel #11
0
 /**
  * @param Model_User $to
  * @param Model_User $from
  * @param string $message
  * @return bool|string
  */
 public function send($to, $from = "", $message = "")
 {
     if ($message == "") {
         // Construct Tweet
         $message = "@" . $to->getTwitterUsername() . " you were upvoted by @" . $from->getTwitterUsername() . " on magehero.com/" . $to->getGithubUsername();
     }
     $settings = array('oauth_access_token' => $this->_localConfig->get('twitter_oauth_access_token'), 'oauth_access_token_secret' => $this->_localConfig->get('twitter_oauth_access_token_secret'), 'consumer_key' => $this->_localConfig->get('twitter_consumer_api_key'), 'consumer_secret' => $this->_localConfig->get('twitter_consumer_api_secret'));
     $url = 'https://api.twitter.com/1.1/statuses/update.json';
     $requestMethod = 'POST';
     $postfields = array("status" => $message);
     try {
         $twitter = new TwitterAPIExchange($settings);
         $response = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
         // Error handling for tweet failurs , is not required. I am pretty sure that the voters are not interested
         // in knowing if the tweet was posted or now.
         return $response;
     } catch (Exception $e) {
         return false;
     }
     //var_dump(json_decode($response));die;
 }
Beispiel #12
0
function tweet()
{
    global $APIsettings;
    $categoryCodes = array('w', 'n', 'b', 'tc', 'e', 's');
    $firstIdx = array_rand($categoryCodes);
    $firstCat = $categoryCodes[$firstIdx];
    unset($categoryCodes[$firstIdx]);
    $categoryCodes = array_values($categoryCodes);
    $topics = getTopics($firstCat);
    if (count($topics) > 0) {
        $firstTopic = $topics[array_rand($topics)];
        $headline = getHeadline($firstTopic);
        if ($headline != null && strstr($headline, $firstTopic->name) !== false) {
            $secondCat = $categoryCodes[array_rand($categoryCodes)];
            $newTopics = getTopics($secondCat);
            if (count($newTopics) > 0) {
                $secondTopic = $newTopics[array_rand($newTopics)];
                $newHeadline = str_replace($firstTopic->name, $secondTopic->name, $headline);
                if (strlen($newHeadline) < 141) {
                    // Post the tweet
                    $postfields = array('status' => $newHeadline);
                    $url = "https://api.twitter.com/1.1/statuses/update.json";
                    $requestMethod = "POST";
                    $twitter = new TwitterAPIExchange($APIsettings);
                    echo $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
                } else {
                    tweet();
                }
            } else {
                tweet();
            }
        } else {
            tweet();
        }
    } else {
        tweet();
    }
}
Beispiel #13
0
function sendDirectMessage($param)
{
    $url = $param['api_end_point'] . '/direct_messages/new.json';
    $screen_name = $param['params']['screen_name'];
    $text = $param['params']['message'];
    $requestMethod = 'POST';
    $postFields = array("screen_name" => $screen_name, 'text' => $text);
    $twitter = new TwitterAPIExchange($param['settings']);
    $response = $twitter->buildOauth($url, $requestMethod)->setPostfields($postFields)->performRequest();
    return $response;
}
Beispiel #14
0
            if (strpos($te, '!') !== false && strpos($te, 'http') == false) {
                $toTweetString .= str_replace("!", "?", $te) . ' ';
                $exclaimCount++;
            } else {
                $toTweetString .= $te . ' ';
            }
        }
        if ($exclaimCount > 0) {
            $ripstring = str_replace("&amp;", "&", $toTweetString);
            $ripstring = substr($ripstring, 0, 140);
            //$ripstring = rawurlencode($ripstring);
            //if($client == 'cli') {
            $twitterNew = new TwitterAPIExchange($settings);
            $postfields = array('status' => $ripstring);
            if (strpos($connectingip, 'the.only.allowed.ip') !== false) {
                $postedTweet = $twitterNew->buildOauth('https://api.twitter.com/1.1/statuses/update.json', 'POST')->setPostfields($postfields)->performRequest();
            } else {
            }
            file_put_contents('tweetattempts.html', date('m-d-Y h:iA') . '-' . $usuableTweets . '<br/>' . $postedTweet . '<br/>' . $connectingip . '<br/><br/>', FILE_APPEND | LOCK_EX);
            array_unshift($oldArray, $tweet_id);
            array_push($newIDs, $tweet_id);
            //}
            echo $toTweetString . '<br/><br/>';
            $usuableTweets++;
        }
    } else {
    }
}
//MAKE THE NEW FILE
$info = 'Last Update: ' . date('m-d-Y h:iA') . '<br/> From: ' . $client . '<br/> Number of Tweets: ' . $usuableTweets . '<br/> IP: ' . $_SERVER['REMOTE_ADDR'] . '<br/>Since: ' . $lastTweet . '<br/>Most Recent: ' . $most_recent;
file_put_contents('lastUpdate.html', $info);
 /**
  * Check requirements and publish new discussion to Twitter.
  *
  * @param object $sender DiscussionModel.
  * @param array $args EventArguments.
  * @return void.
  * @package TwitterBot
  * @since 0.1
  */
 public function discussionModel_afterSaveDiscussion_handler($sender, $args)
 {
     $discussion = $args['Discussion'];
     // Exit if this discussion has already been twittered.
     if ($discussion->Attributes['TwitterBot'] == true) {
         return;
     }
     // Exit if discussions from this category shouldn't be twittered
     if (!in_array($discussion->CategoryID, Gdn::config('TwitterBot.CategoryIDs'))) {
         return;
     }
     // Exit if the current user hasn't the permission to twitter
     $roleIds = array_keys(Gdn::userModel()->getRoles($discussion->InsertUserID));
     if (array_intersect($roles, Gdn::config('TwitterBot.RoleIDs'))) {
         return;
     }
     // Exit if only announcements shall be twittered and this is no announcements
     if (Gdn::config('TwitterBot.AnnouncementsOnly') && !$discussion->Announce) {
         return;
     }
     // Exit if checkbox is shown and not ticked
     if (Gdn::config('TwitterBot.ShowCheckbox') && !$args['FormPostValues']['TwitterBot']) {
         return;
     }
     // Exit if plugin is not configured
     $consumerKey = Gdn::config('TwitterBot.ConsumerKey');
     $consumerSecret = Gdn::config('TwitterBot.ConsumerSecret');
     $oAuthAccessToken = Gdn::config('TwitterBot.OAuthAccessToken');
     $oAuthAccessTokenSecret = Gdn::config('TwitterBot.OAuthAccessTokenSecret');
     if (!$consumerKey || !$consumerSecret || !$oAuthAccessToken || !$oAuthAccessTokenSecret) {
         return;
     }
     $title = $discussion->Name;
     $body = Gdn_Format::to($discussion->Body, $discussion->Format);
     $author = $discussion->InsertName;
     $date = $discussion->DateInserted;
     $category = $discussion->Category;
     $url = $discussion->Url;
     $tweet = '"' . $title . '" by ' . $author;
     require_once __DIR__ . '/library/vendors/twitter-api-php/TwitterAPIExchange.php';
     $settings = array('oauth_access_token' => $oAuthAccessToken, 'oauth_access_token_secret' => $oAuthAccessTokenSecret, 'consumer_key' => $consumerKey, 'consumer_secret' => $consumerSecret);
     $twitter = new TwitterAPIExchange($settings);
     $response = $twitter->buildOauth('https://api.twitter.com/1.1/statuses/update.json', 'POST')->setPostfields(array('status' => $tweet))->performRequest();
     $response = json_decode($response, true);
     if (isset($response['created_at'])) {
         // Gdn::controller()->informMessage('This discussion has been published on Twitter', 'Dismissable');
         Gdn::discussionModel()->saveToSerializedColumn('Attributes', $discussion->DiscussionID, 'TwitterBot', true);
     }
 }
Beispiel #16
0
 function tweet()
 {
     Configure::write('debug', 0);
     $this->layout = 'ajax';
     if (!App::import('Lib', 'twitter_api_exchange')) {
         $this->set('message', sprintf(__('Failed to load the %s library! Contact your system administrator.', true), 'Twitter API Exchange'));
         return;
     }
     $this->Game->HomeTeam->Person->contain();
     $person = $this->Game->HomeTeam->Person->read(array('twitter_token', 'twitter_secret'), $this->UserCache->currentId());
     if (empty($person['Person']['twitter_token']) || empty($person['Person']['twitter_secret'])) {
         $this->set('message', __('You have not authorized this site to tweet on your behalf. Configure this in the Profile Preferences page.', true));
         return;
     }
     $settings = array('consumer_key' => Configure::read('twitter.consumer_key'), 'consumer_secret' => Configure::read('twitter.consumer_secret'), 'oauth_access_token' => $person['Person']['twitter_token'], 'oauth_access_token_secret' => $person['Person']['twitter_secret']);
     $url = 'https://api.twitter.com/1.1/statuses/update.json';
     $postfields = array('status' => $this->data['Twitter']['message'], 'lat' => $this->data['Twitter']['lat'], 'long' => $this->data['Twitter']['long']);
     $twitter = new TwitterAPIExchange($settings);
     $response = json_decode($twitter->buildOauth($url, 'POST')->setPostfields($postfields)->performRequest());
     if (!empty($response->id_str)) {
         $this->set('message', __('Your message has been tweeted.', true));
     } else {
         $this->set('message', __('Failed to send the tweet.', true) . ' ' . $response->errors[0]->message);
     }
 }
if (isset($_POST['tweet'])) {
    require_once 'TwitterAPIExchange.php';
    /* tokens */
    $settings = array('oauth_access_token' => '102024246-fPvUBae3FMD1Ab4zQDxzi7SUSvOYPpkZnbaWGNHE', 'oauth_access_token_secret' => 'aBYuCbiItkU99caHK8S4mIzbUBnx8YSB7IP4HrbRpjYTg', 'consumer_key' => 'Sgym1Ov9J4opgdB7gNtQHC0tP', 'consumer_secret' => '5icBNUmq3GcWhT7seMzD34SLMBhAXbCDMBQiOBe4sqZ9gEiXrw');
    // populate
    $tweet = $_POST['tweet'];
    // sanitasi tweet
    // post tweet request settings
    $url = 'https://api.twitter.com/1.1/statuses/update.json';
    $requestmethod = 'POST';
    $postFields = array('status' => $tweet);
    // instance TwitterAPIExchange
    $twitterAPIExchange = new TwitterAPIExchange($settings);
    // throw request
    // then decode json to associative array
    $response = json_decode($twitterAPIExchange->buildOauth($url, $requestmethod)->setPostfields($postFields)->performRequest(), $assoc = true);
    // check for error
    if (isset($response["errors"])) {
        echo "<h3>Oops, we encountered a problem.</h3><p>Here's error message:</p><p><em>" . $response["errors"][0]["message"] . "</em></p>";
        exit;
    }
} else {
    ?>

<form method="post" action="?">
	<textarea name="tweet" id="" cols="30" rows="10"></textarea>
	<input type="submit" value="Tweet">
</form>

<?php 
}
Beispiel #18
0
function bbp_tweet_create_tweet($oauth, $message)
{
    require_once 'functions/twitter-api.php';
    // Including Twitter API wrapper
    // Retweeting the tweet - https://dev.twitter.com/rest/reference/post/statuses/update
    $tweet_url = 'https://api.twitter.com/1.1/statuses/update.json';
    $post_fields = array('status' => $message);
    $request_method = 'POST';
    $twitter = new TwitterAPIExchange($oauth);
    $response = $twitter->buildOauth($tweet_url, $request_method)->setPostfields($post_fields)->performRequest();
}
Beispiel #19
0
 public function post($url, $params = array())
 {
     $twitter = new TwitterAPIExchange($settings);
     return $twitter->buildOauth($url, 'POST')->setPostfields($params)->performRequest();
 }
Beispiel #20
0
<!DOCTYPE html>

<html>
	<?php 
ini_set('display_errors', 1);
require_once 'TwitterAPIExchange.php';
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array('oauth_access_token' => "260761339-a3pWqxRpZV0y9A0QyTVnRLVWOzlmX0x8bfN58g4N", 'oauth_access_token_secret' => "rKKWoOtvG1rPSxVvfsbnL9CK8eCQpLrGkeJuUi1Pbv0oq", 'consumer_key' => "AA3VCruTsNQKUArY0V2vSznVC", 'consumer_secret' => "xuZeCJagWK70LGOQKfdMpjYVmNx0wArhKnirz5MyGyWIbWPQ6B");
/** Perform a GET request and echo the response **/
$url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$jsonTweets = $twitter->buildOauth($url, $requestMethod)->performRequest();
/** Process the response (JSON format) using json_decode: http://docs.php.net/json_decode **/
$response = json_decode($jsonTweets, true);
/** Go through every tweet and print out line by line -- will ideally need some pleasant wrapping with bootstrap -- maybe add IDs to process instead
		 Example of the kind of information that can be returned here: https://dev.twitter.com/rest/reference/get/statuses/home_timeline **/
/** Sets $filter to " " and then sets it to the checked radio button ($_POST['filter']).
		Then checks if $filter says it should be filtered by a specific word. If yes, then $filter is set to $_POST['word'] **/
$filter = " ";
$filter = $_POST['filter'];
if ($filter == "FilterBySpecificWord") {
    $filter = $_POST['word'];
}
//If a server request has been made, update filter word.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    foreach ($response as $tweet) {
        if (is_string(strstr($tweet['text'], "{$filter}", false))) {
            echo "<a href={$tweet['user']['url']}>{$tweet['user']['screen_name']}</a> {$tweet['text']}<br />";
        }
    }
Beispiel #21
0
 private function getRateLimitStatus()
 {
     if (isset($this->_rateLimits)) {
         return $this->_rateLimits;
     }
     $rateLimitWindow = 60 * 15;
     // first check the cache
     $rateLimits = Yii::app()->settings->twitterRateLimits;
     if (ctype_digit($rateLimits)) {
         // setting is set to window expiration date
         if ((int) $rateLimits >= time()) {
             // window hasn't expired
             return false;
         }
     } elseif (is_array($rateLimits)) {
         // if rate limit field is set but doesn't include needed rate limits, there's no
         // way of knowing whether an additional request would surpass the rate limit.
         // Set the rate limit to the window size to ensure that the rate limit gets reset before
         // making another api request.
         if (!isset($rateLimits['resources']['application']['/application/rate_limit_status'])) {
             Yii::app()->settings->twitterRateLimits = time() + $rateLimitWindow;
             Yii::app()->settings->save();
             return false;
         }
         $entry = $rateLimits['resources']['application']['/application/rate_limit_status'];
         if ($entry['reset'] > time()) {
             // end of window hasn't been reached
             if ((int) $entry['remaining'] < 1) {
                 // rate limit on number of requests to retrieve the rate limit has been reached
                 return false;
             } else {
                 // rate limit info is valid
                 //AuxLib::debugLogR ('cache hit');
                 return $rateLimits;
             }
         }
     } else {
         if ($rateLimits !== null) {
             // rate limit was set to an invalid value
             Yii::app()->settings->twitterRateLimits = time() + $rateLimitWindow;
             Yii::app()->settings->save();
             return false;
         }
     }
     //AuxLib::debugLogR ('cache miss');
     // refresh the rate limit status cache
     $credentials = $this->getTwitterCredentials();
     $url = 'https://api.twitter.com/1.1/application/rate_limit_status.json';
     $requestMethod = 'GET';
     $twitter = new TwitterAPIExchange($credentials);
     $rateLimitStatus = CJSON::decode($twitter->buildOauth($url, $requestMethod)->performRequest());
     if (($statusCode = $twitter->getLastStatusCode()) != 200) {
         $this->throwApiException($rateLimitStatus, $statusCode);
     }
     Yii::app()->settings->twitterRateLimits = $rateLimitStatus;
     Yii::app()->settings->save();
     $this->_rateLimits = $rateLimitStatus;
     return $rateLimitStatus;
 }
Beispiel #22
0
<?php

function _URLEncode($array)
{
    $a = array();
    foreach ($array as $k => $v) {
        $a[] = urlencode($k) . "=" . urlencode($v);
    }
    return implode("&", $a);
}
require_once "settings.php";
if (isset($_POST["key"]) and $_POST["key"] == $settings["secretkey"]) {
    require_once "TwitterAPIExchange.php";
    $requestmethod = $_POST["method"];
    $url = "https://api.twitter.com/1.1/";
    $url = $url . $_POST["api"];
    $twitter = new TwitterAPIExchange($settings);
    if ($requestmethod == "POST") {
        $postfields = json_decode($_POST["json"], true);
        echo $twitter->buildOauth($url, $requestmethod)->setPostfields($postfields)->performRequest();
    } elseif ($requestmethod == "GET") {
        $jsondata = json_decode($_POST["json"], true);
        $getfield = "?" . _URLEncode($jsondata);
        echo $twitter->setGetfield($getfield)->buildOauth($url, $requestmethod)->performRequest();
    } else {
        echo 'request method has to be either POST or GET';
    }
} else {
    echo "you don't have access to here";
}
Beispiel #23
0
 public function check_feed_event($feedid, $updatetime, $feedtime, $value, $row = NULL, $test = false)
 {
     global $user, $session, $feed;
     $userid = $session['userid'];
     $sqlFeed = "SELECT * FROM event WHERE `userid` = '{$userid}'";
     if ($test) {
         $sqlFeed = $sqlFeed . " and id = {$feedid}";
     } else {
         $sqlFeed = $sqlFeed . " and (`disabled` <> 1 or `disabled` IS NULL) and (eventfeed = {$feedid} or eventtype=3)";
     }
     $result = $this->mysqli->query($sqlFeed);
     // check type
     while ($row = $result->fetch_array()) {
         if ($row['lasttime'] + $row['mutetime'] > time() && !$test) {
             continue;
         }
         if ($test) {
             $sendAlert = 1;
         } else {
             $sendAlert = 0;
             switch ($row['eventtype']) {
                 case 0:
                     // more than
                     if ($value > $row['eventvalue']) {
                         $sendAlert = 1;
                     }
                     break;
                 case 1:
                     // less than
                     if ($value < $row['eventvalue']) {
                         $sendAlert = 1;
                     }
                     break;
                 case 2:
                     // equal to
                     if ($value == $row['eventvalue']) {
                         $sendAlert = 1;
                     }
                     break;
                 case 3:
                     // inactive
                     // not sure this can be called as no feed updated
                     //if (((time()-$row['lasttime'])/3600)>24) {}
                     $feedData = $feed->get($row['eventfeed']);
                     //error_log("Feeddata: " .$feedData->time);
                     $t = time() - strtotime($feedData['time']);
                     //error_log("t: " .$t);
                     if ($t > $row['eventvalue']) {
                         $sendAlert = 1;
                     }
                     break;
                 case 4:
                     // updated
                     $sendAlert = 1;
                     break;
                 case 5:
                     // increased by
                     $feedname = 'feed_' . $feedid;
                     $resultprev = $this->mysqli->query("SELECT * FROM {$feedname} ORDER BY `time` DESC LIMIT 1,1");
                     $rowprev = $resultprev->fetch_array();
                     //echo "INC == ".$value." > ".$rowprev['data']."+".$row['eventvalue'];
                     if ($value > $rowprev['data'] + $row['eventvalue']) {
                         $sendAlert = 1;
                     }
                     break;
                 case 6:
                     // decreased by
                     $feedname = 'feed_' . $feedid;
                     $resultprev = $this->mysqli->query("SELECT * FROM {$feedname} ORDER BY `time` DESC LIMIT 1,1");
                     $rowprev = $resultprev->fetch_array();
                     //echo "DEC == ".$value."<". $rowprev['data']."-".$row['eventvalue'];
                     if ($value < $rowprev['data'] - $row['eventvalue']) {
                         $sendAlert = 1;
                     }
                     break;
                 case 7:
                     // manual update
                     // Check if event.lasttime is less than feed.time
                     $feedData = $feed->get($feedid);
                     if ($feedData['time'] > $row['lasttime']) {
                         $sendAlert = 1;
                     }
             }
         }
         $feedData = $feed->get($row['eventfeed']);
         $message = $row['message'];
         $message = str_replace('{feed}', $feedData['name'], $message);
         $message = str_replace('{value}', $value, $message);
         $message = htmlspecialchars($message);
         if (empty($message)) {
             $message = "No message body";
         }
         if ($test) {
             $message = 'TEST - ' . $message;
         }
         // event type
         if ($sendAlert == 1) {
             switch ($row['action']) {
                 case 0:
                     // email
                     require_once realpath(dirname(__FILE__)) . '/../event/scripts/phpmailer/class.phpmailer.php';
                     require_once realpath(dirname(__FILE__)) . '/../event/scripts/phpmailer/class.smtp.php';
                     $smtp = $this->get_settings($userid);
                     $mail = new PHPMailer();
                     $mail->IsSMTP();
                     // telling the class to use SMTP
                     $mail->SMTPDebug = 0;
                     // SMTP debug information (for testing)
                     // 0 No output
                     // 1 Commands
                     // 2 Data and commands
                     // 3 As 2 plus connection status
                     // 4 Low-level data output
                     $mail->SMTPAuth = true;
                     // enable SMTP authentication
                     if ($smtp['smtpport'] == 587) {
                         $mail->SMTPSecure = "tls";
                     } else {
                         if ($smtp['smtpport'] == 465) {
                             $mail->SMTPSecure = "ssl";
                         }
                     }
                     // sets the prefix to the server
                     $mail->Host = $smtp['smtpserver'];
                     // sets GMAIL as the SMTP server
                     $mail->Port = $smtp['smtpport'];
                     // set the SMTP port for the GMAIL server
                     $mail->Username = $smtp['smtpuser'];
                     // GMAIL username
                     $salt = $user->get_salt($userid);
                     $mail->Password = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($smtp['smtppassword']), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
                     // GMAIL password
                     $address = $smtp['smtpuser'];
                     $mail->SetFrom($address, 'emoncms');
                     //$mail->AddReplyTo("*****@*****.**', 'First Last");
                     $mail->Subject = $message;
                     //$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                     $mail->MsgHTML($message);
                     $dest = $address;
                     if ($row['setemail'] != '') {
                         $dest = $row['setemail'];
                     }
                     // Allows multiple recipients for the event email. Seperate by semi-colon ;
                     if (strpos($dest, ';') !== false) {
                         $addresses = explode(';', $dest);
                         foreach ($addresses as &$addressee) {
                             $mail->AddAddress($addressee, "emoncms");
                         }
                     } else {
                         $mail->AddAddress($dest, "emoncms");
                     }
                     //$mail->AddAttachment("images/phpmailer.gif");      // attachment
                     //$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
                     if (!$mail->Send()) {
                         echo "Mailer Error: " . $mail->ErrorInfo;
                         error_log("Mailer Error: " . $mail->ErrorInfo);
                     } else {
                         echo "Message sent!";
                         error_log("Message sent");
                     }
                     break;
                 case 1:
                     // set feed
                     $setfeed = $row['setfeed'];
                     $setvalue = $row['setvalue'];
                     $this->redis->hMset("feed:lastvalue:{$setfeed}", array('value' => $setvalue, 'time' => $updatetime));
                     // $this->mysqli->query("UPDATE feeds SET value = '$setvalue', time = '$updatetime' WHERE id='$setfeed'");
                     break;
                 case 2:
                     // call url
                     $explodedUrl = preg_split('/[?]+/', $row['callcurl'], -1);
                     if (count($explodedUrl) > 1) {
                         $explodedUrl[1] = str_replace(' ', '%20', str_replace('{value}', $value, str_replace('{feed}', $feedData->name, $explodedUrl[1])));
                     }
                     $ch = curl_init();
                     $body = $explodedUrl[0] . '?' . $explodedUrl[1];
                     // set URL and other appropriate options
                     curl_setopt($ch, CURLOPT_URL, $body);
                     curl_setopt($ch, CURLOPT_HEADER, 0);
                     curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
                     curl_setopt($ch, CURLOPT_TIMEOUT, 1);
                     // grab URL and pass it to the browser
                     if (curl_exec($ch) === false) {
                         error_log("Curl Error:" . curl_error($ch));
                     }
                     // close cURL resource, and free up system resources
                     curl_close($ch);
                     error_log("Curl Log:" . $body);
                     break;
                 case 3:
                     // Twitter
                     require_once realpath(dirname(__FILE__)) . '/../event/scripts/twitter/twitter-api-php/TwitterAPIExchange.php';
                     $twitter = $this->get_user_twitter($userid);
                     // Twitter disallow duplicate tweets within an unspecified and variable time per account
                     // so add the feed time to make each tweet unique.
                     $message = $message . ' at ' . date("H:i:s", $feedtime);
                     // Set the OAauth values
                     $settings = array('oauth_access_token' => $twitter['usertoken'], 'oauth_access_token_secret' => $twitter['usersecret'], 'consumer_key' => $twitter['consumerkey'], 'consumer_secret' => $twitter['consumersecret']);
                     // Make the API call
                     $url = 'https://api.twitter.com/1.1/statuses/update.json';
                     $requestMethod = 'POST';
                     $postfields = array('status' => $message);
                     $tweet = new TwitterAPIExchange($settings);
                     echo $tweet->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
                     break;
                 case 4:
                     // Prowl
                     require_once realpath(dirname(__FILE__)) . '/scripts/prowlphp/ProwlConnector.class.php';
                     require_once realpath(dirname(__FILE__)) . '/scripts/prowlphp/ProwlMessage.class.php';
                     require_once realpath(dirname(__FILE__)) . '/scripts/prowlphp/ProwlResponse.class.php';
                     $prowl = $this->get_user_prowl($userid);
                     $oProwl = new ProwlConnector();
                     $oMsg = new ProwlMessage();
                     $oProwl->setIsPostRequest(true);
                     $oMsg->setPriority($row['priority']);
                     $oMsg->addApiKey($prowl['prowlkey']);
                     $oMsg->setEvent($message);
                     // These are optional:
                     $message = 'event at ' . date("Y-m-d H:i:s", time());
                     $oMsg->setDescription($message);
                     $oMsg->setApplication('emoncms');
                     $oResponse = $oProwl->push($oMsg);
                     if ($oResponse->isError()) {
                         error_log("Prowl error:" . $oResponse->getErrorAsString());
                     }
                     break;
                 case 5:
                     // NMA
                     require_once realpath(dirname(__FILE__)) . '/scripts/nma/nmaApi.class.php';
                     $nmakey = $this->get_user_nma($userid);
                     $nma = new nmaApi(array('apikey' => $nmakey['nmakey']));
                     $priority = $row['priority'];
                     if ($nma->verify()) {
                         $nma->notify('EmonCMS ' . $message, 'EmonCMS', $message, $priority);
                     }
                     break;
                 case 6:
                     // MQTT
                     require_once realpath(dirname(__FILE__)) . '/scripts/mqtt/phpMQTT.php';
                     $mqttSettings = $this->get_user_mqtt($userid);
                     $salt = $user->get_salt($userid);
                     $mqtttopic = $row['mqtttopic'];
                     $mqtttopic = str_replace('{feed}', $feedData['name'], $mqtttopic);
                     $mqtttopic = str_replace('{value}', $value, $mqtttopic);
                     $mqtttopic = htmlspecialchars($mqtttopic);
                     $mqttqos = $row['mqttqos'];
                     if (empty($mqttqos)) {
                         $mqttqos = 0;
                     }
                     // setup connection
                     $mqtt = new phpMQTT($mqttSettings['mqttbrokerip'], $mqttSettings['mqttbrokerport'], "emoncms");
                     if (empty($mqttSettings['mqttusername'])) {
                         $mqttConnected = $mqtt->connect();
                     } else {
                         $mqttusername = $mqttSettings['mqttusername'];
                         $mqttpassword = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($mqttSettings['mqttpassword']), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
                         $mqttConnected = $mqtt->connect(false, NULL, $mqttusername, $mqttpassword);
                     }
                     if ($mqttConnected) {
                         $mqtt->publish($mqtttopic, $message, $mqttqos);
                     } else {
                         error_log("MQTT connection failed");
                     }
                     $mqtt->close();
                     break;
             }
             // update the lasttime called
             if (!$test) {
                 $this->mysqli->query("UPDATE event SET lasttime = '" . time() . "' WHERE id='" . $row['id'] . "'");
             }
         }
     }
 }