Javascript email encryption, am I doing this right? - javascript

I came up with a way to encrypt email addresses using javascript, but seeing as I am new to programming, I'm not sure how effective my solution is. Basically I'm pulling in an email using Advanced Custom Fields, saving a spam-proofed version of it, then transforming it with javascript in the footer. FYI I am using Wordpress.
Here is the relevant part of the page:
<?php get_header(); ?>
<a href='' id='email'></a>
<script type="text/javascript">
var email_storage = "nospam<?php the_field('team-email'); ?>";
console.log(email_storage);
</script>
<?php get_footer(); ?>
Then this script loads in the footer (after jQuery).
var email_length_nospam = email_storage.length;
var email = email_storage.substr(6,email_length_nospam);
var email_length = email.length;
var at = email.indexOf('#');
var email_name = email.substr(0,at);
var email_domain = email.substr((at+1),email_domain);
console.log(email_length_nospam,email);
jQuery('a#email').html(email_name+'#'+email_domain);
jQuery('a#email').attr('href','mailto:'+email);
My question is this:
Am I missing anything obvious? In other words, would a spam bot easily decode this due to an error on my part?

You could check the generated Javascript from this email link obfuscator generator. For example, this is what gets generated if info#example.com is used for both email address and link text:
{ coded = "DMUm#WyBVJgW.AmV"
key = "RGS5Amu4aKOHnZIix0TzqV8EBle1MQPDyhrkNfCp3gWXdjFbwvcosU9JY726Lt"
shift=coded.length
link=""
for (i=0; i<coded.length; i++) {
if (key.indexOf(coded.charAt(i))==-1) {
ltr = coded.charAt(i)
link += (ltr)
}
else {
ltr = (key.indexOf(coded.charAt(i))-shift+key.length) % key.length
link += (key.charAt(ltr))
}
}
document.write("<a href='mailto:"+link+"'>info#example.com</a>")
}
I'm not sure how effective it is though.

Related

Problems with displaying text in Javascript "N�O�T�I�C�E�", php displays it with no problem

PHP creates the text from metadata from image file which stores it in variable of the same name of IMG source.
No Problems
JavaScript displays the gallery to show images, scroll & enlarge.
During enlargement it gives description of image from source attribute but always displays the text with � after every character. But PHP doesn't.
I've tried encoding which you will see from code & & echo header("Content-Type: text/html; charset=ISO-8859-1");
PHP:
$path = "gallery/";
$objs = new RecursiveIteratorIterator(new
RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST);
$num = 0;
foreach ($objs as $pic){
$pic = str_replace('gallery/', '', $pic);
if ($pic == '..' or $pic == '.'){
continue;
}
$exif = exif_read_data("$DIR/gallery/$pic", 0, true);
$pic = str_replace('.JPG', '', $pic);
${$pic} = $exif['IFD0']['Comments']; ///// php Variable
echo "<script> var $pic = '".$exif['IFD0']['Comments']."';
var $pic = utf8_encode($pic);</script>";
// JS of variable of same name.
}
Sloppy but Works
JQuery:
$('#mSide').on('click',function(){
var src = $('#mPic').attr('src');
var v = src.replace('/gallery/','');
v = v.replace('.JPG','');
v = unescape(encodeURIComponent(v));
$('#fullPic').show();
$('#fullPic').append('<img class=\"fPic\" src=\"'+src+'\"
height=\"90%\" widdth=\"90%\" style=\"margin-left:0px;\" />');
$('#fullPic').append('<span id=\"picSummary\"
style=\"color:#FFFFFF;\" >testing <textarea > '+ window[v] +'</textarea>
</span>');
$('#fullPic').prepend('<input class=\"closeFullP headr\"
value=\"Close\" READONLY><br class=\"closeFullP\">');
});
Sloppy but Works and window[v] is the call
Should display: this is the new val = NOTICE: This e-mail message may contain legally privileged and/or confidential information. If you are not the intended recipient, you are hereby notified that any dissemination of the contents of this message is strictly prohibited. If you have received this message in error, please immediately notify the sender at ########### and delete all copies of this e-mail message and its attachments.
Not: N�O�T�I�C�E�:� �T�h�i�s� �e�-�m�a�i�l�
�m�e�s�s�a�g�e� �m�a�y� �c�o�n�t�a�i�n�
�l�e�g�a�l�l�y� �p�r�i�v�i�l�e�g�e�d� �a�n�d�/�o�r�
�c�o�n�f�i�d�e�n�t�i�a�l� �i�n�f�o�r�m�a�t�i�o�n�.�
�I�f� �y�o�u� �a�r�e� �n�o�t� �t�h�e�
�i�n�t�e�n�d�e�d� �r�e�c�i�p�i�e�n�t�,...............
Never use utf8_encode() or utf8_decode() they make awful assumptions and happily/silently corrupt your data. Always use a function that allows you to explicitly specify your input and output encodings.
The data you're extracting from EXIF is encoded as UTF16-LE, and your page is... something else. I can't tell what and you should probably figure that out and be consistent.
Suggested reading: UTF-8 all the way through
If your page is encoded as ISO-8859-1:
$proper = mb_convert_encoding($input, 'ISO-8859-1', 'UTF-16-LE');
If your page is encoded as UTF-8:
$proper = mb_convert_encoding($input, 'UTF-8', 'UTF-16-LE');
Ref: https://secure.php.net/manual/en/function.mb-convert-encoding.php

Assign Value of Custom Wordpress Post/Page Meta Field to JavaScript Variable

Is there a way via some lines of JavaScript to assign the value of a custom meta field in a Wordpress post/page to a JavaScript variable?
In other words, I've got a custom meta field in all my Wordpress posts and pages named "customamznsearch". I'd like to assign the value of that field to a JavaScript variable with the same name... or different name if need be.
Also, an added bonus would be to also define a static value for the variable if no data is available from that meta field.
This is the code that will be utilizing the "customamznsearch" variable.
<script type="text/javascript">
amzn_assoc_placement = "adunit0";
amzn_assoc_tracking_id = "livcouintheci-20";
amzn_assoc_ad_mode = "search";
amzn_assoc_ad_type = "smart";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "US";
amzn_assoc_textlinks = "";
amzn_assoc_linkid = "0c1ce8995df23ae16ec99d3bb32502ec";
amzn_assoc_default_category = "SportingGoods";
amzn_assoc_default_search_phrase = customamznsearch;
</script>
<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"></script>
This code will be displayed in an Enhanced Text Widget in the footer of my page. The Enhanced Text widget should be fully capable of supporting Text, HTML, CSS, JavaScript, Flash, Shortcodes, and PHP.
After much research, the following snippet of code was what ended up working (please note that I decided to change the variable to 'amazonadserach'):
var amazonadsearch = "<?php global $post;
$amazonadsearch = get_post_meta($post->ID, 'amazonadsearch', true);
echo $amazonadsearch; ?>";
You can just output javascript code from php like this:
<script>
var customamznsearch = "<?php echo addcslashes($customamznsearch, '"'); ?>";
</script>
Or if you mean to get it from the <meta> tags, then:
function getMeta(metaName) {
var metas = document.getElementsByTagName('meta');
for (i=0; i<metas.length; i++) {
if (metas[i].getAttribute("name") == metaName) {
return metas[i].getAttribute("content");
}
}
return "";
}
var twitterTitle = getMeta("twitter:title");

jQuery.post() data returns entire PHP script as string?

I've already set up a basic SimpleCart.js web shop and am trying to implement realseanp's solution for adding a promo/discount code feature.
He uses the following JavaScript to post the user's entered promo code to discount.php:
jQuery("#promoSub").click(function Discount() {
//Interact with PHP file and check for valid Promo Code
jQuery.post("discount.php", { code: jQuery('#code').val() } , function(data) {
console.log(jQuery('#code').val());
if (data=="0" || data=='') {
console.log("Wrong Code");
}
else {
//create our cookie function if promo code is valid
//create cookie for 1 day
createCookie("promo","true",1);
var y = (data/100);
for(var i=0; i<simpleCart.items().length; i++){
var itemPrice = simpleCart.items()[i].price();
var theDiscount = itemPrice * y;
var newPrice = itemPrice - theDiscount;
simpleCart.items()[i].set("price", newPrice)
}
simpleCart.update();
//hides the promo box so people cannot add the same promo over and over
jQuery('#promoCodeDiv').hide();
}
});
});
...which echoes back a 0 or the discount percentage if the correct code has been passed:
<?php
$x = 0;
if ($_POST["code"]=="HOLIDAY") { $x = 5; };
echo $x;
?>
However, when I console.log(data) from within the success function, data appears to be the entirety of the PHP script as a string instead of the echo.
Why is this, and what modifications do I need to make to rectify it? I'm very new to PHP and having difficulty understanding why jQuery.post() isn't receiving the echo.

Basic form submission with jquery/ajax not working

I'm new to jquery and ajax. I'm trying to get my first ajax script to work, but it's not working and I need some assistance, please.
I have a php page that is supposed to post to another php page, where the latter will do some processing and get some files to get zipped and download. The user needs to input a starting and ending date, and the second php script will use this information to prepare the data. This functionality works perfectly fine without jquery, but doesn't work when I add jquery.
What do I want to achieve? I want to post in the to the same php page and get the post output in a <div></div> tag.
My first php page contains (downloadPage.php):
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<form action="doDownload.php" method="post" id="dateRangeID">
<input id='time1' class='input' name="datefield1" style="text-align:center;"/>
<input id='time2' class='input' name="datefield2" style="text-align:center;"/>
<input type="submit" value="Download Data" name="submit" id="submitButton">
</form>
<div id="result"></div> <!-- I would like it to post the result here //-->
The second page (doDownload.php),
<div id="content">
<?php
if(isset($_POST['submit']))
{
$dateVal1 = $_POST['datefield1'];
$dateVal2 = $_POST['datefield2'];
if($dateVal1 != $dateVal2)
{
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="file.zip"');
$fullListOfFiles = $downloadFullTmpFolder.$filesList;
$command = "sudo $ldlib -u myuser /usr/bin/python3 $downloadScriptFile -datadir $gnomeDataDir -time1 $dateVal1C -time2 $dateVal2C -outdir $downloadFullTmpFolder > debug_download.txt 2>&1";
$output = shell_exec($command);
$fp = popen('cat '.$fullListOfFiles.' | sudo -u myuser zip -# -9 - ', 'r');
$bufsize = 1024;
$buff = '';
while( !feof($fp) )
{
$buff = fread($fp, $bufsize);
echo $buff;
}
pclose($fp);
}
else
{
echo("<p>Dates have to be different in order for the download to start.</p>");
}
}
else
{
echo("<p>Error: Page called without submit.</p>");
}
?>
</div>
Finally, the jquery part in downloadPage.php, which if I add it doesn't work anymore (which I'd like to learn how to do right, and I mainly learned from the manual of jquery, the last example in the link)
<script>
/* attach a submit handler to the form */
$("#dateRangeID").submit(
function(event)
{
event.preventDefault();
var $form = $(this),
t1 = $form.find("input[name='datefield1']").val(),
t2 = $form.find("input[name='datefield2']").val(),
subm = $form.find("input[name='submit']").val(),
url = $form.attr('action');
var posting = $.post(url, { datefield1: t1, datefield2: t2, submit: subm} );
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content'); // <--- So this turns out to be wrong. Right is only $(data);
$("#result").empty().append(content);
});
});
</script>
What is wrong in this? Please assist. Thank you.
If you require any additional information, please ask.
Looking at the obvious, you have:
var content = $(data).find('#content');
where, you're trying to find an element with the ID content in one of the following results:
<p>Dates have to be different in order for the download to start.</p>
or
<p>Error: Page called without submit.</p>

Refactoring 3 small bits of PHP function into JS - array, if empty and matching url?

I'm not much of a JS person but I'd like to know how to run my PHP into JS. How can I do the following using Javascript only?
// 1. Getting the request
<?php if($_GET["slider"]=="1"){ ?>
$(".class1 a").click()
<?php } ?>
<?php if($_GET["slider"]=="2"){ ?>
$(".class2 a").click()
// 2. Matching the URL and setting an active class on the list item
<li>My Page</li>
// 3. Nav array and If empty
<?php
$navigation = array(
'previous' => 'page1.php',
);
if (isset($navigation['previous']))
{
?>
<div class="prev">
<a href="<?php echo $navigation['previous']; ?>">
<span class="previous-icon"></span><span>Previous</span>
</a>
</div>
My attempt after Googling..
<?php if(var _GET["slider"]=="1"){ } if(_GET["slider"]=="2"){ if (strrpos(var _SERVER['REQUEST_URI'], 'my_page') !== false ) {} var navigation = {
'previous' : 'page1.php',
};
if ((navigation['previous']))
{
you can get "GET" values (query string) like in this Answer
window.location.href.indexOf("my_page") != -1 , search for window.location and indexOf for further explanation
check code
var navigation = {previous:"page1.php"};
document.write('<a href="'+navigation["previous"]+'">....');`
Arrays can't have string indexes in js, you need to use objects;
you can also use navigation.previous instead.
you can't mix js and html like you do with php, you have to "echo" everything using document.write or other DOM manipulation functions. For further help on these topics, search the bold parts.
To answer your three questions:
1: Clicking something if a variable is in the URL (i.e. /page.php?slider=1): Check out this page, which details how to retrieve variables from URLs in jQuery. In short, you can do something like,
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
to get the variables from a URL, and from there you can check if a variable is set by asking getUrlvars()['slider'] == 1.
2: Matching the url and setting a class as active: You can do something like
if (window.location.href == 'http://www.example.com/page.php') {
$('a').addClass('active');
}
3: If you're looking to create a dynamic list of links using Javascript arrays, you could do something like this:
var myLinks = {
"link_1_title": "http://www.example.com",
"link_2_title": "http://www.stackoverflow.com/"
}
$.each(myLinks, function(key, val) {
$('.navbar').append('' + key + '');
}
For a more detailed explanation about jQuery.each, please see the jQuery doc page.
It sounds like you've got an unholy alliance here of PHP drawing the JS and then the JS doing things. It's a recipe for disaster. Your PHP should pass your data to your JS and then let the JS do the work. Don't mix logic. Have a clean handoff.
<script>
var something = <?php echo $var ?>;
myclass = new someClass(something);
</script>

Categories

Resources