Unink log files that were created the day before in codeigniter - codeigniter

I am trying to unlink files that were created the day before
I have a custom application > core > MY_Log.php file and it creates a log for each error level. For easier reading.
logs > DEBUG-04-08-2016.php
logs > ERROR-04-08-2016.php
logs > INFO-04-08-2016.php
logs > DEBUG-03-08-2016.php
logs > ERROR-03-08-2016.php
logs > INFO-03-08-2016.php
Question how am I able to modify the write_log so could delete / unlink files that were created the day before?
<?php
class MY_Log extends CI_Log {
public function write_log($level, $msg)
{
if ($this->_enabled === FALSE)
{
return FALSE;
}
$level = strtoupper($level);
if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
&& ! isset($this->_threshold_array[$this->_levels[$level]]))
{
return FALSE;
}
$filepath = $this->_log_path . $level .'-'. date('d-m-Y').'.'.$this->_file_ext;
$message = '';
if ( ! file_exists($filepath))
{
$newfile = TRUE;
// Only add protection to php files
if ($this->_file_ext === 'php')
{
$message .= "";
}
}
if ( ! $fp = #fopen($filepath, 'ab'))
{
return FALSE;
}
flock($fp, LOCK_EX);
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
if (strpos($this->_date_fmt, 'u') !== FALSE)
{
$microtime_full = microtime(TRUE);
$microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000);
$date = new DateTime(date('d-m-Y H:i:s.'.$microtime_short, $microtime_full));
$date = $date->format($this->_date_fmt);
}
else
{
$date = date($this->_date_fmt);
}
$message .= $this->_format_line($level, $date, $msg);
for ($written = 0, $length = strlen($message); $written < $length; $written += $result)
{
if (($result = fwrite($fp, substr($message, $written))) === FALSE)
{
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
if (isset($newfile) && $newfile === TRUE)
{
chmod($filepath, $this->_file_permissions);
}
return is_int($result);
}
}

First of use
$config['log_threshold'] = 1;
For only error message, so there will be less number of files
Add below code just before $filepath; to delete previous date logs
$unlink_date = date('Y-m-d',strtotime("-1 days"));
$filepath_unlink = $this->_log_path . $level .'-'. $unlink_date.'.'.$this->_file_ext;
if ( file_exists($filepath_unlink))
{
unlink($filepath_unlink);
}

Related

Custom chunk implementation

Is it possible to customize the chunk configuration in Filepond such that the chunk information is provided to the upload server:
as query parameters instead of headers
with custom query parameter names instead of Upload-Length, Upload-Name, and Upload-Offset
I am trying to fit Filepond's chunk implementation to a third party upload endpoint that I don't have control over.
I have found the Advanced configuration where you provide a process function which I've played with a little bit to see what comes through the options param -- however that appears (I think) to make the chunking calculations my responsibility. My original thought was to manipulate the options.chunkServer.url to include the query params I need but I don't believe this processes individual chunks.
In case it makes a difference, this is being done in React using the react-filepond package.
I made and implementation in Laravel 6 using Traits and some "bad practices" (I didn't have time because ... release in prod) to join chunks into a file
Basically:
post to get unique id folder to storage
get chunks and join together
profit!
Here's the full code:
<?php
namespace App\Http\Traits\Upload;
use Closure;
use Faker\Factory as Faker;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
trait Uploadeable
{
public function uploadFileInStorage(Request $request, Closure $closure)
{
// get the nex offset for next chunk send
if (($request->isMethod('options') || $request->isMethod('head')) && $request->has('patch')) {
//get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// reead all chunks in directory
$patch = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// read offsets for calculate
$offsets = array();
$size = 0;
$last_offset = 0;
foreach ($patch as $filename) {
$size = Storage::size($filename);
list($dir, $offset) = explode('file.patch.', $filename, 2);
array_push($offsets, $offset);
if ($offset > 0 && !in_array($offset - $size, $offsets)) {
$last_offset = $offset - $size;
break;
}
// last offset is at least next offset
$last_offset = $offset + $size;
}
// return offset
return response($last_offset, 200)
->header('Upload-Offset', $last_offset);
}
// chunks
if ($request->isMethod('patch') && $request->has('patch')) {
// get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// read headers
$offset = $request->header('upload-offset');
$length = $request->header('upload-length');
// should be numeric values, else exit
if (!is_numeric($offset) || !is_numeric($length)) {
return response('', 400);
}
// get the file name
$name = $request->header('Upload-Name');
// sleep server for get a diference between file created to sort
usleep(500000);
// storage the chunk with name + offset
Storage::put($dir . 'file.patch.' . $offset, $request->getContent());
// calculate total size of patches
$size = 0;
$patch = Storage::files($dir);
foreach ($patch as $filename) {
$size += Storage::size($filename);
}
// make the final file
if ($size == $length) {
// read all chunks in directory
$files = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// create output file
//Log::info(storage_path('app'));
$new_file_name = $final_name = trim(storage_path('app') . DIRECTORY_SEPARATOR . $dir . $name);
$file_handle = fopen($new_file_name, 'w');
// write patches to file
foreach ($files as $filename) {
// get offset from filename
list($dir, $offset) = explode('.patch.', $filename, 2);
// read chunk
$patch_handle = fopen(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename), 'r');
$patch_contents = fread($patch_handle, filesize(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename)));
fclose($patch_handle);
// apply patch
fseek($file_handle, $offset);
fwrite($file_handle, $patch_contents);
}
// done with file
fclose($file_handle);
// file permission (prefered 0755)
chmod($final_name, 0777);
// remove patches
foreach ($patch as $filename) {
$new_file_name = storage_path('app') . DIRECTORY_SEPARATOR . trim($filename);
unlink($new_file_name);
}
// simple class (no time to explain)
$file = new UploadedFile(
$final_name,
basename($final_name),
mime_content_type($final_name),
filesize($final_name),
false
);
$dir = $request->patch . DIRECTORY_SEPARATOR;
$object = new \stdClass();
$object->full_path = (string)$file->getPathname();
$object->directory = (string)($dir);
$object->path = (string)($dir . basename($final_name));
$object->name = (string)$file->getClientOriginalName();
$object->mime_type = (string)$file->getClientMimeType();
$object->extension = (string)$file->getExtension();
$object->size = (string)$this->formatSizeUnits($file->getSize());
// exec closure
$closure($file, (object)$object, $request);
}
// response
return response()->json([
'message' => 'Archivo subido correctamente.',
'filename' => $name
], 200);
}
// get dir unique id folder temp
if ($request->isMethod('post')) {
$faker = Faker::create();
$unique_id = $faker->uuid . '-' . time();
$unique_folder_path = $unique_id;
// create directory
Storage::makeDirectory($unique_folder_path);
// permisos directorio
chmod(storage_path('app') . DIRECTORY_SEPARATOR . $unique_folder_path . DIRECTORY_SEPARATOR, 0777);
// response with folder
return response($unique_id, 200)
->header('Content-Type', 'text/plain');
}
}
private function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' bytes';
} elseif ($bytes == 1) {
$bytes = $bytes . ' byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
}
ยดยดยด

How to add another array value in codeigniter using getRecords

The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .

Call to undefined function mcrypt_decrypt() - CometChat Laravel

Hi I've already installed the CometChat, but I'm facing the following error:
Call to undefined function mcrypt_decrypt() in /home/vagrant/changeglobe/public/cometchat/integration.php on line 89
I'm using Homestead with Nginx for Laravel. I have read at many places that I need to enable mycrypt, but did not found any correct. Please let me know about this issue if you know. Thank you.
Try replacing the getUserID() function in /cometchat/integration.php file with the code below:
function getUserID() {
$userid = 0;
if (!empty($_SESSION['basedata']) && $_SESSION['basedata'] != 'null') {
$_REQUEST['basedata'] = $_SESSION['basedata'];
}
if (!empty($_REQUEST['basedata'])) {
if (function_exists('mcrypt_encrypt') && defined('ENCRYPT_USERID') && ENCRYPT_USERID == '1') {
$key = "";
if( defined('KEY_A') && defined('KEY_B') && defined('KEY_C') ){
$key = KEY_A.KEY_B.KEY_C;
}
$uid = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode(rawurldecode($_REQUEST['basedata'])), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
if (intval($uid) > 0) {
$userid = $uid;
}
} else {
$userid = $_REQUEST['basedata'];
}
}
if (!empty($_COOKIE['laravel_session'])) {
$session= cookie_decrypt($_COOKIE['laravel_session']);
$data = file_get_contents(dirname(dirname(dirname(__FILE__))).'/storage/framework/sessions/'.$session);
if (!empty($data)) {
$k = explode(';i:',$data);
$m = explode(';s:',$k[1]);
$userid = $m[0];
}
}
$userid = intval($userid);
return $userid;
}
If you are still facing issues please create a support ticket https://my.cometchat.com/tickets and our team will assist you.

how to change csv filename variable in profile action xml of Dataflow-Advanced profile on run time?

I want to use Dataflow-Advanced profile to import the csv from frontend. i have googled and find a stand-alone script for that, but problem is that now this script work only for fixed csv file. I want to change the csv file name on run time to import through stand-alone script. Please refer screen-shot link https://www.diigo.com/item/image/5hhy6/7pxw?size=o to more clear. Could anyone help me to get achieve this?
Here is sample script:
require_once 'app/Mage.php';
umask(0);
ini_set("memory_limit","1024M");
Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML,
Mage_Core_Model_App_Area::PART_TRANSLATE);
setlocale(LC_ALL, 'en_US');
$localeName = "en_US";
Mage::app()->getLocale()->setDefaultLocale($localeName);
Mage::app()->getLocale()->setLocale($localeName);
Mage::app()->getLocale()->setLocaleCode($localeName);
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode());
Mage::app()->setCurrentStore(0);
Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_TRANSLATE);
Mage::app();
$profileId = 11; //put your profile id here
$logFileName= date("j-n-Y")."-import.log";
$recordCount = 0;
Mage::log("Import Started",null,$logFileName);
$profile = Mage::getModel('dataflow/profile');
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);
Mage::getSingleton('admin/session')->setUser($userModel);
if ($profileId) {
$profile->load($profileId);
if (!$profile->getId()) {
Mage::getSingleton('adminhtml/session')->addError('The profile you are trying to save no longer exists');
}
}
Mage::register('current_convert_profile', $profile);
$profile->run();
$batchModel = Mage::getSingleton('dataflow/batch');
if ($batchModel->getId()) {
if ($batchModel->getAdapter()) {
$batchId = $batchModel->getId();
$batchImportModel = $batchModel->getBatchImportModel();
$importIds = $batchImportModel->getIdCollection();
$batchModel = Mage::getModel('dataflow/batch')->load($batchId);
$adapter = Mage::getModel($batchModel->getAdapter());
$adapter->setBatchParams($batchModel->getParams());
foreach ($importIds as $importId) {
$recordCount++;
try{
$batchImportModel->load($importId);
if (!$batchImportModel->getId()) {
$errors[] = Mage::helper('dataflow')->__('Skip undefined row');
continue;
}
$importData = $batchImportModel->getBatchData();
try {
$adapter->saveRow($importData);
} catch (Exception $e) {
Mage::log($e->getMessage(),null,$logFileName);
continue;
}
if ($recordCount%20 == 0) {
Mage::log($recordCount . ' - Completed!!',null,$logFileName);
}
} catch(Exception $ex) {
Mage::log('Record# ' . $recordCount . ' - Error - ' . $ex->getMessage(),null,$logFileName);
}
}
foreach ($profile->getExceptions() as $e) {
Mage::log($e->getMessage(),null,$logFileName);
}
}
}
Mage::log("Import Completed",null,$logFileName);
Looking forward for positive response!
Thanks in advance!
I got the solution.
require_once 'app/Mage.php';
umask(0);
ini_set("memory_limit","1024M");
Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML,
Mage_Core_Model_App_Area::PART_TRANSLATE);
setlocale(LC_ALL, 'en_US');
$localeName = "en_US";
Mage::app()->getLocale()->setDefaultLocale($localeName);
Mage::app()->getLocale()->setLocale($localeName);
Mage::app()->getLocale()->setLocaleCode($localeName);
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode());
Mage::app()->setCurrentStore(0);
Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_TRANSLATE);
Mage::app();
$profileId = 11; //put your profile id here
$logFileName= date("j-n-Y")."-import.log";
$recordCount = 0;
Mage::log("Import Started",null,$logFileName);
$profile = Mage::getModel('dataflow/profile');
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);
Mage::getSingleton('admin/session')->setUser($userModel);
if ($profileId) {
$profile->load($profileId);
if (!$profile->getId()) {
Mage::getSingleton('adminhtml/session')->addError('The profile you are trying to save no longer exists');
}
//code to change the csv file name :: START
//echo "<pre>"; print_r($profile->getData('actions_xml')); echo "</pre>";
$str = $profile->getData('actions_xml');
$newCsv = 'import_products_new.csv'; // put your logic to get new file name as per your requirement
$new_action_xml = str_replace('import_products_old.csv', $newCsv, $str); //'import_products_old.csv' using static, as we know filename in already saved profile
$profile->setActionsXml($new_action_xml);
//code to change the csv file name :: END
}
Mage::register('current_convert_profile', $profile);
$profile->run();
$batchModel = Mage::getSingleton('dataflow/batch');
if ($batchModel->getId()) {
if ($batchModel->getAdapter()) {
$batchId = $batchModel->getId();
$batchImportModel = $batchModel->getBatchImportModel();
$importIds = $batchImportModel->getIdCollection();
$batchModel = Mage::getModel('dataflow/batch')->load($batchId);
$adapter = Mage::getModel($batchModel->getAdapter());
$adapter->setBatchParams($batchModel->getParams());
foreach ($importIds as $importId) {
$recordCount++;
try{
$batchImportModel->load($importId);
if (!$batchImportModel->getId()) {
$errors[] = Mage::helper('dataflow')->__('Skip undefined row');
continue;
}
$importData = $batchImportModel->getBatchData();
try {
$adapter->saveRow($importData);
} catch (Exception $e) {
Mage::log($e->getMessage(),null,$logFileName);
continue;
}
if ($recordCount%20 == 0) {
Mage::log($recordCount . ' - Completed!!',null,$logFileName);
}
} catch(Exception $ex) {
Mage::log('Record# ' . $recordCount . ' - Error - ' . $ex->getMessage(),null,$logFileName);
}
}
foreach ($profile->getExceptions() as $e) {
Mage::log($e->getMessage(),null,$logFileName);
}
}
}
Mage::log("Import Completed",null,$logFileName);
Hope this helps someone!
Thanks!

smarty path problem

here is my folder
index.php
smartyhere
-Smarty.class.php
admin
-index.php
-users.php
in index.php -> $smarty->display('index.tpl');
in admin/index.php -> $smarty->display('adminindex.tpl');
got error Smarty error: unable to read resource: "adminindex.tpl"
any idea ?
thx
try to understand code
which urlencode is doing path
<?php
print_r($file);
if (isset($file)) {
$var = explode("-", $file);
print_r($var);
$prefix = $var[0];
$script = $var[1];
} else {
$file = "c-home1";
$prefix = "c";
$script = "home";
$modid = 0;
}
if ($script=="") {
$script="prod_list";
}
/*
* following code finds out the modules from suffix
* and find out the script name
*/
switch ($prefix) {
case "c":
$module = "content";
break;
case "m":
$module = "myaccount";
break;
default:
$module = "content";
break;
}
$smarty->assign("module",$module);
/*
* following code finds out the modules from suffix and
* find out the script name
*/
$include_script .= $module."/".$script.".php";
if (file_exists($include_script)) {
include_once $include_script;
} else {
include_once "content/error.php";
}
if ($script!='home') {
if ($script == 'termsandcondition') {
$smarty->display("content/termsandcondition.tpl");
} else {
$smarty->display("template.tpl");
}
} else {
$smarty->display("template_home.tpl");
$smarty->assign("msg", $msg);
$smarty->assign("msglogin", $msglogin);
}

Resources