Main function to call who process the vendors
to create the wallets and register or verify the bank information.

@param DateTime $lastUpdate
@param $tmpFilesPath

@codeCoverageIgnore
339139
public function process($tmpFilesPath, DateTime $lastUpdate = null)
    {
        try {
            $this->logger->info('Control Mirakl Settings', array('miraklId' => null, "action" => "Wallet creation"));
            // control mirakl settings
            $boolControl = $this->getControlMiraklSettings($this->documentTypes);
            if ($boolControl === false) {
                // log critical
                $title = $this->criticalMessageMiraklSettings;
                $message = $this->formatNotification->formatMessage($title);
                $this->logger->critical($message, array('miraklId' => null, "action" => "Wallet creation"));
            } else {
                $this->logger->info(
                    'Control Mirakl Settings OK',
                    array('miraklId' => null, "action" => "Wallet creation")
                );
            }

            $this->logger->info('Vendor Processing', array('miraklId' => null, "action" => "Wallet creation"));

            //Vendor data fetching from Mirakl
            $this->logger->info(
                'Vendors fetching from Mirakl',
                array('miraklId' => null, "action" => "Wallet creation")
            );
            $miraklData = $this->getVendors($lastUpdate);
            $this->logger->info(
                '[OK] Fetched vendors from Mirakl : ' . count($miraklData),
                array('miraklId' => null, "action" => "Wallet creation")
            );

            //Wallet creation
            $this->logger->info('Wallet creation', array('miraklId' => null, "action" => "Wallet creation"));
            $vendorCollection = $this->registerWallets($miraklData);
            $this->logger->info(
                '[OK] Wallets : ' . count($vendorCollection),
                array('miraklId' => null, "action" => "Wallet creation")
            );

            //Vendor saving
            $this->logger->info("Saving vendor", array('miraklId' => null, "action" => "Wallet creation"));
            $this->vendorManager->saveAll($vendorCollection);
            $this->logger->info("[OK] Vendor saved", array('miraklId' => null, "action" => "Wallet creation"));

            //File transfer
            $this->logger->info('Transfer files', array('miraklId' => null, "action" => "Wallet creation"));
            $this->transferFiles(
                array_keys($vendorCollection),
                $tmpFilesPath
            );

            // Bank data updating
            $this->logger->info('Update bank data', array('miraklId' => null, "action" => "Wallet creation"));
            $this->handleBankInfo($vendorCollection, $miraklData, $tmpFilesPath);
            $this->logger->info('[OK] Bank info updated', array('miraklId' => null, "action" => "Wallet creation"));

            $this->logVendorManager->saveAll($this->vendorsLogs);
        } catch (Exception $e) {
            try {
                // log critical
                $title = 'Error Vendor:Process ';
                $exceptionMsg = $e->getMessage();
                $message = $this->formatNotification->formatMessage($title, false, $exceptionMsg);
                $this->logger->critical($message);
            } catch (\Exception $ex) {
                $this->handleException($e, "critical", array('miraklId' => null, "action" => "Wallet creation"));
            }
        }
    }
817093
private function isFullChunkFilePresent($fileUuid, $tempPath, $totalChunks)
    {
        for ($i = 0; $i < $totalChunks; ++$i) {
            if (!file_exists($tempPath . DIRECTORY_SEPARATOR . $fileUuid . $i)) {
                return false;
            }
        }

        return true;
    }
568389
protected function createDummyUploadFolder()
    {
        $uploadFolderPath = $this->getUploadFolderPath();
        if (is_dir($uploadFolderPath)) {
            return;
        }

        $creationSuccessful = GeneralUtility::mkdir($uploadFolderPath);
        if (!$creationSuccessful) {
            throw new \RuntimeException(
                'The upload folder ' . $uploadFolderPath . ' could not be created.',
                1334439408
            );
        }

        $this->dummyFolders['uploadFolder'] = $uploadFolderPath;
    }
1208510
public function store(string $name, array $characteristics, $data, \DateTime $lastMod = null) {
		$nameDirPath = $this->buildNameDirPath($name);
		if (!$nameDirPath->isDir()) {
			if ($this->dirPerm === null) {
				throw new IllegalStateException('No directory permission set for FileCacheStore.');
			}
			
			$nameDirPath->mkdirs($this->dirPerm);
		}
		
		if ($this->filePerm === null) {
			throw new IllegalStateException('No file permission set for FileCacheStore.');
		}
		
		if ($lastMod === null) {
			$lastMod = new \DateTime();
		}
		
		$filePath = $nameDirPath->ext($this->buildFileName($characteristics));
				
		$lock = $this->createWriteLock((string) $filePath);
		IoUtils::putContentsSafe($filePath->__toString(), serialize(array('characteristics' => $characteristics, 
				'data' => $data, 'lastMod' => $lastMod->getTimestamp())));
		
		
		$filePath->chmod($this->filePerm);
		$lock->release();
	}
30873
public function upload(File $tmpFile)
    {
        $clusterFileName = $this->_generateClusterFileName($tmpFile);

        $dir = $this->rootBasePath;
        $localPath = $this->getClusterDir($clusterFileName);

        $clusterFileSrc = $clusterFileName;

        if ($localPath) {
            $clusterFileSrc = $localPath.DIRECTORY_SEPARATOR.$clusterFileSrc;
        }

        try {
            $dir = new Dir($dir.DIRECTORY_SEPARATOR.$localPath);
            $resultFile = $dir->newFile($clusterFileName);
            $tmpFile->move($resultFile);

        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

        return $clusterFileSrc;
    }
217630
protected function sendHeaders($tmpFile)
    {
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Type: application/pdf');
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: ' . filesize($tmpFile));
    }
357678
protected function registerMigrationFiles($packagePath)
    {
        $packagePath = rtrim($packagePath, '/');
        $packageKey = substr($packagePath, strrpos($packagePath, '/') + 1);
        $migrationsDirectory = Files::concatenatePaths(array($packagePath, 'Migrations/Code'));
        if (!is_dir($migrationsDirectory)) {
            return;
        }

        foreach (Files::getRecursiveDirectoryGenerator($migrationsDirectory, '.php') as $filenameAndPath) {
            /** @noinspection PhpIncludeInspection */
            require_once($filenameAndPath);
            $baseFilename = basename($filenameAndPath, '.php');
            $className = '\\Neos\\Flow\\Core\\Migrations\\' . $baseFilename;
            /** @var AbstractMigration $migration */
            $migration = new $className($this, $packageKey);
            $this->migrations[$migration->getVersionNumber()] = $migration;
        }
    }
1320205
public function touch($created = null, $lastAccessed = null) {
		$created = $created instanceof DateTime
			? $created->getTimestamp() 
			: ($created === null ? time() : $created);
		$lastAccessed = $lastAccessed instanceof DateTime
			? $lastAccessed->getTimestamp()
			: ($lastAccessed === null ? time() : $lastAccessed);

		if (!@touch($this->pathname, $created, $lastAccessed)) {
			throw new FileException(sprintf('Failed to touch file at %s', $this->pathname));
		}
	}
1126942
protected function process($tmp_name, $name, $size, $type, $error, $index = 0, $content_range = null)
    {
        $this->fileContainer = $file = new File($tmp_name, $name);
        $file->name = $this->getFilename($name, $type, $index, $content_range, $tmp_name);
        $file->size = $this->fixIntegerOverflow(intval($size));
        $completed = false;

        if ($file->name) { //since the md5 filename generator would return false if it's allowDuplicate property is set to false and the file already exists.

            if ($this->validate($tmp_name, $file, $error, $index)) {
                // Now that we passed the validation, we can work with the file
                $upload_path = $this->pathresolver->getUploadPath();
                $file_path = $this->pathresolver->getUploadPath($file->name);
                $append_file = $content_range && $this->filesystem->isFile($file_path) && $file->size > $this->getFilesize($file_path);

                if ($tmp_name && $this->filesystem->isUploadedFile($tmp_name)) {
                    // This is a normal upload from temporary file
                    if ($append_file) {
                        // Adding to existing file (chunked uploads)
                        $this->filesystem->writeToFile($file_path, $this->filesystem->getFileStream($tmp_name), true);
                    } else {
                        // Upload full file
                        $this->filesystem->moveUploadedFile($tmp_name, $file_path);
                    }
                } else {
                    // This is a PUT-type upload
                    $this->filesystem->writeToFile($file_path, $this->filesystem->getInputStream(), $append_file);
                }

                $file_size = $this->getFilesize($file_path, $append_file);

                if ($this->logger) {
                    $this->logger->debug('Processing ' . $file->name, [
                        'File path' => $file_path,
                        'File object' => $file,
                        'Append to file?' => $append_file,
                        'File exists?' => $this->filesystem->isFile($file_path),
                        'File size' => $file_size,
                    ]);
                }

                if ($file->size == $file_size) {
                    // Yay, upload is complete!
                    $completed = true;
                } else {
                    if (! $content_range) {
                        // The file is incomplete and it's not a chunked upload, abort
                        $this->filesystem->unlink($file_path);
                        $file->error = 'abort';
                    }
                }

                $file = new File($file_path, $name);
                $file->completed = $completed;
                $file->size = $file_size;

                if ($completed) {
                    $this->processCallbacksFor('completed', $file);
                }
            }
        }

        return $file;
    }
1034287
public function setLastModified($lastModified)
    {
        if ($lastModified instanceof DateTime) {
            $this->lastModified = $lastModified;
            return;
        } elseif ($lastModified instanceof Model) {
            $this->lastModified = $lastModified->updated_at;
            return;
        }

        $this->lastModified = new DateTime($lastModified);
    }
1084219
public function writer($tmpPath = '')
    {
        $tmpPath = $tmpPath ?: $this->config->get('general.timestampPath');
        if (!$tmpPath) {
            $tmpPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR;
        }
        $timestamp = [
            'js' => $this->config->get('js.timestamp'),
            'css' => $this->config->get('css.timestamp'),
        ];
        $writer = new AssetWriter($timestamp, $tmpPath, $this->config->theme());
        $writer->configTimestamp($this->config->modifiedTime());
        $writer->filterRegistry($this->filterRegistry());
        return $writer;
    }
1244045
@VisibleForTesting
  void updateLastModifiedTime(final Path path) {
    try {
      Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
    } catch (final IOException ex) {
      log.warn("Error when updating last modified time for {}", path, ex);
    }
  }
375893
public function load($tmpFile, $folderPath = false) {
				
		if(!$folderPath) $folderPath = Config::inst()->get('Upload', 'uploads_folder');
		
		// @TODO This puts a HUGE limitation on files especially when lots
		// have been uploaded.
		$base = Director::baseFolder();
		$parentFolder = Folder::find_or_make($folderPath);

		// Generate default filename
        $fileArray = explode('/', $tmpFile);
        $fileName = $fileArray[(count($fileArray)-1)];
		$nameFilter = FileNameFilter::create();
		$file = $nameFilter->filter($fileName);
		$fileName = basename($file);

		$relativeFilePath = ASSETS_DIR . "/" . $folderPath . "/$fileName";
		
		// if filename already exists, version the filename (e.g. test.gif to test1.gif)
		while(file_exists("$base/$relativeFilePath")) {
			$i = isset($i) ? ($i+1) : 2;
			$oldFilePath = $relativeFilePath;
			// make sure archives retain valid extensions
			if(substr($relativeFilePath, strlen($relativeFilePath) - strlen('.tar.gz')) == '.tar.gz' ||
				substr($relativeFilePath, strlen($relativeFilePath) - strlen('.tar.bz2')) == '.tar.bz2') {
					$relativeFilePath = preg_replace('/[0-9]*(\.tar\.[^.]+$)/', $i . '\\1', $relativeFilePath);
			} else if (strpos($relativeFilePath, '.') !== false) {
				$relativeFilePath = preg_replace('/[0-9]*(\.[^.]+$)/', $i . '\\1', $relativeFilePath);
			} else if (strpos($relativeFilePath, '_') !== false) {
				$relativeFilePath = preg_replace('/_([^_]+$)/', '_'.$i, $relativeFilePath);
			} else {
				$relativeFilePath .= '_'.$i;
			}
			if($oldFilePath == $relativeFilePath && $i > 2) {
				user_error("Couldn't fix $relativeFilePath with $i tries", E_USER_ERROR);
			}
		}
		
		if(file_exists($tmpFile) && copy($tmpFile, $base."/".$relativeFilePath)) {
			$this->owner->ParentID = $parentFolder->ID;
			// This is to prevent it from trying to rename the file
			$this->owner->Name = basename($relativeFilePath);
			$this->owner->write();
			return true;
		} else {
			return false;
		}
	}
747786
private function clientCacheForFile($path)
	{
		$lastModified = filemtime($path);

		if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified)
		{
			header('HTTP/1.0 304 Not Modified');
			exit;
		}
	}
1060310
public function saveFile(FileCreateOrUpdateEvent $event)
    {
        $model = $event->getModel();
        $model->setFile(sprintf("tmp/%s", $event->getUploadedFile()->getFilename()));
        $con = Propel::getWriteConnection(ProductImageTableMap::DATABASE_NAME);
        $con->beginTransaction();

        try {
            $nbModifiedLines = $model->save($con);
            $event->setModel($model);

            if (!$nbModifiedLines) {
                throw new FileException(
                    sprintf(
                        'File "%s" (type %s) with parent id %s failed to be saved',
                        $event->getParentName(),
                        \get_class($model),
                        $event->getParentId()
                    )
                );
            }

            $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile());

            $event->setUploadedFile($newUploadedFile);
            $con->commit();
        } catch (\Exception $e) {
            $con->rollBack();

            throw $e;
        }
    }
977503
@POST
    public Response createTransaction(@PathParam("path") final String externalPath) throws URISyntaxException {

        if (batchService.exists(session.getId(), getUserPrincipal())) {
            LOGGER.debug("renewing transaction {}", session.getId());
            batchService.refresh(session.getId(), getUserPrincipal());
            final Response.ResponseBuilder res = noContent();
            session.getFedoraSession().getExpires().ifPresent(expires -> {
                res.expires(from(expires));
            });
            return res.build();
        }

        if (externalPath != null && !externalPath.isEmpty()) {
            return status(BAD_REQUEST).build();
        }

        batchService.begin(session.getFedoraSession(), getUserPrincipal());
        session.makeBatchSession();
        LOGGER.info("Created transaction '{}'", session.getId());

        final Response.ResponseBuilder res = created(
                new URI(translator().toDomain("/tx:" + session.getId()).toString()));
        session.getFedoraSession().getExpires().ifPresent(expires -> {
            res.expires(from(expires));
        });
        return res.build();
    }
61065
protected function renameTempFile(
        /*# string */ $tmpFile,
        /*# string */ $realPath
    )/*# : bool */ {
        if (@rename($tmpFile, $realPath) &&
            @chmod($realPath, PermissionAwareInterface::PERM_ALL)) {
            return true;
        }
        $err = error_get_last();
        $this->setError($err['message'], Message::STR_WRITEFILE_FAIL);
        @unlink($tmpFile);
        return false;
    }