<?php 

class Tableau
{
    public function get_trusted_url_tableau($userTableau, $serverTableau, $view_url)
    {
        $params = ':embed=y&:loadOrderID=0&:display_spinner=no&:showShareOptions=true&:display_count=no&:showVizHome=no&:toolbar=no&:tooltip=yes&:original_view=yes&:refresh=yes&:revert=all&:tabs=yes&:linktarget=_blank&:render=true';

        $ticket = $this->get_trusted_ticket_tableau($serverTableau, $userTableau, $_SERVER['REMOTE_ADDR']);

        if ($ticket != '-1') {
            return "https://".$serverTableau."/trusted/".$ticket."/".$view_url."?".$params."";
        } else {
            return 0;
        }
    }

    public function get_trusted_ticket_tableau($wgserver, $userTableau, $remote_addr)
    {
        $params = array(
            'username' => $userTableau,
            'client_ip' => $remote_addr
        );

        // return $this->do_post_request_tableau("https://$wgserver/trusted", $params);
        return $this->do_post_request_tableau("https://".$wgserver."/trusted", $params);
    }

    public function do_post_request_tableau($url, $data, $optional_headers = null)
    { 
        // var_dump($url,$data);exit;
        $params = array('http' => array(
                  'method' => 'POST',
                  'content' => http_build_query($data),
                  'header' => 'Content-Type: application/x-www-form-urlencoded'
                ));
        if ($optional_headers !== null) {
            $params['http']['header'] = $optional_headers;
        }
        $ctx = stream_context_create($params);
        $fp = @fopen($url, 'rb', false, $ctx);
        if (!$fp) {
            throw new Exception("Problem with $url, $fp");
        }
        $response = @stream_get_contents($fp);
        
        if ($response === false) {
            throw new Exception("Problem reading data from $url, $fp");
        }
        return $response;
    }

    public function postCURL($_url, $_param){
        // die(print_r($_param));
        
        $postData = '';
        //create name value pairs seperated by &
        foreach($_param as $k => $v) 
        { 
            $postData .= $k . '='.$v.'&'; 
        }
        rtrim($postData, '&');


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, false); 
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    
        curl_setopt($ch,CURLOPT_TIMEOUT,1000);

        $output=curl_exec($ch);

        curl_close($ch);

        return $output;
    }
}
