summaryrefslogtreecommitdiff
path: root/linkshorter/index.php
blob: 8d05977e9c0cde17de38f0f3191a3b5644bce009 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
require 'functions.php';
require 'config.php';
require '../tools/class/redis.php';

if ( ! isset($_REQUEST['url']) || $_REQUEST['url'] == "" ){
	if ( ! isset($_REQUEST['checkpassword']) || $_REQUEST['checkpassword'] != 1 )

		require 'view/templ-index.php';

	else {

		if ( ! isset($_REQUEST["short"]) || $_REQUEST["short"] == "" ){
			require 'view/templ-notfound.php';
			exit;
		}

		$db = new Database(REDIS_CONNECT, REDIS_SELECT);

		$options = json_decode( $db->get($_REQUEST["short"]), true );

		if ( password_verify( $_REQUEST["password"] . PEPPER, $options["password"] ) )
			redirect($options["url"]);
		else
			_do_output("Failure!", "Wrong password supplied");
	}

} else {

	$url = trim($_REQUEST['url']);

	if( ! preg_match("/^https?:\/\//", $url) ){
		$heading = "Failure!";
		$reason = "This doesn't look like a valid URL.";
		_do_output($heading, $reason);
	}

	$options = array("url" => $url);
	if ( ! isset($_REQUEST["short"]) || $_REQUEST["short"] == "" )
		$options["short"] = "";
	else
		$options["short"] = $_REQUEST["short"];

	if ( ! isset($_REQUEST["ttl"]) || $_REQUEST["ttl"] == "" )
		$options["ttl"] = "";
	else {
		if ( ! preg_match( "/^[0-9]+$/", trim($_REQUEST["ttl"]) ) ){
			_do_output("Failure!", "Your Lifetime doesn't look like a valid number.");
		}
		$options["ttl"] = $_REQUEST["ttl"];
	}

	if ( ! isset($_REQUEST["password"]) || $_REQUEST["password"] == "" )
		$options["password"] = "";
	else
		$options["password"] = password_hash($_REQUEST["password"] . PEPPER, PASSWORD_DEFAULT);
	
	$db = new Database(REDIS_CONNECT, REDIS_SELECT);

	if ( $options["short"] != "" && $db->exists($options["short"]) )
		_do_output("Failure!", "Query string '".htmlentities($options["short"])."' already taken. Please choose a different one.");

	if ( $options["short"] == "" )
		$options["short"] = getToken();
		
	if ( $options["ttl"] != "" ){
		if ( ! $db->set($options["short"], json_encode($options), $options["ttl"]) ){
			_do_output("Failure!", "Database went away. :(");
		}
	} else {
		if ( ! $db->set($options["short"], json_encode($options)) ){
			_do_output("Failure!", "Database went away. :(");
		}
	}

	_do_output("Success!", "Your short link is <a href=\"" . SHORTDOMAIN . htmlentities($options["short"]) . "\" title=\"".htmlentities($options["url"])."\">". SHORTDOMAIN . htmlentities($options["short"]) ."</a>");
}