public function testInstall() { $composer = new ComposerTestFramework\Composer\Wrapper(); $artifactDirectory = new \SplFileInfo($this->tempdir()); $pluginDirectory = new \SplFileInfo(realpath(__DIR__ . '/../../')); $projectDirectory = new \SplFileInfo($this->tempdir()); //var_dump($pluginDirectory, $artifactDirectory, $projectDirectory); $composer->archive($pluginDirectory, $artifactDirectory); $composerJson = new \SplTempFileObject(); $composerJsonContent = <<<composerJson { "repositories": [ { "type": "artifact", "url": "{$artifactDirectory}/" }, { "type": "composer", "url": "http://packages.firegento.com" } ], "require": { "cotya/composer-magento-plugin": "dev-master@dev", "firegento/psr0autoloader": "dev-master" } } composerJson; $composerJson->fwrite($composerJsonContent); $composer->install($projectDirectory, $composerJson); $this->assertFileNotExists($projectDirectory . '/vendor/magento-hackathon/magento-composer-installer/composer.json'); }
/** * 配列をCSVレコード風の文字列に変換して返します。 * @param string[] $fields * @return string */ public function convertToCSVRecord(array $fields) : string { $csv = new \SplTempFileObject(); $csv->fputcsv($fields); $csv->rewind(); return rtrim($csv->fgets(), "\r\n"); }
public static function getFileObjectFromContents($contents) { $fileobject = new \SplTempFileObject(); $fileobject->fwrite($contents); $fileobject->rewind(); return $fileobject; }
/** * @param string $content * * @return Statement * @throws \InvalidArgumentException */ public function parseContent($content) { if (is_string($content) === false) { throw new \InvalidArgumentException('Argument "$content" isn\'t a string type'); } $fileObject = new \SplTempFileObject(); $fileObject->fwrite($content); return $this->parseFileObject($fileObject); }
public function binaryProvider() : array { return [[function () : \SplFileObject { return new \SplFileObject(__DIR__ . '/resources/formats-output-dictionary.csv'); }, file_get_contents(__DIR__ . '/resources/formats-output-dictionary.csv')], [function () : \SplFileObject { $file = new \SplTempFileObject(); $file->fwrite('𩸽'); return $file; }, '𩸽']]; }
/** * */ private function initializeBeforeRead() { if ($this->generator === null) { $this->generator = $this->delegatedStream->read($this->blockSize); $this->resource = $this->generator->current(); $this->resource->rewind(); } }
public function action_post_index_collection() { // Get payload from CSV repo $csv = service('repository.csv')->get($this->request->param('csv_id')); $fs = service('tool.filesystem'); $reader = service('filereader.csv'); $transformer = service('transformer.csv'); // Read file $file = new SplTempFileObject(); $contents = $fs->read($csv->filename); $file->fwrite($contents); // Get records // @todo read up to a sensible offset and process the rest later $records = $reader->process($file); // Set map and fixed values for transformer $transformer->setMap($csv->maps_to); $transformer->setFixedValues($csv->fixed); $this->_usecase = service('factory.usecase')->get($this->_resource(), 'import')->setPayload($records)->setTransformer($transformer); }
protected function _generateThumbnail($file) { try { $thumb = PhpThumbFactory::create($file)->setOptions(array('jpegQuality' => 50)); } catch (Exception $e) { // GD is not available return false; } $thumb_size = $this->getThumbnailSize(); $thumb->resize($thumb_size['x'], $thumb_size['y']); ob_start(); echo $thumb->getImageAsString(); $str = ob_get_clean(); if ($str) { $file = new SplTempFileObject(); $file->fwrite($str); return $file; } return false; }
/** * Get writable copy of the file * * @return SplFileObject */ protected function getWritableFile() { if ($this->tmpfile === null) { $this->tmpfile = new \SplTempFileObject(131072); $this->file->rewind(); foreach ($this->file as $line) { $this->tmpfile->fwrite($line); } } return $this->tmpfile; }
/** * Export Job as Tmx File * * @param $jid * @param $jPassword * @param $sourceLang * @param $targetLang * * @return SplTempFileObject $tmpFile * */ public function exportJobAsCSV($jid, $jPassword, $sourceLang, $targetLang) { $tmpFile = new SplTempFileObject(15 * 1024 * 1024); $csv_fields = array("Source: {$sourceLang}", "Target: {$targetLang}"); $tmpFile->fputcsv($csv_fields); $result = getTranslationsForTMXExport($jid, $jPassword); foreach ($result as $k => $row) { $row_array = array($row['segment'], $row['translation']); $tmpFile->fputcsv($row_array); } $tmpFile->rewind(); return $tmpFile; }
<?php use Exception as sp93553c; function foo() { throw new sp93553c('Hello!'); } use SplTempFileObject as sp176274; $spc8ed6d = new sp176274(); if (!$spc8ed6d->valid() == 0) { foo(); }
/** * Removes a row from the CSV file by streaming to a temporary file, ignoring * the specified line number(s). * * @param int|array $rowNumber The zero-based integer row number to remove, * or an array of integers to remove multiple rows (row 0 is header row) * @param mixed $replaceWith The row data to replace with, or null to just * remove to original row * * @return boolean True if any changes were made, otherwise false */ public function updateRow($rowNumber, $replaceWith) { $this->changesMade = true; $changed = false; $rowNumberArray = []; // Ensure we are working with an array. if (is_array($rowNumber)) { $rowNumberArray = $rowNumber; } else { array_push($rowNumberArray, $rowNumber); } $temp = new TempFile(self::TEMP_FILE_SIZE); $temp->setFlags(File::READ_CSV | File::READ_AHEAD | File::SKIP_EMPTY | File::DROP_NEW_LINE); $this->lock(); $this->file->fseek(0); // Copy contents of file into temp: while (!$this->file->eof()) { $temp->fwrite($this->file->fread(1024)); } $temp->rewind(); $this->file->ftruncate(0); $this->file->fseek(0); foreach ($temp as $rowNumber => $row) { if (in_array($rowNumber - 1, $rowNumberArray)) { // Current row is to be updated or deleted. Do not write original // row back to file. if (!is_null($replaceWith)) { // Ensure that $replaceWidth is an indexed array. if ($this->isAssoc($replaceWith)) { $replaceWith = $this->toIndexed($replaceWith); } $replaceWith = $this->fillMissing($replaceWith, $row); $this->file->fputcsv($replaceWith); } $changed = true; continue; } $this->file->fputcsv($row); } $this->file->flock(LOCK_UN); return $changed; }
public function printactofreceiving($orders) { if (is_string($orders)) { $orders = [$orders]; } $params = []; foreach ($orders as $order => $seats) { if (is_int($order)) { list($order, $seats) = [$seats, 1]; } $params[] = ['@number' => $order, '@seats' => $seats]; } $params = ['Orders' => ['Order' => $params]]; $resp = $this->request(__FUNCTION__, $params, true); $headers = $resp->getHeaders(); $tmp = new \SplTempFileObject(); $tmp->fwrite($resp->getBody()); return $tmp; }
/** * Send CDR EOF (Central Directory Record End-of-File) record. Most values * point to the corresponding values in the ZIP64 CDR. The optional comment * still goes in this CDR however. * * @return \SplTempFileObject */ private function addCdrEof() { $comment = $this->archive->getComment(); $fields = [['V', 0x6054b50], ['v', 0xffff], ['v', 0xffff], ['v', 0xffff], ['v', 0xffff], ['V', 0xffffffff], ['V', 0xffffffff], ['v', strlen($comment)]]; $ret = PackHelper::packFields($fields) . $comment; $stream = new \SplTempFileObject(); $stream->fwrite($ret); $stream->rewind(); return $stream; }
public function parse(\SplFileInfo $file, string $filename = null, string $title = null) : Dictionary { $this->filenames = []; if ($file instanceof \SplTempFileObject) { $binary = (new \esperecyan\dictionary_php\Parser())->getBinary($file); } if (!$file instanceof \SplFileObject) { $file = $file->openFile(); } else { $file->rewind(); } $finfo = new Finfo(FILEINFO_MIME_TYPE); $type = isset($binary) ? $finfo->buffer($binary) : $finfo->file($file->getRealPath()); switch ($type) { case 'application/zip': $this->header = true; $quizFile = $this->parseArchive($file); $binary = file_get_contents($quizFile); if (!mb_check_encoding($binary, 'Windows-31J')) { throw new SyntaxException(sprintf(_('%sの辞書の符号化方式 (文字コード) は Shift_JIS でなければなりません。'), 'Inteligenceω')); } $txt = new \SplTempFileObject(); $txt->fwrite(mb_convert_encoding($binary, 'UTF-8', 'Windows-31J')); $files = new \FilesystemIterator($quizFile->getPath(), \FilesystemIterator::SKIP_DOTS); unlink($quizFile); break; case 'text/csv': case 'text/plain': $txt = $file; break; default: throw new SyntaxException(_('Inteligenceωの辞書はテキストファイルかZIPファイルでなければなりません。')); } $filesCount = count($this->filenames) + 1; if ($filesCount > GenericDictionaryParser::MAX_FILES) { throw new SyntaxException(sprintf(_('アーカイブ中のファイル数は %1$s 個以下にしてください: 現在 %2$s 個'), GenericDictionaryParser::MAX_FILES, $filesCount)); } $dictionary = new Dictionary($files ?? [], $this->filenames); $txt->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY); foreach ($txt as $line) { $this->parseLine($dictionary, $line); } $this->parseLine($dictionary); if (!$dictionary->getWords()) { throw new SyntaxException(_('正常に変換可能な行が見つかりませんでした。')); } if ($this->wholeText !== '') { $regard = $this->generateRegard(); if ($regard) { $metaFields['@regard'] = $this->generateRegard(); } } if (!is_null($title)) { $metaFields['@title'] = $title; } elseif (!is_null($filename)) { $titleFromFilename = $this->getTitleFromFilename($filename); if ($titleFromFilename) { $metaFields['@title'] = $titleFromFilename; } } if (isset($metaFields)) { $dictionary->setMetadata($metaFields); } return $dictionary; }
/** * Get the csv file as a string. * * @return string */ public function asString() { $tmp = new \SplTempFileObject(); foreach ($this->data as $row) { $tmp->fputcsv($row, $this->delimiter); if ($this->lineEnding !== "\n") { $tmp->fseek(-1, \SEEK_CUR); $tmp->fwrite($this->lineEnding); } } # Find out how much data we have written $length = $tmp->ftell(); if ($length < 1) { return ""; } # Reset the internal pointer and return all the data we have written $tmp->fseek(0); return $tmp->fread($length); }
public function testMaximumNesting() { if (!function_exists('xdebug_is_enabled')) { $this->markTestSkipped('xDebug is not installed'); } $xdebug_start = !xdebug_is_enabled(); if ($xdebug_start) { xdebug_enable(); } ini_set('xdebug.max_nesting_level', 200); $file = new \SplTempFileObject(); for ($i = 0; $i < 500; $i++) { $file->fwrite("1,2,3\n"); } $reader = new CsvReader($file); $reader->rewind(); $reader->setStrict(true); $reader->setColumnHeaders(array('one', 'two')); $current = $reader->current(); $this->assertEquals(null, $current); if ($xdebug_start) { xdebug_disable(); } }
/** * @param string $input * @expectedException \esperecyan\dictionary_php\exception\SyntaxException * @dataProvider invalidDictionaryProvider */ public function testSyntaxException(string $input) { $temp = new \SplTempFileObject(); $temp->fwrite(preg_replace('/\\n */u', "\r\n", $input)); (new CatchmParser())->parse($temp); }
public function actionExportpi() { $piSitesId = array("6", "10", "3", "7", "14", "16", "17", "18", "19"); $accountIds = implode(",", $piSitesId); $fileName = date("Y-m-d") . '-All-PI-sites-entry'; header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private", false); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"{$fileName}.csv\";"); header("Content-Transfer-Encoding: binary"); $results = Yii::app()->db->createCommand("SELECT * FROM claimrecord WHERE account_id IN ({$accountIds}) ORDER BY date_created DESC")->queryAll(); //write the contents to csv and passthru it $tempExportCsv = new SplTempFileObject(); foreach ($results as $currentLine) { $curArr = json_decode($currentLine['claimData'], true); $curArr = array_values($curArr); /*check if mobile number exists in the blacklist record*/ $tempExportCsv->fputcsv($curArr); } $tempExportCsv->rewind(); $tempExportCsv->fpassthru(); }
/** * Import routes from a specified Asset ID * * @throws \Exception */ public function routes() { $message = null; try { $id = $this->inputfilter->clean($this->app->get('PARAMS.id'), 'alnum'); $item = (new \Dsc\Mongo\Collections\Assets())->setState('filter.id', $id)->getItem(); if (empty($item->id)) { throw new \Exception('Invalid Item'); } $file = new \SplTempFileObject(); // TODO Push this to the Assets model switch ($item->storage) { case "s3": $contents = @file_get_contents($item->url); break; case "gridfs": default: $length = $item->length; $chunkSize = $item->chunkSize; $chunks = ceil($length / $chunkSize); $collChunkName = $item->collectionNameGridFS() . ".chunks"; $collChunks = $item->getDb()->{$collChunkName}; $contents = null; for ($i = 0; $i < $chunks; $i++) { $chunk = $collChunks->findOne(array("files_id" => $item->_id, "n" => $i)); $contents .= $chunk["data"]->bin; } break; } $file->fwrite($contents); $reader = new \Ddeboer\DataImport\Reader\CsvReader($file, ","); $reader->setHeaderRowNumber(0); $this->app->set('item', $item); $this->app->set('count', count($reader)); $skipped = 0; $inserted = 0; $updated = 0; $failed = 0; $errors = array(); foreach ($reader as $row) { set_time_limit(0); if (empty($row['Original'])) { $skipped++; continue; } if (strpos($row['Original'], '/') === 0) { $row['Original'] = substr($row['Original'], 1); } if (empty($row['Original'])) { $skipped++; continue; } $redirect = \Redirect\Admin\Models\Routes::findOne(array('url.alias' => $row['Original'])); if (empty($redirect->id)) { // insert $redirect = new \Redirect\Admin\Models\Routes(); $redirect->{'url.alias'} = $row['Original']; $redirect->{'url.redirect'} = $row['Target']; try { $redirect->save(); $inserted++; } catch (\Exception $e) { $failed++; $errors[] = $e->getMessage(); } } else { // update $redirect->{'url.alias'} = $row['Original']; $redirect->{'url.redirect'} = $row['Target']; try { $redirect->save(); $updated++; } catch (\Exception $e) { $failed++; $errors[] = $e->getMessage(); } } } $this->app->set('skipped', $skipped); $this->app->set('inserted', $inserted); $this->app->set('updated', $updated); $this->app->set('failed', $failed); $this->app->set('errors', $errors); $this->app->set('message', $message); echo $this->theme->render('Redirect/Admin/Views::importer/routes_results.php'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); $this->app->reroute('/admin/redirect/import'); return; } }
public function doAction() { $data = CatUtils::getEditingLogData($this->jid, $this->password, true); $data = $data[0]; $csvHandler = new SplTempFileObject(-1); $csvHandler->setCsvControl(';'); $csv_fields = array("Job ID", "Segment ID", "Suggestion Source", "Words", "Match percentage", "Time-to-edit", "Post-editing effort", "HTER", "Segment", "Suggestion", "Translation", "MT QE", "ID translator", "Suggestion1-source", "Suggestion1-translation", "Suggestion1-match", "Suggestion1-origin", "Suggestion2-source", "Suggestion2-translation", "Suggestion2-match", "Suggestion2-origin", "Suggestion3-source", "Suggestion3-translation", "Suggestion3-match", "Suggestion3-origin", "Choosen-Suggestion", "Statistically relevant"); $csvHandler->fputcsv($csv_fields); foreach ($data as $d) { $statistical_relevant = $d['stats-valid'] == 'No' ? 0 : 1; $sid = $d['sid']; $sugg_source = $d['ss']; $rwc = $d['rwc']; $sugg_match = $d['sm']; $sugg_tte = $d['tte']; $pe_effort_perc = $d['pe_effort_perc']; $hter = $d['ter']; $segment = $d['source_csv']; $suggestion = $d['sug_csv']; $translation = $d['translation_csv']; $id_translator = $d['tid']; $s1_source = ""; $s2_source = ""; $s3_source = ""; $s1_translation = ""; $s2_translation = ""; $s3_translation = ""; $s1_match = ""; $s2_match = ""; $s3_match = ""; $s1_origin = ""; $s2_origin = ""; $s3_origin = ""; $mt_qe = $d['mt_qe']; if (!empty($d['sar'])) { $sar = json_decode($d['sar']); $s1_source = $sar[0]->segment; $s1_translation = $sar[0]->translation; $s1_match = $sar[0]->match; if (isset($sar[1])) { $s2_source = $sar[1]->segment; $s2_translation = $sar[1]->translation; $s2_match = $sar[1]->match; } if (isset($sar[2])) { $s3_source = $sar[2]->segment; $s3_translation = $sar[2]->translation; $s3_match = $sar[2]->match; } $s1_origin = substr($sar[0]->created_by, 0, 2) == 'MT' ? 'MT' : 'TM'; $s2_origin = substr($sar[1]->created_by, 0, 2) == 'MT' ? 'MT' : 'TM'; $s3_origin = substr($sar[2]->created_by, 0, 2) == 'MT' ? 'MT' : 'TM'; } $row_array = array($this->jid, $sid, $sugg_source, $rwc, $sugg_match, $sugg_tte, $pe_effort_perc, $hter, $segment, $suggestion, $translation, $mt_qe, $id_translator, $s1_source, $s1_translation, $s1_match, $s1_origin, $s2_source, $s2_translation, $s2_match, $s2_origin, $s3_source, $s3_translation, $s3_match, $s3_origin, $d['sp'], $statistical_relevant); $csvHandler->fputcsv($row_array); } $csvHandler->rewind(); foreach ($csvHandler as $row) { $this->content .= $row; } }
public function actionIndex() { $uploadedFile = CUploadedFile::getInstanceByName("blackListedFile"); if (isset($_GET['downloadSampleFile'])) { $headers = array("Mobilephone"); $contents = array(array("447123456789"), array("447123456455"), array("447123456321")); $tempFile = new SplTempFileObject(); $tempFile->fputcsv($headers); foreach ($contents as $currentLine) { $tempFile->fputcsv($currentLine); } $tempFile->rewind(); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=SampleFile.csv"); header("Pragma: no-cache"); header("Expires: 0"); $tempFile->fpassthru(); die; } if (isset($_POST['singleBlackList']) && !empty($_POST['singleBlackList'])) { $newMobileNum = new BlackListedMobile(); $newMobileNum->mobile_number = $_POST['singleBlackList']; $newMobileNum->queue_id = 1; if ($newMobileNum->save()) { Yii::app()->user->setFlash('success', '<strong>New blacklist mobile numberSaved!</strong>'); } else { Yii::app()->user->setFlash('error', '<strong>Error!</strong>' . CHtml::errorSummary($newMobileNum)); } } if (isset($_POST['massiveTextArea']) && !empty($_POST['massiveTextArea'])) { /*@TODO get total now , using randomQueue */ $queueName = $_POST['randomQueue'] ? $_POST['randomQueue'] : 'Task : upload - ' . rand(0, 9999); $criteriaJobQueue = new CDbCriteria(); $criteriaJobQueue->compare("queue_name", $queueName); $jobQueueModl = JobQueue::model()->find($criteriaJobQueue); /*@TODO $total_before*/ $total_before = 0; if (!$jobQueueModl) { $jobQueueModl = new JobQueue(); //@TODO declare above , $jobQueueModl->queue_name = $queueName; $jobQueueModl->save(false); //pre save } else { $criteriaTotalBefore = new CDbCriteria(); $criteriaTotalBefore->compare("queue_id", $jobQueueModl->queue_id); $total_before = BlackListedMobile::model()->count($criteriaTotalBefore); } /*write posted textarea to file*/ $tp = tempnam(Yii::getPathOfAlias('application.data'), "tempWrite"); $tempName = $tp . '.csv'; $linecount = 0; $tempContainer2 = explode("\n", $_POST['massiveTextArea']); $tempContainer2 = array_filter($tempContainer2); $linecount = count($tempContainer2); file_put_contents($tempName, implode(PHP_EOL, $tempContainer2)); // $handle = fopen($tempName, "r"); // while(!feof($handle)){ // $line = fgets($handle); // ++$linecount; // } // fclose($handle); $jobQueueModl->filename = $tempName; //ignore this $jobQueueModl->status = JobQueue::$JOBQUEUE_STATUS_PRELOADED; /*check number files' number of line*/ // Total_records , $jobQueueModl->total_records = $linecount; $jobQueueModl->processed_record = $linecount; /*update job queue record*/ if ($jobQueueModl->save()) { $filePath = $tempName; /*load to database*/ $tempFile2 = tempnam(__DIR__, "tempContainer"); $appendCommand = sprintf('cat "%s" | gawk \'{print $0",0%s"}\' > "%s" ', $filePath, $jobQueueModl->queue_id, $tempFile2); system($appendCommand); system("mv \"{$tempFile2}\" \"{$filePath}\""); $sqlCommand = <<<EOL LOAD DATA LOCAL INFILE "%s" INTO TABLE black_listed_mobile FIELDS TERMINATED BY "%s" LINES TERMINATED BY "%s" IGNORE 0 LINES (mobile_number,queue_id) EOL; $sqlCommand = sprintf($sqlCommand, $filePath, ',', '\\n'); $mainCommand = "mysql --user=dncsyste_dnc --password=hitman052529 --database=dncsyste_dnc -e '{$sqlCommand}'"; exec($mainCommand); $criteriaTotalBefore = new CDbCriteria(); $criteriaTotalBefore->compare("queue_id", $jobQueueModl->queue_id); /* $total_now*/ $total_now = BlackListedMobile::model()->count($criteriaTotalBefore); if (Yii::app()->request->isAjaxRequest) { header("Content-Type: application/json"); $numOfInsertedData = $total_now - $total_before; $numOfInsertedData = $numOfInsertedData <= 0 ? 0 : $numOfInsertedData; $numOfDeletedData = $linecount - ($total_now - $total_before); $numOfDeletedData = $numOfDeletedData <= 0 ? 0 : $numOfDeletedData; $jsonResult = array("numOfInsertedData" => $numOfInsertedData, "numOfDeletedData" => $numOfDeletedData); echo json_encode($jsonResult); die; } else { Yii::app()->user->setFlash('success', '<strong>File Imported!</strong>You have successfully imported new blacklisted mobile number. '); } } else { Yii::app()->user->setFlash('error', CHtml::errorSummary($newQueueFile)); } } if ($uploadedFile) { set_time_limit(0); $newFileLocation = Yii::getPathOfAlias("application.uploaded_files") . DIRECTORY_SEPARATOR . rand(0, 9999) . '-' . $uploadedFile->name; //save new queue file $newQueueFile = new JobQueue(); $uploadedFile->saveAs($newFileLocation); $newQueueFile->queue_name = "Task : " . $uploadedFile->name . ' - ' . rand(0, 9999); $newQueueFile->filename = $newFileLocation; $newQueueFile->status = JobQueue::$JOBQUEUE_STATUS_PRELOADED; /*check number files' number of line*/ $linesTotal = 0; $handle = fopen($newQueueFile->filename, "r"); while (!feof($handle)) { $line = fgets($handle); ++$linesTotal; } fclose($handle); $newQueueFile->total_records = $linesTotal; $newQueueFile->processed_record = $linesTotal; if ($newQueueFile->save()) { $filePath = $newQueueFile->filename; $tempFile2 = tempnam(__DIR__, "tempContainer"); $appendCommand = sprintf('gawk \'{print $0",0%s"}\' "%s" > "%s"', $newQueueFile->queue_id, $filePath, $tempFile2); system($appendCommand); system("mv \"{$tempFile2}\" \"{$filePath}\""); /*append queue identification for blacklist*/ $rawContents = file_get_contents($filePath); // print_r( explode("\n",$rawContents) ); // die(); $sqlCommand = <<<EOL LOAD DATA LOCAL INFILE "%s" INTO TABLE black_listed_mobile FIELDS TERMINATED BY "%s" LINES TERMINATED BY "%s" IGNORE 0 LINES (mobile_number,queue_id) EOL; $sqlCommand = sprintf($sqlCommand, $filePath, ',', '\\n'); $mainCommand = "mysql --user=dncsyste_dnc --password=hitman052529 --database=dncsyste_dnc -e '{$sqlCommand}'"; exec($mainCommand); $undoLink = "<a href='" . Yii::app()->getBaseUrl(true) . "/blacklist/delete?queue_id={$newQueueFile->queue_id}' onClick='return confirm(\"Are you sure you want to delete this ?\")'> Undo Action </a>"; Yii::app()->user->setFlash('success', '<strong>File Imported!</strong>You have successfully imported new blacklisted mobile number. ' . $undoLink); } else { Yii::app()->user->setFlash('error', CHtml::errorSummary($newQueueFile)); } } $this->render('index'); }
<?php namespace com\github\gooh\InterfaceDistiller; include __DIR__ . '/../src/autoload.php'; $reflector = new \ReflectionClass('ConcreteFoo'); $methodIterator = new Filters\RegexMethodIterator(new Filters\NoImplementedMethodsIterator(new Filters\NoInheritedMethodsIterator(new Filters\NoOldStyleConstructorIterator(new Filters\NoMagicMethodsIterator(new \ArrayIterator($reflector->getMethods()))), $reflector)), '(^get)'); $distillate = new Distillate(); $distillate->setInterfaceName('MyInterface'); $distillate->setExtendingInterfaces('Iterator, SeekableIterator'); foreach ($methodIterator as $method) { $distillate->addMethod($method); } $file = new \SplTempFileObject(-1); $writer = new Distillate\Writer($file); $writer->writeToFile($distillate); $file->rewind(); $file->fpassthru();
private function updateOrDelete($id, $data = null) { /* Thanks to https://www.daniweb.com/web-development/php/threads/102279/deleting-a-line-from-a-file#post1353582 */ /* * Create a new SplFileObject representation of the file * Open it for reading and writing and place the pointer at the beginning of the file * @see fopen for additional modes */ $file = new \SplFileObject($this->filename, 'a+'); /* * Set a bitmask of the flags to apply - Only relates to reading from file * In this case SplFileObject::DROP_NEW_LINE to remove new line charachters * and SplFileObject::SKIP_EMPTY to remove empty lines */ $file->setFlags(7); /* * Lock the file so no other user can interfere with reading and writing while we work with it */ $file->flock(LOCK_EX); /* * Create a SplTempFileObject * 0 indicates not to use memory to store the temp file. * This is probably slower than using memory, but for a large file it will be much more effective * than loading the entire file into memory * @see http://www.php.net/manual/en/spltempfileobject.construct.php for more details */ $temp = new \SplTempFileObject(0); /* * Lock the temp file just in case */ $temp->flock(LOCK_EX); /* * Iterate over each line of the file only loading one line into memory at any point in time */ foreach ($file as $key => $line) { if ($key != $id) { /* * If this line does NOT match out delete write it to the temp file * Append a line ending to it */ $temp->fwrite($line . PHP_EOL); } else { if ($data !== null) { $temp->fwrite($data . PHP_EOL); } } } /* * Truncate the existing file to 0 */ $file->ftruncate(0); /* * Write the temp file back to the existing file */ foreach ($temp as $line) { /* * Iterate over temp file and put each line back into original file */ $file->fwrite($line); } /* * Release the file locks */ $temp->flock(LOCK_UN); $file->flock(LOCK_UN); return true; }
protected function _createThumbnail($file) { @ini_set('memory_limit', '256M'); try { $imagine = new \Imagine\Gd\Imagine(); $image = $imagine->open($file); $size = $this->getThumbnailSize(); $image_size = $image->getSize(); $larger = max($image_size->getWidth(), $image_size->getHeight()); $scale = max($size['x'], $size['y']); $new_size = $image_size->scale(1 / ($larger / $scale)); $image = $image->thumbnail($new_size, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND); $file = new SplTempFileObject(); $file->fwrite((string) $image); return $file; } catch (Exception $e) { return false; } }
/** * Removes a Key/Value pair based on its position in the file * * @param integer $position The offset position in the file */ public function remove($position) { $temp = new \SplTempFileObject(-1); $this->file->flock(LOCK_EX); $filesize = $this->file->getSize(); $metadata = $this->getMetadata($position); // Seek past the document we want to remove $this->file->fseek($metadata->length, SEEK_CUR); // Write everything after the target document to memory $temp->fwrite($this->file->fread($filesize)); // Clear the file up to the target document $this->file->ftruncate($position); // Write Temp back to the end of the file $temp->fseek(0); $this->file->fseek(0, SEEK_END); $this->file->fwrite($temp->fread($filesize)); $this->file->flock(LOCK_UN); }
public function motopressTable($attrs, $content = null) { extract(shortcode_atts(self::addStyleAtts(array()), $attrs)); global $motopressCESettings; require_once $motopressCESettings['plugin_root'] . '/' . $motopressCESettings['plugin_name'] . '/includes/getLanguageDict.php'; $motopressCELang = motopressCEGetLanguageDict(); if (!empty($classes)) { $classes = ' ' . $classes; } if (self::$isNeedFix && empty($mp_style_classes)) { if (!empty($style) && $style != 'none') { $mp_style_classes = 'motopress-table-style-' . $style; } if (!empty($custom_class)) { $mp_style_classes .= ' ' . $custom_class; } } if (!empty($mp_style_classes)) { $mp_style_classes = ' ' . $mp_style_classes; } $result = '<div class="motopress-table-obj' . self::getMarginClasses($margin) . $classes . '">'; $content = trim($content); $content = preg_replace('/^<p>|<\\/p>$/', '', $content); $content = preg_replace('/<br[^>]*>\\s*\\r*\\n*/is', "\n", $content); if (!empty($content)) { // $result .= '<table class="' . self::getBasicClasses(self::PREFIX . 'table', true) . $mp_style_classes . '">'; $result .= '<table class="' . self::getBasicClasses(self::PREFIX . 'table') . $mp_style_classes . '">'; $i = 0; if (version_compare(PHP_VERSION, '5.3.0', '>=')) { $rows = explode("\n", $content); $rowsCount = count($rows); foreach ($rows as $row) { $row = str_getcsv($row); $isLast = $i === $rowsCount - 1 ? true : false; self::addRow($row, $i, $isLast, $result); $i++; } } else { $tmpFile = new SplTempFileObject(); $tmpFile->setFlags(SplFileObject::SKIP_EMPTY); $tmpFile->setFlags(SplFileObject::DROP_NEW_LINE); $write = $tmpFile->fwrite($content); if (!is_null($write)) { $tmpFile->rewind(); while (!$tmpFile->eof()) { $row = $tmpFile->fgetcsv(); $isLast = $tmpFile->eof(); self::addRow($row, $i, $isLast, $result); $i++; } } } $result .= '</table>'; } else { $result .= $motopressCELang->CETableObjNoData; } $result .= '</div>'; return $result; }
/** * Compute the content MD5 hash of the request body (streams request body contents to a * temporary file and incrementaly computes the hash value replacing the requests input * URL with the URL of the created file). * * @param HttpRequest $request * @return string */ protected function computeContentMd5(HttpRequest $request) { if (!$request->hasEntity()) { return md5(''); } $hash = hash_init('md5'); $in = $request->getEntity()->getInputStream(); $tmp = new \SplTempFileObject(); $fp = $tmp->openFile('wb', false); try { flock($fp, LOCK_EX); while (false !== ($chunk = $in->read())) { hash_update($hash, $chunk); fwrite($fp, $chunk); } } finally { @fclose($fp); } $request->setEntity(new StreamEntity($tmp->openFile('rb', false))); return hash_final($hash); }
/** * @param string[] $endOfLineMap Associative array of file names and line * endings. Shell style globs using "*" are * allowed. * @param string[] $paths List of paths to search for files to * convert. If empty uses current/present * working directory from getcwd(). * @param string[] $excludedFiles List of files that should be excluded from * having line endings changed. * * @throws \DomainException * @throws \InvalidArgumentException * @throws PeolFileException * @throws PeolPathException * @return self */ public function convertFiles(array $endOfLineMap, array $paths = array(), array $excludedFiles = array()) { $paths = $paths ?: array(getcwd()); /** * @var string $path */ foreach ($paths as $path) { $path = $this->normalizePath($path); if (!is_readable($path) || !is_dir($path) || !is_writable($path)) { continue; } foreach ($endOfLineMap as $glob => $eol) { $filterItr = $this->getNewGlobFilter($path, $glob, $excludedFiles); if (empty($filterItr)) { return $this; } /** * @var \FilesystemIterator $fsi */ foreach ($filterItr as $fsi) { $fullName = $fsi->getRealPath(); if (!$fsi->isWritable()) { $mess = 'File is NOT writable: ' . $fullName; throw new PeolFileException($mess); } $file = $fsi->openFile('rb+', false); if (!$file->flock(LOCK_EX)) { $mess = 'Could NOT get write lock on ' . $fullName; throw new PeolFileException($mess); } try { $tempFile = new \SplTempFileObject(); foreach ($file as $line) { $this->convertString($line, $eol); $tempFile->fwrite($line); } $tempFile->fflush(); $tempFile->rewind(); $file->ftruncate(0); $file->fflush(); $file->rewind(); foreach ($tempFile as $line) { $file->fwrite($line); } $file->fflush(); } catch (\RuntimeException $exp) { $mess = 'File I/O failed on temp file for ' . $fullName; throw new PeolFileException($mess, 0, $exp); } unset($tempFile, $file); } } } return $this; }
/** * @param string $input * @return \SplTempFileObject */ protected function generateTempFileObject(string $input) : \SplTempFileObject { $temp = new \SplTempFileObject(); $temp->fwrite($input); return $temp; }