New function : shortenLink

This commit is contained in:
Divlo 2019-12-11 20:46:57 +01:00
parent 3e3f13d079
commit d07f03724b
16 changed files with 298 additions and 25 deletions

3
.gitignore vendored
View File

@ -1,2 +1,3 @@
htaccess htaccess
php/keyVariable.php php/keyVariable.php
php/config_database

View File

@ -24,6 +24,9 @@ Puis créer un nouveau fichier dans ```/php``` du nom de ```keyVariable.php```,
$apiWeather = 'votre clé api pour openweathermap.org'; $apiWeather = 'votre clé api pour openweathermap.org';
``` ```
Sachez tout de même que vous ne pourrez pas utiliser la fonction linkShortener car elle dépend de [short-links.divlo.fr/](https://short-links.divlo.fr/).
Cependant, vous avez accès à la structure de la base de donnée dans ```/php/short_links.sql```.
Enjoy! =D Enjoy! =D
## Librairies ## Librairies

View File

@ -102,6 +102,14 @@ pre code {
line-height: 2; line-height: 2;
} }
.original-link-list {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
vertical-align: middle;
}
/* FOOTER */ /* FOOTER */
footer footer
{ {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

View File

@ -88,6 +88,16 @@ switch ($currentpage) {
$description = "Convertis du Markdown en HTML."; $description = "Convertis du Markdown en HTML.";
$image = 'https://function.divlo.fr/img/function-image/convertMarkdown.png'; $image = 'https://function.divlo.fr/img/function-image/convertMarkdown.png';
break; break;
case '/views/function-views/linkShortener.php':
$title = "Raccourcisseurs de liens";
$description = "Une URL trop longue ? Raccourcissez-là !";
$image = 'https://function.divlo.fr/img/function-image/linkShortener.png';
break;
case '/views/short_links-list.php':
$title = 'Liste des liens récemment raccourcit';
$description = "La liste de vos liens raccourcit les plus récents.";
$image = 'https://function.divlo.fr/img/function-image/linkShortener.png';
break;
default: default:
$title = 'Erreur 404'; $title = 'Erreur 404';
$description = "Cette page n'existe pas!"; $description = "Cette page n'existe pas!";

13
php/short_links.sql Normal file
View File

@ -0,0 +1,13 @@
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
DROP TABLE IF EXISTS `short_links`;
CREATE TABLE IF NOT EXISTS `short_links` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`url` text NOT NULL,
`shortcut` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
COMMIT;

100
php/shortenLink.php Normal file
View File

@ -0,0 +1,100 @@
<?php
/**
* Convertis une string en camelCase (seulement si la string contient des espaces)
* @param string $str
* @return string
*/
function camelCase($str, array $noStrip = []) {
$str = preg_replace('/[^a-z0-9' . implode("", $noStrip) . ']+/i', ' ', $str);
$str = trim($str);
$str = ucwords($str);
$str = str_replace(" ", "", $str);
$str = lcfirst($str);
return $str;
}
/**
* Génére une string d'une taille donnée
* @param number $length
* @return string
*/
function uniqueId($length = 8) {
return substr(md5(uniqid(mt_rand(), true)), 0, $length);
}
/**
* Vérifie si une valeur se trouve en bdd
* @param string $bdd
* @param string $valueToFind
* @param string $valueName
* @return array
*/
function alreadyExists($bdd, $valueToFind, $valueName, $typeURL = false) {
$array = array("isInDatabase" => false, $valueName => "");
$req = $bdd->prepare('SELECT * FROM short_links WHERE ' . $valueName . ' = ?');
$req->execute(array($valueToFind));
while ($result = $req->fetch()) {
$array['isInDatabase'] = true;
if($typeURL) {
$array["shortcut"] = $result["shortcut"];
}
}
return $array;
}
$array = array("url" => "", "option"=> "", "message" => "");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Si le formulaire est envoyé
if(isset($_POST['url']) && isset($_POST['option'])) {
$array["url"] = $_POST["url"];
$array["option"] = $_POST["option"];
// Si ce n'est pas un lien valide
if(!filter_var($array["url"], FILTER_VALIDATE_URL)) {
$array["message"] = "Veuillez entré une URL valide.";
} else {
// Connexion à la base de donnée
require_once('./config_database/connectDB.php');
// URL déjà en base de donnée ?
$urlInDatabase = alreadyExists($bdd, $array["url"], "url", true);
if($urlInDatabase['isInDatabase']) {
$shortcutURL = $linkPath . '?q=' . $urlInDatabase['shortcut'];
$array['message'] = 'Adresse déjà raccourcie : <a target="_blank" href="' . $shortcutURL . '">' . $shortcutURL . '</a>';
} else {
if($array['option'] == "userShortcut" && isset($_POST['userShortcut']) && !empty($_POST['userShortcut'])) {
// Shortcut choisis par l'utilisateur
$shortcut = camelCase($_POST['userShortcut']);
} else {
// Shortcut unique aléatoire
do {
$shortcut = uniqueId();
} while(alreadyExists($bdd, $shortcut, "shortcut")['isInDatabase']);
}
$shortcutURL = $linkPath . '?q=' . $shortcut;
if(alreadyExists($bdd, $shortcut, "shortcut")['isInDatabase']) {
$array['message'] = 'Le shortcut "' . $shortcut . '" est déjà pris, veuillez en choisir un autre.';
} else {
// Envoi de l'URL et du shortcut dans la base de donnée
$req = $bdd->prepare('INSERT INTO short_links(url, shortcut) VALUES (?, ?)');
$req->execute(array($array['url'], $shortcut));
$array['message'] = 'URL raccourcie : <a target="_blank" href="' . $shortcutURL . '">'. $shortcutURL .'</a>';
// URL et Shortcut en Cookie
if(isset($_COOKIE['shortcuts']) && !empty($_COOKIE['shortcuts'])) {
$data = json_decode($_COOKIE['shortcuts'], true);
} else {
$data = array();
}
array_push($data, array("url" => $array['url'], "shortcut" => $shortcutURL));
setcookie('shortcuts', json_encode($data), time()+3600*24*365, '/');
}
}
}
}
echo json_encode($array);
}
?>

View File

@ -95,16 +95,6 @@ $(function () {
$('.resultsRandomQuote').html(getRandomQuote()); $('.resultsRandomQuote').html(getRandomQuote());
} }
/* Permet d'afficher la liste des citations/proverbes */
if(chemin === "/views/quote-list.php") {
window.onload = $('.totalLengthQuote').html('Total de ' + quotes.length + ' citations.');
let resultat = "";
for (index in quotes) {
resultat = resultat + `<tr> <td class="quote-element-list important">${quotes[index]["source"]}</td> <td class="quote-element-list">${quotes[index]["quote"]}</td> </tr>`;
}
$(".quote-list").append(resultat);
}
$("#submitConvertCurrency").click(() => { $("#submitConvertCurrency").click(() => {
let value = $('#value').val(); let value = $('#value').val();
const currencyOfTheValue = $("#currencyOfTheValue option:selected").val(); const currencyOfTheValue = $("#currencyOfTheValue option:selected").val();
@ -212,4 +202,21 @@ $(function () {
localStorage.setItem("texteMarkdown", textMarkdown); localStorage.setItem("texteMarkdown", textMarkdown);
$('.results').html(convertedHTML); $('.results').html(convertedHTML);
}); });
$('#formLinkShortener').submit((e) => {
e.preventDefault();
const postdata = $('#formLinkShortener').serialize();
$.ajax({
type: 'POST',
url: '../../php/shortenLink.php',
data: postdata,
success: (text) => {
try {
$(".results").html(JSON.parse(text).message);
} catch (error) {
$(".results").html("URL invalide.");
}
}
});
});
}); });

View File

@ -158,4 +158,26 @@ function isValidDate(verifyDate, currentDate) {
*/ */
function createSessionCookie(name, value) { function createSessionCookie(name, value) {
document.cookie = escape(name) + "=" + escape(value) + " ; path=/"; document.cookie = escape(name) + "=" + escape(value) + " ; path=/";
} }
/**
* @function getCookieValue
* @description Récupère la valeur d'un cookie.
* @param {string} name Nom du cookie
* @param {string} value Valeur du cookie
*/
function getCookieValue(cname) {
const name = cname + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const ca = decodedCookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

View File

@ -34,6 +34,29 @@ $(function () {
/* Permet d'afficher l'heure en temps réel sur le footer */ /* Permet d'afficher l'heure en temps réel sur le footer */
realDateTime('realDateTime'); realDateTime('realDateTime');
/* Permet d'afficher la liste des citations/proverbes */
if(chemin === "/views/quote-list.php") {
window.onload = $('.totalLengthQuote').html('Total de ' + quotes.length + ' citations.');
let resultat = "";
for (index in quotes) {
resultat = resultat + `<tr> <td class="quote-element-list important">${quotes[index]["source"]}</td> <td class="quote-element-list">${quotes[index]["quote"]}</td> </tr>`;
}
$(".quote-list").append(resultat);
}
/* Permet d'afficher la liste des liens récemment raccourcit */
if(chemin === "/views/short_links-list.php") {
try {
const shortcuts = JSON.parse(getCookieValue("shortcuts"));
window.onload = $('.totalLengthLinksList').html(`Total de ${shortcuts.length} lien(s) raccourcit récemment.`);
let resultat = "";
for (element of shortcuts) {
resultat += `<tr> <td class="original-link-list"><a href="${element["url"]}" target="_blank">${element["url"]}</a></td> <td class="link-list"><a href="${element["shortcut"]}" target="_blank">${element["shortcut"]}</a></td> </tr>`;
}
$(".links-list").append(resultat);
} catch(error) {}
}
/* Window Scroll Top Button */ /* Window Scroll Top Button */
const $btnScrollTop = $('.scroll-top-arrow'); const $btnScrollTop = $('.scroll-top-arrow');
$btnScrollTop.on('click', function () { $btnScrollTop.on('click', function () {
@ -41,6 +64,18 @@ $(function () {
return false; return false;
}); });
// Affiche l'input selon le choix de l'utilisateur sur la page linkShortener
if(chemin === '/views/function-views/linkShortener.php') {
$('.hideUserShortcut').hide();
$("#option").bind("keyup change", () => {
if ($("#option").val() == "userShortcut") {
$('.hideUserShortcut').show();
} else {
$('.hideUserShortcut').hide();
}
});
}
/* Date Picker */ /* Date Picker */
$.fn.datepicker.dates['fr'] = { $.fn.datepicker.dates['fr'] = {
days: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"], days: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"],

View File

@ -103,7 +103,7 @@
<p class="function-list-description">Vérifie si un nombre fait partie des nombres d'Armstrong ou non.</p> <p class="function-list-description">Vérifie si un nombre fait partie des nombres d'Armstrong ou non.</p>
</div> </div>
</div> </div>
<div class="col-sm-12 col-md-6 col-md-6 pb-4"> <div class="col-sm-12 col-md-6 pb-4">
<div class="text-center pb-5"> <div class="text-center pb-5">
<h2 class="function-list-title"><a href="./function-views/heapAlgorithm.php">Heap's algorithm</a></h2> <h2 class="function-list-title"><a href="./function-views/heapAlgorithm.php">Heap's algorithm</a></h2>
<a href="./function-views/heapAlgorithm.php"><img class="function-list-image" src="/img/function-image/heapAlgorithm.png" alt="Heap's algorithm"></a> <a href="./function-views/heapAlgorithm.php"><img class="function-list-image" src="/img/function-image/heapAlgorithm.png" alt="Heap's algorithm"></a>
@ -113,13 +113,19 @@
</div> </div>
<div class="row"> <div class="row">
<div class="col-sm-12 pb-4"> <div class="col-sm-12 col-md-6 pb-4">
<div class="text-center pb-5"> <div class="text-center pb-5">
<h2 class="function-list-title"><a href="./function-views/convertMarkdown.php">Markdown</a></h2> <h2 class="function-list-title"><a href="./function-views/convertMarkdown.php">Markdown</a></h2>
<a href="./function-views/convertMarkdown.php"><img class="function-list-image" src="/img/function-image/convertMarkdown.png" alt="Markdown"></a> <a href="./function-views/convertMarkdown.php"><img class="function-list-image" src="/img/function-image/convertMarkdown.png" alt="Markdown"></a>
<p class="function-list-description">Convertis du Markdown en HTML.</p> <p class="function-list-description">Convertis du Markdown en HTML.</p>
</div> </div>
</div> </div>
<div class="col-sm-12 col-md-6 pb-4">
<div class="text-center pb-5">
<h2 class="function-list-title"><a href="./function-views/linkShortener.php">Raccourcisseurs de liens</a></h2>
<a href="./function-views/linkShortener.php"><img class="function-list-image" src="/img/function-image/linkShortener.png" alt="Raccourcisseurs de liens"></a>
<p class="function-list-description">Une URL trop longue ? Raccourcissez- !</p>
</div>
</div> </div>
</div> </div>

View File

@ -12,10 +12,10 @@
<img class="function-image" src="/img/function-image/filterStudents.png" alt="Carte étudiant"> <img class="function-image" src="/img/function-image/filterStudents.png" alt="Carte étudiant">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="nameEntered">Entrez les prénoms :</label> <label for="nameEntered">Entrer les prénoms :</label>
<input name="nameEntered" type="text" id="nameEntered" placeholder="(e.g : 'Prénom1, Prénom2, Prénom3, ...')" class="form-control"> <input name="nameEntered" type="text" id="nameEntered" placeholder="(e.g : 'Prénom1, Prénom2, Prénom3, ...')" class="form-control">
<br> <br>
<label for="filteredLetter">Entrez la lettre à filtré :</label> <label for="filteredLetter">Entrer la lettre à filtré :</label>
<input name="filteredLetter" type="text" id="filteredLetter" placeholder="(e.g : 'A')" class="form-control"> <input name="filteredLetter" type="text" id="filteredLetter" placeholder="(e.g : 'A')" class="form-control">
<br> <br>
<div class="form-row text-center"> <div class="form-row text-center">

View File

@ -0,0 +1,40 @@
<!-- Config -->
<?php include("../../php/config.php");?>
<!-- Header -->
<?php include("../../incl/header.php");?>
<!-- Page Content -->
<div class="container">
<h1><span class="important"><?php echo $title?></span> :</h1>
<p class="pt-3 text-center">
<?php echo $description?>
<div class="text-center">
<img class="function-image" src="/img/function-image/linkShortener.png" alt="Raccourcisseurs de liens">
</div>
<br>
<div class="text-center">
<a href="/views/short_links-list.php">La liste de vos liens raccourcit les plus récents.</a>
</div>
</p>
<form id="formLinkShortener" method="post">
<div class="form-group">
<label for="url">Entrez le lien :</label> <br>
<input name="url" type="url" id="url" placeholder="(e.g : divlo.fr)" class="form-control"> <br class="hideUserShortcut">
<label class="hideUserShortcut" for="userShortcut">Entrez le nom du raccourci :</label> <br class="hideUserShortcut">
<input name="userShortcut" type="text" id="userShortcut" placeholder="(e.g : divlo)" class="form-control hideUserShortcut"> <br>
<label for="option">Choisissez une option : </label> <br>
<select class="form-control" id="option" name="option">
<option value="randomShortcut">Raccourci aléatoire</option>
<option value="userShortcut">Donner un nom au raccourci</option>
</select>
<br>
<button type="submit" class="btn btn-dark text-center">Envoyer</button>
<br>
</div>
<p class="results text-center"></p>
</form>
<!-- Footer -->
<?php include("../../incl/footer.php");?>

View File

@ -14,16 +14,16 @@
</p> </p>
<table class="table table-bordered mt-5"> <table class="table table-bordered mt-5">
<thead> <thead>
<tr> <tr>
<th class="text-center" scope="col">Source</th> <th class="text-center" scope="col">Source</th>
<th class="text-center" scope="col">Citation/Proverbe</th> <th class="text-center" scope="col">Citation/Proverbe</th>
</tr> </tr>
</thead> </thead>
<tbody class="quote-list text-center"> <tbody class="quote-list text-center">
</tbody> </tbody>
</table> </table>
<!-- Footer --> <!-- Footer -->
<?php include("../incl/footer.php");?> <?php include("../incl/footer.php");?>

View File

@ -0,0 +1,28 @@
<!-- Config -->
<?php include("../php/config.php");?>
<!-- Header -->
<?php include("../incl/header.php");?>
<!-- Page Content -->
<div class="container">
<h1><span class="important"><?php echo $title?></span> :</h1>
<p class="pt-3 text-center">
<span class="totalLengthLinksList"></span><br>
<a href="/views/function-views/linkShortener.php">Revenir au raccourcisseur de liens.</a>
</p>
<table class="table table-bordered mt-5">
<thead>
<tr>
<th class="text-center" scope="col">Liens originaux</th>
<th class="text-center" scope="col">Liens raccourcit</th>
</tr>
</thead>
<tbody class="links-list text-center">
</tbody>
</table>
<!-- Footer -->
<?php include("../incl/footer.php");?>