If I have 14000 records then there is memory space issue coming and if records are 1000 I am able to upload but takes 00:30 mints .
Can anyone help me to optimize this code that I can upload records in minimum time?
Here is my code:
<?php
namespace ProjectName\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
class TakeoverController extends Controller {
public function uploadtakeoverAction(Request $request) {
ini_set('max_execution_time', 0); //0=NOLIMIT
ini_set('memory_limit', '8192M');
//start - code to check ip address
$checkipaddress = $this->get('userlogin')->CheckIPAddress();
if (empty($checkipaddress)) {
return $this->redirect($this->generateUrl('admin'));
}
//end - code to check ip address
$em = $this->getDoctrine()->getManager();
$helper = $this->get('common_helper_function');
$reqImage = $_FILES;
$validExtensions = array('xls', 'xlsx');
if (isset($_FILES) && !empty($_FILES)) {
$ext = pathinfo($_FILES['file']["name"], PATHINFO_EXTENSION);
if (!in_array($ext, $validExtensions)) {
echo "1";
die;
}
}
$admin = $this->get('security.context')->getToken()->getUser();
$takeoverfile = $this->uploadtakeoverFile($reqImage);
$takeovertm = array();
$insertedrecord = array();
$existingrecord = array();
$importmulitpletakeover = array();
$atmservicesamount = array();
$errormessage = '';
$neeerro = '';
if ($takeoverfile) {
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
$file = $takeoverfile;
if (!file_exists($file)) {
exit("Please run 05featuredemo.php first.");
}
$objPHPExcel = \PHPExcel_IOFactory::load($file);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$i = 0;
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
$totalindex = $row->getRowIndex();
// echo $row->getRowIndex();
if ($row->getRowIndex() != 1) { // first index is title index so not cosider
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
//the below columns are from A to AF
if ($cell->getColumn() == 'A') {
$val1= trim($cell->getValue());
}
if ($cell->getColumn() == 'B') {
$val2= $cell->getValue();
}
if ($cell->getColumn() == 'C') {
$val3= trim($cell->getValue());
}
if ($cell->getColumn() == 'D') {
$val3.=', ' . trim($cell->getValue());
}
if ($cell->getColumn() == 'E') {
$val3.=', ' . trim($cell->getValue());
}
}
// insert this fields into database from here of column A to AF
}
unlink($takeoverfile);
$response = new Response(json_encode($importmulitpletakeover));
return $response;
} else {
$message = 'Image has not been uploaded ';
echo "2";
die;
}
}
}}}
protected function uploadtakeoverFile($uploadedReceipt) {
//start - code to check ip address
$checkipaddress = $this->get('userlogin')->CheckIPAddress();
if (empty($checkipaddress)) {
return $this->redirect($this->generateUrl('admin'));
}
//end - code to check ip address
$basicPath = $_SERVER['DOCUMENT_ROOT'] . '/ProjectName/web/uploads';
$basicReceiptPath = $basicPath . '/FolderName';
if (null === $uploadedReceipt) {
return;
} else {
$extention = explode('.', #$uploadedReceipt['file']["name"]);
$filename = #$extention[0] . '_' . time() . '.' . #$extention[1];
$this->path = $basicReceiptPath . '/' . #$filename;
if (move_uploaded_file($uploadedReceipt['file']["tmp_name"], $this->path))
return $this->path;
else
return false;
}
}
}
The most effective style will be to only use Doctrine DBAL and write SQL code.
Documentation states that Doctrine ORM is not fit for mass inserts.
There are "hacks" like disabling SQLLogger and batch processing, but using only DBAL will save you more time.
Related
I just recently implemented box/spout library replacing the phpspreadsheet library in favour of memory efficiency.
I am also able to produce the excel file using it.
But after opening the excel file using ms office 2019, I cannot edit the cells at all, it just seems all shown read-only.
But if I use phpspreadsheet to generate the same thing, I can edit the file.
Do any of you folks know anything that I am missing out here.
Following is my implementation of box/spout
use Box\Spout\Common\Type;
use Box\Spout\Writer\Common\Creator\Style\StyleBuilder;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
function exprot_table($xmlObjectArray, $rows)
{
error_reporting(E_ALL);
$head = (array) $rows[0];
$headArray = array_keys($head);
$writer = WriterEntityFactory::createWriter(Type::XLSX);
$writer->openToBrowser("demoexcel.xlsx");
$rowFromValues = WriterEntityFactory::createRowFromArray($headArray);
$writer->addRow($rowFromValues);
$excelRows = array();
foreach ($rows as $key => $row) {
$row = (array) $row;
$cells = array();
foreach ($headArray as $keyc => $column) {
$fieldType = $xmlObjectArray[$column]['type'];
$col_name = $this->get_col_name($keyc);
// set date formate
if ($fieldType == "datetime") {
if (! empty($row[$column])) {
// Get server time zone offset in seconds and add or subtract from main value
$timeZoneOffset = date('Z', $row[$column]);
$date = $row[$column] + $timeZoneOffset;
$date = Date::PHPToExcel(trim($date));
$cellstyle = (new StyleBuilder())->setFormat('dd mmm yyyy')->build();
$cells[] = WriterEntityFactory::createCell($date, $cellstyle);
} else {
$cells[] = WriterEntityFactory::createCell('');
}
} elseif ($fieldType == "money") {
if (strlen($row[$column]) > 0) {
$cellstyle = (new StyleBuilder())->setFormat('#,##0.00;[Red]#,##0.00')->build();
$cells[] = WriterEntityFactory::createCell($row[$column], $cellstyle);
} else {
$cells[] = WriterEntityFactory::createCell('');
}
}elseif ($fieldType == "number") {
if (strlen($row[$column]) > 0) {
$cellstyle = (new StyleBuilder())->setFormat('#,##')->build();
$cells[] = WriterEntityFactory::createCell($row[$column], $cellstyle);
} else {
$cells[] = WriterEntityFactory::createCell('');
}
} elseif ($fieldType == "image") {
$value = $row[$column];
if (! empty($value)) {
$imageFolder = $this->config->item('img_upload_path');
$subDirectory = (string) $xmlObjectArray[$column]['sub_directory'];
if (isset($subDirectory) and ! empty($subDirectory)) {
$imageFolder .= $subDirectory . "/";
}
$filePath = $imageFolder . $value;
if (stripos($value, 'https://') !== false || stripos($value, 'http://') !== false) {
$cells[] = WriterEntityFactory::createCell('=HYPERLINK("'. $value .'","'. $value .'")');
} else {
$cells[] = WriterEntityFactory::createCell($value);
}
}
} elseif ($fieldType == "file") {
$value = $row[$column];
$imageFolder = $this->config->item('img_upload_path');
if (! empty($value)) {
$value = CDN_URL . $imageFolder . $value;
}
$cells[] = WriterEntityFactory::createCell($value);
} else {
$cells[] = WriterEntityFactory::createCell($row[$column]);
}
}
$excelRows[] = WriterEntityFactory::createRow($cells);
}
$writer->addRows($excelRows);
ob_clean();
$writer->close();
exit();
}
I download a TS3AntiVPN but it shoes an error. I use a Linux Server running Debian 9 Plesk installed.
PHP Warning: Invalid argument supplied for foreach() in
/var/www/vhosts/suspectgaming.de/tsweb.suspectgaming.de/antivpn/bot.php
on line 29
How do I solve this problem?
<?php
require("ts3admin.class.php");
$ignore_groups = array('1',); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if(!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while(true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
foreach($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups'] );
if(is_array($ignore_groups)){
foreach($ignore_groups as $ig){
if(in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
}else{
if(in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip='.$val['connection_client_ip'].'');
$file = json_decode($file, true);
if($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
}
?>
You might be missing data in your first array. You may add an if statement to check if there is data in your $clientList['data'] var:
if (is_array($clientList['data'])) {
}
Or you might also check if sizeof(); of your array is larger than a number, you may desire.
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
}
Code
require "ts3admin.class.php";
$ignore_groups = array('1'); // now supports one input and array input
$msg_kick = "VPN";
$login_query = "serveradmin";
$pass_query = "";
$adres_ip = "94.249.254.216";
$query_port = "10011";
$port_ts = "9987";
$nom_bot = "AntiVPN";
$ts = new ts3Admin($adres_ip, $query_port);
if (!$ts->getElement('success', $ts->connect())) {
die("Anti-Proxy");
}
$ts->login($login_query, $pass_query);
$ts->selectServer($port_ts);
$ts->setName($nom_bot);
while (true) {
sleep(1);
$clientList = $ts->clientList("-ip -groups");
if (is_array($clientList['data']) && sizeof($clientList['data']) > 0) {
foreach ($clientList['data'] as $val) {
$groups = explode(",", $val['client_servergroups']);
if (is_array($ignore_groups)) {
foreach ($ignore_groups as $ig) {
if (in_array($ig, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
} else {
if (in_array($ignore_groups, $groups) || ($val['client_type'] == 1)) {
continue;
}
}
$file = file_get_contents('https://api.xdefcon.com/proxy/check/?ip=' . $val['connection_client_ip'] . '');
$file = json_decode($file, true);
if ($file['message'] == "Proxy detected.") {
$ts->clientKick($val['clid'], "server", $msg_kick);
}
}
} else {
echo "There might be no data in Client List";
}
}
I'm working on phpexcel. The File I'm working on is from tally export file. I have to read this file and save the data to each user .
For example from this file I need only A2:G10 as HTML/TABLE. So i can display to the particular member (Adv. Chandra Mogan) individually.
I NEED A TABLE FOR ONLY A PORTION OF THE SHEET
What I have done so far:
protected function doExcelUpdate() {
$inputFileName = $this->getParameter('temp_directory') . '/file.xls';
if (!file_exists($inputFileName)) {
$this->addFlash('sonata_flash_error', 'File: not found in temp directory');
return;
}
$this->addFlash('sonata_flash_info', 'File: exist');
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
$this->addFlash('sonata_flash_error', 'Error in PHPExcel');
return;
}
$sheet = $objPHPExcel->getSheet(0);
if (!$sheet) {
$this->addFlash('sonata_flash_error', 'Error in reading sheet');
return;
}
$objPHPExcel->getSheet(0)
->getStyle('A1:G10')
->getProtection()
->setLocked(
PHPExcel_Style_Protection::PROTECTION_PROTECTED
);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->setSheetIndex(0);
$objWriter->save($this->getParameter('temp_directory') . '/output.html');
}
A1:G10 is not locked. Entire sheet is printed.
First point: "Locking" doesn't change the sheet size, or set a "view window"; it protects parts of the sheet from being edited.
Second point: "Locking" is a feature of Excel, and supported for excel writers, but not for HTML.
Third point: there is no direct mechanism to write only part of a worksheet.
As a suggestion, you might create a new blank worksheet, and then copy the data/style information from the cell range that you want in your your main worksheet to that new worksheet starting from cell A1; then send that worksheet to the HTML Writer.
You can't achive this using locked or hidden cells when you use HTML writer.
You can use a workaround creating a new worksheet and after adding the portion you want to display.
For mantain style on new worksheet (like font, color, border) you must extract it for each cell from the orginal worksheet and apply to the copied cells.
The same thing is for merged cells in the old worksheet.
Your function doExcelUpdate() should be like this:
protected function doExcelUpdate()
{
$inputFileName = $this->getParameter('temp_directory').'/file.xls';
if (!file_exists($inputFileName)) {
$this->addFlash('sonata_flash_error', 'File: not found in temp directory');
return;
}
$this->addFlash('sonata_flash_info', 'File: exist');
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$originalPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
$this->addFlash('sonata_flash_error', 'Error in PHPExcel');
return;
}
$originalSheet = $originalPHPExcel->getSheet(0);
if (!$sheet) {
$this->addFlash('sonata_flash_error', 'Error in reading sheet');
return;
}
// Get the data of portion you want to output
$data = $originalSheet->rangeToArray('A1:G11');
$newPHPExcel = new PHPExcel;
$newPHPExcel->setActiveSheetIndex(0);
$newSheet = $newPHPExcel->getActiveSheet();
$newSheet->fromArray($data);
// Duplicate style for each cell from original sheet to the new sheet
for ($i = 1; $i < 11; $i++) {
for ($j = 0; $j <= 6; $j++) {
$style = $originalSheet->getStyleByColumnAndRow($j, $i);
$newSheet->duplicateStyle($style, PHPExcel_Cell::stringFromColumnIndex($j).(string)$i);
}
}
// Merge the same cells that are merged in the original sheet
foreach ($originalSheet->getMergeCells() as $cells) {
$inRange = false;
foreach (explode(':', $cells) as $cell) {
$inRange = $originalSheet->getCell($cell)->isInRange('A1:G11');
}
// Merge only if in range of the portion of file you want to output
if ($inRange) {
$newSheet->mergeCells($cells);
}
}
$objWriter = PHPExcel_IOFactory::createWriter($newPHPExcel, 'HTML');
$objWriter->save($this->getParameter('temp_directory').'/output.html');
}
UP TO NOW FOR THE WORK TO BE COMPLETED, I HAVE DONE THIS,
private function doExcelUpdate() {
$inputFileName = $this->getParameter('temp_directory') . '/file.xls';
$synopsis = PHPExcel_IOFactory::load($inputFileName)->getSheet(0);
$column = $synopsis->getHighestColumn();
$row = $synopsis->getHighestRow();
$this->cleanUserPayment();
$this->doExcelUpdateTable($synopsis, $column, $row);
$this->deleteExcelFile();
}
private function cleanUserPayment() {
$em = $this->getDoctrine()->getManager();
$classMetaData = $em->getClassMetadata('AppBundle\Entity\UserPayment');
$connection = $em->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
$connection->beginTransaction();
try {
$connection->query('SET FOREIGN_KEY_CHECKS=0');
$q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName());
$connection->executeUpdate($q);
$connection->query('SET FOREIGN_KEY_CHECKS=1');
$connection->commit();
} catch (\Exception $e) {
$connection->rollback();
}
}
private function doExcelUpdateTable($synopsis, $column, $row) {
set_time_limit(300);
$t = [];
for ($r = 1; $r <= $row; $r++) {
for ($c = "A"; $c <= $column; $c++) {
$cell = $synopsis->getCell($c . $r)->getFormattedValue();
if ($cell == 'Ledger:') {
$t[] = $r;
}
}
}
$t[] = $row+1;
$numItems = count($t);
$i = 0;
$em = $this->getDoctrine()->getManager();
foreach ($t as $key => $value) {
if (++$i != $numItems) {
$up = new UserPayment();
$up->setName($synopsis->getCell('B' . $value)->getFormattedValue());
$up->setMessage($this->doExcelUpdateTableCreate($synopsis, $column, $value, $t[$key + 1]));
$em->persist($up);
// $this->addFlash('sonata_flash_error', 'Output: ' . $synopsis->getCell('B' . $value)->getFormattedValue() . $this->doExcelUpdateTableCreate($synopsis, $column, $value, $t[$key + 1]));
}
}
$em->flush();
$this->addFlash('sonata_flash_success', "Successfully updated user bills. Total data updated::" . count($t));
}
private function doExcelUpdateTableCreate($synopsis, $column, $rowS, $rowE) {
$mr = NULL;
$x = 0;
$alphas = range('A', $column);
$oneTable = '<table border="1">';
for ($r = $rowS; $r < $rowE; $r++) {
$oneTable .= "<tr>";
for ($c = "A"; $c <= $column; $c++) {
if ($x > 0) {
$x--;
continue;
}
$mr = NULL;
$x = 0;
$cell = $synopsis->getCell($c . $r);
$cellVal = $cell->getFormattedValue();
if ($cellVal == NULL) {
$cellVal = " ";
}
$cellRange = $cell->getMergeRange();
if ($cellRange) {
$mr = substr($cellRange, strpos($cellRange, ":") + 1, 1);
$upto = array_search($mr, $alphas);
$x = ($upto - array_search($c, $alphas));
$oneTable .= "<td colspan=" . ($x + 1) . " style='text-align:right;'>" . $cellVal . "</td>";
} else {
$oneTable .= "<td>" . $cellVal . "</td>";
}
}
$oneTable .= "</tr>";
}
$oneTable .= "</table>";
return $oneTable;
}
private function deleteExcelFile() {
$filesystem = new \Symfony\Component\Filesystem\Filesystem();
$filesystem->remove($this->getParameter('temp_directory') . '/file.xls');
}
I need to refresh modifications after install module.
public function install() {
$this->load->controller('marketplace/modification/refresh');
}
I tried this. Its worked but the page redirected to modification listing. How can i do without redirect. I am using opencart 3.
If you don't want to edit modification.php or clone its refresh function, You can use this:
public function install(){
$data['redirect'] = 'extension/extension/module';
$this->load->controller('marketplace/modification/refresh', $data);
}
You could not controll by this way as you are doing:
You need to do this as
public function install() {
$this->refresh();
}
protected function refresh($data = array()) {
$this->load->language('marketplace/modification');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('setting/modification');
if ($this->validate()) {
// Just before files are deleted, if config settings say maintenance mode is off then turn it on
$maintenance = $this->config->get('config_maintenance');
$this->load->model('setting/setting');
$this->model_setting_setting->editSettingValue('config', 'config_maintenance', true);
//Log
$log = array();
// Clear all modification files
$files = array();
// Make path into an array
$path = array(DIR_MODIFICATION . '*');
// While the path array is still populated keep looping through
while (count($path) != 0) {
$next = array_shift($path);
foreach (glob($next) as $file) {
// If directory add to path array
if (is_dir($file)) {
$path[] = $file . '/*';
}
// Add the file to the files to be deleted array
$files[] = $file;
}
}
// Reverse sort the file array
rsort($files);
// Clear all modification files
foreach ($files as $file) {
if ($file != DIR_MODIFICATION . 'index.html') {
// If file just delete
if (is_file($file)) {
unlink($file);
// If directory use the remove directory function
} elseif (is_dir($file)) {
rmdir($file);
}
}
}
// Begin
$xml = array();
// Load the default modification XML
$xml[] = file_get_contents(DIR_SYSTEM . 'modification.xml');
// This is purly for developers so they can run mods directly and have them run without upload after each change.
$files = glob(DIR_SYSTEM . '*.ocmod.xml');
if ($files) {
foreach ($files as $file) {
$xml[] = file_get_contents($file);
}
}
// Get the default modification file
$results = $this->model_setting_modification->getModifications();
foreach ($results as $result) {
if ($result['status']) {
$xml[] = $result['xml'];
}
}
$modification = array();
foreach ($xml as $xml) {
if (empty($xml)){
continue;
}
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
$dom->loadXml($xml);
// Log
$log[] = 'MOD: ' . $dom->getElementsByTagName('name')->item(0)->textContent;
// Wipe the past modification store in the backup array
$recovery = array();
// Set the a recovery of the modification code in case we need to use it if an abort attribute is used.
if (isset($modification)) {
$recovery = $modification;
}
$files = $dom->getElementsByTagName('modification')->item(0)->getElementsByTagName('file');
foreach ($files as $file) {
$operations = $file->getElementsByTagName('operation');
$files = explode('|', $file->getAttribute('path'));
foreach ($files as $file) {
$path = '';
// Get the full path of the files that are going to be used for modification
if ((substr($file, 0, 7) == 'catalog')) {
$path = DIR_CATALOG . substr($file, 8);
}
if ((substr($file, 0, 5) == 'admin')) {
$path = DIR_APPLICATION . substr($file, 6);
}
if ((substr($file, 0, 6) == 'system')) {
$path = DIR_SYSTEM . substr($file, 7);
}
if ($path) {
$files = glob($path, GLOB_BRACE);
if ($files) {
foreach ($files as $file) {
// Get the key to be used for the modification cache filename.
if (substr($file, 0, strlen(DIR_CATALOG)) == DIR_CATALOG) {
$key = 'catalog/' . substr($file, strlen(DIR_CATALOG));
}
if (substr($file, 0, strlen(DIR_APPLICATION)) == DIR_APPLICATION) {
$key = 'admin/' . substr($file, strlen(DIR_APPLICATION));
}
if (substr($file, 0, strlen(DIR_SYSTEM)) == DIR_SYSTEM) {
$key = 'system/' . substr($file, strlen(DIR_SYSTEM));
}
// If file contents is not already in the modification array we need to load it.
if (!isset($modification[$key])) {
$content = file_get_contents($file);
$modification[$key] = preg_replace('~\r?\n~', "\n", $content);
$original[$key] = preg_replace('~\r?\n~', "\n", $content);
// Log
$log[] = PHP_EOL . 'FILE: ' . $key;
}
foreach ($operations as $operation) {
$error = $operation->getAttribute('error');
// Ignoreif
$ignoreif = $operation->getElementsByTagName('ignoreif')->item(0);
if ($ignoreif) {
if ($ignoreif->getAttribute('regex') != 'true') {
if (strpos($modification[$key], $ignoreif->textContent) !== false) {
continue;
}
} else {
if (preg_match($ignoreif->textContent, $modification[$key])) {
continue;
}
}
}
$status = false;
// Search and replace
if ($operation->getElementsByTagName('search')->item(0)->getAttribute('regex') != 'true') {
// Search
$search = $operation->getElementsByTagName('search')->item(0)->textContent;
$trim = $operation->getElementsByTagName('search')->item(0)->getAttribute('trim');
$index = $operation->getElementsByTagName('search')->item(0)->getAttribute('index');
// Trim line if no trim attribute is set or is set to true.
if (!$trim || $trim == 'true') {
$search = trim($search);
}
// Add
$add = $operation->getElementsByTagName('add')->item(0)->textContent;
$trim = $operation->getElementsByTagName('add')->item(0)->getAttribute('trim');
$position = $operation->getElementsByTagName('add')->item(0)->getAttribute('position');
$offset = $operation->getElementsByTagName('add')->item(0)->getAttribute('offset');
if ($offset == '') {
$offset = 0;
}
// Trim line if is set to true.
if ($trim == 'true') {
$add = trim($add);
}
// Log
$log[] = 'CODE: ' . $search;
// Check if using indexes
if ($index !== '') {
$indexes = explode(',', $index);
} else {
$indexes = array();
}
// Get all the matches
$i = 0;
$lines = explode("\n", $modification[$key]);
for ($line_id = 0; $line_id < count($lines); $line_id++) {
$line = $lines[$line_id];
// Status
$match = false;
// Check to see if the line matches the search code.
if (stripos($line, $search) !== false) {
// If indexes are not used then just set the found status to true.
if (!$indexes) {
$match = true;
} elseif (in_array($i, $indexes)) {
$match = true;
}
$i++;
}
// Now for replacing or adding to the matched elements
if ($match) {
switch ($position) {
default:
case 'replace':
$new_lines = explode("\n", $add);
if ($offset < 0) {
array_splice($lines, $line_id + $offset, abs($offset) + 1, array(str_replace($search, $add, $line)));
$line_id -= $offset;
} else {
array_splice($lines, $line_id, $offset + 1, array(str_replace($search, $add, $line)));
}
break;
case 'before':
$new_lines = explode("\n", $add);
array_splice($lines, $line_id - $offset, 0, $new_lines);
$line_id += count($new_lines);
break;
case 'after':
$new_lines = explode("\n", $add);
array_splice($lines, ($line_id + 1) + $offset, 0, $new_lines);
$line_id += count($new_lines);
break;
}
// Log
$log[] = 'LINE: ' . $line_id;
$status = true;
}
}
$modification[$key] = implode("\n", $lines);
} else {
$search = trim($operation->getElementsByTagName('search')->item(0)->textContent);
$limit = $operation->getElementsByTagName('search')->item(0)->getAttribute('limit');
$replace = trim($operation->getElementsByTagName('add')->item(0)->textContent);
// Limit
if (!$limit) {
$limit = -1;
}
// Log
$match = array();
preg_match_all($search, $modification[$key], $match, PREG_OFFSET_CAPTURE);
// Remove part of the the result if a limit is set.
if ($limit > 0) {
$match[0] = array_slice($match[0], 0, $limit);
}
if ($match[0]) {
$log[] = 'REGEX: ' . $search;
for ($i = 0; $i < count($match[0]); $i++) {
$log[] = 'LINE: ' . (substr_count(substr($modification[$key], 0, $match[0][$i][1]), "\n") + 1);
}
$status = true;
}
// Make the modification
$modification[$key] = preg_replace($search, $replace, $modification[$key], $limit);
}
if (!$status) {
// Abort applying this modification completely.
if ($error == 'abort') {
$modification = $recovery;
// Log
$log[] = 'NOT FOUND - ABORTING!';
break 5;
}
// Skip current operation or break
elseif ($error == 'skip') {
// Log
$log[] = 'NOT FOUND - OPERATION SKIPPED!';
continue;
}
// Break current operations
else {
// Log
$log[] = 'NOT FOUND - OPERATIONS ABORTED!';
break;
}
}
}
}
}
}
}
}
// Log
$log[] = '----------------------------------------------------------------';
}
// Log
$ocmod = new Log('ocmod.log');
$ocmod->write(implode("\n", $log));
// Write all modification files
foreach ($modification as $key => $value) {
// Only create a file if there are changes
if ($original[$key] != $value) {
$path = '';
$directories = explode('/', dirname($key));
foreach ($directories as $directory) {
$path = $path . '/' . $directory;
if (!is_dir(DIR_MODIFICATION . $path)) {
#mkdir(DIR_MODIFICATION . $path, 0777);
}
}
$handle = fopen(DIR_MODIFICATION . $key, 'w');
fwrite($handle, $value);
fclose($handle);
}
}
// Maintance mode back to original settings
$this->model_setting_setting->editSettingValue('config', 'config_maintenance', $maintenance);
// Do not return success message if refresh() was called with $data
$this->session->data['success'] = $this->language->get('text_success');
$url = '';
if (isset($this->request->get['sort'])) {
$url .= '&sort=' . $this->request->get['sort'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
}
}
I hope it shouwl work for you.
This process is used to refresh the modification when your module installing.
if you need globally this then please tell me I will update you process.
I'm Using this PHP IMAP Class: http://code.google.com/p/php-imap/source/browse/trunk/ImapMailbox.php on a current project. After a few modifications the class is working. However whenever the class downloads .docx files they are always corrupt and have to be recovered by office.
protected function initMailPart(IncomingMail $mail, $partStruct, $partNum) {
$data = $partNum ? $this->imap_fetchbody($this->mbox, $mail->mId, $partNum, FT_UID) : $this->imap_body($this->mbox, $mail->mId, FT_UID);
if($partStruct->encoding == 1) {
$data = $this->imap_utf8($data);
}
elseif($partStruct->encoding == 2) {
$data = $this->imap_binary($data);
}
elseif($partStruct->encoding == 3) {
$data = $this->imap_base64($data);
}
elseif($partStruct->encoding == 4) {
$data = $this->imap_qprint($data);
}
$data = trim($data);
$params = array();
if(!empty($partStruct->parameters)) {
foreach($partStruct->parameters as $param) {
$params[strtolower($param->attribute)] = $param->value;
}
}
if(!empty($partStruct->dparameters)) {
foreach($partStruct->dparameters as $param) {
$params[strtolower($param->attribute)] = $param->value;
}
}
if(!empty($params['charset'])) {
$data = iconv($params['charset'], $this->serverEncoding, $data);
}
// attachments
if($this->attachmentsDir) {
$filename = false;
$attachmentId = $partStruct->ifid ? trim($partStruct->id, " <>") : null;
if(empty($params['filename']) && empty($params['name']) && $attachmentId) {
$filename = $attachmentId . '.' . strtolower($partStruct->subtype);
}
elseif(!empty($params['filename']) || !empty($params['name'])) {
$filename = !empty($params['filename']) ? $params['filename'] : $params['name'];
$filename = $this->decodeMimeStr($filename);
$filename = $this->quoteAttachmentFilename($filename);
}
if($filename) {
if($this->attachmentsDir) {
$filepath = rtrim($this->attachmentsDir, '/\\') . DIRECTORY_SEPARATOR . $filename;
file_put_contents($filepath, $data);
$mail->attachments[$filename] = $filepath;
}
else {
$mail->attachments[$filename] = $filename;
}
if($attachmentId) {
$mail->attachmentsIds[$filename] = $attachmentId;
}
}
}
if($partStruct->type == 0 && $data) {
if(strtolower($partStruct->subtype) == 'plain') {
$mail->textPlain .= $data;
}
else {
$mail->textHtml .= $data;
}
}
elseif($partStruct->type == 2 && $data) {
$mail->textPlain .= trim($data);
}
if(!empty($partStruct->parts)) {
foreach($partStruct->parts as $subpartNum => $subpartStruct) {
$this->initMailPart($mail, $subpartStruct, $partNum . '.' . ($subpartNum + 1));
}
}
}
protected function decodeMimeStr($string, $charset = 'UTF-8') {
$newString = '';
$elements = $this->imap_mime_header_decode($string);
for($i = 0; $i < count($elements); $i++) {
if($elements[$i]->charset == 'default') {
$elements[$i]->charset = 'iso-8859-1';
}
$newString .= iconv($elements[$i]->charset, $charset, $elements[$i]->text);
}
return $newString;
}
Try wading into the binary files with a good editor, both before and after the round-trip from IMAP, to see if there's something obvious. I've had similar problems where whitespace made its way into the PHP script (e.g. at the end of a file after the close ?> tag); most formats won't blink but .docx may get kicked into a recovery if there's whitespace left over at the end.