/** * Zips the generated file * * @param string $temp Path of the temporary file (generated) to zip * @param string $filename Filename of the (generated) file to zip * @return string Path to the generated zip file */ protected function zip($temp, $filename) { $path = public_path("download/{$filename}.zip"); $zipper = new Zipper(); $zipper->make($path)->add([$temp, public_path('temp/normalize.css')])->close(); return $path; }
/** * Creates a new zip file and returns the complete file path. * * @return string */ public function handle() { if ($this->batch->files->count() > 0) { $fileName = $this->generateFileName($this->batch->name); $zip = $this->zipper->make($fileName); foreach ($this->batch->files as $file) { if ($file instanceof Upload) { $zip->add($file->getCompletePath()); } } $path = $zip->getFilePath(); $zip->close(); return $path; } return false; }
public function testListFiles() { // testing empty file $this->file->shouldReceive('isFile')->with('foo.file')->andReturn(true); $this->file->shouldReceive('isFile')->with('bar.file')->andReturn(true); $this->assertEquals(array(), $this->archive->listFiles()); // testing not empty file $this->archive->add('foo.file'); $this->archive->add('bar.file'); $this->assertEquals(array('foo.file', 'bar.file'), $this->archive->listFiles()); // testing with a empty sub dir $this->file->shouldReceive('isFile')->with('/path/to/subDirEmpty')->andReturn(false); $this->file->shouldReceive('files')->with('/path/to/subDirEmpty')->andReturn(array()); $this->file->shouldReceive('directories')->with('/path/to/subDirEmpty')->andReturn(array()); $this->archive->folder('subDirEmpty')->add('/path/to/subDirEmpty'); $this->assertEquals(array('foo.file', 'bar.file'), $this->archive->listFiles()); // testing with a not empty sub dir $this->file->shouldReceive('isFile')->with('/path/to/subDir')->andReturn(false); $this->file->shouldReceive('isFile')->with('sub.file')->andReturn(true); $this->file->shouldReceive('files')->with('/path/to/subDir')->andReturn(array('sub.file')); $this->file->shouldReceive('directories')->with('/path/to/subDir')->andReturn(array()); $this->archive->folder('subDir')->add('/path/to/subDir'); $this->assertEquals(array('foo.file', 'bar.file', 'subDir/sub.file'), $this->archive->listFiles()); }
/** * @param Request $request */ private function checkFiles(Request $request) { $fileNameWithoutExt = str_random(32); $fileName = $fileNameWithoutExt . '.' . $request->file('file')->getClientOriginalExtension(); $directory = public_path() . '/resources/uploads/'; $request->file('file')->move($directory, $fileName); $zipper = new Zipper(); File::makeDirectory($directory . $fileNameWithoutExt); $zipper->make($directory . $fileName)->extractTo($directory . $fileNameWithoutExt); $createdProductCategories = []; $dataTransferResultErrors = ['productCategories' => array(), 'productLines' => array(), 'products' => array(), 'otherErrors' => array()]; $dataTransferResultWarnings = ['productCategories' => array(), 'productLines' => array(), 'products' => array()]; $findResults = File::glob($directory . $fileNameWithoutExt . '/img/'); if (count($findResults) == 0) { array_push($dataTransferResultErrors['otherErrors'], 'отсутствует папка с изображениями img'); } $findResults = File::glob($directory . $fileNameWithoutExt . '/products.xlsx'); if (count($findResults) == 0) { array_push($dataTransferResultErrors['otherErrors'], 'отсутствует файл Excel версии 2007 и выше. Убедитесь, что структура архива соотвествует образцу. Обратите внимание, что папка img и файл Excel находятся в корне архива, а не в папке, которая находится в корне архива'); } if (count($dataTransferResultErrors['otherErrors'])) { Session::put('dataTransferResult.Errors', $dataTransferResultErrors); Session::put('dataTransferResult.Warnings', $dataTransferResultWarnings); File::delete($directory . $fileName); File::deleteDirectory($directory . $fileNameWithoutExt); return; } Excel::selectSheets('Категории')->load($directory . $fileNameWithoutExt . '/products.xlsx', function ($reader) use($directory, $fileNameWithoutExt, $createdProductCategories, $dataTransferResultErrors, $dataTransferResultWarnings, $fileName, $request) { $productCategories = []; foreach ($reader->toArray() as $row) { if ($row['nomer'] == null) { continue; } array_push($productCategories, $row['nomer']); $imagePattern = '/img/product-category-' . $row['nomer']; $findResults = File::glob($directory . $fileNameWithoutExt . $imagePattern . '*'); if (count($findResults) == 0) { $dataTransferResultErrors['productCategories'][$row['nomer']] = 'У категории с номером ' . $row['nomer'] . ' отсутствует изображение: ' . $imagePattern; } if ($row['nomer'] <= ProductCategory::max('id')) { $dataTransferResultErrors['productCategories'][$row['nomer'] . ' дублирование данных (категория)'] = 'Категория с номером ' . $row['nomer'] . ' возможно уже присутствует в базe. Проверьте условие минимальности номера категории'; } } Excel::selectSheets('Линейки продукции')->load($directory . $fileNameWithoutExt . '/products.xlsx', function ($reader) use($directory, $fileNameWithoutExt, $createdProductCategories, $dataTransferResultErrors, $dataTransferResultWarnings, $fileName, $productCategories, $request) { $productLines = []; foreach ($reader->toArray() as $row) { if ($row['nomer'] == null) { continue; } array_push($productLines, $row['nomer']); if (!in_array($row['kategoriya'], $productCategories) && ProductCategory::find($row['kategoriya']) == null) { $dataTransferResultErrors['productLines'][$row['nomer'] . ' целостость данных (категория)'] = 'У линейки продукции указана несущестующая категория: ' . $row['kategoriya']; } $imagePattern = '/img/product-line-' . $row['nomer']; $findResults = File::glob($directory . $fileNameWithoutExt . $imagePattern . '*'); if (count($findResults) == 0) { $dataTransferResultErrors['productLines'][$row['nomer']] = 'У линейки продукции с номером ' . $row['nomer'] . ' отсутствует изображение: ' . $imagePattern; } if ($row['nomer'] <= ProductLine::max('id')) { $dataTransferResultErrors['productLines'][$row['nomer'] . ' дублирование данных (линейка продукции)'] = 'Линейка продукции с номером ' . $row['nomer'] . ' возможно уже присутствует в базe. Проверьте условие минимальности номера линейки продукции'; } } Excel::selectSheets('Продукция')->load($directory . $fileNameWithoutExt . '/products.xlsx', function ($reader) use($directory, $fileNameWithoutExt, $createdProductCategories, $dataTransferResultErrors, $dataTransferResultWarnings, $fileName, $productLines, $productCategories, $request) { foreach ($reader->toArray() as $row) { if ($row['nomer'] == null) { continue; } if ($row['kategoriya'] == null && $row['lineyka_produktsii'] == null) { $dataTransferResultErrors['products'][$row['nomer'] . ' целостость данных (нет привязки)'] = 'У продукции должна быть либо категория либо линейка продукции'; } if ($row['kategoriya'] != null && $row['lineyka_produktsii'] != null) { $dataTransferResultErrors['products'][$row['nomer'] . ' целостость данных (плохая привязка)'] = 'У продукции не может быть одновременно категории и линейка продукции'; } if ($row['kategoriya'] != null && !in_array($row['kategoriya'], $productCategories) && ProductCategory::find($row['kategoriya']) == null) { $dataTransferResultErrors['products'][$row['nomer'] . ' целостость данных (категория)'] = 'У продукции указана несущестующая категория: ' . $row['kategoriya']; } if ($row['lineyka_produktsii'] != null && !in_array($row['lineyka_produktsii'], $productLines) && ProductLine::find($row['lineyka_produktsii']) == null) { $dataTransferResultErrors['products'][$row['nomer'] . ' целостость данных (категория)'] = 'У продукции указана несущестующая категория: ' . $row['lineyka_produktsii']; } $imagePattern = '/img/product-' . $row['nomer']; $findResults = File::glob($directory . $fileNameWithoutExt . $imagePattern . '*'); if (count($findResults) == 0) { $dataTransferResultErrors['products'][$row['nomer']] = 'У продукции с номером ' . $row['nomer'] . ' отсутсвует основное изображение: ' . $imagePattern; } $imagePattern = '/img/product-' . $row['nomer'] . '-color-'; $findResults = File::glob($directory . $fileNameWithoutExt . $imagePattern . '*'); $notFoundProductColorImages = []; foreach ($findResults as $findResult) { $colorNumber = substr($findResult, strpos($findResult, 'color') + 6, strpos($findResult, '.') - strpos($findResult, 'color') - 6); $imagePattern = '/img/product-' . $row['nomer'] . '-image-' . $colorNumber; $findProductColorImageResults = File::glob($directory . $fileNameWithoutExt . $imagePattern . '*'); if (count($findProductColorImageResults) == 0) { array_push($notFoundProductColorImages, $imagePattern); } } if (count($notFoundProductColorImages) > 0) { $dataTransferResultWarnings['products'][$row['nomer'] . ' предупреждение об изображении для палитры'] = 'У продукции с номером ' . $row['nomer'] . ' отсутсвуют изображения продукта для цветовой палитры: '; foreach ($notFoundProductColorImages as $foundProductColorImage) { $dataTransferResultWarnings['products'][$row['nomer'] . ' предупреждение об изображении для палитры'] .= $foundProductColorImage . ', '; } } $imagePattern = '/img/product-' . $row['nomer'] . '-image-'; $findResults = File::glob($directory . $fileNameWithoutExt . $imagePattern . '*'); $notFoundProductColors = []; foreach ($findResults as $findResult) { $colorNumber = substr($findResult, strpos($findResult, 'image') + 6, strpos($findResult, '.') - strpos($findResult, 'color') - 6); $colorPattern = '/img/product-' . $row['nomer'] . '-color-' . $colorNumber; $findProductColorResults = File::glob($directory . $fileNameWithoutExt . $colorPattern . '*'); if (count($findProductColorResults) == 0) { array_push($notFoundProductColors, $colorPattern); } } if (count($notFoundProductColors) > 0) { $dataTransferResultWarnings['products'][$row['nomer'] . ' предупреждение о самом изображении палитры'] = 'У продукции с номером ' . $row['nomer'] . ' отсутсвуют изображения самой цветовой палитры: '; foreach ($notFoundProductColors as $notFoundProductColor) { $dataTransferResultWarnings['products'][$row['nomer'] . ' предупреждение о самом изображении палитры'] .= $notFoundProductColor . ', '; } } } Session::put('dataTransferResult.Errors', $dataTransferResultErrors); Session::put('dataTransferResult.Warnings', $dataTransferResultWarnings); if (count($dataTransferResultErrors['productCategories']) == 0 && count($dataTransferResultErrors['productLines']) == 0 && count($dataTransferResultErrors['products']) == 0) { Session::put('dataTransferResult.FilesPath', $directory . $fileNameWithoutExt); } else { File::delete($directory . $fileName); File::deleteDirectory($directory . $fileNameWithoutExt); } }); }); }); }
/** * Parse attachments * @return array Returns array with failed or success data * (See parser-common/src/Parser.php) for more info. */ public function parse() { // Validate user based regex try { preg_match(config("{$this->configBase}.parser.file_regex"), '', $matches); } catch (\Exception $e) { $this->warningCount++; return $this->failed('Configuration error in the regular expression'); } foreach ($this->parsedMail->getAttachments() as $attachment) { if (strpos($attachment->filename, '.zip') !== false && $attachment->contentType == 'application/octet-stream') { $zip = new Zipper(); if (!$this->createWorkingDir()) { return $this->failed("Unable to create working directory"); } file_put_contents($this->tempPath . $attachment->filename, $attachment->getContent()); $zip->zip($this->tempPath . $attachment->filename); $zip->extractTo($this->tempPath); foreach ($zip->listFiles() as $index => $compressedFile) { if (strpos($compressedFile, '.csv') !== false) { // For each CSV file we find, we are going to do magic (however they usually only send 1 zip) if (preg_match(config("{$this->configBase}.parser.file_regex"), $compressedFile, $matches)) { $this->feedName = $matches[1]; // If feed is known and enabled, validate data and save report if ($this->isKnownFeed() && $this->isEnabledFeed()) { $csvReports = new Reader\CsvReader(new SplFileObject($this->tempPath . $compressedFile)); $csvReports->setHeaderRowNumber(0); foreach ($csvReports as $report) { // Handle field mappings first $aliasses = config("{$this->configBase}.feeds.{$this->feedName}.aliasses"); if (is_array($aliasses)) { foreach ($aliasses as $alias => $real) { if (array_key_exists($alias, $report)) { $report[$real] = $report[$alias]; unset($report[$alias]); } } } /* * Legacy 3.x fix for migrations. * * This resolves shadowserver errors where the CSV was send in duplicate resulting * in the header fields being used as data. If the header is detected the row can * be skipped safely */ if ($report['ip'] === 'ip') { continue; } // Sanity check if ($this->hasRequiredFields($report) === true) { // incident has all requirements met, filter and add! $report = $this->applyFilters($report); $incident = new Incident(); $incident->source = config("{$this->configBase}.parser.name"); $incident->source_id = false; $incident->ip = $report['ip']; $incident->domain = false; $incident->class = config("{$this->configBase}.feeds.{$this->feedName}.class"); $incident->type = config("{$this->configBase}.feeds.{$this->feedName}.type"); $incident->timestamp = strtotime($report['timestamp']); $incident->information = json_encode($report); // some rows have a domain, which is an optional column we want to register switch ($this->feedName) { case "spam_url": if (isset($report['url'])) { $incident->domain = getDomain($report['url']); } break; case "ssl_scan": if (isset($report['subject_common_name'])) { /* * Common name does not add http://, but that is required for * the domain helper check so lets add it manually */ $testurl = "http://{$report['subject_common_name']}"; $incident->domain = getDomain($testurl); } break; case "compromised_website": if (isset($report['http_host'])) { $incident->domain = getDomain($report['http_host']); } break; } $this->incidents[] = $incident; } //End hasRequired fields } // End foreach report loop } // End isKnown & isEnabled } else { // Pregmatch failed to get feedName from attachment $this->warningCount++; } } else { // Attached file is not a CSV within a ZIP file $this->warningCount++; } } // End each file in ZIP attachment loop } // End if not a ZIP attachment } // End foreach attachment loop return $this->success(); }
public function getJust($idCarga) { $carga = Cargas::find($idCarga); if ($carga) { //obtener cargas $empresa = $carga->empresa()->orderBy('tipo_receptor')->get(); $sat = $carga->sat()->orderBy('tipo_receptor')->get(); $diff = new DiferenciasCFID($sat, $empresa, $carga->rfc); $just_emitidos = $diff->get_justificados_emitidos(); $just_recibidos = $diff->get_justificados_recibidos(); $array = ['rfc' => $carga->rfc, 'nombre' => $carga->contribuyente->nombre, 'justEm' => $just_emitidos, 'justRec' => $just_recibidos]; $namePdf = $carga->rfc . "_" . time() . ".pdf"; \PDF::loadView('descargas.reporte-justificados', $array)->save(storage_path('temp') . "/{$namePdf}"); $nameZip = "just_" . time() . ".zip"; $zipper = new Zipper(); $zipper->make(storage_path("temp/{$nameZip}"))->add(storage_path('temp') . "/{$namePdf}"); $anexos = $diff->getAnexos(); foreach ($anexos as $anexo) { $zipper->folder($anexo['uuid']); foreach ($anexo['anexos'] as $file) { $zipper->add($file->file); } } $zipper->close(); return response()->download(storage_path("temp/{$nameZip}"), $nameZip); } }
/** * Sweet baby jesus, I know I know! * * Used to upload a blueprint and do the necessary * checks to ensure that the upload is valid * * @param NbtParser $parser * @param ImageManipulate $manipulator * @param Zipper $zipper * @param PathBuilder $pathBuilder * @param PostUploadRequest $request * @param Blueprint $blueprint * @param BlueprintModsUsed $blueprintModsUsed * @param Filesystem $file * @param Guard $guard * @param Repository $repository * * @return \Illuminate\Http\RedirectResponse */ public function postUpload(NbtParser $parser, ImageManipulate $manipulator, Zipper $zipper, PathBuilder $pathBuilder, PostUploadRequest $request, Blueprint $blueprint, BlueprintModsUsed $blueprintModsUsed, Filesystem $file, Guard $guard, Repository $repository) { $input = $request->get('upload'); // Make sure that the blueprint is valid // ...well sort of, it can't be checked for sure $parser->loadFile($request->file('upload.blueprint')); if (!array_key_exists(0, $parser->root) || empty($parser->root) || !array_key_exists('type', $parser->root[0])) { return redirect()->back()->with('blueprintNotValid', true)->withInput(); } // Arrays to be inserted into the database // Blueprint things $blueprintInsert = []; // Process the blueprint foreach ($parser->root[0]['value'] as $key => $value) { $value['name'] != 'version' ?: ($blueprintInsert['bc_version'] = $value['value']); $value['name'] != 'sizeY' ?: ($blueprintInsert['sizeY'] = $value['value']); $value['name'] != 'sizeZ' ?: ($blueprintInsert['sizeZ'] = $value['value']); $value['name'] != 'sizeX' ?: ($blueprintInsert['sizeX'] = $value['value']); } // Set some fields that are easy to set, just to get it out of the way $blueprintInsert['name'] = trim($input['name']); $blueprintInsert['version'] = trim($input['version']); $blueprintInsert['author_name'] = trim($input['author_name']); $blueprintInsert['survival_creative'] = $input['play_mode']; $blueprintInsert['description'] = trim($input['description']); $blueprintInsert['user_id'] = $guard->user()->getAuthIdentifier(); $blueprintInsert['uploaded_at'] = Carbon::now()->toDateTimeString(); $blueprintInsert['archive_name'] = str_replace(' ', '', $input['name']) . '_' . getRandomId() . '.zip'; // Get the buildcraft image storage path $buildcraftImagesStoragePath = $pathBuilder->create()->fromPublicPath($repository->get('blueprint.paths.storage.buildcraft.images')); // Get the buildcraft archives storage path $buildcraftArchivesStoragePath = $pathBuilder->create()->fromPublicPath($repository->get('blueprint.paths.storage.buildcraft.archives')); // Get the buildcraft temp storage path $buildcraftTempStoragePath = $pathBuilder->create()->fromPublicPath($repository->get('blueprint.paths.storage.buildcraft.temp')); // Compress and move the required screenshot $manipulator->setFileInfo($request->file('upload.required_screenshot'))->compress()->move($buildcraftImagesStoragePath)->createThumb(500)->exitClean(); //Might as well add it to the insert array $blueprintInsert['screenshot'] = $manipulator->getFileName(); // Get a temporary name for the blueprint $temporary_name = getRandomId() . '.' . $request->file('upload.blueprint')->getClientOriginalExtension(); // Move the blueprint to a temporary folder in order to archive it. $request->file('upload.blueprint')->move($buildcraftTempStoragePath, $temporary_name); // Add blueprint to the archive $zipper->make($buildcraftArchivesStoragePath . $blueprintInsert['archive_name'])->add($buildcraftTempStoragePath . $temporary_name)->add($buildcraftImagesStoragePath . $blueprintInsert['screenshot']); // Compress and move the first optional screenshot // Get the file name, create a thumb // Also add the file to the archive if (null !== $request->file('upload.optional_screenshot_0')) { $manipulator->setFileInfo($request->file('upload.optional_screenshot_0'))->compress()->move($buildcraftImagesStoragePath)->createThumb(500)->exitClean(); $blueprintInsert['screenshot_optional_0'] = $manipulator->getFileName(); $zipper->add($buildcraftImagesStoragePath . $blueprintInsert['screenshot_optional_0']); } else { $blueprintInsert['screenshot_optional_0'] = null; } // Compress and move the second optional screenshot // Get the file name, create a thumb // Also add the file to the archive if (null !== $request->file('upload.optional_screenshot_1')) { $manipulator->setFileInfo($request->file('upload.optional_screenshot_1'))->compress()->move($buildcraftImagesStoragePath)->createThumb(500)->exitClean(); $blueprintInsert['screenshot_optional_1'] = $manipulator->getFileName(); $zipper->add($buildcraftImagesStoragePath . $blueprintInsert['screenshot_optional_1']); } else { $blueprintInsert['screenshot_optional_1'] = null; } //Clean up $zipper->close(); if ($file->exists($buildcraftTempStoragePath . $temporary_name)) { $file->delete($buildcraftTempStoragePath . $temporary_name); } // Insert the blueprint data $blueprint->insert($blueprintInsert); // Get the last inserted id $blueprint_id = $blueprint->id; $modsUsedInsert = []; // Get a list of the mods used $mods_used = $this->getModsUsed($parser->root[0]); if (null !== $mods_used) { // Make a valid array to insert foreach ($mods_used as $key => $value) { $modsUsedInsert[] = ['blueprint_id' => $blueprint_id, 'mod_name' => $value]; } // Insert into mods used too $blueprintModsUsed->insert($modsUsedInsert); } // Welp, that's that return redirect()->route('buildcraft::user::getUpload', ['user_id' => Auth::user()->id])->with('blueprintUploadSuccess', true); }
/** * Adds database dump to the package * * @param Zipper $zipper * @return Zipper */ protected function addDbdumpToPackage(Zipper $zipper) { $fileName = sys_get_temp_dir() . '/' . date('Y-m-d_His') . '-mysqldump.sql'; MySql::create()->setDbName(env('DB_DATABASE'))->setUserName(env('DB_USERNAME'))->setPassword(env('DB_PASSWORD'))->dumpToFile($fileName); $zipper->folder('database')->add($fileName); return $zipper; }
public function add(Zipper $zipper, PathBuilder $pathBuilder, Request $request, BlueprintCollection $blueprintCollection, Filesystem $file, Repository $repository, Collection $collection) { $input = $request->get('collection'); // Check if the blueprint already belongs to this collection $search = $blueprintCollection->where(['collection_id' => $input['id'], 'blueprint_id' => $input['blueprint_id']])->get()->toArray(); if (!empty($search)) { return redirect()->back()->with('blueprintAlreadyInCollection', true); } // Insert the blueprint in the collection $insert = $blueprintCollection->insert(['collection_id' => $input['id'], 'blueprint_id' => $input['blueprint_id']]); if ($insert) { // Create an archive to server to the user rather than creating it when it's downloaded // Get all the collection current archives first $collection = $collection->select('id', 'archive_name', 'name')->where(['id' => $input['id']])->with(['blueprints' => function ($query) { $query->select('archive_name'); }])->first(); $buildcraftArchiveStoragePath = $pathBuilder->create()->fromPublicPath($repository->get('blueprint.paths.storage.buildcraft.archives')); // Delete the previous archive(if any) if (null !== $collection->archive_name) { $file->delete($buildcraftArchiveStoragePath . $collection->archive_name); } // Create a random name for the collection archive $collectionArchiveName = str_replace(' ', '', $collection->name) . '_' . getRandomId() . '_collection' . '.zip'; // Start creating the archive $zipper->make($buildcraftArchiveStoragePath . $collectionArchiveName); foreach ($collection->blueprints as $key => $value) { // Add each archive to the the newly created archive $zipper->add($buildcraftArchiveStoragePath . $value->archive_name); } //Clean up $zipper->close(); // Update the archive name in the collections table $collection->archive_name = $collectionArchiveName; $collection->save(); // Welp, that's that return redirect()->back()->with('blueprintAddedToCollection', true); } // Or not return redirect()->back()->with('blueprintNotAddedToCollection', true); }
public function getJust(Request $request) { try { $contr = $request->cont; $desde = Carbon::createFromFormat('Y-m-d', $request->desde)->startOfDay(); $hasta = Carbon::createFromFormat('Y-m-d', $request->hasta)->endOfDay(); } catch (\Exception $e) { return view('vacio'); } $sat = ArchivoSat::whereBetween('fecha', array($desde, $hasta))->where(function ($q) use($contr) { $q->where('rfc_emisor', '=', $contr)->orWhere('rfc_receptor', '=', $contr); })->get(); $empresa = ArchivoEmpresa::whereBetween('fecha', array($desde, $hasta))->where(function ($q) use($contr) { $q->where('rfc_emisor', '=', $contr)->orWhere('rfc_receptor', '=', $contr); })->get(); $todos = $sat->count() + $empresa->count(); if ($todos == 0) { return view('vacio'); } $diff = new DiferenciasCFID($sat, $empresa, $contr); $just_emitidos = $diff->get_justificados_emitidos(); $just_recibidos = $diff->get_justificados_recibidos(); $contr = Contribuyente::where('rfc', '=', $contr)->first(); $array = ['nombre' => $contr->nombre, 'rfc' => $contr->rfc, 'justEm' => $just_emitidos, 'justRec' => $just_recibidos]; $namePdf = $contr->rfc . "_" . time() . ".pdf"; \PDF::loadView('descargas.reporte-justificados', $array)->save(storage_path('temp') . "/{$namePdf}"); $nameZip = "just_" . time() . ".zip"; $zipper = new Zipper(); $zipper->make(storage_path("temp/{$nameZip}"))->add(storage_path('temp') . "/{$namePdf}"); $anexos = $diff->getAnexos(); foreach ($anexos as $anexo) { $zipper->folder($anexo['uuid']); foreach ($anexo['anexos'] as $file) { $zipper->add($file->file); } } $zipper->close(); return response()->download(storage_path("temp/{$nameZip}"), $nameZip); }
public function run() { $zipper = new Zipper(); $zipper->make($this->path)->add($this->files); }
public function postExportPdf(Request $request) { $ids = null; if ($request->exists("checkall")) { $filter = !is_null($request->input('search')) ? $this->buildSearch() : ''; $args["params"] = $filter; $rows = $this->model->getRows($args); foreach ($rows["rows"] as $row) { $ids[] = $row->id; } } if (!$ids) { $ids = $request->input('ids'); } if (count($ids) > 0) { $uid = uniqid(); $zip = new \Chumper\Zipper\Zipper(); $zip->make(storage_path() . "/app/tmp/{$uid}/facturas.zip"); foreach ($ids as $id) { $view = $this->getHtmlContent($id); $nombreFact = "factura-{$this->data['row']->serfac}-{$this->data['row']->ejefac}-{$this->data['row']->numfac}.pdf"; $pdfContents = \PDF::loadHTML($view)->setPaper('a4')->setOption('margin-right', 0)->setOption('margin-bottom', 0)->setOption('margin-left', 0)->setOption('margin-top', 0)->output(); $zip->addString($nombreFact, $pdfContents); $this->data['subgrid'] = isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'][0] : array(); } $zip->close(); $response = \Response::make(file_get_contents(storage_path() . "/app/tmp/{$uid}/facturas.zip")); $size = \Storage::drive("local")->size("tmp/{$uid}/facturas.zip"); \Storage::drive("local")->deleteDirectory("tmp/{$uid}"); $response->header('Content-Disposition', 'attachment; filename="facturas.zip"'); $response->header('Content-Length', '$size'); return $response; } }
public function postEmpresa(Request $request) { ini_set('max_execution_time', $this->max_time); if (!$request->hasFile('empresa')) { return response()->json(['error' => "Ya se subio el archivo"], 200); } $file = $request->empresa; if ($file->getClientOriginalExtension() != "xml" && $file->getClientOriginalExtension() != "zip") { return response()->json(['error' => "El formato debe de ser xml o zip"], 200); } try { if ($file->getClientOriginalExtension() == "zip") { $errores = array(); $zipper = new Zipper(); $zipper->make($file->getRealPath()); $count = 0; foreach ($zipper->listFiles() as $file) { $fileExpled = explode(".", $file); if ($fileExpled[count($fileExpled) - 1] == "xml") { $nombre = $file; try { $resp = $this->empresaFiles($zipper->getFileContent($file)); } catch (\Exception $e) { $resp = "no"; $errMess = $e->getMessage(); $errores[] = "Error: {$errMess} en archivo: {$nombre} "; } if ($resp == "yes") { $count++; } } } if (count($errores) > 0) { return response()->json(['error' => $errores], 200); } } else { $nombre = $file->getClientOriginalName(); $text = file_get_contents($file->getRealPath()); $this->empresaFiles($text, false); } } catch (\Exception $e) { return response()->json(['error' => "Archivo: {$nombre} => " . $e->getMessage()], 200); } return response()->json("yes", 200); }
public function download(Request $request) { $digits = 5; $build_string = 'milligram_custom_' . str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT); $temp_path = 'temp/' . $build_string . '.css'; $temp = fopen($temp_path, 'a'); $base = file_get_contents('milligram/Base.css'); $blockquote = file_get_contents('milligram/Blockquote.css'); $button = file_get_contents('milligram/Button.css'); $code = file_get_contents('milligram/Code.css'); $form = file_get_contents('milligram/Form.css'); $grid = file_get_contents('milligram/Grid.css'); $link = file_get_contents('milligram/Link.css'); $list = file_get_contents('milligram/List.css'); $misc = file_get_contents('milligram/Misc.css'); $spacing = file_get_contents('milligram/Spacing.css'); $table = file_get_contents('milligram/Table.css'); $typography = file_get_contents('milligram/Typography.css'); $utility = file_get_contents('milligram/Utility.css'); if ($request->has('base')) { file_put_contents($temp_path, $base, FILE_APPEND); } if ($request->has('blockquote')) { file_put_contents($temp_path, $blockquote, FILE_APPEND); } if ($request->has('button')) { file_put_contents($temp_path, $button, FILE_APPEND); } if ($request->has('code')) { file_put_contents($temp_path, $code, FILE_APPEND); } if ($request->has('form')) { file_put_contents($temp_path, $form, FILE_APPEND); } if ($request->has('grid')) { file_put_contents($temp_path, $grid, FILE_APPEND); } if ($request->has('link')) { file_put_contents($temp_path, $link, FILE_APPEND); } if ($request->has('list')) { file_put_contents($temp_path, $list, FILE_APPEND); } if ($request->has('misc')) { file_put_contents($temp_path, $misc, FILE_APPEND); } if ($request->has('spacing')) { file_put_contents($temp_path, $spacing, FILE_APPEND); } if ($request->has('table')) { file_put_contents($temp_path, $table, FILE_APPEND); } if ($request->has('typography')) { file_put_contents($temp_path, $typography, FILE_APPEND); } if ($request->has('utility')) { file_put_contents($temp_path, $utility, FILE_APPEND); } fclose($temp); $zipper = new Zipper(); $zipper->make('download/' . $build_string . '.zip')->add([$temp_path, 'temp/normalize.css']); $zipper->close(); $download_path = rtrim(app()->basePath('public/'), '/') . "/download/" . $build_string . '.zip'; return response()->download($download_path, $build_string . '.zip', ['Content-type' => 'application/zip']); }
/** * List files that are within the archive * * @return array * @static */ public static function listFiles() { return \Chumper\Zipper\Zipper::listFiles(); }