<?php

/* if this is an api request, make sure it's permitted */
if (((int)$_REQUEST['api']) && (SITE_CONFIG_ENABLE_API == 'no'))
{
    echo '[API DISABLED]';
    exit;
}

/* if this is an api request, make sure it's permitted */
if (((int)$_REQUEST['api']) && ((SITE_CONFIG_ENABLE_API_AUTH == 'yes') && (!isset($_REQUEST['key']))))
{
    echo '[API DISABLED]';
    exit;
}

/* is this an api request? If yes set a few defaults */
if ((int) $_REQUEST['api'])
{
    $_REQUEST['submitted']  = 1;
    $_REQUEST['agreeTerms'] = 1;
}

/* validate any submission */
if ((int) $_REQUEST['submitted'])
{
    $longUrl    = trim($_REQUEST['longUrl']);
    $agreeTerms = trim($_REQUEST['agreeTerms']);
    $isPrivate  = (int) $_REQUEST['shortUrlType'];
    $password   = trim($_REQUEST['shortUrlPassword']);
    $expiryDate = trim($_REQUEST['shortUrlExpiryDate']);
    $totalUses  = (int) $_REQUEST['shortUrlUses'];
    $customUrl  = shortUrl::prepareShortUrlPart($_REQUEST['customUrl']);
    $longUrl    = shortUrl::standardiseUrl($longUrl);

    /* check url structure */
    if (!(int) $agreeTerms)
    {
        setError(t("please_agree_terms_and_conditions"));
    }
    /* check to see if they have been banned from the site for creating urls ($bannedIP setup in includes/master.inc.php) */
    elseif (strtolower($bannedIP) == "creating urls")
    {
        setError(t("not_permitted_to_create_urls_on_site"));
    }
    /* check the structure of the url */
    elseif (!isValidUrl($longUrl))
    {
        setError(t("error_with_url"));
    }
    /* check that they are not using the site url to restrict infinate loops */
    elseif (substr(strtolower($longUrl), 0, strlen(WEB_ROOT)) == strtolower(WEB_ROOT))
    {
        setError(t("can_not_create_url_on_this_site"));
    }
    elseif ($expiryDate)
    {
        if (!dater($expiryDate))
        {
            setError(t("date_entered_is_incorrect"));
        }
    }

    if ($customUrl)
    {
        /* check custom url does not already exist */
        if ($shortUrlObj = shortUrl::loadByUrl($customUrl))
        {
            setError(t("custom_short_url_already_exits"));
        }
    }

    if (!isErrors())
    {
        // don't do this for API requests
        if (!isset($_REQUEST['api']))
        {
            // only if captcha is configured
            if (useCaptcha() == true)
            {
                /* do we require captcha validation? */
                $showCaptcha = false;
                if (!isset($_REQUEST['recaptcha_response_field']))
                {
                    $showCaptcha = true;
                }

                /* check captcha */
                if (isset($_REQUEST['recaptcha_response_field']))
                {
                    $resp = recaptcha_check_answer(SITE_CONFIG_CAPTCHA_PRIVATE_KEY, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
                    if (!$resp->is_valid)
                    {
                        setError(t("invalid_captcha", "Captcha confirmation text is invalid."));
                        $showCaptcha = true;
                    }
                }

                if ($showCaptcha == true)
                {
                    include_once('captcha.inc.php');
                    exit;
                }
            }
        }
    }

    /* create the short url */
    if (!isErrors())
    {
        $shortUrlObj = new shortUrl($longUrl);
        $shortUrlObj->isPrivate = (int) $isPrivate;
        if ($password)
            $password    = MD5($password);
        else
            $password    = null;
        $shortUrlObj->password = $password;
        if ($expiryDate)
            $shortUrlObj->expiryDate = dater($expiryDate, "Y-m-d H:i:s");
        else
            $shortUrlObj->expiryDate = null;
        $shortUrlObj->totalUses = (int) $totalUses;

        // add user id if user is logged in
        if ($Auth->loggedIn())
        {
            $shortUrlObj->userId = (int) $Auth->id;
        }
        elseif (((int)$_REQUEST['api']) && (isset($_REQUEST['key'])))
        {
            /* lookup user account if api key passed */
            $user = UserPeer::loadUserByAPIKey(trim($_REQUEST['key']));
            if($user)
            {
                $shortUrlObj->userId = (int) $user->id;
            }
        }

        if (!$newShortUrl = $shortUrlObj->createShortUrl($customUrl))
        {
            setError(t("problem_creating_short_url"));
        }
        else
        {
            /* if this is a twitter link, redirect remote */
            if ((int) $_REQUEST['postToTwitter'])
            {
                $shortUrl = $shortUrlObj->compileShortUrl();
                redirect("http://twitter.com/intent/tweet?text=" . rawurlencode($shortUrl));
            }
            /* if this is an api request, just return the text */
            elseif (((int) $_REQUEST['api']) && ((int) $_REQUEST['return_url_text']))
            {
                $shortUrl = $shortUrlObj->compileShortUrl();
                echo $shortUrl;
                exit;
            }
            /* normal */
            else
            {
                redirect(WEB_ROOT . "/viewUrl." . SITE_CONFIG_PAGE_EXTENSION . "?u=" . (int) $newShortUrl->id);
            }
        }
    }
}
