Joomla JMail code not working - Javascript works fine - javascript

I'll try to be thorough and brief here. I am currently working in Joomla for the first time, but I've developed before. I am using Joomla 3.4. What I am trying to do:
A user signs up for our newsletter through a specific page that directs them to a coupon.
The next page shows them the coupon and has an email tag in the URL (i.e. &email='email')
I am trying to code within a module to parse out that email and send a copy of the coupon to that users email automatically.
I can't use a general automatic email when any user subscribes, because only users that sign up from that specific page will get the coupon. I have turned all text filtering off and am using basic module editor. When I save the module, the code shows just fine in the edit box. When I viewed the source of the page, that script tags would still be there, but the code would all be blank. I have now gone into phpmyadmin and can edit the module directly there. Now, the script is showing up just fine.
I've tried many different fixes, including adding a jQuery($) function load in order to bypass any issues with mootools. Wondering if it was an issue with Javascript, I cleared the script and made a simple alert("Testing..."); script that fired just fine on the page. This means that there must be something within my full script that is not working correctly. Any help or other ideas would be wonderful. I have spent over a day on this already and am at wits' end. Here's the code:
<script type="text/javascript">
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec (window.location.search))
$recipient = decodeURIComponent(name[1]);
}
$mailer = JFactory::getMailer();
$config = JFactory::getConfig();
$sender = array(
$config->get( 'config.mailfrom' ),
$config->get( 'config.fromname' )
);
$mailer->setSender($sender);
get('email');
$mailer->addRecipient($recipient);
$body = '<h2>Thank you for joining our mailing list!</h2>
'<div>Here is your coupon for a FREE 8" 1-topping pizza at Goodfellas!'
'<img src="http://www.goodfellas309.com/main/images/pizzacoupon.jpg" alt="pizza coupont"/></div>';
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setSubject('Your Free Pizza!');
$mailer->setBody($body);
$send = $mailer->Send;
if ( $send !== true ) {
echo 'Error sending email: ' . $send->__toString();
} else {
alert("An email with your coupon has been sent to you! Thank you for joining our mailing list!");
}
');
</script>
I have even attempted an inline PHP parse through Joomla with this code wrapping the javascript:
<?php
$document = JFactory::getDocument();
$document->addScriptDeclaration('
-Javascript here-
');
?>
I've always loved StackOverflow, and the answered questions have gotten me out of so many jams. I just can't find the answer to this anywhere. Thanks for your time!

Put the following inside your module.
<?php
// Get the email from the url
$jinput = JFactory::getApplication()->input;
$recipient = $jinput->get('email', '', 'string');
$mailer = JFactory::getMailer();
$config = JFactory::getConfig();
$sender = array(
$config->get( 'config.mailfrom' ),
$config->get( 'config.fromname' )
);
$mailer->setSender($sender);
$mailer->addRecipient($recipient);
$body = '<h2>Thank you for joining our mailing list!</h2>'
.'<div>Here is your coupon for a FREE 8" 1-topping pizza at Goodfellas!'
.'<img src="http://www.goodfellas309.com/main/images/pizzacoupon.jpg" alt="pizza coupont"/></div>';
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setSubject('Your Free Pizza!');
$mailer->setBody($body);
$send = $mailer->Send;
if ( $send !== true ) {
echo '<script type="text/javascript">Error sending email: ' . $send->__toString() . '</script>';
} else {
echo '<script type="text/javascript">alert("An email with your coupon has been sent to you! Thank you for joining our mailing list!");</script>';
}
Note: Depending on where you're putting this code you might need an extension like this one to make the php run.

Related

Securely Upload data to Server from HTML Form

My website allows users to input and upload 2 things:
Their name - which they type into a textfield in an HTML form
And a photo - which they upload from their computer also using this same form.
Upon hitting "submit" my Javascript code calls a PHP script sitting on my server, that PHP script takes that data and writes it into a JSON file, puts that file in the right folder, also puts the image where it needs to go - and it all works perfectly thus far.
However, it just dawned on me that anyone reading my Javascript code can find the URL of my PHP script - which means they can then copy-paste that URL directly into the browser - and wreak all sorts of havoc.
Obviously I need to go about all this in a different way.
Should I just not use PHP for this? If so, what other languages or platforms are available for me to do what I just described - in a way that's impossible to hack?
Or is there a way to obfuscate the URL of my PHP script so that no one can copy-paste it into the browser address bar?
Any advice would be greatly appreciated!
================================
UPDATE:
Here’s my PHP script:
<?php
$tokenID = $_POST["tokenIDNum"];
$fileName = "TokenMetadata/token". $tokenID .".json";
$userName = $_POST["userName"];
$imageURL = $_POST["userImageURL"];
// Log out for verification:
echo "Here's what I got so far:<br/>";
echo "tokenID: " .$tokenID ."<br/>";
echo "userName: " .$userName ."<br/>";
echo "imageURL: " .$imageURL ."<br/>";
// CREATE AND SAVE THE NEW METADATA-FILE:
$newMetadataFile = fopen($fileName, "wb");
if( $newMetadataFile == false ) {
// Do debugging or logging here:
echo "OPPS! We got an 'fopen' problem!";
}
else {
$contentString = "{\r\n";
$contentString = $contentString. ' "name" : “Fun Token # ' . $tokenID . '",';
$contentString = $contentString. "\r\n";
$contentString = $contentString. ' "description" : "Another token from our FUN Collection.",';
$contentString = $contentString. "\r\n";
$contentString = $contentString. ' "image" : "' .$imageURL;
$contentString = $contentString. "\r\n}";
fwrite($newMetadataFile, $contentString);
fclose($newMetadataFile);
}
// or die("Unable to open file!");
// $myfile = fopen("token.json", "w") or die("Unable to open file!");
?>
When I copy-paste the URL for this script into my browser - which is what I worry some bad actor might do - it creates a new EMPTY JSON file - and that's without me passing any arguments into that URL. So I'm pretty sure right now someone could not only create new phoney JSON files in this manner, but also rewrite existing ones with false data if they were to pass values for my arguments.
What I need to know is if it's even possible to prevent bad actors from doing this - or if I have to go about this in some totally different way?
My understanding is that if I add SESSION and perhaps CAPTCH I might be ok? (Obviously, I'm no PHP expert.)
Would love any thoughts/suggestions regarding that - before I spend hours going down that rabbit hole.

JavaScript function won't run after using header(), but does run if no use of header() (in php)

I apologize if my question title is at all confusing, this is my first post and despite reading https://stackoverflow.com/help/on-topic I feel like I may still have some flaws in my question-writing abilities.
TL;DR: JavaScript animation works if I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), but doesn't if I do (and I need to). Any reasons or solutions?
Anyway,
The context:
I have a html form embedded in a php document which is used to upload an image, delete an image, etc.
The main code takes place on ProjectUserProfile.php (and works perfectly), and after the image has been uploaded, I use header("location: ProjectUserProfile.php?UploadSuccessful") to return to the page, and prompt a refresh.
The problem:
If I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), the image will not change, etc, so it is a necessity for me to use it. However, recently I have implemented "slide in notifications" if you will which display success and error messages. These work correctly normally, but fail to appear if I return to the page using header("location: ProjectUserProfile.php?UploadSuccessful").
<?php
// all the uploading etc that works occurs here
header("location: ProjectUserProfile.php?UploadSuccessful");
echo "<script> openMessage('Information','The duplicate files were successfully uploaded!') </script>";
?>
After redirecting to ProjectUserProfile.php?UploadSuccessful, there is failure to acknowledge openMessage, and so nothing happens.
Whereas, had I not used header("location: ProjectUserProfile.php?UploadSuccessful"), the "notification" would slide in and work.
Does anyone have any solutions or suggestions?
Relevant code for the javascript function 'openMessage()' below:
function openMessage(Purpose, DisplayText){
var notificationDiv = document.getElementById("slideinNotification");
if(notificationDiv){
alert("exists");
}
else{
alert("does not exist");
}
document.addEventListener("DOMContentLoaded", function(event){
if(Purpose == "Information"){
document.getElementById("slideInNotification").style.backgroundColor = "#4CAF50";
}
else if(Purpose == "Warning"){
document.getElementById("slideInNotification").style.backgroundColor = "#FF9800";
}
else if(Purpose == "Error"){
document.getElementById("slideInNotification").style.backgroundColor = "#F44336";
}
document.getElementById("notificationMessage").innerHTML = DisplayText;
moveElement();
});
}
<?php
if($filesWereDeleted == true){
$connection = new mysqli("localhost", "root", "root", "project");
$result = $connection -> query("UPDATE UserProfileImage SET UploadStatus = 1 WHERE UserUniqueID = '$userProfileId'");
header("location: ProjectUserProfile.php?DeletionSuccessful");
echo "<script> openMessage('Information','The profile image was successfully deleted!') </script>";
}
?>
<div id = "slideInNotification" class = "slideNotification">
<p id = "notificationMessage" class = "notificationInfo"></p>
×
</div>
First, your UPDATE query exposed to SQL Injection, if you get the id from the user, I hope note, read about prepared statement.
Second, about your problem, you echo the notify script in the same response you send the Location header , so before the the browser even load your JavaScript code it redirect the client to the new page when your notify javascript code not echoed...
If your problem is that user updates it's image and it's doesn't appear due it cached you can use uniqid() in the get query of image src or modify time, more effective
The thing is, once you use header("location: ProjectUserProfile.php?DeletionSuccessful"); you're not supposed to write anything into the output, as the browser will ignore it. That aside, I'm not exactly sure about how a single line of <script> openMessage('Information','The duplicate files were successfully uploaded!') </script> could mean anything to the browser, since that wouldn't constitute an HTML document by itself, unless you're receiving it through AJAX or loading it into an <iframe>; but even then, I doubt mixing control instructions (a redirect) with view markup (the script tag) would be a good idea.
You're going to have to post the confirmation message in ProjectUserProfile.php, so move your script tag there. You can use that ?UploadSuccessful bit as reference for you to know whether to include your script for the message in the document is necessary or not.

HTML email confirmations - can I us js or php within the email?

I created an html email confirmation that gets sent to people who fill out my order form.
In the Shipping Address fields of the email I want it to show either: the separate shipping address they entered OR the same info from their billing address IF they didn't enter separate shipping info. This is what I have done:
<td><?php
$txt = false;
if( file_exists( 'text46' ) )
$txt = file_get_contents( 'text46' );
else if ( file_!exists( 'text46' ) )
$txt = file_get_contents( 'text12' );
?>
</td>
Dont' laugh. I got this code from somewhere else and it looked like the closet thing I've seen that could work (but it doesn't). But I have NO idea what some of it means. Like: should $txt=false?
I don't know. I just need this table data in the email to show 'text46' (the shipping address) if it was entered on the form, and if it wasn't then I want the table data to show 'text12' (the billing address). Can this even be done in the actual email?
I'm a MAJOR beginner and I know what I want it to do, but I have no idea how to do it.
You can't put code inside an e-mail and expect that it will work because of some simple reasons:
When people receive your e-mail, the service that handles it automatically blocks any code inside of it from being executed. So javascript will not work, PHP neither, and so on. It would be a huge security flaw if this could be possible.
PHP will never work anyway because is a server-side language. This means that it can't be executed on your pc. It needs to be executed on a server that sends a response back when finished.
Lear more about what server-side means: http://en.wikipedia.org/wiki/Server-side_scripting
Update:
Need to let everyone know that I found a solution. Instead of putting anything IN the email that would get ignored by email clients, I found some code that would auto-fill the Shipping fields on my form if a box was checked. Then I get the results in the email like I wanted.
I could have done this months ago if I had known to ask if emails would even work with scripts in them. Your answers helped me look for a different way to get the overall job done.
Thanks for all the help guys!
Here is the code I used for the auto-fill and the check box:`
<script type="text/javascript">
function SetShipping(checked) {
if (checked) {
document.getElementById("Shippingitem46_text_1").value = document.getElementById("item12_text_1").value;
document.getElementById("Shippingitem47_text_1").value = document.getElementById("item17_text_1").value;
document.getElementById("Shippingitem48_text_1").value = document.getElementById("item14_text_1").value;
document.getElementById("Shippingitem49_select_1").value = document.getElementById("item15_select_1").value;
document.getElementById("Shippingitem50_text_1").value = document.getElementById("item51_text_1").value;
document.getElementById("Shippingitem52_text_1").value = document.getElementById("item18_text_1").value;
} else {
document.getElementById("Shippingitem46_text_1").value = '';
document.getElementById("Shippingitem47_text_1").value = '';
document.getElementById("Shippingitem48_text_1").value = '';
document.getElementById("Shippingitem49_select_1").value = '';
document.getElementById("Shippingitem50_text_1").value = '';
document.getElementById("Shippingitem52_text_1").value = '';
}
}
</script>
<div class="fb-checkbox" style="color: rgb(168, 28, 45); font-weight: bold; font-size: 11px;">
<input type="checkbox" onclick="SetShipping(this.checked);"/>Check Box to copy info to Shipping.
</div>`

Ajax and jquery not sending data correctly to php

I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

How do I put a session value into a javascript?

I have a session['password']. I would like to get the session value and use it to validate against user's input.
if(opw != $_session['password']){
errors[errors.length] = "Sorry, password does not match.";
}
This is what I have been trying, however if I input this they do not read the session. And ignore this conditions. How do I actually insert session value into Javascript?
As the other answers have suggested, you have to embed your PHP session value into the javascript when the page is generator. But the others have forgotten one important thing - you have to generate VALID javascript or your entire script will get killed with a syntax error.
if (opw != <?php echo json_encode($_SESSION['password']) ?>) {
Note the call to json_encode - it's not just enough to output the password string. You have to make sure that the password becomes a VALID javascript string, which json_encode ensures.
Your inline JavaScript code:
var session = <?php print $_SESSION['password']; ?>;
Is that what you're looking for?
You need to surround the $_SESSION in <?php echo ?>. This causes the PHP variable to be printed into the Javascript on the page.
if(opw != <?php echo $_SESSION['password']; ?> ){
However, this is a deeply insecure method of checking a password and I advise against using it. If not transferred over SSL, the password will be sent in plain text on every page view. Furthermore, it is likely to be cached by the web browser where anyone with access to the computer may read it.
You'll have to actually echo out the errors manually:
// do all of your validation and add all of the errors to an array.
if($opw != $_session['password']){
$errors[] = "Sorry, password does not match.";
}
echo "<script type=\"text/javascript\">var errors = ".
json_encode( $errors ).";</script>";
Then, later:
<script type="text/javascript">alert(errors)</script>
Please note that PHP is totally different from JS. PHP is a server side coding-language, meaning it get's executed when your server is rendering the requested page. In that page (which contains some HTML) there can also be JS. However, JS cannot connect to PHP in the way you think it does. For this you could use Ajax or something (but that's way too complicated for the goal you're trying to achieve).
You probably want something like this
// eg. index.php or something
...
<?php
session_start();
if ($_POST['password'] == 'somePassYouDefined') {
echo 'Authenticated';
}else if (isset($_POST['password'])) {
echo 'Couldn\'t authenticate ...';
}else {
?>
<form method='post'>
<input type='password' name='password' placeholder='Password' />
<input type='submit' />
</form>
<?php
}
?>
ASP version:
if(opw != '<%=Session("password")%>' ){
I added quotes because a password is usually a string.
When the user runs this script, the html page that is downloaded to their computer will display the password IN PLAIN TEXT, ie:
if(opw != 'BOBSPASSWORD' ){
So, if they don't know or have a password, they can view/source and find it.

Categories