Lots more stuff for accounts and managing dictionaries in the database.

All this PHP stuff really needs to be in a new branch.
This commit is contained in:
Robbie Antenesse 2015-11-04 14:12:39 -07:00
parent 30abe592db
commit 898dabedb2
6 changed files with 342 additions and 26 deletions

2
.gitignore vendored
View File

@ -1 +1,3 @@
php/google/
images/favicon.png
images/lexiconga.png

View File

@ -10,7 +10,7 @@ if (isset($_GET['logout']) && $current_user > 0) {
session_destroy();
header('Location: ./index2.php?loggedout');
}
if (isset($_GET['login'])) {
elseif (isset($_GET['login'])) {
if (isset($_POST['email']) && isset($_POST['password'])) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
if (EmailExists($_POST['email'])) {
@ -30,10 +30,10 @@ if (isset($_GET['login'])) {
header('Location: ./index2.php?error=loginemailorpasswordblank');
}
}
if (isset($_GET['createaccount'])) {
elseif (isset($_GET['createaccount'])) {
if (isset($_POST['email']) && isset($_POST['password'])) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && !EmailExists($_POST['email'])) {
if (query("INSERT INTO users (email, password, allow_email) VALUES ('" . $_POST['email'] . "','" . crypt($_POST['password'], $_POST['email']) . "'," . (($_POST['allowemails'] != "on") ? 0 : 1) . ")")) {
if (query("INSERT INTO users (email, password, public_name, allow_email) VALUES ('" . $_POST['email'] . "','" . crypt($_POST['password'], $_POST['email']) . "','" . htmlspecialchars($_POST['publicname'], ENT_QUOTES) . "'," . (($_POST['allowemails'] != "on") ? 0 : 1) . ")")) {
header('Location: ./index2.php?success');
} else {
header('Location: ./index2.php?error=couldnotcreate');
@ -45,7 +45,7 @@ if (isset($_GET['createaccount'])) {
header('Location: ./index2.php?error=createemailorpasswordblank');
}
}
if (isset($_GET['error'])) {
elseif (isset($_GET['error'])) {
if ($_GET['error'] == "couldnotcreate") {
$notificationMessage = "Could not create account.<br>Please try again later.";
} elseif ($_GET['error'] == "emailcreateinvalid") {
@ -73,10 +73,10 @@ if (isset($_GET['error'])) {
$notificationMessage = "Something seems to have gone wrong, but I don't know what.<br>Please try again.";
}
}
if (isset($_GET['success'])) {
elseif (isset($_GET['success'])) {
$notificationMessage = "Your account was created successfully!<br>Please log in using the email address and password you used to create it and you can start accessing your dictionaries anywhere!";
}
if (isset($_GET['loggedout'])) {
elseif (isset($_GET['loggedout'])) {
$notificationMessage = "You have been successfully logged out.<br>You will only be able to use the dictionary saved to your browser.";
}
?>
@ -250,6 +250,10 @@ if (isset($_GET['loggedout'])) {
<script src="js/defiant-js/defiant-latest.min.js"></script>
<!-- Main Script -->
<script src="js/dictionaryBuilder.js"></script>
<script>
currentUser = <?php echo $current_user; ?>;
publicName = <?php echo Get_Public_Name($current_user); ?>;
</script>
<?php include_once("php/google/analytics.php"); ?>
</body>
</html>

View File

@ -1,11 +1,14 @@
/* global markdown */
/* global Defiant */
var currentVersion = 0.2;
var currentVersion = 0.3;
var currentUser = 0;
var publicName = "Someone";
var currentDictionary = {
name: "New",
description: "A new dictionary.",
creatorName: publicName,
words: [],
settings: {
allowDuplicates: false,
@ -13,10 +16,12 @@ var currentDictionary = {
partsOfSpeech: "Noun,Adjective,Verb,Adverb,Preposition,Pronoun,Conjunction",
isComplete: false
},
externalID: 0,
dictionaryImportVersion: currentVersion // This needs to always be last.
}
};
var defaultDictionaryJSON = JSON.stringify(currentDictionary); //Saves a stringifyed default dictionary.
var previousDictionary = {};
var savedScroll = {
x: 0,
@ -57,6 +62,9 @@ loginForm = '<div class="settingsCol"><form id="loginForm" method="post" action=
<label><span>Confirm Password</span> \
<input type="password" id="createAccountPasswordConfirmField" name="confirmpassword" /> \
</label> \
<label><span>Public Name <span class="clickable" onclick="alert(\'This is the name we greet you with. It is also the name displayed if you ever decide to share any of your dictionaries.\n\nNote: this is not a username, and as such may not be unique. Use something people will recognize you as to differentiate from other people who might use the same name!\')">?</span></span> \
<input type="text" id="createAccountPublicNameField" name="publicname" /> \
</label> \
<label><b>Allow Emails</b> \
<input type="checkbox" id="createAccountAllowEmailsField" name="allowemails" checked="checked" /> \
</label> \
@ -88,6 +96,7 @@ function ValidateCreateAccount() {
var emailValue = document.getElementById("createAccountEmailField").value;
var passwordValue = document.getElementById("createAccountPasswordField").value;
var passwordConfirmValue = document.getElementById("createAccountPasswordConfirmField").value;
var publicNameValue = document.getElementById("createAccountPublicNameField").value;
if (emailValue == "") {
errorMessage.innerHTML = "Email cannot be blank!";
@ -101,6 +110,9 @@ function ValidateCreateAccount() {
} else if (passwordValue != passwordConfirmValue) {
errorMessage.innerHTML = "Passwords do not match!";
return false;
} else if (publicNameValue == "") {
errorMessage.innerHTML = "Public Name cannot be blank!";
return false;
} else {
var emailCheck = new XMLHttpRequest();
emailCheck.open('GET', "php/ajax_createaccountemailcheck.php?email=" + emailValue);
@ -191,7 +203,7 @@ function AddWord() {
}
} else {
currentDictionary.words.push({name: word, simpleDefinition: simpleDefinition, longDefinition: longDefinition, partOfSpeech: partOfSpeech});
SaveAndUpdateDictionary(false);
SaveAndUpdateDictionary(false, true);
}
@ -245,9 +257,10 @@ function EditWord(index) {
document.getElementById("editWordButtonArea").style.display = "block";
}
function SaveAndUpdateDictionary(keepFormContents) {
function SaveAndUpdateDictionary(keepFormContents, sendWords) {
sendWords = (typeof sendWords !== 'undefined') ? sendWords : false;
currentDictionary.words.sort(dynamicSort("name"));
SaveDictionary();
SaveDictionary(sendWords);
ShowDictionary();
if (!keepFormContents) {
ClearForm();
@ -261,7 +274,7 @@ function UpdateWord(wordIndex, word, simpleDefinition, longDefinition, partOfSpe
currentDictionary.words[wordIndex].longDefinition = longDefinition;
currentDictionary.words[wordIndex].partOfSpeech = partOfSpeech;
SaveAndUpdateDictionary();
SaveAndUpdateDictionary(false, true);
window.scroll(savedScroll.x, savedScroll.y);
}
@ -272,7 +285,7 @@ function DeleteWord(index) {
currentDictionary.words.splice(index, 1);
SaveAndUpdateDictionary(true);
SaveAndUpdateDictionary(true, true);
}
function CloseUpdateConflictArea() {
@ -463,7 +476,7 @@ function SaveSettings() {
HideSettingsWhenComplete();
SaveAndUpdateDictionary(true);
SaveAndUpdateDictionary(true, false);
}
function HideSettingsWhenComplete() {
@ -514,24 +527,119 @@ function HideSettings() {
function EmptyWholeDictionary() {
if (confirm("This will delete the entire current dictionary. If you do not have a backed up export, you will lose it forever!\n\nDo you still want to delete?")) {
currentDictionary = JSON.parse(defaultDictionaryJSON);
SaveAndUpdateDictionary(false);
SaveAndUpdateDictionary(false, true);
SetPartsOfSpeech();
HideSettings();
}
}
function SaveDictionary() {
function SaveDictionary(sendWords) {
localStorage.setItem('dictionary', JSON.stringify(currentDictionary));
//location.reload();
//Always save local copy of current dictionary, but if logged in also send to database.
if (currentUser > 0) {
sendWords = (typeof sendWords !== 'undefined') ? sendWords : false;
SendDictionary(sendWords);
}
SavePreviousDictionary();
}
function SendDictionary(sendWords) {
sendWords = (typeof sendWords !== 'undefined') ? sendWords : false;
var action = "";
var postString = "";
if (currentDictionary.externalID > 0) {
action = "update";
postString = DataToSend(sendWords);
} else {
action = "new";
postString = DataToSend(true);
}
var sendDictionary = new XMLHttpRequest();
sendDictionary.open('POST', "php/ajax_dictionarymanagement.php?action=" + action);
sendDictionary.onreadystatechange = function() {
if (sendDictionary.readyState == 4 && sendDictionary.status == 200) {
if (sendDictionary.responseText == "updated successfully") {
console.log(sendDictionary.responseText);
} else if (!isNaN(parseInt(sendDictionary.responseText))) {
currentDictionary.externalID = parseInt(sendDictionary.responseText);
console.log("saved successfully");
} else {
console.log(sendDictionary.responseText);
}
return true;
} else {
return false;
}
}
sendDictionary.send(postString);
}
function DataToSend(doSendWords) {
var data = "";
if (currentDictionary.externalID == 0) {
data = "name=" + encodeURIComponent(currentDictionary.name) + "&description=" + encodeURIComponent(currentDictionary.description) + "&words=" + encodeURIComponent(JSON.stringify(currentDictionary.words));
data += "&allowduplicates=" + ((currentDictionary.settings.allowDuplicates) ? "1" : "0") + "&casesensitive=" + ((currentDictionary.settings.caseSensitive) ? "1" : "0");
data += "&partsofspeech=" + encodeURIComponent(currentDictionary.settings.partsOfSpeech) + "&iscomplete=" + ((currentDictionary.settings.isComplete) ? "1" : "0") + "&ispublic=0";
} else {
if (currentDictionary.name != previousDictionary.name) {
data += "name=" + encodeURIComponent(currentDictionary.name);
}
if (currentDictionary.description != previousDictionary.description) {
data += ((data=="") ? "" : "&") + "description=" + encodeURIComponent(currentDictionary.description);
}
if (doSendWords) {
data += ((data=="") ? "" : "&") + "words=" + encodeURIComponent(JSON.stringify(currentDictionary.words));
}
if (currentDictionary.settings.allowDuplicates != previousDictionary.allowDuplicates) {
data += ((data=="") ? "" : "&") + "allowduplicates=" + ((currentDictionary.settings.allowDuplicates) ? "1" : "0");
}
if (currentDictionary.settings.caseSensitive != previousDictionary.caseSensitive) {
data += ((data=="") ? "" : "&") + "casesensitive=" + ((currentDictionary.settings.caseSensitive) ? "1" : "0");
}
if (currentDictionary.settings.partsOfSpeech != previousDictionary.partsOfSpeech) {
data += ((data=="") ? "" : "&") + "partsofspeech=" + encodeURIComponent(currentDictionary.settings.partsOfSpeech);
}
if (currentDictionary.settings.isComplete != previousDictionary.isComplete) {
data += ((data=="") ? "" : "&") + "iscomplete=" + ((currentDictionary.settings.isComplete) ? "1" : "0");
}
data += ((data=="") ? "" : "&") + "ispublic=0";
}
return data;
}
function LoadDictionary() {
if (localStorage.getItem('dictionary')) {
var tmpDictionary = JSON.parse(localStorage.getItem('dictionary'));
if (tmpDictionary.words.length > 0) {
currentDictionary = JSON.parse(localStorage.getItem('dictionary'));
if (currentUser > 0) { //If logged in, load the dictionary from database
var loadDictionary = new XMLHttpRequest();
loadDictionary.open('GET', "php/ajax_dictionarymanagement.php?action=load");
loadDictionary.onreadystatechange = function() {
if (loadDictionary.readyState == 4 && loadDictionary.status == 200) {
if (loadDictionary.responseText == "no dictionaries") {
SendDictionary();
console.log(loadDictionary.responseText);
} else if (loadDictionary.responseText == "could not load" ||
loadDictionary.responseText == "not signed in" ||
loadDictionary.responseText == "no info provided") {
console.log(loadDictionary.responseText);
} else {
currentDictionary = JSON.parse(loadDictionary.responseText);
}
return true;
} else {
return false;
}
}
loadDictionary.send();
} else { //Otherwise load the local one.
if (localStorage.getItem('dictionary')) {
var tmpDictionary = JSON.parse(localStorage.getItem('dictionary'));
if (tmpDictionary.words.length > 0) {
currentDictionary = JSON.parse(localStorage.getItem('dictionary'));
}
tmpDictionary = null;
}
tmpDictionary = null;
}
HideSettingsWhenComplete();
@ -544,8 +652,20 @@ function LoadDictionary() {
document.getElementById("wordEntryForm").style.display = "none";
}
// Update search snapshot
//dictionarySearchSnapshot = Defiant.getSnapshot(currentDictionary);
SavePreviousDictionary();
}
function SavePreviousDictionary () {
// Save non-word data to check if anything has changed (words can identify themselves if changed).
// Used to minimize data pushed to database.
previousDictionary = {
name: currentDictionary.name,
description: currentDictionary.description,
allowDuplicates: currentDictionary.settings.allowDuplicates,
caseSensitive: currentDictionary.settings.caseSensitive,
partsOfSpeech: currentDictionary.settings.partsOfSpeech,
isComplete: currentDictionary.settings.isComplete
};
}
function ExportDictionary() {

View File

@ -0,0 +1,168 @@
<?php
require_once("../required.php");
if ($_GET['action'] == 'getall') {
Get_Dictionaries();
}
elseif ($_GET['action'] == 'load') {
Load_Current_Dictionary();
}
elseif ($_GET['action'] == 'new') {
Save_Current_DictionaryAsNew();
}
elseif ($_GET['action'] == 'update') {
Update_Current_Dictionary();
}
elseif ($_GET['action'] == 'switch') {
Switch_Current_Dictionary();
}
function Get_Dictionaries() {
if (isset($_SESSION['user'])) {
if ($_SESSION['user'] > 0) {
$query = "SELECT `id`, `name` FROM `dictionaries` WHERE `user`=" . $_SESSION['user'] . " ORDER BY `name` ASC;";
$dictionaries = query($query);
if ($dictionaries) {
if (num_rows($dictionaries) > 0) {
while ($dict = fetch_assoc($dictionaries)) {
$_SESSION['dictionaries'][] = $dict['id']; // Save a list of all dictionaries user has.
//list for the switch dictionaries dropdown.
$list = $dict['id'] . '_IDNAMESEPARATOR_' . $dict['name'] . '_DICTIONARYSEPARATOR_';
echo $list;
return true;
}
} else {
echo "no dictionaries";
}
} else {
echo "could not load";
}
} else {
echo "not signed in";
}
} else {
echo "no info provided";
}
return false;
}
function Load_Current_Dictionary() {
if (isset($_SESSION['user'])) {
$query = "SELECT * FROM `dictionaries` WHERE `is_current`=1 AND `user`=" . $_SESSION['user'] . ";";
$dictionary = query($query);
if ($dictionary) {
if (num_rows($dictionary) === 1) {
while ($dict = fetch_assoc($dictionary)) {
$_SESSION['dictionary'] = $dict['id'];
$json = '{"name":"' . $dict['name'] . '","description":"' . $dict['description'] . '","words":"' . $dict['words'] . '",';
$json .= '"settings":{"allowDuplicates":' . ($dict['allow_duplicates'] == 1) ? "true" : "false" . ',';
$json .= '"caseSensitive":' . ($dict['case_sensitive'] == 1) ? "true" : "false" . ',';
$json .= '"partsOfSpeech":"' . $dict['parts_of_speech'] . ',';
$json .= '"isComplete":' . ($dict['is_complete'] == 1) ? "true" : "false" . '},';
$json .= '"externalID":"' . $dict['id'] . ',';
$json .= '"dictionaryImportVersion":' . $dict['import_version'] . '}';
echo $json;
return true;
}
} else {
echo "more than 1 returned";
}
} else {
echo "could not load";
}
} else {
echo "no info provided";
}
return false;
}
function Save_Current_DictionaryAsNew() {
if (isset($_SESSION['user'])) {
$query = "INSERT INTO `dictionaries`(`user`, `is_current`, `name`, `description`, `words`, `allow_duplicates`, `case_sensitive`, `parts_of_speech`, `is_complete`, `is_public`) ";
$query .= "VALUES (" . $_SESSION['user'] . ",1,'" . $_POST['name'] . "','" . $_POST['description'] . "','" . $_POST['words'] . "'," . $_POST['allowduplicates'] . "," . $_POST['casesensitive'] . "," . $_POST['partsofspeech'] . "," . $_POST['iscomplete'] . "," . $_POST['ispublic'] . ")";
$update = query($query);
if ($update) {
$_SESSION['dictionary'] = mysql_insert_id(connection());
$_SESSION['dictionaries'][] = $_SESSION['dictionary']; //Add new id to valid dictionaries.
echo $_SESSION['dictionary'];
return true;
} else {
echo "could not update";
}
} else {
echo "no info provided";
}
return false;
}
function Update_Current_Dictionary() {
if (isset($_SESSION['dictionary'])) {
$query = "UPDATE `dictionaries` SET ";
if (isset($_POST['name'])) {
$query .= "`name`='" . $_POST['name'] . "', ";
}
if (isset($_POST['description'])) {
$query .= "`description`='" . $_POST['description'] . "', ";
}
if (isset($_POST['words'])) {
$query .= "`words`='" . $_POST['words'] . "', ";
}
if (isset($_POST['allowDuplicates'])) {
$query .= "`allow_duplicates`=" . $_POST['allowduplicates'] . ", ";
}
if (isset($_POST['casesensitive'])) {
$query .= "`case_sensitive`=" . $_POST['casesensitive'] . ", ";
}
if (isset($_POST['partsofspeech'])) {
$query .= "`parts_of_speech`='" . $_POST['partsofspeech'] . "', ";
}
if (isset($_POST['iscomplete'])) {
$query .= "`is_complete`=" . $_POST['iscomplete'] . ", ";
}
if (isset($_POST['ispublic'])) {
$query .= "`is_public`=" . $_POST['ispublic'] . ", ";
}
$query .= "`last_updated`='" . date("Y-m-d H:i:s") . "'";
$query .= " WHERE `id`=" . $_SESSION['dictionary'] . " AND `user`=" . $_SESSION['user'] . ";";
$update = query($query);
if ($update) {
echo "updated successfully";
return true;
} else {
echo "could not update";
}
} else {
echo "no info provided";
}
return false;
}
function Switch_Current_Dictionary() {
if (isset($_POST['newdictionaryid']) && isset($_SESSION['user'])) {
if (in_array($_POST['newdictionaryid'], $_SESSION['dictionaries'])) {
//Clear is_current from all user's dictionaries and then update the one they chose, only if the chosen dictionary is valid.
$query = "UPDATE `dictionaries` SET `is_current`=0 WHERE `user`=" . $_SESSION['user'] . ";";
$query .= "UPDATE `dictionaries` SET `is_current`=1 WHERE `id`=" . $_POST['newdictionaryid'] . " AND `user`=" . $_SESSION['user'] . ";";
$update = multi_query($query);
if ($update) {
Load_Current_Dictionary();
return true;
} else {
echo "could not update";
}
} else {
echo "invalid dictionary";
}
} else {
echo "no info provided";
}
return false;
}
?>

View File

@ -5,6 +5,11 @@ function query ($query_string) {
return $query;
}
function multi_query ($query_string) {
$query = mysqli_multi_query(connection(), $query_string);
return $query;
}
function num_rows ($query_results) {
$num_rows = mysqli_num_rows($query_results);

View File

@ -23,7 +23,7 @@ function Validate_Login($email, $password) {
}
function Get_User_Id($email) {
$query = "SELECT id FROM users WHERE name='" . $email . "'";
$query = "SELECT id FROM users WHERE email='" . $email . "'";
$users = query($query);
if ($users && num_rows($users) > 0) {
@ -32,7 +32,24 @@ function Get_User_Id($email) {
return $user["id"];
}
} else {
return "More than one username returned!";
return "More than one user id returned!";
}
} else {
return "No User";
}
}
function Get_Public_Name($id) {
$query = "SELECT public_name FROM users WHERE id=" . $id;
$users = query($query);
if ($users && num_rows($users) > 0) {
if (num_rows($users) === 1) {
while($user = fetch_assoc($users)) {
return $user["public_name"];
}
} else {
return "More than one public name returned!";
}
} else {
return "No User";