document.addEventListener('DOMContentLoaded', () => { const titleInput = document.getElementById('title'); const mediaInput = document.getElementById('media'); const paperInput = document.getElementById('paper'); const dateInput = document.getElementById('date'); const urlInput = document.getElementById('url'); const disciplineInput = document.getElementById('discipline'); const areaInput = document.getElementById('area'); const tagInput = document.getElementById('tags'); const tagList = document.getElementById('taglist'); const tagSpan = document.getElementById('tag-span'); const intNameInput = document.getElementById('name'); const intStatusInput = document.getElementById('status'); const instInput = document.getElementById('institution'); const labInput = document.getElementById('lab'); const emailInput = document.getElementById('email'); const consentCheck = document.getElementById('consent-check'); const captchaQtn = document.getElementById('captcha-qtn'); const captchaInput = document.getElementById('captcha'); const submitBtn = document.querySelector('button#submit-btn'); const spinner = document.getElementById('spinner'); const checkmark = document.getElementById('checkmark'); submitBtn.disabled = true; // Create & listen to "captcha" function getRandomNb() { return Math.floor(Math.random() * 9) + 1; } const nb1 = getRandomNb(); const nb2 = getRandomNb(); function drawCaptcha() { const numbers = { 1: 'un', 2: 'deux', 3: 'trois', 4: 'quatre', 5: 'cinq', 6: 'six', 7: 'sept', 8: 'huit', 9: 'neuf', }; var canvas = document.createElement('canvas'); canvas.width = 170; canvas.height = 60; var ctx = canvas.getContext('2d'); ctx.font = '24px Arial'; let ltr1 = numbers[nb1] || nb1; let ltr2 = numbers[nb2] || nb2; ctx.fillText(ltr1 + ' + ' + ltr2 + ' = ', 10, 50); var img = document.createElement('img'); img.style.display = 'inline-block'; img.style.verticalAlign = 'super'; canvas.toBlob(function (blob) { img.src = URL.createObjectURL(blob); }); captchaQtn.appendChild(img); } drawCaptcha(); // captchaQtn.textContent = `${nb1} + ${nb2} = `; function checkCaptcha() { const captchaRight = nb1 + nb2; const captchaAnswer = Number(captchaInput.value); if (captchaAnswer === captchaRight) { return true; } else { return false; } } captchaInput.addEventListener('input', () => { const captcha = checkCaptcha(); if (captcha && consentCheck.checked) { submitBtn.disabled = false; } else { submitBtn.disabled = true; } }); // Listen to consent checkbox consentCheck.addEventListener('change', () => { const captcha = checkCaptcha(); if (captcha && consentCheck.checked) { submitBtn.disabled = false; } else { submitBtn.disabled = true; } }); // Create list of existing tags for input suggestions createTagList(); tagInput.setAttribute('list', 'taglist'); const blogTags = []; async function createTagList() { const url = 'https://blogs.univ-tlse2.fr/saes/wp-json/wp/v2/tags?per_page=100&page='; let i = 1; let morePages = true; while (morePages) { try { const pageUrl = url + i; const response = await fetch(pageUrl); if (response && response.ok) { const data = await response.json(); if (data.length > 0) { blogTags.push(...data); i++; } else { morePages = false; } } else { window.alert( 'Échec de la création de la liste de mots-clefs. Cliquez sur "OK" pour recharger la page.' ); location.reload(); } } catch (error) { window.alert( 'Échec de la création de la liste de mots-clefs. Cliquez sur "OK" pour recharger la page.' ); location.reload(); } } for (let tag of blogTags) { const opt = document.createElement('option'); opt.value = tag.name; tagList.appendChild(opt); } } let userTags = []; let t = 1; tagInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') { const tagName = tagInput.value.replaceAll(/<[^>]*>/gu, '').trim(); let tagNames = []; if (tagName.includes(',') || tagName.includes(';')) { tagNames = tagName.split(/[,;]/); } else { tagNames.push(tagName); } for (let tN of tagNames) { tN = tN.trim(); userTags.push(tN); const tagLabel = document.createElement('span'); tagLabel.id = `tag${t}`; tagLabel.classList.add('tag-label'); tagLabel.textContent = tN; const tagDelete = document.createElement('span'); tagDelete.textContent = '❌'; tagDelete.style.cursor = 'pointer'; tagDelete.style.marginLeft = '0.5em'; tagDelete.onclick = () => { userTags = userTags.filter((tag) => tag !== tN); tagLabel.remove(); }; tagLabel.appendChild(tagDelete); tagSpan.appendChild(tagLabel); t++; } tagInput.value = ''; } }); // Manage required inputs const reqInputs = Array.from( document.getElementsByClassName('required-input') ); reqInputs.forEach((i) => { i.addEventListener('input', () => { i.removeAttribute('style'); }); }); // Correct URL input urlInput.onchange = () => { if (urlInput.value && !urlInput.value.startsWith('http')) { urlInput.value = 'https://' + urlInput.value; } }; // Listen to submit button submitBtn.addEventListener('click', buildPost); // Build draft post contents async function buildPost() { const title = titleInput.value.replaceAll(/<[^>]*>/gu, ''); const media = mediaInput.value.replaceAll(/<[^>]*>/gu, ''); const paper = paperInput.value.replaceAll(/<[^>]*>/gu, ''); const date = dateInput.value.replaceAll(/<[^>]*>/gu, ''); let url = urlInput.value; // if (url.length > 0 && !url.startsWith('http')) { // url = 'https://' + url; // } const categories = []; categories.push(media); for (let option of disciplineInput.options) { if (option.selected) { categories.push(option.value); } } for (let option of areaInput.options) { if (option.selected) { categories.push(option.value); } } const intName = intNameInput.value.replaceAll(/<[^>]*>/gu, ''); const intStatus = intStatusInput.value.replaceAll(/<[^>]*>/gu, ''); const inst = instInput.value.replaceAll(/<[^>]*>/gu, ''); const lab = labInput.value.replaceAll(/<[^>]*>/gu, ''); const email = emailInput.value.replaceAll(/<[^>]*>/gu, ''); // Check if all required inputs are filled in & display alert if not const missingValue = reqInputs.find((v) => !v.value); if (missingValue) { const missing = []; for (let i of reqInputs) { if (!i.value) { missing.push(i.name); i.style.outline = 'solid 2px red'; } } const missingString = missing.join(', '); missingValue.focus(); window.alert( 'Saisissez les informations manquantes: ' + missingString ); spinner.style.display = 'none'; return; } const dateArray = date.split('-'); const year = dateArray[0]; const month = dateArray[1]; const day = dateArray[2]; const postDate = `${day}/${month}/${year}`; let content = `
Média : ${media}
Émission ou journal : ${paper}
Date : ${postDate}
URL : ${url}

Intervenant·e :
${intName}
${intStatus}
${inst}
${lab}
Courriel : ${email}
`; // Build post preview const confirmDialog = document.getElementById('confirm-dialog'); const subContent = document.getElementById('submission-content'); subContent.innerHTML = `${title}

` + content; const subCats = document.getElementById('submission-cats'); if (categories.length > 0) { subCats.innerHTML = `Catégorie(s) : ${categories.join( ', ' )}`; } const subTags = document.getElementById('submission-tags'); if (userTags.length > 0) { subTags.innerHTML = `Mot(s)-clef(s) : ${userTags.join( ', ' )}`; } const yesBtn = document.getElementById('confirm-btn'); const noBtn = document.getElementById('cancel-btn'); yesBtn.onclick = async () => { const confirmMsg = document.getElementById('confirm-message'); const dialogBtns = document.getElementById('dialog-btns'); const spinnerDiv = document.getElementById('spinner-div'); confirmMsg.style.display = 'none'; dialogBtns.style.display = 'none'; spinnerDiv.style.display = 'block'; checkmark.style.display = 'none'; spinner.style.display = 'inline-block'; const tagIDs = await checkTag(userTags); const cats = await retrieveCategories(categories); const id = await submitPost(title, content, cats, tagIDs); const closeBtn = document.createElement('span'); closeBtn.textContent = '❌'; closeBtn.style.float = 'right'; closeBtn.style.cursor = 'pointer'; setTimeout(() => { spinnerDiv.before(closeBtn); sendMail(title, id); }, 1500); closeBtn.onclick = () => { confirmDialog.close(); confirmMsg.style.display = 'block'; dialogBtns.style.display = 'block'; spinnerDiv.style.display = 'none'; checkmark.style.display = 'none'; closeBtn.remove(); }; }; noBtn.onclick = () => { confirmDialog.close(); spinner.style.display = 'none'; return; }; confirmDialog.showModal(); subContent.focus(); } // Retrieve tag IDs async function checkTag(userTags) { const tagIDs = []; for (let tag of userTags) { try { const foundTag = blogTags.find((t) => t.name === tag); if (foundTag) { tagIDs.push(foundTag.id); } else { const tagID = await createTag(tag); tagIDs.push(tagID); } } catch (error) { console.error(error.message); } } return tagIDs; } // Create new tag async function createTag(tag) { try { const url = 'https://blogs.univ-tlse2.fr/saes/wp-json/wp/v2/tags'; const token = 'Ow5wmOLJmEIJTBniP0gZJRnvLkc33pIrgrgqITjXZOu57S67Mby5LNxbo1HcAKaEYAd2chLTy6pH01AEyOLlGfOAJ4JRihrDSx7usXGyXfd64NIquooi5PGcqSIcdK78'; const headers = new Headers(); headers.append('Authorization', 'Bearer ' + token); headers.append('Content-type', 'application/json'); const tagData = { name: tag, }; const response = await fetch(url, { method: 'POST', headers: headers, body: JSON.stringify(tagData), }); if (response && response.ok) { const data = await response.json(); if (data) { return data.id; } } else { console.error(response.message); window.alert( `Could not create tag "${tag}": ${response.message}` ); return; } } catch (error) { console.error(error.message); } } // Retrieve category IDs async function retrieveCategories(categories) { const url = 'https://blogs.univ-tlse2.fr/saes/wp-json/wp/v2/categories'; const cats = []; for (let cat of categories) { try { const catUrl = url + `?search=${cat}`; const response = await fetch(catUrl); if (response && response.ok) { const data = await response.json(); if (data[0]) { cats.push(data[0].id); } else { window.alert( `Category ${cat} does not exist, skipping` ); continue; } } else { console.error('Could not fetch categories from blog'); continue; } } catch (error) { console.error(error); window.alert( `There was a problem retrieving category ${cat}, please try again` ); return; } } return cats; } // Post draft to Wordpress API async function submitPost(title, content, categories, tags) { const postUrl = 'https://blogs.univ-tlse2.fr/saes/wp-json/wp/v2/posts'; const token = 'Ow5wmOLJmEIJTBniP0gZJRnvLkc33pIrgrgqITjXZOu57S67Mby5LNxbo1HcAKaEYAd2chLTy6pH01AEyOLlGfOAJ4JRihrDSx7usXGyXfd64NIquooi5PGcqSIcdK78'; const headers = new Headers(); headers.append('Authorization', 'Bearer ' + token); headers.append('Content-type', 'application/json'); let postData = { title: title, content: { raw: content }, categories: categories, tags: tags, status: 'draft', comment_status: 'closed', }; return fetch(postUrl, { method: 'POST', headers: headers, body: JSON.stringify(postData), }) .then((response) => response.json()) .then((data) => { if (data.id) { spinner.style.display = 'none'; checkmark.style.display = 'inline-block'; const id = data.id; return id; } else { console.error('Failed to create post: ', data); spinner.style.display = 'none'; window.alert(data.message); } }) .catch((error) => { spinner.style.display = 'none'; console.error('Error: ', error); }); } // Prompt user to send notification email to admins function sendMail(title, id) { const mailLink = document.createElement('a'); const mailSubject = encodeURIComponent( `Nouvelle soumission d'intervention médiatique` ); const mailBody = encodeURIComponent( `Veuillez consulter la soumission suivante : ${title}, https://blogs.univ-tlse2.fr/saes/wp-admin/post.php?post=${id}&action=edit` ); mailLink.setAttribute( 'href', `mailto:blandine.pennec@univ-tlse2.fr,zachary.baque@univ-tlse2.fr?subject=${mailSubject}&body=${mailBody}` ); mailLink.click(); } });