<?php
/**
 * Helper Component for the youTrack-Links Plugin
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Dominic Pöllath <dominic.poellath@ils-gmbh.net>
 */

if(!defined('DOKU_INC')) die();

class helper_plugin_youtracklinks extends DokuWiki_Plugin
{


    // Method: POST, PUT, GET etc
    // Data: array("param" => "value") ==> index.php?param=value
    function CallAPI($method, $url, $data = false, $cookiejar = false)
    {
        if (!function_exists('curl_init')) {
            throw new Exception("You have to install curl first.");
        }


        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        switch ($method)
        {
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);
                if ($data)
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                break;
            default:
                if ($data)
                    $url = sprintf("%s?%s", $url, http_build_query($data));
        }


        curl_setopt($curl, CURLOPT_URL, $url);


        // Optional Authentication:
        // curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        // curl_setopt($curl, CURLOPT_USERPWD, "username:password");
        // curl_setopt($curl, CURLOPT_COOKIEJAR,  $ckfile);
        if ($cookiejar) {
            curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiejar);
            curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiejar);
        }

        $content = curl_exec($curl);
        curl_close($curl);
        return $content ? $content : null;
    }



    /**
     * getter function for the youTrack url without ending slash
     */
    function getYouTrackURL() {
        $url = $this->getConf('youtrack_external_url');
        return substr($url, -1) === '/' ? substr($url, 0, strlen($url)-1) : $url;
    }


    /**
     * function to perform login
     */
    function loginYouTrack($url, $cookiejar) {
        $content = $this->CallAPI("POST", "$url/rest/user/login",
            array("login" => $this->getConf('login_user'),
                "password" => $this->getConf('login_pass')), $cookiejar);

        return (simplexml_load_string($content) == "ok");
    }

    /**
     * function to fetch issue details from YouTrack
     */

    function fetchYouTrackIssue($id) {

        if ($id == null || $id == "")
            return null;
        $url = $this->getYouTrackURL();
        if ($url == '')
            return null;

        $cookiejar = false;
        // check if should login
        if ($this->getConf('should_login')) {
            $cookiejar = tempnam (sys_get_temp_dir(), "CURLCOOKIE");
            // do login
            if (!$this->loginYouTrack($url, $cookiejar)) {
                throw new Exception("Logindata not correct, or REST login is not enabled.");
            }
        }
        // fetch issue
        $xml = $this->CallAPI("GET", $url . "/rest/issue/$id", false, $cookiejar);
        if ($xml == null || $xml == '')
            return null;
        // clean jar
        if ($cookiejar)
            unlink($cookiejar) or die("Can't unlink $cookiejar");
        return simplexml_load_string($xml);

    }

    /**
     * function to generate html link to the issue with name of issue
     */
    function generateLinkForIssue($issue) {

        if ($issue == null || $issue['0'] == "You are not logged in.") {
            return null;
        }

        $url = $this->getYouTrackURL();
        $target = $this->getConf('open_in_new_window') ? '_blank' : '_self';

        $resolved = false;

        $id = $issue->attributes()->id;
        foreach($issue as $key => $field) {
            if ($field->attributes()->name == 'summary') {
                $summary = $field->value;
                break;
            }
            if ($field->attributes()->name == 'resolved') {
                $resolved = true;
            }
        }

        if (!$resolved)
            foreach($issue as $key => $field) {
                if ($field->attributes()->name == 'resolved') {
                    $resolved = true;
                    break;
                }
            }

        return "<span" . ($resolved ? " style='text-decoration: line-through;'" : "") . "><a target='$target' href='$url/issue/$id'><b>$id</b> $summary</a></span> ";
    }


}