im trying to open a log file and see if a text does not exist, if it doesnt exist then continue, but at the same time i want to check its the log file has not been sent per mail already.
public function start() {
$pattern = $this->config["twp_pattern"] ?? '*.log';
$pathLog = (isset($this->config["twp_path"])) ? trim($this->config["twp_path"], '/') : 'var/log';
$lastRun = (isset($this->config['twp_last_run'])) ? str_replace('T', ' ', $this->config['twp_last_run']) : false;
$path = getcwd() . '/' . $pathLog . '/' . $pattern;
$this->now = new \DateTime();
foreach (glob($path) as $log) {
$open = fopen($log, 'r') or die ('File opening failed');
$content = fread($open,filesize($log));
var_dump($content);
fclose($log);
if (!$lastRun || filectime($log) < strtotime($lastRun) && $this->checkIfAlreadyExists($content) === false) {
continue;
}
$logs[] = $log;
}
if (!empty($logs)) {
$success =$this->sendMail($logs);
}
if($success === false){
return false;
}
$this->setLastRun();
return true;
}
public function checkIfAlreadyExists($content){
if (!preg_match_all('/already exists/', $content)) {
echo "is not there";
return false;
}else{
echo "is there";
return true;
}
}
my problem is even tho email has been sent, it will send it again when i run
function start()
if i remove the && $this->checkIfAlreadyExists($content) === false, it will not longer send logs per mail that has already been sent. can anyone spot my mistake ? Thanks
Fixed by changing my if statement
if ((!$lastRun || filectime($log) < strtotime($lastRun)) || ($this->checkIfAlreadyExists($content))) {
continue;
}
Thanks for your time and the help ! <3
Related
I'm writing some server side scripts for my web host that will do a whole bunch of auto updating for client side applications. As long as the user has properly identified themselves as the owner with the app name and password they should be able to upload to a repository on the server created automatically; however, I don't want to allow any scripts to be uploaded such that it could run on the server. I intend to allow people to create their own repositories without having to ask me so is there anyway to block this potential vulnerability?
This is the setup code for the repositories, named APPSEtUP.php :
<?php
$app = str_replace("_", " ", TDecode($_POST['app']));
$pass = str_replace("_", " ", TDecode($_POST['pass']));
$command = str_replace("_", " ", TDecode($_POST['command']));
$worked = false;
if ($command == "SETUP_API") { $worked = SETUP_API($app, $pass); }
if ($command == "MAKE_DIR") { $worked = Make_Directory($app, $pass, TDecode($_POST['DIR']), TDecode($_POST['up'])); }
if ($worked) { echo "SUCCESS!"; }
return;
function Make_Directory($api, $pw, $dir, $up) {
$path = $_SERVER['REQUEST_URI'];
if ($path == "/scripts/APPSETUP.php") { echo "API FAILURE: 008\r\n"; return false; }
if (!startsWith($path, "/scripts/Apps/")) { echo "API FAILURE: 009\r\n"; return false; }
if (!Get_API_PW("./security.LOCK", $pass)) { echo "API FAILURE: 010\r\n"; return false; }
if ($path != "/scripts/Apps/".$api."/APPSETUP.php") { echo "API FAILURE: 011\r\n"; return false; }
while (startsWith($dir, ".") || startsWith($dir, "/")) { $dir = substr($dir, -(strlen($dir)-1)); }
while (endsWith($dir, "/")) { $dir = substr($dir, 0, strlen($dir)-1); }
if (!(file_exists("./".$dir."/") || mkdir("./".$dir."/", "0777", true))) { echo "API FAILURE: 012\r\n"; return false; }
if ($up == "true" && !(file_exists("./".$dir."/UploadFile.php") || copy("./UploadFile.php", "./".$dir."/UploadFile.php"))) {
echo "API FAILURE: 013\r\n"; return false;
} return true;
}
function startsWith($haystack, $needle) {
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
function endsWith($haystack, $needle) {
$length = strlen($needle);
return $length === 0 || (substr($haystack, -$length) === $needle);
}
function SETUP_API($api, $pw) {
$temp1 = "./Templates/USERLOG.php";
$temp2 = "./Templates/UploadFile.php";
$temp3 = "./APPSETUP.php";
$dest1 = "./Apps/";
$dest2 = "./Apps/".$api."/";
$dest3 = "./Apps/".$api."/USERLOG.php";
$dest4 = "./Apps/".$api."/security.LOCK";
$dest5 = "./Apps/".$api."/UploadFIle.php";
$dest6 = "./Apps/".$api."/APPSETUP.php";
if (!(file_exists($dest1) || mkdir($dest1, 0777, true))) { echo "API FAILURE: 001\r\n"; return false; }
if (!(file_exists($dest2) || mkdir($dest2, 0777, true))) { echo "API FAILURE: 002\r\n"; return false; }
if (!file_exists($dest4)) { if (!App_Reset($dest2, $dest4, $pw)) { echo "API FAILURE: 003\r\n"; return false; } }
if (!Get_API_PW($dest4, $pw)) { echo "API FAILURE: 004\r\n"; return false; }
if (!copy($temp1, $dest3)) { echo "API FAILURE: 005\r\n"; return false; }
if (!copy($temp2, $dest5)) { echo "API FAILURE: 006\r\n"; return false; }
if (!copy($temp3, $dest6)) { echo "API FAILURE: 007\r\n"; return false; }
return true;
}
function App_Reset($api, $sec, $pw) {
try {
Delete_Bad_App($api);
$pWriter = fopen($sec, "w");
fwrite($pWriter, TEncode($pw));
fclose($pWriter);
return true;
} catch (exception $e) { return false; }
}
function Delete_Bad_App($api) {
$di = new RecursiveDirectoryIterator($api, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
$file->isDir() ? rmdir($file) : unlink($file);
} return;
}
function Get_API_PW($sec, $guess) {
try {
$pReader = fopen($sec, "r");
$pw = TDecode(fread($pReader, filesize($sec)));
fclose($pReader);
return $pw == $guess;
} catch (exception $e) { return false; }
}
function TriceInt($c) {
$b = unpack("C*", $c)[1] % 255;
$foo = (string)$b;
while (strlen($foo) < 3) { $foo = "0".$foo; }
return $foo;
}
function TEncode($str) {
if (TEncoded($str)) { return $str; }
return implode(array_map("TriceInt", str_split($str, 1)));
}
function TDecode($str) {
if (!TEncoded($str)) { return $str; }
return implode(array_map("chr", array_map('intval', str_split($str, 3))));
}
function TEncoded($str) {
return (ctype_digit($str) && strlen($str) % 3 == 0);
}
?>
and here is the script that is for uploading files.
<?php
$uploads_dir = './';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>
Do note that the upload script is named UploadFile.php and is located in a templates folder as referenced in the setup script.
So following the suggestions in the comments of the question I tried disabling script execution with .htaccess but because I'm using a Windows Server hosted by godaddy I was using the wrong kind of file to do so. I found this link which explained how to do the same thing in web.config which does apply to Windows servers.
http://issues.umbraco.org/issue/U4-8472
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<clear />
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" resourceType="Either" requireAccess="Read" />
</handlers>
</system.webServer>
</configuration>
What is the best way to inform who use my generator function if something errors occurs, instead of writing weird return or raising exception like this piece of code
function csv_file_generator($csvFilename, $delimiter = ";", $enclousure = '"') {
if(($csvHandler = fopen($csvFilename, 'rb')) === false) {
return;
}
while (($row = fgetcsv($csvHandler, 0, $delimiter, $enclousure)) !== false) {
yield $row;
}
if (feof($csvHandler) === false) {
return;
}
if (fclose($csvHandler) === false) {
return;
}
return; /* Exit Generator */
}
<?php
class CsvFileGenerator {
protected $fp;
protected $delimiter;
protected $enclousure;
public function __construct($filename, $delimiter = ";", $enclousure = '"'){
$this->delimiter=$delimiter;
$this->enclousure=$enclousure;
if(!file_exists($filename)){
throw new Exception("file [$filename] dont exists");
}
if(!is_readable($filename)){
throw new Exception("file [$filename] is not readable");
}
$this->fp = fopen($filename, 'rb');
if($this->fp === false){
throw new Exception("cant open [$filename]");
}
}
public function getGenerator(){
while (($row = fgetcsv($this->fp, 0, $this->delimiter, $this->enclousure)) !== false) {
yield $row;
}
}
public function __destruct() {
if($this->fp){
fclose($this->fp);
}
}
}
foreach( (new CsvFileGenerator('mycsvfile.csv'))->getGenerator() as $line){
#do some
}
One way to rome. :-)
How about callbacks?
function gen($i, $on_close = null, $on_error = null) {
while ($i--) {
yield $i;
if ($i === 5 && is_callable($on_close)) {
$on_close();
}
}
}
$closed = false;
$gen = gen(10, function () use (&$closed) {
$closed = true;
});
foreach ($gen as $x) {
if ($closed) {
break;
}
echo $x, PHP_EOL;
}
I'll admit its not pretty. Another options could be to return instances of special classes to let your main code know something is wrong.
Hey guys I have my script here that is supposed to do some stuff then delete a file, unfortunetly my files never unlink. I"m wondering what the reason for this might be? Permissions was the only thing I could think of, or maybe the output buffer is messing up? I really don't know, but would appreciate some advice on how to handle it. Issue in question is that last IF() block.
public function remoteFtp() {
$enabled = Mage::getStoreConfig('cataloginventory/settings/use_ftp');
$remove = Mage::getStoreConfig('cataloginventory/settings/ftp_remove_file');
if ($enabled == 0) {
return true;
}
$base_path = Mage::getBaseDir('base');
$ftp_url = Mage::getStoreConfig('cataloginventory/settings/ftp_url');
$ftp_user = Mage::getStoreConfig('cataloginventory/settings/ftp_user');
$ftp_pass = Mage::getStoreConfig('cataloginventory/settings/ftp_password');
$ftp_remote_dir = Mage::getStoreConfig('cataloginventory/settings/ftp_remote_dir');
$ftp_filename_filter = Mage::getStoreConfig('cataloginventory/settings/ftp_remote_filename');
$ftp_file = $base_path . '/edi/working/working.edi';
$handle = fopen($ftp_file, 'w');
$conn_id = ftp_connect($ftp_url);
ftp_login($conn_id, $ftp_user, $ftp_pass) or die("unable to login");
if ($ftp_remote_dir) {
ftp_chdir($conn_id, $ftp_remote_dir);
}
//is there a file
$remote_list = ftp_nlist($conn_id, ".");
$exists = count($remote_list);
if ($exists > 0) {
$len = strlen($ftp_filename_filter) - 1;
foreach ($remote_list as $name) {
if (substr($ftp_filename_filter, 0, 1) == "*") {
if (substr($name, '-' . $len) == substr($ftp_filename_filter, '-' . $len)) {
$ftp_remote_name = $name;
}
}
if (substr($ftp_filename_filter, strlen($name) - 1) == "*") {
if (substr($ftp_filename_filter, 0, $len) == substr($name, 0, $len)) {
$ftp_remote_name = $name;
}
}
if ($ftp_filename_filter == $name) {
$ftp_remote_name = $name;
}
}
}
if (ftp_fget($conn_id, $handle, $ftp_remote_name, FTP_ASCII, 0)) {
echo "successfully written to $ftp_file <br />";
if ($remove == 1) {
ftp_delete($conn_id, $ftp_remote_name);
}
} else {
echo "There was a problem while downloading $ftp_remote_name to $ftp_file <br />";
}
ftp_close($conn_id);
}
The answer was that the system variable $remove = Mage::getStoreConfig('cataloginventory/settings/ftp_remove_file'); was set to BOOL(false)
I'm having an issue with a PHP print statement that repeats the output continuously for about 40 or 50 times, then stops. I thought it was supposed to print only one line. I'm still somewhat new to PHP, so I don't understand what I'm doing wrong. The code in question is located at the bottom of the snippet.
Thanks in advance.....
<?php
$query = $_POST['query'];
find_files('.');
function find_files($seed) {
if(! is_dir($seed)) return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs))) {
if($dh = opendir($dir)) {
while( false !== ($file = readdir($dh))) {
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if(is_dir($path)) {
$dirs[] = $path;
} else {
if(preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
check_files($path);
}
}
}
closedir($dh);
}
}
}
function check_files($this_file) {
$query = $_POST['query'];
$str_to_find = $query;
if ((isset($str_to_find)) && (empty($str_to_find))) {
print '<p>Your search produced no results</p>';
} else {
if(!($content = file_get_contents($this_file))) {
echo("<p>Could not check $this_file</p>\n");
} else {
if(stristr($content, $str_to_find)) {
echo("<p>$this_file -> contains $str_to_find</p>\n");
}
}
unset($content);
}
}
?>
'Your search produced no results' will be printed out once for every file that your loop sees. You should do the check before you call find_files():
if (!isset($str_to_find) || empty($str_to_find)) {
print '<p>Your search produced no results</p>';
} else {
find_files('.');
}
You can then remove that bit of code from check_files().
You have the print statement inside of the check_files() function, which is being called from inside your while... loop. So, yes, it's going to be executed each time that loop executes and the conditions match.
By !== you maybe meant !=?
I'm writing a code in PHP which deletes a file if it's more than a day old.
but i t does not do so, and append line after it :(
$fileName = 'news/'.$_COOKIE['sign'];
if (isset($_COOKIE['sign']))
{
if ((file_exists($fileName)) && (date("d",filemtime($fileName))==date("d")))
{
$data = file_get_contents($fileName);
if ($data == '')
{
$data = 'Temporary network problem !';
unlink($fileName);
}
echo $data;
}
else
echo 'Fetch and put new news';
$fileName = 'news/'.$_COOKIE['sign'];
if (isset($_COOKIE['sign'])) {
if ((file_exists($fileName)) && (date("d", filemtime($fileName)) == date("d"))) {
$data = file_get_contents($fileName);
if ($data == '') {
$data = 'Temporary network problem !';
unlink($fileName);
}
echo $data;
}
elseif(file_exists($fileName)) { //if not above, then delete it!
unlink($fileName);
}
else {
echo 'Fetch and put new news';
}
}