<?php

include_once 'Preferences.php';
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


if (isset($_REQUEST['cmd']) && $_REQUEST['cmd'] == 'get_short_url' && isset($_REQUEST['long_url'])) {
    $longurl = $_REQUEST['long_url'];

    echo get_short_url($longurl);
}

function get_short_url($url) {

    $url_fflink = Preferences::DOMAIN . "api.php";

    $data = array(
        "create_short_url" => TRUE,
        "url" => "$url"
    );


    $response_json = curl_operations($url_fflink, $data);
    $jsondecode = json_decode($response_json);
    if ($jsondecode->is_error == '1') {
        return $url;
    } else {
        return $jsondecode->short_url;
    }
}

function curl_operations($url, $data = NULL) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if (!is_null($data)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
