/**
 * Gets the user iamge of the twitter account provided by $twitter
 * @params:
 *		$twitter		:array
 *	 		$twitter['consumer_key']	:string
 *			$twitter['consumer_secret']	:string
 *	 		$twitter['access_key']		:string
 *			$twitter['access_secret']	:string
 *@returns the image url on success, false otherwise
 */
function get_pic($twitter)
{
    $connection = new TwitterOAuth($twitter['consumer_key'], $twitter['consumer_secret'], $twitter['access_key'], $twitter['access_secret']);
    $response = $connection->get("users/show", array("id" => $twitter['name']));
    $url = $response->profile_image_url;
    $http_info = $connection->http_info;
    if ($http_info['http_code'] != 200) {
        log_this("......... error: tried to fetch user image from @" . $twitter['name'], json_encode($response));
        return false;
    } else {
        log_this("......... success: received user image from @" . $twitter['name'], json_encode($response));
        return $url;
    }
}
/** LF-API documentation http://www.public-software-group.org/liquid_feedback_frontend_api

/**
 * Queries the LiquidFeeback instance provided by $lf with $query
 * @params:
 * 		$lf['base_dir']		:the base of the LiquidFeedback instance, e.g. 'lqpp.de/be'
 *		$lf['api_key']		:your LiquidFeeback API key
 *		$query				:the query to sent, e.g. 'min_id=0' to get all initiatives
 * @returns an array of initiatives
 * 
 * As of now the LF-API throws an error when using the state selector.
 */
function lf_query($lf, $query)
{
    $query = $lf['base_dir'] . '/api/initiative.html?key=' . $lf['api_key'] . '&api_engine=json&' . $query;
    $ch = curl_init($query);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpcode != 200) {
        log_this("error: tried to fetch \"{$query}\" from " . $lf['base_dir'], $response);
        return false;
    } else {
        log_this("success: fetched \"{$query}\" from " . $lf['base_dir'], $response);
        return my_json_decode($response);
    }
}
/**
 * Shorens the provided url with bit.ly
 * @params:
 *		$url	:string, the url to be shortened
 * @returns the shortened url or false
 */
function shortlink($url)
{
    //Url verkürzen
    $ch = curl_init('http://api.bit.ly/v3/shorten?login='******'&apiKey=' . BL_API_KEY . '&uri=' . urlencode($url) . '&format=json');
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $response = my_json_decode($response);
    if ($httpcode != 200) {
        log_this("error: tried to shorten '{$url}'", $reponse);
        return false;
    } else {
        log_this("success: shortened '{$url}'", $reponse);
        return stripslashes($response['data']['url']);
    }
}
/**
 * Decodes a JSON string
 * @params
 *		$json	:string, JSON to decode
 * @returns an array corresponding to the JSON string
 */
function my_json_decode($json)
{
    // found on php.net (and modified)
    $comment = false;
    $out = '$x=';
    for ($i = 0; $i < strlen($json); $i++) {
        if (!$comment) {
            if (in_array($json[$i], array('{', '['))) {
                $out .= ' array(';
            } else {
                if (in_array($json[$i], array('}', ']'))) {
                    $out .= ')';
                } else {
                    if ($json[$i] == ':') {
                        $out .= '=>';
                    } else {
                        $out .= $json[$i];
                    }
                }
            }
        } else {
            $out .= $json[$i];
        }
        if ($json[$i] == '"' and $json[$i - 1] != "\\") {
            $comment = !$comment;
        }
    }
    if (eval($out . ';') === false) {
        log_this("error: my_json_decode", "{$out}");
        return array();
    } else {
        log_this("success: my_json_decode", $out);
        return $x;
    }
}
/**
 * Drops $db_events_table
 * @returns nothing
 */
function clear_logged_events()
{
    global $db_events_table;
    $query = "DROP TABLE {$db_events_table}";
    $result = mysql_query($query);
    log_this("cleared logged events", "dropped table '{$db_events_table}'");
}
foreach ($bots as $name => $bot) {
    log_this("––––––––––––  processing bot '{$name}'");
    echo "** BOT '{$name}' running \n*****************************\n";
    log_and_flush();
    //Log and flush the output buffer :)
    $db_events_table = $name . "_events";
    // every bot gets his own table to log events
    //clear_logged_events();			// reset the bot
    process($bot, !table_exists($db_events_table));
    /* 
    	If the events table does not exists nothing will be twittered.
    	This way old stuff wont be twittered in the first run. 
    	Instead the table is created and logs the old events.
    */
    summary_tweet($bot);
    //Daily summary.
    echo "\n\n\n\n";
    //print_table($db_events_table);	// shows all logged events for debugging
}
log_and_flush();
//Log and flush the output buffer for the last time
ob_end_clean();
//end output buffer
log_this("––––––––––––– done. ", $log);
//write the output of this script to the log table
mysql_close(DB);
?>