In the code below, the code would stop from executing further when Kiyoh would not be reachable. This is not good for production. So I was wondering what the best way would be to replace the die function, in a way that the content would execute further -even when Kiyoh would not be reachable-.
The code looks like:
<?php
// Get KiyOh rating
$readdir = $_SERVER['DOCUMENT_ROOT'] . '/kiyoh/';
$file = 'kiyohdata.dat';
// Open the file to get existing content
$kiyohdata = file_get_contents($readdir . $file);
if( $kiyohdata === false ) { // NOT CACHED
$xml = simplexml_load_file('https://www.kiyoh.nl/widgetfeed.php?company=YYYYY') or die("Error: Cannot create object");
$kiyohdata = explode(",", $xml->channel->description);
if(!empty($kiyohdata)) {
file_put_contents($readdir . $file, serialize($kiyohdata));
}
} else { // IS CACHED
$kiyohdata = unserialize($kiyohdata);
}
$cijfer = str_replace('Average score ', '', $kiyohdata[0]);
$cijfer = str_replace('.', ',', $cijfer);
$aantal = str_replace(' Total reviews ', '', $kiyohdata[2]);
?>
I tried with placing an exception: throw new Exception("Kiyoh is not available at the moment");, but the page crashes anyway (Magento 1.9.4.3 webshop).
this wil send you the error per email
<?php
$to_email_address = webmaster#example.com
// Get KiyOh rating
$readdir = $_SERVER['DOCUMENT_ROOT'] . '/kiyoh/';
$file = 'kiyohdata.dat';
// Open the file to get existing content
$kiyohdata = file_get_contents($readdir . $file);
if( $kiyohdata === false ) { // NOT CACHED
$xml = simplexml_load_file('https://www.kiyoh.nl/widgetfeed.php?company=YYYYY') or mail($to_email_address,"GOOGOO hapened !","Error: Cannot create object");
$kiyohdata = explode(",", $xml->channel->description);
if(!empty($kiyohdata)) {
file_put_contents($readdir . $file, serialize($kiyohdata));
}
} else { // IS CACHED
$kiyohdata = unserialize($kiyohdata);
}
$cijfer = str_replace('Average score ', '', $kiyohdata[0]);
$cijfer = str_replace('.', ',', $cijfer);
$aantal = str_replace(' Total reviews ', '', $kiyohdata[2]);
?>
Related
I need to check if the excel file is currently open using PHPSpreadsheet.
I thought of a solution by handling this line $writer->save(file_name) into if else condition but still doesn't work.
if($writer->save(file_name){
//file is open
}else{
//file is not open
}
What else can I do to solve my problem?
I need to check if the excel file is currently open using PHPSpreadsheet.
Checking if a file is open isn't really useful, since the open/closed state could change at any time, or the failure could be caused by other filesystem problems.
What you need to do is handle the failure during file operations as:
try {
$writer->save(file_name);
}
catch (Exception $e) {
echo 'Unable to save file. Please close any other applications(s) that are using it: [", $e->getMessage(), "]\n";
}
Answered by #terry-carmen will be Incorrect in following situation:
It will still show "Resource Unavailable" error If file is exists but being used by some application and $writer->save() will try to unlink() the file.
To Overcome this situations I edited the save() function as following:
(Located at: "\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx.php")
public function save($pFilename)
{
if ($this->spreadSheet !== null) {
// garbage collect
$this->spreadSheet->garbageCollect();
// If $pFilename is php://output or php://stdout, make it a temporary file...
$originalFilename = $pFilename;
if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
$pFilename = #tempnam(File::sysGetTempDir(), 'phpxltmp');
if ($pFilename == '') {
$pFilename = $originalFilename;
}
}
$saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false);
$saveDateReturnType = Functions::getReturnDateType();
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
// Create string lookup table
$this->stringTable = [];
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
}
// Create styles dictionaries
$this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet));
$this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet));
$this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet));
$this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet));
$this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet));
$this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet));
// Create drawing dictionary
$this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet));
$zip = new ZipArchive();
if (file_exists($pFilename)) {
// Added by muhammad.begawala#gmail.com
// '#' will stop displaying "Resource Unavailable" error because of file is open some where.
// 'unlink($pFilename) !== true' will check if file is deleted successfully.
// Throwing exception so that we can handle error easily instead of displaying to users.
if (#unlink($pFilename) !== true) {
throw new WriterException('Could not delete file: ' . $pFilename . ' Please close all applications that are using it.');
}
}
// Try opening the ZIP file
if ($zip->open($pFilename, ZipArchive::OVERWRITE) !== true) {
if ($zip->open($pFilename, ZipArchive::CREATE) !== true) {
throw new WriterException('Could not open ' . $pFilename . ' for writing.');
}
}
// Add [Content_Types].xml to ZIP file
$zip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts));
//if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
if ($this->spreadSheet->hasMacros()) {
$macrosCode = $this->spreadSheet->getMacrosCode();
if ($macrosCode !== null) {
// we have the code ?
$zip->addFromString('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin
if ($this->spreadSheet->hasMacrosCertificate()) {
//signed macros ?
// Yes : add the certificate file and the related rels file
$zip->addFromString('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate());
$zip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet));
}
}
}
//a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
if ($this->spreadSheet->hasRibbon()) {
$tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target');
$zip->addFromString($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data'));
if ($this->spreadSheet->hasRibbonBinObjects()) {
$tmpRootPath = dirname($tmpRibbonTarget) . '/';
$ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write
foreach ($ribbonBinObjects as $aPath => $aContent) {
$zip->addFromString($tmpRootPath . $aPath, $aContent);
}
//the rels for files
$zip->addFromString($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet));
}
}
// Add relationships to ZIP file
$zip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet));
$zip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet));
// Add document properties to ZIP file
$zip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet));
$zip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet));
$customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet);
if ($customPropertiesPart !== null) {
$zip->addFromString('docProps/custom.xml', $customPropertiesPart);
}
// Add theme to ZIP file
$zip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet));
// Add string table to ZIP file
$zip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable));
// Add styles to ZIP file
$zip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet));
// Add workbook to ZIP file
$zip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas));
$chartCount = 0;
// Add worksheets
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$zip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts));
if ($this->includeCharts) {
$charts = $this->spreadSheet->getSheet($i)->getChartCollection();
if (count($charts) > 0) {
foreach ($charts as $chart) {
$zip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas));
++$chartCount;
}
}
}
}
$chartRef1 = 0;
// Add worksheet relationships (drawings, ...)
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
// Add relationships
$zip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts));
// Add unparsedLoadedData
$sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName();
$unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) {
$zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']);
}
}
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) {
$zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']);
}
}
$drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection();
$drawingCount = count($drawings);
if ($this->includeCharts) {
$chartCount = $this->spreadSheet->getSheet($i)->getChartCount();
}
// Add drawing and image relationship parts
if (($drawingCount > 0) || ($chartCount > 0)) {
// Drawing relationships
$zip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts));
// Drawings
$zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
} elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) {
// Drawings
$zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
}
// Add comment relationship parts
if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
// VML Comments
$zip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i)));
// Comments
$zip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i)));
}
// Add unparsed relationship parts
if (isset($unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['vmlDrawings'])) {
foreach ($unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['vmlDrawings'] as $vmlDrawing) {
$zip->addFromString($vmlDrawing['filePath'], $vmlDrawing['content']);
}
}
// Add header/footer relationship parts
if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
// VML Drawings
$zip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)));
// VML Drawing relationships
$zip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)));
// Media
foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
$zip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
}
}
}
// Add media
for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) {
$imageContents = null;
$imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
if (strpos($imagePath, 'zip://') !== false) {
$imagePath = substr($imagePath, 6);
$imagePathSplitted = explode('#', $imagePath);
$imageZip = new ZipArchive();
$imageZip->open($imagePathSplitted[0]);
$imageContents = $imageZip->getFromName($imagePathSplitted[1]);
$imageZip->close();
unset($imageZip);
} else {
$imageContents = file_get_contents($imagePath);
}
$zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
} elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
ob_start();
call_user_func(
$this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
$this->getDrawingHashTable()->getByIndex($i)->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
$zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
}
}
Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
// Close file
if ( #$zip->close() === false ) { // updated by muhammad.begawala#gmail.com
throw new WriterException("Could not close zip file $pFilename.");
}
// If a temporary file was used, copy it to the correct file stream
if ($originalFilename != $pFilename) {
if (copy($pFilename, $originalFilename) === false) {
throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename.");
}
#unlink($pFilename);
}
return true;
// Return True to make sure that file is created successfully with no ExceptionsAdded by muhammad.begawala#gmail.com
} else {
throw new WriterException('PhpSpreadsheet object unassigned.');
}
}
Major Changes:
1) Handling "Resource Unavailable" error by unlink() as Exception using try catch so that It doesn't show error when file is being used by some applications when we tries to delete it using unlink.
if (file_exists($pFilename)) {
// Added by muhammad.begawala#gmail.com
// '#' will stop displaying "Resource Unavailable" error because of file is open some where.
// 'unlink($pFilename) !== true' will check if file is deleted successfully.
// Throwing exception so that we can handle error easily instead of displaying to users.
if (#unlink($pFilename) !== true) {
throw new WriterException('Could not delete file: ' . $pFilename . ' Please close all applications that are using it.');
}
}
2) $writer->save('hello world.xlsx') will return TRUE if file is successfully created else throw Exception.
Usage:
try {
$writer->save('hello world.xlsx');
echo 'File Created';
}
catch (Exception $e) {
echo $e->getMessage(); // Will print Exception thrown by save()
}
This is the whole crawler code that I am trying to build. This code is a single domain crawler. But it has a big problem, when I checked the database it was saving some of the links again and again, which creates an infinite loop. I want to solve this problem without using my database because checking each link for a presence in my database will make this crawler slow. How can I do that? + If you have any suggestions to make it faster?
<?php
include_once('ganon.php');
ini_set('display_errors', '1');
function gethost($link)
{
$link = trim($link, '/');
if (!preg_match('#^http(s)?://#', $link))
{
$link = 'http://' . $link;
}
$urlParts = parse_url($link);
$domain = preg_replace('/^www\./', '', $urlParts['host']);
return $domain;
}
function store($raw, $link)
{
$html = str_get_dom($raw);
$title = $html('title', 0)->getPlainText();
$con = #mysqli_connect('somehost', 'someuser', 'somepassword', 'somedatabase');
if (!$con)
{
echo "Error: " . mysqli_connect_error();
exit();
}
$query = "INSERT INTO `somedatabase`.`sometable` (`title`, `url`) VALUES ('$title', '$link');";
mysqli_query($con, $query);
mysqli_close($con);
echo $title."<br>";
}
function crawl_save_crawl($target)
{
$curl = curl_init($target);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($curl);
if(curl_errno($curl))
{
echo 'Curl error: ' . curl_error($curl);
}
curl_close($curl);
$dom = str_get_dom($result);
foreach($dom('a') as $element)
{
$href = $element->href;
if (0 !== strpos($href, 'http'))
{
$path = '/' . ltrim($href, '/');
if (extension_loaded('http'))
{
$href = http_build_url("http://www.".gethost($target), array('path' => $path));
}
else
{
$parts = parse_url("http://www.".gethost($target));
$href = $parts['scheme'] . '://';
if (isset($parts['user']) && isset($parts['pass']))
{
$href .= $parts['user'] . ':' . $parts['pass'] . '#';
}
$href .= $parts['host'];
if (isset($parts['port']))
{
$href .= ':' . $parts['port'];
}
$href .= dirname($parts['path'], 1).$path;
}
}
if (gethost($target) == gethost($href))
{
crawl_save_crawl($href);
}
}
store($result, $target);
}
$url=$_GET['u'];
crawl_save_crawl($url);
?>
In your crawl_save_crawl() function, you could store the links you've already visited and therefore stop the code going back to them. Using a static variable isn't ideal, but in such a limited piece of code it serves the purpose it was intended for (to hold it's value across calls).
This doesn't stop it searching things other pages have searched, but stops it looping in itself.
function crawl_save_crawl($target)
{
static $alreadyDone = null;
if ( $alreadyDone == null ) {
$alreadyDone = [$target];
}
In the first loop, this will add the current reference in as this would previously have caused it to be missing.
Then before you call the same routing, you can test if it's already been checked...
$visit = trim(str_replace(["http://","https://"], "", $href), '/');
if (in_array($visit, $alreadyDone) === false &&
gethost($target) == gethost($href))
{
$alreadyDone[] = $visit;
crawl_save_crawl($href);
}
This may still look as though it's visiting the same page, but as your logic sometimes creates a href with 'www.' at the start, this may be different than without it. So when ccrawling stackoverflow, this means there is stackoverflow.com and www.stackoverflow.com.
I'm trying to rewrite our Windows FTP server configuration script that was created for IIS and now we're trying to get something similar working for Filezilla Server.
The structure goes like this, we have a batch file which is a for loop of another batch file, so we can batch configure our FTP websites. This batch file I'm currently trying to get working contains a line of code to execute a PHP script to set up the FTP username and password in Filezilla as well as doing a few other neat things.
Now, running CreateIIStmp.bat var1 var2 works just fine. But executing the BatchCreateIIS.bat seems to skip the execution of the php script, or the php script fails. (I'm just looking into how I put in some error handling into the PHP script to catch any error and display it, but I'm not a (PHP) developer/coder so I'll be updating this when I figure it out.)
Here's a stripped down version of what I'm talking about:
The initial batch file BatchCreateIIS.bat:
#Echo off
for /f %%X in (NewWebsiteEntries.txt) do start cmd.exe /c "CreateIIStmp.bat %%X %%X"
echo ...
echo *** BATCH PROCESS HAS BEEN COMPLETED ***
pause
The CreateIIStmp.bat:
# echo off
C:\php5\php-win.exe -f filezilla-user-script.php -- %1 %2
pause
#echo on
The NewWebsiteEntries.txt:
somedomain.com ftpuname
somedomain2.net ftpuname2
The filezilla-user-script.php:
<?php
$xmlfolder = 'C:/Program Files (x86)/FileZilla Server/';
$xmlfilename = 'FileZilla Server.xml';
$ftpRoot = 'C:/inetpub/wwwroot/';
$ftpDocumentation = 'C:/Documentation ftp server/';
$xmlfile = $xmlfolder . $xmlfilename;
$xmlbackupfile = $xmlfolder . #date("Y-m-d-H-i-s") . '_FileZilla_Server.xml';
// Copy Config for backup
createXMLbackup($xmlfile,$xmlbackupfile);
//Load XML file
$xml = simplexml_load_file($xmlfile);
$msg = "Allowed usernames: 20 characters out of a...z A...Z 0...9 _ \n\nPlease input username (Ctrl+C to quit)";
// Copy Config for backup before each change, too.
createXMLbackup($xmlfile,$xmlbackupfile);
echo "\n\n";
$input = ($argv[2]);
echo "\n";
//echo 'Userinput: ' . $input . "\n";
$isvalid = isUserID($input);
//var_dump($isvalid);
if($isvalid)
{
$ftpUserFolder = $ftpRoot . ($argv[1]);
if ((file_exists($ftpUserFolder) && is_dir($ftpUserFolder)))
{
echo "The directory $ftpUserFolder exists.\nPlease select another user name.\n";
}
else
{
//echo "The directory $ftpUserFolder does not exist\n";
if(!check_user_exists($xml,$input))
{
echo "Adding user $input...\n";
if (!mkdir($ftpUserFolder))
{
die("Could not create directory $ftpUserFolder \n");
}
else
{
echo "Directory $ftpUserFolder created.\n";
}
$password = generatePassword();
//echo 'Password: ' . $password . "\n";
$user = $xml->Users->addChild('User');
$user->addAttribute('Name', $input);
$option = $user->addChild('Option', md5($password));
$option->addAttribute('Name', 'Pass');
$option = $user->addChild('Option');
$option->addAttribute('Name', 'Group');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'Bypass server userlimit');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'User Limit');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'IP Limit');
$option = $user->addChild('Option', '1');
$option->addAttribute('Name', 'Enabled');
$option = $user->addChild('Option', 'none');
$option->addAttribute('Name', 'Comments');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'ForceSsl');
$filter = $user->addChild('IpFilter');
$filter->addChild('Disallowed');
$filter->addChild('Allowed');
$permissions = $user->addChild('Permissions');
$permission = $permissions->addChild('Permission');
$permission->addAttribute('Dir', str_replace("/","\\",$ftpUserFolder));
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileRead');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileWrite');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'FileDelete');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileAppend');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirCreate');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'DirDelete');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirList');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirSubdirs');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'IsHome');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'AutoCreate');
$speed = $user->addChild('SpeedLimits');
$speed->addAttribute('DlType', '1');
$speed->addAttribute('DlLimit', '10');
$speed->addAttribute('ServerDlLimitBypass', '0');
$speed->addAttribute('UlType', '1');
$speed->addAttribute('UlLimit', '10');
$speed->addAttribute('ServerUlLimitBypass', '0');
$speed->addChild('Download');
$speed->addChild('Upload');
$rv = $xml->asXML($xmlfile);
//echo $rv . "\n";
if(!$rv)
{
die('SimpleXML could not write file');
}
//$newentry = $xml->addChild('element', iconv('ISO-8859-1', 'UTF-8', $write));
//The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode()
//to work with texts in ISO-8859-1 encoding or Iconv for other encodings.
//make human readable, parse using DOM function
//otherwise everything will be printed on one line
if( !file_exists($xmlfile) ) die('Missing file: ' . $xmlfile);
else
{
$dom = new DOMDocument("1.0","ISO-8859-1");
//Setze die Flags direkt nach dem Initialisieren des Objektes:
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
//$dl = #$dom->load($xmlfile); // remove error control operator (#) to print any error message generated while loading.
$dl = $dom->load($xmlfile); // remove error control operator (#) to print any error message generated while loading.
if ( !$dl ) die('Error while parsing the document: ' . $xmlfile);
//echo $dom->save($xmlfile) . "\n";
if(!$dom->save($xmlfile))
{
die('DOMDocument could not write file');
}
}
//Create documentation
$docuFile = $ftpDocumentation . $input . '.txt';
//echo $docuFile . "\n";
$docuString = "Username: " . $input . "\n";
$docuString = $docuString . "Password: " . $password . "\n";
$docuString = $docuString . "Folder: " . str_replace("/","\\",$ftpUserFolder) . "\n";
$docuString = $docuString . "Date: " . #date("d.m.Y") . "\n";
// $docuString = $docuString . "\n";
// $docuString = $docuString . "Direct link:\n";
// $docuString = $docuString . "ftp://" . $input . ":" . $password . "#ftp.yourcompany.com";
$handleDocuFile = fopen($docuFile, "wt");
if(!$handleDocuFile)
{
die('Could not fopen docu file');
}
$rv = fwrite($handleDocuFile, $docuString);
if(!$rv)
{
die('Could not fwrite docu file');
}
// Close xml file
$rv = fclose($handleDocuFile);
if(!$rv)
{
die('Could not fclose docu file');
}
echo "Documentary file written.\n";
$ftpExecutable = "\"C:\\Program Files (x86)\\FileZilla Server\\FileZilla server.exe\" /reload-config";
$command = $ftpExecutable;
$last_line = system($command, $retval);
echo ("Filezilla reloaded, user active.\n");
echo ("Close Notepad to add another user or quit.\n");
$command = "C:\\Windows\\System32\\notepad.exe $docuFile";
$last_line = system($command, $retval);
}
else
{
echo "Username $input already exists...\n";
}
}
}
else
{
echo "Username $input is invalid\n";
}
function check_user_exists($xml,$username)
{
$children=$xml->Users->children();
foreach($children as $child)
{
if ($child->getName()=='User')
{
foreach($child->attributes() as $attributes )
{
if(trim($attributes) == trim($username))
{
echo "Username $username already exists... \n";
return true;
}
}
}
}
return false;
}
function isUserID($username)
{
//return preg_match('/^\w{2,20}$/', $username);
return preg_match('/^[A-Za-z0-9][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/', $username);
}
function isValid($str)
{
//return !preg_match('/[^A-Za-z0-9.#\\-$]/', $str);
return !preg_match('/[^A-Za-z0-9\_\-]/', $str);
}
function getInput($msg)
{
fwrite(STDOUT, "$msg: ");
$varin = trim(fgets(STDIN,20));
return $varin;
//$input = fgets($fr,128); // read a maximum of 128 characters
}
function createXMLbackup($xmlfile,$xmlbackupfile)
{
// Copy Config for backup
$rv = copy($xmlfile,$xmlbackupfile);
if(!$rv)
{
die('Problem creating xml backup file');
}
echo "\nBackup file created\n";
}
function generatePassword ($length = 15)
{
// start with a blank password
$password = "";
$possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// we refer to the length of $possible a few times, so let's grab it now
$maxlength = strlen($possible);
// check for length overflow and truncate if necessary
if ($length > $maxlength)
{
$length = $maxlength;
}
// set up a counter for how many characters are in the password so far
$i = 0;
// add random characters to $password until $length is reached
while ($i < $length)
{
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, $maxlength-1), 1);
// have we already used this character in $password?
if (!strstr($password, $char))
{
// no, so it's OK to add it onto the end of whatever we've already got...
$password .= $char;
// ... and increase the counter by one
$i++;
}
}
// done!
return $password;
}
?>
I've looked around and there are some places that suggest using # in front of calling in PHP so: #C:\php5\php-win.exe -f filezilla-user-script.php -- %1 %2 but that doesn't work, and I can see that my script does work, just not in this nested form.
Maybe there's an approach to this problem that I'm missing? Or something that I don't know about executing scripts in nested batch scripts?
In your BatchCreateIIS.bat, when you use this:
start cmd.exe /c "CreateIIStmp.bat %%X %%X"
the parent cmd.exe will not wait for each instance of CreateIIStmp.bat (and child processes) to finish. Since you seem to be writing to the same XML file, it is likely that the DOM that get written last persists. Instead try this:
call "CreateIIStmp.bat %%X %%X"
Hello i'm rely stuck here,
Ok i already have a working function to update my database for ONE specified file, in my directory,
now i need a php code to do the same thing for each file on directory and then delete it.
$fileName = "IEDCBR361502201214659.RET";
$cnab240 = RetornoFactory::getRetorno($fileName, "linhaProcessada");
$retorno = new RetornoBanco($cnab240);
$retorno->processar();
the function linhaProcessada is
function linhaProcessada2($self, $numLn, $vlinha) {
if($vlinha["registro"] == $self::DETALHE )
{
if($vlinha["registro"] == $self::DETALHE && $vlinha["segmento"] == "T" ) {
//define a variavel do nosso numero como outra usavel
$query ="SELECT * FROM jos_cobra_boletos WHERE nosso_numero = ".$vlinha['nosso_numero']."";
echo "Boleto de numero: ".$vlinha['nosso_numero']." Atualizado com sucesso!<hr>";
$testResult = mysql_query($query) or die('Error, query failed');
if(mysql_fetch_array($testResult) == NULL){
}else{
$query = "UPDATE jos_cobra_boletos
SET status_pagamento='Pago'
WHERE nosso_numero=".$vlinha['nosso_numero']."";
$result = mysql_query($query) or die('Erro T');
}
}
}
}
Really need help on this one
PHP's opendir() ought to do the trick. More info here: http://php.net/manual/en/function.opendir.php
<?php
// Set Directory
$dir = '/abs/path/with/trailing/slash/';
if ($handle = opendir( $dir )) { // Scan directory
while (false !== ($file = readdir($handle))) { // Loop each file
$fileName = $dir . $file;
// Run code on file
$cnab240 = RetornoFactory::getRetorno($fileName, "linhaProcessada");
$retorno = new RetornoBanco($cnab240);
$retorno->processar();
// Delete file
unlink( $fileName );
}
closedir( $handle );
}
<? //PHP 5.4+
foreach(
new \GlobIterator(
__DIR__ . '/*.RET', //Or other directory where these files are
\FilesystemIterator::SKIP_DOTS |
\FilesystemIterator::CURRENT_AS_PATHNAME
)
as $pathname
){
(new RetornoBanca(
RetornoFactory::getRetorno($pathname, 'linhaProcessada')
))
->processar();
\unlink($pathname);
}
?>
Is there a way of importing product tags via a spreadsheet?
if not through a module, can this be done through a script?
Tags to be imported format should be like this
And place the about spreadsheet in root/tagimport/tagsheet.csv
and paste the following code in root/tagimport/importtag.php
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();
$fileName = 'importtag.csv';
getAttributeCsv($fileName);
function getAttributeCsv($fileName){
$file = fopen($fileName,"r");
$RemoveLine = 0;
while(!feof($file)){
$data = fgetcsv($file);
if($RemoveLine != 0){
$labelText[] = $data[1];
}$RemoveLine++;
}createAttribute($labelText);
fclose($file);
}
function createAttribute($labelText)
{
foreach($labelText as $tag){
if($tag){
$quote = Mage::getModel('tag/tag');
$quote->loadByName($tag);
if(!$quote->getId()){
$quote->setName($tag);
$quote->setStatus(1);
$quote->setFirstStoreId(0);
$quote->setPopularity(0);
$quote->save();
##### Save product tags in "tag_properties"
$connectionresource = Mage::getSingleton('core/resource');
$connectionWrite = $connectionresource->getConnection('core_write');
$table = 'tag_properties';
$query = "insert into ".$table." "."(tag_id,store_id,base_popularity) values "."(:tag_id, :store_id, :base_popularity)";
$binds = array(
'tag_id' => $quote->getTagId(),
'store_id' => '1',
'base_popularity' => '0',
);
$connectionWrite->query($query, $binds);
echo 'Tags Imported Successfully';
}
}
}
}
run the above php file using
www.yourdomain.com/tagimport/importtag.php
If you have tags csv like below, (the first col is product SKU, the second column is the tag name)
8697550050245,White Egg
6291104283077,Organic Egg
6291100152520,Eco Veg Fed Egg
5701607588896,Organic Egg
Below script will import the tags for you
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 0);
ini_set('request_terminate_timeout', 0);
set_time_limit(0);
require_once 'app/Mage.php';
Mage::app("admin");
$storeId = 1;
try {
$h = fopen(dirname(__FILE__) . '/var/tags.csv', 'r');
if ($h !== FALSE) {
$updated = '';
$notFound = '';
while (($data = fgetcsv($h, 1000, ",")) !== FALSE) {
$sku = preg_replace("/[^A-Za-z0-9 ]/", '', $data[0]);
$tagName = preg_replace("/[^A-Za-z0-9\&\/\(\)\- ]/", '', $data[1]);
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
if(!empty($product) && !empty($tagName)) {
$tagName = strtolower($tagName);
$tag = Mage::getModel('tag/tag');
$tag->loadByName($tagName);
if (!$tag->getId()) {
$tag->setName($tagName)
->setFirstCustomerId(null)
->setFirstStoreId($storeId)
->setStatus($tag->getApprovedStatus())
->save();
}
$tag->saveRelation($product->getId(), null, $storeId);
$updated.= $sku.','.$tagName.'<br >';
}else{
$notFound.= $sku.','.$tagName.'<br >';
}
}
fclose($h);
}
echo $updated;
echo "<hr>";
echo "**************** BELOW TAGS ARE NOT UPDATED ********************************";
echo "<hr>";
echo $notFound;
} catch (Exception $e) {
echo $e->getMessage();
die;
}