Create select to make the CsvFile attributes
to export

@return  String
480912
protected function createSelect($config = null)
	{
		$config = $config ? $config : $this->config;
		$select = array();
		if( ($columns = $config["columns"]) )
		{
			foreach($columns as $db_key => $export_key)
			{
				$select[]= "{$db_key} as {$export_key}";
			}
		}
		return $select;
	}
150648
public function definition () {
        $mform = $this->_form;

        $mform->addElement('header', 'generalhdr', get_string('general'));

        $mform->addElement('filepicker', 'coursefile', get_string('coursefile', 'tool_uploadcourse'));
        $mform->addRule('coursefile', null, 'required');
        $mform->addHelpButton('coursefile', 'coursefile', 'tool_uploadcourse');

        $choices = csv_import_reader::get_delimiter_list();
        $mform->addElement('select', 'delimiter_name', get_string('csvdelimiter', 'tool_uploadcourse'), $choices);
        if (array_key_exists('cfg', $choices)) {
            $mform->setDefault('delimiter_name', 'cfg');
        } else if (get_string('listsep', 'langconfig') == ';') {
            $mform->setDefault('delimiter_name', 'semicolon');
        } else {
            $mform->setDefault('delimiter_name', 'comma');
        }
        $mform->addHelpButton('delimiter_name', 'csvdelimiter', 'tool_uploadcourse');

        $choices = core_text::get_encodings();
        $mform->addElement('select', 'encoding', get_string('encoding', 'tool_uploadcourse'), $choices);
        $mform->setDefault('encoding', 'UTF-8');
        $mform->addHelpButton('encoding', 'encoding', 'tool_uploadcourse');

        $choices = array('10' => 10, '20' => 20, '100' => 100, '1000' => 1000, '100000' => 100000);
        $mform->addElement('select', 'previewrows', get_string('rowpreviewnum', 'tool_uploadcourse'), $choices);
        $mform->setType('previewrows', PARAM_INT);
        $mform->addHelpButton('previewrows', 'rowpreviewnum', 'tool_uploadcourse');

        $this->add_import_options();

        $mform->addElement('hidden', 'showpreview', 1);
        $mform->setType('showpreview', PARAM_INT);

        $this->add_action_buttons(false, get_string('preview', 'tool_uploadcourse'));
    }
710024
private function createFile()
    {
        $file = fopen($this->storage, "w");
        fputs($file, '{}');
        fclose($file);
        return json_decode('{}');
    }
182021
public function create()
    {
        $this->data['mrkdwn_in'] = [];

        if ($this->markdownInText) {
            $this->data['mrkdwn_in'][] = 'text';
        }

        if ($this->markdownInPretext) {
            $this->data['mrkdwn_in'][] = 'pretext';
        }

        if ($this->markdownInFields) {
            $this->data['mrkdwn_in'][] = 'fields';
        }

        return Attachment::fromData($this->data);
    }
1186803
public function export()
    {
        $tables = $this->db->getDatabase()->getTables(true);

        $sql = [];

        foreach ($tables as $table) {
            // Table
            $sql[] = MysqlGrammar::dropTable($table, true);
            $sql[] = $this->getCreateTable($table);

            // Data
            $inserts = $this->getInserts($table);

            if ($inserts) {
                $sql[] = $inserts;
            }
        }

        return implode(";\n\n", $sql);
    }
84672
public function generate ()
	{
		$startTime = microtime (true);

		if (!is_dir($this->reportDir)) 
		{
			echo "Creating new directory {$this->reportDir}... ";
			mkdir ($this->reportDir);	
			echo "OK\n";
		}

		echo "Generating CSV report to {$this->reportDir} ... ";

		$this->generateCsvForDirectory ($this->report);
		foreach ($this->report->getChildrenRecursively(new DirectorySpecification) as $item) 
		{
			$this->generateCsvForDirectory ($item);
		}

		$totalTime = number_format (microtime(true) - $startTime, 2);
		echo "OK ({$totalTime}s).\n";
	}
1256079
protected function buildSelect()
	{
		//define a container fields array
		$fields = array();

		//
		$where = $order = $limit = $join ="";

		//
		$template = "SELECT %s %s FROM %s %s %s %s %s";

		//loop through the fields
		foreach ($this->fields as $table => $tableFields) 
		{
			//loop through the fields checking for aliases
			foreach ($tableFields as $field => $alias) 
			{
				//if field is string, return field name
				if ( is_string($field) && $field != 'COUNT(1)')
				{
					//add to fields array
					$fields[] = "{$table}.{$field} AS {$alias}";

				}
				elseif (is_string($field) && $field == 'COUNT(1)') 
				{
					//add to fields array
					$fields[] = "{$field} AS {$alias}";

				}
				//not an array, return alias
				else
				{
					//get alias as field name
					$fields[] = "{$table}.{$alias}";

				}

			}

		}

		//turn the fields into a string
		$fields = join(", ", $fields);

		//get the query joins
		$queryJoin = $this->joins;

		//check if the join parameter is empty
		if ( ! empty($queryJoin) ) 
		{
			$joinTables = "(" . join(", ", $queryJoin['tables']) . ")";
			$joinConditions = "(" . join(" AND ", $queryJoin['conditions']) . ")";
			//add the joins
			$join = " LEFT JOIN $joinTables ON $joinConditions";

		}

		//get the where clause
		$queryWhere = $this->wheres;

		//check if the wheres clause is empty
		if ( ! empty($queryWhere) ) 
		{
			//append where clause
			$joined = join(" AND ", $queryWhere);

			//assign string to $where var
			$where = "WHERE {$joined}";

		}

		//get the order clause
		$queryOrder = $this->orders;

		//check if the orders clause is empty
		if ( ! empty($queryOrder) ) 
		{
			//get the direction if order
			$orderDirection = $this->directions;

			//assign string to order variable
			$order = "ORDER BY {$queryOrder} {$orderDirection}";

		}

		//get the limits clause
		$queryLimit = $this->limits;

		//check if the limits clause is empty
		if ( ! empty($queryLimit) ) 
		{
			//get the offset
			$limitOffset = $this->offset;

			//if offset has been defined
			if ( $limitOffset ) 
			{
				//get the limit string with offset
				$limit = "LIMIT {$limitOffset}, {$queryLimit}";

			}
			//limit offset undefined
			else
			{
				//get the limit string
				$limit = "LIMIT {$queryLimit}";

			}

		}

		//return the formated query string in the format of $template
		return sprintf($template, $this->distinct, $fields, $this->froms, $join, $where, $order, $limit);

	}
64118
protected function buildValuesForInsert()
    {
        return ' (' . $this->indentCsv(array_keys($this->col_values)) . ') VALUES (' .
        $this->indentCsv(array_values($this->col_values)) . ')';
    }
265760
public function getSelect()
    {
        $concat = null;

        foreach ($this->fieldDescriptors as $fieldDescriptor) {
            if (null == $concat) {
                $concat = $fieldDescriptor->getSelect();
            } else {
                $concat = 'CONCAT(' . $concat . ', CONCAT(\'' . $this->glue . '\', ' . $fieldDescriptor->getSelect() . '))';
            }
        }

        return $concat;
    }
446153
public function makeReport()
    {
        $project = $this->element->project;
        $projectMetrics = $project->metrics;
        $coveredStatements = intval($projectMetrics['coveredstatements']);
        $statementsTotal = intval($projectMetrics['statements']);
        $reportTotal = round($this->safeDivision($coveredStatements, $statementsTotal) * 100);
        $fileReports = $this->makeFileReports($project);
        $report = new CoverageReport($reportTotal, $fileReports);
        return $report;
    }
585899
public function generateExportFileData($gridField)
    {
        $csvColumns = $this->getExportColumnsForGridField($gridField);

        $csvWriter = Writer::createFromFileObject(new \SplTempFileObject());
        $csvWriter->setDelimiter($this->getCsvSeparator());
        $csvWriter->setEnclosure($this->getCsvEnclosure());
        $csvWriter->setNewline("\r\n"); //use windows line endings for compatibility with some csv libraries
        $csvWriter->setOutputBOM(Writer::BOM_UTF8);

        if (!Config::inst()->get(get_class($this), 'xls_export_disabled')) {
            $csvWriter->addFormatter(function (array $row) {
                foreach ($row as &$item) {
                    // [SS-2017-007] Sanitise XLS executable column values with a leading tab
                    if (preg_match('/^[-@=+].*/', $item)) {
                        $item = "\t" . $item;
                    }
                }
                return $row;
            });
        }

        if ($this->csvHasHeader) {
            $headers = [];

            // determine the CSV headers. If a field is callable (e.g. anonymous function) then use the
            // source name as the header instead
            foreach ($csvColumns as $columnSource => $columnHeader) {
                if (is_array($columnHeader) && array_key_exists('title', $columnHeader)) {
                    $headers[] = $columnHeader['title'];
                } else {
                    $headers[] = (!is_string($columnHeader) && is_callable($columnHeader)) ? $columnSource : $columnHeader;
                }
            }

            $csvWriter->insertOne($headers);
            unset($headers);
        }

        //Remove GridFieldPaginator as we're going to export the entire list.
        $gridField->getConfig()->removeComponentsByType(GridFieldPaginator::class);

        $items = $gridField->getManipulatedList();

        // @todo should GridFieldComponents change behaviour based on whether others are available in the config?
        foreach ($gridField->getConfig()->getComponents() as $component) {
            if ($component instanceof GridFieldFilterHeader || $component instanceof GridFieldSortableHeader) {
                $items = $component->getManipulatedData($gridField, $items);
            }
        }

        /** @var DataObject $item */
        foreach ($items->limit(null) as $item) {
            if (!$item->hasMethod('canView') || $item->canView()) {
                $columnData = [];

                foreach ($csvColumns as $columnSource => $columnHeader) {
                    if (!is_string($columnHeader) && is_callable($columnHeader)) {
                        if ($item->hasMethod($columnSource)) {
                            $relObj = $item->{$columnSource}();
                        } else {
                            $relObj = $item->relObject($columnSource);
                        }

                        $value = $columnHeader($relObj);
                    } else {
                        $value = $gridField->getDataFieldValue($item, $columnSource);

                        if ($value === null) {
                            $value = $gridField->getDataFieldValue($item, $columnHeader);
                        }
                    }

                    $columnData[] = $value;
                }

                $csvWriter->insertOne($columnData);
            }

            if ($item->hasMethod('destroy')) {
                $item->destroy();
            }
        }

        return (string)$csvWriter;
    }
838730
public function prepare_package() {
        $entries = $this->exportdata['entries'];
        $aliases = array();
        $categories = array();
        if (is_array($this->exportdata['aliases'])) {
            foreach ($this->exportdata['aliases'] as $alias) {
                if (!array_key_exists($alias->entryid, $aliases)) {
                    $aliases[$alias->entryid] = array();
                }
                $aliases[$alias->entryid][] = $alias->alias;
            }
        }
        if (is_array($this->exportdata['categoryentries'])) {
            foreach ($this->exportdata['categoryentries'] as $cat) {
                if (!array_key_exists($cat->entryid, $categories)) {
                    $categories[$cat->entryid] = array();
                }
                $categories[$cat->entryid][] = $cat->name;
            }
        }
        if ($this->get('exporter')->get('formatclass') == PORTFOLIO_FORMAT_SPREADSHEET) {
            $csv = glossary_generate_export_csv($entries, $aliases, $categories);
            $this->exporter->write_new_file($csv, clean_filename($this->cm->name) . '.csv', false);
            return;
        } else if ($this->get('exporter')->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
            $ids = array(); // keep track of these to make into a selection later
            global $USER, $DB;
            $writer = $this->get('exporter')->get('format')->leap2a_writer($USER);
            $format = $this->exporter->get('format');
            $filename = $this->get('exporter')->get('format')->manifest_name();
            foreach ($entries as $e) {
                $content = glossary_entry_portfolio_caller::entry_content(
                    $this->course,
                    $this->cm,
                    $this->glossary,
                    $e,
                    (array_key_exists($e->id, $aliases) ? $aliases[$e->id] : array()),
                    $format
                );
                $entry = new portfolio_format_leap2a_entry('glossaryentry' . $e->id, $e->concept, 'entry', $content);
                $entry->author    = $DB->get_record('user', array('id' => $e->userid), 'id,firstname,lastname,email');
                $entry->published = $e->timecreated;
                $entry->updated   = $e->timemodified;
                if (!empty($this->keyedfiles[$e->id])) {
                    $writer->link_files($entry, $this->keyedfiles[$e->id], 'glossaryentry' . $e->id . 'file');
                    foreach ($this->keyedfiles[$e->id] as $file) {
                        $this->exporter->copy_existing_file($file);
                    }
                }
                if (!empty($categories[$e->id])) {
                    foreach ($categories[$e->id] as $cat) {
                        // this essentially treats them as plain tags
                        // leap has the idea of category schemes
                        // but I think this is overkill here
                        $entry->add_category($cat);
                    }
                }
                $writer->add_entry($entry);
                $ids[] = $entry->id;
            }
            $selection = new portfolio_format_leap2a_entry('wholeglossary' . $this->glossary->id, get_string('modulename', 'glossary'), 'selection');
            $writer->add_entry($selection);
            $writer->make_selection($selection, $ids, 'Grouping');
            $content = $writer->to_xml();
        }
        $this->exporter->write_new_file($content, $filename, true);
    }
428246
public function csv_export()
    {
        $search = $this->app->make('Concrete\Controller\Search\Users');
        $result = $search->getCurrentSearchObject();

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename=concrete5_users.csv',
        ];
        $app = $this->app;
        $config = $this->app->make('config');
        $bom = $config->get('concrete.export.csv.include_bom') ? $config->get('concrete.charset_bom') : '';

        return StreamedResponse::create(
            function () use ($app, $result, $bom) {
                $writer = $app->build(
                    UserExporter::class,
                    [
                        'writer' => $this->app->make(WriterFactory::class)->createFromPath('php://output', 'w'),
                    ]
                );
                echo $bom;
                $writer->setUnloadDoctrineEveryTick(50);
                $writer->insertHeaders();
                $writer->insertList($result->getItemListObject());
            },
            200,
            $headers);
    }
128375
protected function getFormData()
    {
        $data = array();
        $inputTagNames = array('input', 'textarea', 'select');
        $skipNames = array('ext', 'form');

        /** @var DOMElement $element */
        $element = $this->xml->getElementsByTagName('form')->item(0);
        $elements = $element->getElementsByTagName('*');

        for ($i = 0; $i < $elements->length; $i++)
        {
            $element = $elements->item($i);

            $isElement = $element->nodeType == XML_ELEMENT_NODE;
            $isInputTag = $isElement && in_array($element->nodeName, $inputTagNames);

            if ($isInputTag)
            {
                $name = $element->getAttribute('name');
                if (in_array($name, $skipNames))
                {
                    continue;
                }
                if ($name)
                {
                    if ($element->getAttribute('type') == 'file')
                    {
                        $data[$name]['file'] = $_FILES[$name];
                    }
                    else
                    {
                        $data[$name]['data'] = arg($name);
                    }
                    $data[$name]['label'] = $this->getLabelAttr($element);
                    if (!$data[$name]['label'])
                    {
                        $data[$name]['label'] = $name;
                    }

                    switch ($element->nodeName)
                    {
                        case 'input':
                            switch ($element->getAttribute('type'))
                            {
                                case 'checkbox':
                                    $data[$name]['data'] = $data[$name]['data'] ? strYes : strNo;
                                    break;
                            }
                            break;
                    }
                }
            }
        }

        return $data;
    }
1194585
protected function buildCols()
    {
        if (!$this->cols) {
            throw new Exception('No columns in the SELECT.');
        }

        $cols = array();
        foreach ($this->cols as $key => $val) {
            if (is_int($key)) {
                $cols[] = $this->quoteNamesIn($val);
            } else {
                $cols[] = $this->quoteNamesIn("$val AS $key");
            }
        }

        return $this->indentCsv($cols);
    }
752590
public function GetSelect() {
      // Close off any open query elements.
      $this->_EndQuery();
      
      $Sql = (!$this->_Distinct) ? 'select ' : 'select distinct ';

      // Don't escape the field if it is numeric or an asterisk (all columns)
      $Selects = array();
      foreach($this->_Selects as $Key => $Expr) {
         $Field = $Expr['Field'];
         $Function = $Expr['Function'];
         $Alias = $Expr['Alias'];
         $CaseOptions = ArrayValue('CaseOptions', $Expr);
         if ($Field != '*' && !is_numeric($Field))
            $Field = $this->EscapeIdentifier($Field);

         if ($Alias == '' && $Function != '')
            $Alias = $Field;

         // if (in_array(strtolower($Function), array('max', 'min', 'avg', 'sum', 'count')))
         if ($Function != '') {
				if(strpos($Function, '%s') !== FALSE)
					$Field = sprintf($Function, $Field);
				else
					$Field = $Function.'('.$Field.')';
			}

         if ($CaseOptions !== FALSE)
            $Field = 'case ' . $Field . $CaseOptions . ' end';

         if ($Alias != '')
            $Field .= ' as '.$this->QuoteIdentifier($Alias);

         if ($Field != '')
            $Selects[] = $Field;
      }
      $Sql .= (count($Selects) == 0) ? '*' : implode(', ', $Selects);

      if (count($this->_Froms) > 0)
         $Sql .= "\nfrom ".$this->_FromTables($this->_Froms);

      if (count($this->_Joins) > 0) {
         $Sql .= "\n";
         $Sql .= implode("\n", $this->_Joins);
      }

      if (count($this->_Wheres) > 0)
         $Sql .= "\nwhere ";

      $Sql .= implode("\n", $this->_Wheres);

      // Close any where groups that were left open.
      for ($i = 0; $i < $this->_OpenWhereGroupCount; ++$i) {
         $Sql .= ')';
      }
      $this->_OpenWhereGroupCount = 0;

      if (count($this->_GroupBys) > 0) {
         $Sql .= "\ngroup by ";

         // special consideration for table aliases
         if (count($this->_AliasMap) > 0 && $this->Database->DatabasePrefix)
            $Sql .= implode(', ', $this->_FilterTableAliases($this->_GroupBys));
         else
            $Sql .= implode(', ', $this->_GroupBys);
      }

      if (count($this->_Havings) > 0)
         $Sql .= "\nhaving ".implode("\n", $this->_Havings);

      if (count($this->_OrderBys) > 0)
         $Sql .= "\norder by ".implode(', ', $this->_OrderBys);

      if (is_numeric($this->_Limit)) {
         $Sql .= "\n";
         $Sql = $this->GetLimit($Sql, $this->_Limit, $this->_Offset);
      }

      return $Sql;
   }
888555
public function toString()
	{
		$attributes = $this->buildAttributes();

		$select = array();
		$select[] = '<select '.$attributes.'>';

		$firstValue = $this->firstValue;
		
		$value = isset($this->override) ? $this->override : (isset($this->attributes['value']) ? $this->attributes['value'] : '');

		if($firstValue)
		{
			$selected = $value == $firstValue['value'] ? 'selected' : '';
			$select[] = '<option '.$selected.' value="'.$firstValue['value'].'">'.$firstValue['label'].'</option>';
		}

		foreach($this->options as $val => $label)
		{
			if(is_array($label))
			{
				$select[] = '<optgroup label="'.$val.'">';
				foreach($label as $v => $l)
				{
					$selected = $v === $value ? 'selected' : '';
					$select[] = '<option '.$selected.' value="'.$v.'">'.$l.'</option>';
				}
				$select[] = '</optgroup>';
			}
			else
			{
				$selected = $val === $value ? 'selected' : '';
				$select[] = '<option '.$selected.' value="'.$val.'">'.$label.'</option>';
			}
		}

		$select[] = '</select>';

		return implode('', $select);
	}