Controller to output csv file of all materials for structure
@var $structure
@var string $delimiter Export file delimiter
@var string $fileName Export file name
349053
public function tocsv($collection, $fileName = null, $delimiter = ';')
    {
        s()->async(true);

        ini_set('memory_limit', '2048M');

        // Set passed file name or generate it
        $fileName = $fileName ?: 'Export' . date('dmY') . '.csv';

        // Output file from browser
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel; charset=utf-8');
        header('Content-Disposition: attachment; filename=' . $fileName);
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');

        // Write to php temp because php natively support csv files creation
        $handle = fopen('php://temp', 'r+');
        //fputs($handle, chr(0xEF) . chr(0xBB) . chr(0xBF)); // UTF-8 BOM
        foreach ($collection->toArray() as $line) {
            fputcsv($handle, $line, $delimiter);
        }

        // Read file from temp
        rewind($handle);
        $csv = '';
        while (!feof($handle)) {
            $csv .= fread($handle, 8192);
        }
        fclose($handle);

        // Convert to Excel readable format
        echo mb_convert_encoding($csv, 'Windows-1251', 'UTF-8');
    }
1214744
public function export()
	{
		$result = [];
		foreach ($this->getListBuilder()->getResult() as $item) {
			foreach ($item->getFields() as $field) {
				$value = $field->getValue();

				if (!is_string($value)) {
					$value = $value->toArray();
				}

				$result[$item->getIdentifier()][$field->getName()] = $value;
			}
		}

		\Excel::create($this->getFilename(), function($excel) use ($result) {
			$excel->setTitle('Export');
			$excel->setCreator('Bauhaus')
				->setCompany('KraftHaus');

			$excel->sheet('Excel sheet', function($sheet) use ($result) {
				$sheet->setOrientation('landscape');
				$sheet->fromArray($result);
			});

		})->download('xls');
	}
522315
def structureOutput(fileUrl, fileName, searchFiles, format=True, space=40):
	""""""
	#First, remove the filename
	if format:
		splitUrls = fileUrl[1:].split('/')
		fileUrl = ""
		for splitUrl in splitUrls:
			# This is a gimmicky fix to make formatting consistent
			# Cemetech doesn't have /pub/ at the front of it's repo paths
			# Also, Omnimaga has a /files/ we need to get rid of similarly
			# This probably *should* be repo-dependent, but oh well
			if splitUrl != "" and (not "." in splitUrl) and (splitUrl != "pub" and splitUrl != "files"):
				fileUrl += splitUrl + '/'
			elif "." in splitUrl:
				archiveName = splitUrl

	#Now, format the output
	if searchFiles:
		fileName = archiveName
	pause = (space - len(fileUrl))
	output = fileUrl
	output += (" " * pause)
	output += fileName
	return output
1363524
public static function dump(
        iterable $row,
        string $delimiter = ',',
        string $enclosure = '"',
        string $escape = '\\'
    ): string {
        $row = Arr::from($row);

        $res = fopen('php://temp', 'r+');

        try {
            $written = Thrower::call('fputcsv', $res, $row, $delimiter, $enclosure, $escape);
            $out = stream_get_contents($res, -1, 0);
        } catch (\Throwable $e) {
            throw new \RuntimeException('Failed to write CSV row.', 0, $e);
        } finally {
            fclose($res);
            unset($res);
        }

        if ($written === 0 || $written === false) {
            throw new \RuntimeException('Failed to write CSV row.');
        }

        return $out;
    }
633216
protected function getTables()
    {
        if (empty($this->config['tables'])) {
            return '';
        }
        $tables = [];
        // Tables specified in both tables and structureTables should only
        // export their structure. @see getStructureTables().
        $allTables = array_diff($this->config['tables'], $this->config['structureTables']);
        foreach ($allTables as $table) {
            $tables[] = escapeshellarg($table);
        }
        return implode($tables);
    }
119908
private function lazyParseStructure(): void
    {
        if (true === $this->structureParsed) {
            return;
        }
        $this->structureParsed = true;

        $this->lazyLoadStructure();

        $this->type = self::$typesMap[$this->structure->type] ?? self::TYPE_UNKNOWN;

        // In our context, \ENCOTHER is as useful as an uknown encoding
        $this->encoding = self::$encodingsMap[$this->structure->encoding] ?? self::ENCODING_UNKNOWN;
        $this->subtype  = $this->structure->subtype;

        if (isset($this->structure->bytes)) {
            $this->bytes = $this->structure->bytes;
        }
        if ($this->structure->ifdisposition) {
            $this->disposition = $this->structure->disposition;
        }
        if ($this->structure->ifdescription) {
            $this->description = $this->structure->description;
        }

        $this->parameters = new Parameters();
        if ($this->structure->ifparameters) {
            $this->parameters->add($this->structure->parameters);
        }

        if ($this->structure->ifdparameters) {
            $this->parameters->add($this->structure->dparameters);
        }

        // When the message is not multipart and the body is the attachment content
        // Prevents infinite recursion
        if (self::isAttachment($this->structure) && !$this instanceof Attachment) {
            $this->parts[] = new Attachment($this->resource, $this->getNumber(), '1', $this->structure);
        }

        if (isset($this->structure->parts)) {
            $parts = $this->structure->parts;
            // https://secure.php.net/manual/en/function.imap-fetchbody.php#89002
            if ($this instanceof Attachment && $this->isEmbeddedMessage() && 1 === \count($parts) && \TYPEMULTIPART === $parts[0]->type) {
                $parts = $parts[0]->parts;
            }
            foreach ($parts as $key => $partStructure) {
                $partNumber = (!$this instanceof Message) ? $this->partNumber . '.' : '';
                $partNumber .= (string) ($key + 1);

                $newPartClass = self::isAttachment($partStructure)
                    ? Attachment::class
                    : SimplePart::class
                ;

                $this->parts[] = new $newPartClass($this->resource, $this->getNumber(), $partNumber, $partStructure);
            }
        }
    }
16105
public function exportFile( stdClass $params )
	{
		$this->_checkParams( $params, array( 'site', 'items' ) );
		$this->_setLocale( $params->site );
		$context = $this->_getContext();

		$items = (array) $params->items;
		$lang = ( property_exists( $params, 'lang' ) ) ? (array) $params->lang : array();

		$config = $context->getConfig();

		/** controller/extjs/catalog/export/text/default/exportdir
		 * Directory where exported files of catalog texts are stored
		 *
		 * All exported files are stored in this file system directory directory.
		 *
		 * The export directory must be relative to the "basedir" configuration
		 * option. If
		 *
		 *  /var/www/test
		 *
		 * is the configured base directory and the export directory should be
		 * located in
		 *
		 *  /var/www/test/htdocs/files/exports
		 *
		 * then the configuration for the export directory must be
		 *
		 *  htdocs/files/exports
		 *
		 * Avoid leading and trailing slashes for the export directory string!
		 *
		 * @param string Relative path in the file system
		 * @since 2014.03
		 * @category Developer
		 * @see controller/extjs/media/default/basedir
		 */
		$dir = $config->get( 'controller/extjs/catalog/export/text/default/exportdir', 'uploads' );

		/** controller/extjs/catalog/export/text/default/dirperms
		 * Directory permissions used when creating the directory if it doesn't exist
		 *
		 * The representation of the permissions is in octal notation (using 0-7)
		 * with a leading zero. The first number after the leading zero are the
		 * permissions for the web server creating the directory, the second is
		 * for the primary group of the web server and the last number represents
		 * the permissions for everyone else.
		 *
		 * You should use 0700 for the permissions as the web server needs
		 * to write into the new directory but the files shouldn't be publicall
		 * available. The group permissions are only important if you plan to
		 * retrieve the files directly via FTP or by other means because then
		 * you need to be able to read and manage those files. In this case use
		 * 0770 as permissions.
		 *
		 * A more detailed description of the meaning of the Unix file permission
		 * bits can be found in the Wikipedia article about
		 * {@link https://en.wikipedia.org/wiki/File_system_permissions#Numeric_notation file system permissions}
		 *
		 * @param integer Octal Unix permission representation
		 * @since 2014.03
		 * @category Developer
		 * @category User
		 */
		$perms = $config->get( 'controller/extjs/catalog/export/text/default/dirperms', 0700 );

		/** controller/extjs/catalog/export/text/default/downloaddir
		 * Directory where the exported files can be found through the web
		 *
		 * The exported files are stored in this directory directory.
		 *
		 * The download directory must be relative to the document root of your
		 * virtual host. If the document root is
		 *
		 *  /var/www/test/htdocs
		 *
		 * and the exported files will be in
		 *
		 *  /var/www/test/htdocs/files/exports
		 *
		 * then the configuration for the download directory must be
		 *
		 *  files/exports
		 *
		 * Avoid leading and trailing slashes for the export directory string!
		 *
		 * @param string Relative path in the URL
		 * @since 2014.03
		 * @category Developer
		 */
		$downloaddir = $config->get( 'controller/extjs/catalog/export/text/default/downloaddir', 'uploads' );

		$foldername = 'catalog-text-export_' . date('Y-m-d_H:i:s') . '_' . md5( time() . getmypid() );
		$tmpfolder = $dir . DIRECTORY_SEPARATOR . $foldername;

		if( is_dir( $dir ) === false && mkdir( $dir, $perms, true ) === false ) {
			throw new Controller_ExtJS_Exception( sprintf( 'Couldn\'t create directory "%1$s" with permissions "%2$o"', $dir, $perms ) );
		}

		$context->getLogger()->log( sprintf( 'Create export directory for catalog IDs: %1$s', implode( ',', $items ) ), MW_Logger_Abstract::DEBUG );

		$filename = $this->_exportData( $items, $lang, $tmpfolder );
		$downloadFile = $downloaddir . DIRECTORY_SEPARATOR . basename( $filename );

		return array(
			'file' => '<a href="'.$downloadFile.'">'.$context->getI18n()->dt( 'controller/extjs', 'Download' ).'</a>',
		);
	}
433314
public function export()
    {
        $path = $this->module->dataPath;
        FileHelper::createDirectory($path, $this->module->dirMode);

        $summary = $this->collectSummary();
        $dataFile = "$path/{$this->tag}.data";
        $data = [];
        $exceptions = [];
        foreach ($this->module->panels as $id => $panel) {
            try {
                $data[$id] = serialize($panel->save());
            } catch (\Exception $exception) {
                $exceptions[$id] = new FlattenException($exception);
            }
        }
        $data['summary'] = $summary;
        $data['exceptions'] = $exceptions;

        file_put_contents($dataFile, serialize($data));
        if ($this->module->fileMode !== null) {
            @chmod($dataFile, $this->module->fileMode);
        }

        $indexFile = "$path/index.data";
        $this->updateIndexFile($indexFile, $summary);
    }
842377
protected function getContainer()
	{
		$config = $this->getContext()->getConfig();

		/** controller/jobs/subscription/export/csv/location
		 * Temporary file or directory where the content is stored which should be exported
		 *
		 * The path can point to any supported container format as long as the
		 * content is in CSV format, e.g.
		 * * Directory container / CSV file
		 * * Zip container / compressed CSV file
		 * * PHPExcel container / PHPExcel sheet
		 *
		 * @param string Absolute file or directory path
		 * @since 2018.04
		 * @category Developer
		 * @category User
		 * @see controller/jobs/subscription/export/csv/container/type
		 * @see controller/jobs/subscription/export/csv/container/content
		 * @see controller/jobs/subscription/export/csv/container/options
		 */
		$location = $config->get( 'controller/jobs/subscription/export/csv/location', sys_get_temp_dir() );

		/** controller/jobs/subscription/export/csv/container/type
		 * Nave of the container type to read the data from
		 *
		 * The container type tells the exporter how it should retrieve the data.
		 * There are currently three container types that support the necessary
		 * CSV content:
		 * * Directory
		 * * Zip
		 * * PHPExcel
		 *
		 * '''Note:''' For the PHPExcel container, you need to install the
		 * "ai-container" extension.
		 *
		 * @param string Container type name
		 * @since 2015.05
		 * @category Developer
		 * @category User
		 * @see controller/jobs/subscription/export/csv/location
		 * @see controller/jobs/subscription/export/csv/container/content
		 * @see controller/jobs/subscription/export/csv/container/options
		 */
		$container = $config->get( 'controller/jobs/subscription/export/csv/container/type', 'Directory' );

		/** controller/jobs/subscription/export/csv/container/content
		 * Name of the content type inside the container to read the data from
		 *
		 * The content type must always be a CSV-like format and there are
		 * currently two format types that are supported:
		 * * CSV
		 * * PHPExcel
		 *
		 * '''Note:''' for the PHPExcel content type, you need to install the
		 * "ai-container" extension.
		 *
		 * @param array Content type name
		 * @since 2015.05
		 * @category Developer
		 * @category User
		 * @see controller/jobs/subscription/export/csv/location
		 * @see controller/jobs/subscription/export/csv/container/type
		 * @see controller/jobs/subscription/export/csv/container/options
		 */
		$content = $config->get( 'controller/jobs/subscription/export/csv/container/content', 'CSV' );

		/** controller/jobs/subscription/export/csv/container/options
		 * List of file container options for the subscription export files
		 *
		 * Some container/content type allow you to hand over additional settings
		 * for configuration. Please have a look at the article about
		 * {@link http://aimeos.org/docs/Developers/Utility/Create_and_read_files container/content files}
		 * for more information.
		 *
		 * @param array Associative list of option name/value pairs
		 * @since 2015.05
		 * @category Developer
		 * @category User
		 * @see controller/jobs/subscription/export/csv/location
		 * @see controller/jobs/subscription/export/csv/container/content
		 * @see controller/jobs/subscription/export/csv/container/type
		 */
		$options = $config->get( 'controller/jobs/subscription/export/csv/container/options', [] );

		return \Aimeos\MW\Container\Factory::getContainer( $location, $container, $content, $options );
	}
1038260
public function save( & $structure )
    {
        $id = $this->getSaveProperty( $structure, 'id' );

        if ( empty( $id ) )
        {
            $selector = $this->getSaveProperty( $structure, 'selector', '' );
            $media    = $this->getSaveProperty( $structure, 'media', '' );
            $rootId   = $this->getSaveProperty( $structure, 'rootParagraphId' );
            $sql      = $this->sql();
            $select   = $sql->select()
                            ->columns( array( 'id' ) )
                            ->where( array(
                                'selector'        => $selector,
                                'media'           => $media,
                                'rootParagraphId' => $rootId,
                            ) )
                            ->limit( 1 );

            $result = $sql->prepareStatementForSqlObject( $select )
                          ->execute();

            if ( $result->getAffectedRows() )
            {
                foreach ( $result as $row )
                {
                    $this->setSaveProperty( $structure, 'id', $row['id'] );
                }
            }
        }

        $result = parent::save( $structure );
        $id     = $this->getSaveProperty( $structure, 'id' );

        if ( $result > 0 && ! empty( $id ) )
        {
            switch ( true )
            {
                case $structure instanceof Structure:
                    $properties = $structure->getRawProperties();
                    break;

                case is_array( $structure ):
                    $properties = isset( $structure['properties'] )
                        ? $structure['properties']
                        : array();
                    break;

                case is_object( $structure ):
                    $properties = isset( $structure->properties )
                        ? $structure->properties
                        : array();
                    break;

                default:
                    return $result;
            }

            $sql = $this->sql( $this->getTableInSchema(
                static::$propertyTableName
            ) );

            if ( empty( $properties ) )
            {
                $delete = $sql->delete()
                              ->where( array(
                                  'ruleId' => $id,
                              ) );

                $result += $sql->prepareStatementForSqlObject( $delete )
                               ->execute()
                               ->getAffectedRows();
            }
            else
            {
                $propNames = array();

                foreach ( $properties as $name => $spec )
                {
                    $propNames[] = $propName = empty( $spec['name'] )
                        ? $name : $spec['name'];

                    $result += $this->saveProperty(
                        $id,
                        $propName,
                        $spec['value'],
                        $spec['priority']
                    );
                }

                $delete = $sql->delete()
                              ->where( array(
                                  'ruleId' => $id,
                                  new NotIn( 'name', $propNames ),
                              ) );

                $result += $sql->prepareStatementForSqlObject( $delete )
                               ->execute()
                               ->getAffectedRows();
            }
        }

        return $result;
    }
1002431
protected function export()
    {
        $filesystem = new Filesystem();
        $handle = fopen($this->config['path'] . $this->prefix, "w");

        $checkPermissions = true;
        if (PHP_SAPI == 'cli') {
            $checkPermissions = false;
        }

        if (!$this->export->Init(
            $handle,
            $this->config["id"],
            false,
            true,
            $this->session["work_dir"],
            $this->session["file_dir"],
            $checkPermissions
        )
        ) {
            throw new ExportException('Failed to initialize export');
        }

        $this->export->DoNotDownloadCloudFiles();
        $this->export->StartExport();

        $this->export->StartExportMetadata();
        $this->export->ExportProperties($this->session["property_map"]);
        $this->export->ExportSections(
            $this->session["section_map"],
            time(),
            $this->config['interval'],
            $this->config["sections"],
            $this->session["property_map"]
        );
        $this->export->EndExportMetadata();

        $this->export->StartExportCatalog();
        $this->export->ExportElements(
            $this->session["property_map"],
            $this->session["section_map"],
            time(),
            $this->config['interval'],
            0,
            $this->config["elements"]
        );
        $this->export->EndExportCatalog();

        $this->export->ExportProductSets();
        $this->export->EndExport();

        fclose($handle);
        $filesystem->remove($this->config['path']);
        $filesystem->rename($this->config['path'] . $this->prefix, $this->config['path'], true);
    }
783111
public function input() {
		$output = '<script type="text/html" data-template="' . esc_attr( $this->name() ) . '">';
		if ( ! empty( $this->struct['template'] ) && file_exists( $this->struct['template'] ) ) {
			ob_start();
			include $this->struct['template'];
			$output .= ob_get_clean();
		}
		$output .= '</script>';
		echo $output;

		return $output;
	}
738785
protected function createOutputContents(
        array $header,
        $delimiter = ',',
        $enclosure = '"',
        $toConvert = true
    )
    {
        $fp = fopen("php://temp", 'r+b');

        // header
        if ($header) {
            fputcsv($fp, $header, $delimiter, $enclosure);
        }

        foreach ($this->rows as $row) {
            fputcsv($fp, $row, $delimiter, $enclosure);
        }

        rewind($fp);

        $buffer = stream_get_contents($fp);

        if ($toConvert === false) {
            fclose($fp);
            return $buffer;
        }

        $ret = $this->convert($buffer);

        fclose($fp);

        return $ret;
    }
612254
public function export()
    {
        $path = $this->module->dataPath;
        FileHelper::createDirectory($path, $this->module->dirMode);

        $summary = $this->collectSummary();
        $dataFile = "$path/{$this->tag}.log";
        $data = [];

        $data['log'] = $this->save();

        $data['summary'] = $summary;
        file_put_contents($dataFile, $this->convertArrayToText($data));
        if ($this->module->fileMode !== null) {
            @chmod($dataFile, $this->module->fileMode);
        }

        $indexFile = "$path/index.data";
        $this->updateIndexFile($indexFile, $summary);
    }
528391
public function export( $data = null, $type = null, $delimiter = null ) {

		if ( ! empty( $data ) ) {
			$this->set_data( $data );
		}

		if ( ! empty( $type ) && in_array( $type, $this->types, true ) ) {
			$this->type = $type;
		}

		if ( ! empty( $delimiter ) ) {
			$this->delimiter = $delimiter;
		}

		if ( method_exists( $this, "build_{$this->type}" ) ) {
			call_user_func( array( $this, 'build_' . $this->type ) );
		}

		return $this->built;
	}
1158850
protected function writeCsvContent($resource)
    {
        $columns    = $this->exportInfo->columns;
        $strategies = $this->getColumnStrategyInstances();

        $delimiter = $this->getDelimiterSymbol();
        $enclosure = $this->getEnclosureSymbol();
        $escape    = $this->getEscapeSymbol();


        // Generate header row, if not disabled
        if ($this->shouldHaveHeaderRow()) {

            $headers = array_map(
                function (ModelExportColumnDataInterface $column) {
                    return $column->header();
                },
                $columns
            );

            fputcsv($resource, $headers, $delimiter, $enclosure, $escape);
        }

        // For each query chunk: get a model instance,
        // and for each column, generate the column content using the strategies
        $this->query->chunk(
            static::CHUNK_SIZE,
            function ($records) use ($resource, $columns, $strategies, $delimiter, $enclosure, $escape) {
                /** @var Collection|Model[] $records */

                foreach ($records as $record) {

                    $fields = [];

                    foreach ($strategies as $key => $strategy) {
                        $fields[] = $strategy->render($record, $columns[$key]->source);
                    }

                    fputcsv($resource, $fields, $delimiter, $enclosure, $escape);
                }
            }
        );
    }
984137
public function createStructure(array $structure, $parent = '/')
    {
        foreach ($structure as $key => $value) {
            if (is_array($value)) {
                $this->createDir($parent.$key);
                $this->createStructure($value, $parent.$key.'/');
            } else {
                $this->createFile($parent.$key, $value);
            }
        }
    }