Feat: Include patched extension via local packages

This commit is contained in:
Björn Fromme
2023-06-30 13:14:14 +02:00
parent a3ea0127c5
commit f75a23a508
321 changed files with 111975 additions and 63 deletions
@@ -0,0 +1,155 @@
<?php
namespace Frappant\FrpFormAnswers\Command;
use Frappant\FrpFormAnswers\Domain\Model\FormEntryDemand;
use Frappant\FrpFormAnswers\Domain\Repository\FormEntryRepository;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use TYPO3\CMS\Core\Exception;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException;
use TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException;
use TYPO3\CMS\Fluid\View\StandaloneView;
use Frappant\FrpFormAnswers\Domain\Model\FormEntry;
use Symfony\Component\Console\Command\Command;
class MailAdminNotificationCommand extends Command
{
/**
* Configure the command by defining the name, options and arguments.
*/
protected function configure()
{
$this
->setDescription('Sends a notification mail with a list of not exportet form entries.')
->addArgument(
'mailto',
InputArgument::REQUIRED,
'E-Mail Address the Mail should be sent to.'
)
->addOption(
'formname',
'',
InputOption::VALUE_OPTIONAL,
'Name of the form to be checked.'
)
->addOption(
'title',
'',
InputOption::VALUE_OPTIONAL,
'Subject Label.'
);
}
/**
* @param $mails
* @return string
*/
public function generateMailBody($mails)
{
// Rendering of the output via fluid
$view = GeneralUtility::makeInstance(StandaloneView::class);
$view->setFormat('html');
$templateRootPath = GeneralUtility::getFileAbsFileName(
'EXT:frp_form_answers/Resources/Private/CommandTask/Templates'
);
$partialRootPaths = GeneralUtility::getFileAbsFileName(
'EXT:frp_form_answers/Resources/Private/CommandTask/Partials'
);
$layoutRootPaths = GeneralUtility::getFileAbsFileName(
'EXT:frp_form_answers/Resources/Private/CommandTask/Layouts'
);
$view->setTemplateRootPaths(array($templateRootPath));
$view->setPartialRootPaths(array($partialRootPaths));
$view->setLayoutRootPaths(array($layoutRootPaths));
$view->setTemplatePathAndFilename(
GeneralUtility::getFileAbsFileName(
'EXT:frp_form_answers/Resources/Private/CommandTask/Templates/FormEntries/InMail.html'
)
);
$view->assignMultiple(['mails' => $mails]);
return $view->render();
}
/**
* Email notification about sent forms.
*
* @param InputInterface $input
* @param OutputInterface $output
* @throws Exception
*/
public function execute(InputInterface $input, OutputInterface $output)
{
$mailto = $input->getArgument('mailto');
$formname = $input->getOption('formname');
$title= $input->getOption('title');
if (empty($mailto)) {
throw new Exception('You need to provide at least one email address.');
}
$formEntryRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(FormEntryRepository::class);
$search = GeneralUtility::makeInstance(FormEntryDemand::class);
$search->setAllPids(true);
if ($formname) {
$output->writeln("Searching for form ".$formname);
$search->setFormName($formname);
}else{
$output->writeln("Searching for no specific form");
}
$frommail = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'];
if (!empty($frommail)) {
$output->writeln("Default E-Mail Address: ".$frommail);
$from = $frommail;
} else {
throw new Exception("['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'] is not set.");
}
$records = $formEntryRepository->findByDemand($search);
if ($records->count()) {
$output->writeln($records->count()." entries found");
/** @var FormEntry $row */
foreach ($records as $row) {
$output->writeln("Sending entry with uid:".$row->getUid());
$row->setExported(true);
try {
$formEntryRepository->update($row);
} catch (IllegalObjectTypeException $e) {
$output->writeln($e->getMessage());
return;
} catch (UnknownObjectException $e) {
$output->writeln($e->getMessage());
return;
}
}
$body = $this->generateMailBody($records);
$date = date("d/m/y");
if (!empty($title)) {
$subject = $title;
} else {
$subject = "Scheduler mails update " . $date;
}
$trim = GeneralUtility::trimExplode(',', $mailto, 1);
foreach ($trim as $singlemail) {
$mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
$mail
->setSubject($subject)
->setFrom(array($from))
->setTo(array($singlemail))
->setBody($body, 'text/html')
->send();
}
} else {
$output->writeln("Nothing to send.");
}
}
}
@@ -0,0 +1,387 @@
<?php
namespace Frappant\FrpFormAnswers\Controller;
use Frappant\FrpFormAnswers\Domain\Model\FormEntryDemand;
use TYPO3\CMS\Backend\Clipboard\Clipboard;
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Template\Components\Menu\Menu;
use TYPO3\CMS\Backend\Utility\BackendUtility as BackendUtilityCore;
use TYPO3\CMS\Backend\View\BackendTemplateView;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
/***
*
* This file is part of the "Form Answer Saver" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2017 !frappant <[email protected]>
*
***/
/**
* FormEntryController
*/
class FormEntryController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
/**
* Backend Template Container
*
* @var string
*/
protected $defaultViewObjectName = \TYPO3\CMS\Backend\View\BackendTemplateView::class;
/**
* pageRepository
*
* @var \TYPO3\CMS\Core\Domain\Repository\PageRepository
*/
protected $pageRepository = null;
/**
* Inject a page repository to enable DI
*
* @param \TYPO3\CMS\Core\Domain\Repository\PageRepository $pageRepository
*/
public function injectPageRepository(\TYPO3\CMS\Core\Domain\Repository\PageRepository $pageRepository)
{
$this->pageRepository = $pageRepository;
}
/**
* formEntryRepository
*
* @var \Frappant\FrpFormAnswers\Domain\Repository\FormEntryRepository
*/
protected $formEntryRepository;
/**
* Inject a page repository to enable DI
*
* @param \Frappant\FrpFormAnswers\Domain\Repository\FormEntryRepository $formEntryRepository
*/
public function injectFormEntryRepository(\Frappant\FrpFormAnswers\Domain\Repository\FormEntryRepository $formEntryRepository)
{
$this->formEntryRepository = $formEntryRepository;
}
/**
* dataExporter
*
* @var \Frappant\FrpFormAnswers\DataExporter\DataExporter
*/
protected $dataExporter = null;
/**
* Inject a page repository to enable DI
*
* @param \Frappant\FrpFormAnswers\DataExporter\DataExporter $dataExporter
*/
public function injectDataExporter(\Frappant\FrpFormAnswers\DataExporter\DataExporter $dataExporter)
{
$this->dataExporter = $dataExporter;
}
/**
* formAnswersUtility
*
* @var \Frappant\FrpFormAnswers\Utility\FormAnswersUtility
*/
protected $formAnswersUtility = null;
/**
* Inject a page repository to enable DI
*
* @param \Frappant\FrpFormAnswers\Utility\FormAnswersUtility $formAnswersUtility
*/
public function injectFormAnswersUtility(\Frappant\FrpFormAnswers\Utility\FormAnswersUtility $formAnswersUtility)
{
$this->formAnswersUtility = $formAnswersUtility;
}
/**
* @var IconFactory
*/
protected $iconFactory;
/**
* Set up the doc header properly here
*
* @param ViewInterface $view
* @return void
*/
protected function initializeView(ViewInterface $view)
{
/** @var BackendTemplateView $view */
parent::initializeView($view);
$this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
if ($this->actionMethodName != 'exportAction') {
$view->getModuleTemplate()->getDocHeaderComponent()->setMetaInformation([]);
$pageRenderer = $this->view->getModuleTemplate()->getPageRenderer();
$pageRenderer->addInlineLanguageLabelFile('EXT:lang/Resources/Private/Language/locallang_core.xlf');
$this->createMenu();
$this->createButtons();
$view->assign('showSupportArea', $this->showSupportArea());
}
}
/**
* Create menu
*
*/
protected function createMenu()
{
$uriBuilder = $this->objectManager->get(UriBuilder::class);
$uriBuilder->setRequest($this->request);
$menu = $this->view->getModuleTemplate()->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
$menu->setIdentifier('news');
$actions = [
['action' => 'list', 'label' => 'Overview'],
['action' => 'prepareExport', 'label' => 'Export'],
['action' => 'prepareRemove', 'label' => 'Remove'],
];
foreach ($actions as $action) {
$item = $menu->makeMenuItem()
->setTitle($action['label'])
->setHref($uriBuilder->reset()->uriFor($action['action'], [], 'FormEntry'))
->setActive($this->request->getControllerActionName() === $action['action']);
$menu->addMenuItem($item);
}
if ($menu instanceof Menu) {
$this->view->getModuleTemplate()->getDocHeaderComponent()->getMenuRegistry()->addMenu($menu);
}
}
/**
* Create the panel of buttons
*
*/
protected function createButtons()
{
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
$uriBuilder->setRequest($this->request);
// Refresh
$refreshButton = $buttonBar->makeLinkButton()
->setHref(GeneralUtility::getIndpEnv('REQUEST_URI'))
->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.reload'))
->setIcon($this->iconFactory->getIcon('actions-refresh', Icon::SIZE_SMALL));
$buttonBar->addButton($refreshButton, ButtonBar::BUTTON_POSITION_RIGHT);
}
/**
* action list
*
* @return void
*/
public function listAction()
{
$pageIds = $this->formAnswersUtility->prepareFormAnswersArray();
if (count($pageIds) > 0) {
$this->view->assign('subPagesWithFormEntries', $this->pageRepository->getMenuForPages(array_keys($pageIds)));
$this->view->assign('formEntriesStatus', $pageIds);
}
$this->view->assign('pid', (int)GeneralUtility::_GP('id'));
$this->view->assign('formNames', $this->formAnswersUtility->getAllFormNames());
$this->view->assign('settings', $this->settings);
}
/**
* action prepareRemove
*
* @return void
*/
public function prepareRemoveAction()
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_frpformanswers_domain_model_formentry');
$queryBuilder->getRestrictions()->removeAll();
$count = $queryBuilder->count('*')
->from('tx_frpformanswers_domain_model_formentry')
->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(\Frappant\FrpFormAnswers\Utility\BackendUtility::getCurrentPid(), \PDO::PARAM_INT)))
->andWhere($queryBuilder->expr()->eq('deleted', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT)))
->execute()->fetchFirstColumn();
//DebuggerUtility::var_dump($count);
$this->view->assign('count', $count[0]);
}
/**
* action prepareRemove
*
* @return void
*/
public function removeAction()
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_frpformanswers_domain_model_formentry');
$queryBuilder->delete('tx_frpformanswers_domain_model_formentry')
->where($queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter(\Frappant\FrpFormAnswers\Utility\BackendUtility::getCurrentPid(), \PDO::PARAM_INT)))
->andWhere($queryBuilder->expr()->eq('deleted', $queryBuilder->createNamedParameter(1, \PDO::PARAM_INT)))
->execute();
$this->addFlashMessage(
LocalizationUtility::translate('LLL:EXT:frp_form_answers/Resources/Private/Language/de.locallang_be.xlf:flashmessage.removeEntries.body', null, [\Frappant\FrpFormAnswers\Utility\BackendUtility::getCurrentPid()]),
LocalizationUtility::translate('LLL:EXT:frp_form_answers/Resources/Private/Language/de.locallang_be.xlf:flashmessage.removeEntries.title'),
\TYPO3\CMS\Core\Messaging\FlashMessage::OK,
true);
$this->redirect('list');
}
/**
* action show
*
* @param \Frappant\FrpFormAnswers\Domain\Model\FormEntry $formEntry
* @return void
*/
public function showAction(\Frappant\FrpFormAnswers\Domain\Model\FormEntry $formEntry)
{
$this->view->assign('formEntry', $formEntry);
}
/**
* action prepareExport
*
* @return void
*/
public function prepareExportAction()
{
$demandObject = GeneralUtility::makeInstance(FormEntryDemand::class);
$this->view->assign('formEntryDemand', $demandObject);
$this->view->assign('formHashes', $this->formAnswersUtility->getAllFormHashes());
}
public function initializeExportAction(){
$format = $this->request->getArguments()['format'];
switch ($format){
case 'Csv':
$this->defaultViewObjectName = \Frappant\FrpFormAnswers\View\FormEntry\ExportCsv::class;
break;
case 'Xls':
$this->defaultViewObjectName = \Frappant\FrpFormAnswers\View\FormEntry\ExportXls::class;
break;
case 'Xml':
$this->defaultViewObjectName = \Frappant\FrpFormAnswers\View\FormEntry\ExportXml::class;
break;
}
}
/**
* action export
* @param FormEntryDemand $formEntryDemand
* @return void The Excel file with data
* @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
* @throws \TYPO3\CMS\Extbase\Mvc\Exception\UnsupportedRequestTypeException
*/
public function exportAction(FormEntryDemand $formEntryDemand)
{
$formEntries = $this->formEntryRepository->findbyDemand($formEntryDemand);
if (count($formEntries) === 0) {
$this->addFlashMessage('No entries found with your criteria',
'No Entries found',
FlashMessage::WARNING,
true
);
$this->redirect('list');
}
$extensionConfiguration = $GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['frp_formanswers'];
$exportData = $this->dataExporter->getExport($formEntries, $formEntryDemand, $extensionConfiguration['useSubmitUid']['value']);
$this->formEntryRepository->setFormsToExported($formEntries);
$this->view->assign('rows', $exportData);
$this->view->assign('formEntryDemand', $formEntryDemand);
}
/**
* @param string $formName
* @throws \TYPO3\CMS\Extbase\Mvc\Exception\StopActionException
*/
public function deleteFormnameAction($formName = ''){
if(strlen($formName) > 0){
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tx_frpformanswers_domain_model_formentry');
$queryBuilder->update(
'tx_frpformanswers_domain_model_formentry',
[ 'deleted' => 1 ], // set
[ 'form' => $formName, 'pid' => \Frappant\FrpFormAnswers\Utility\BackendUtility::getCurrentPid()]
);
$this->addFlashMessage(
LocalizationUtility::translate('LLL:EXT:frp_form_answers/Resources/Private/Language/de.locallang_be.xlf:flashmessage.deleteFormName.body', 'frp_form_answers', [$formName, \Frappant\FrpFormAnswers\Utility\BackendUtility::getCurrentPid()]),
LocalizationUtility::translate('LLL:EXT:frp_form_answers/Resources/Private/Language/de.locallang_be.xlf:flashmessage.deleteFormName.title'),
\TYPO3\CMS\Core\Messaging\FlashMessage::OK,
true);
}
$this->redirect('list');
}
/**
* Show support area only for admins in given percent of time
*
* @param int $probabilityInPercent
* @return bool
*/
private function showSupportArea(int $probabilityInPercent = 10): bool
{
if (!$this->getBackendUser()->isAdmin()) {
return false;
}
if (mt_rand() % 100 <= $probabilityInPercent) {
return true;
}
return false;
}
/**
* Returns the LanguageService
*
* @return LanguageService
*/
protected function getLanguageService(): LanguageService
{
return $GLOBALS['LANG'];
}
/**
* Get backend user
*
* @return BackendUserAuthentication
*/
protected function getBackendUser(): BackendUserAuthentication
{
return $GLOBALS['BE_USER'];
}
}
@@ -0,0 +1,82 @@
<?php
namespace Frappant\FrpFormAnswers\DataExporter;
use Frappant\FrpFormAnswers\Domain\Model\FormEntryDemand;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
class DataExporter
{
/**
* getExport
* @param Array $rowAnswers Assossiative rray with all rowAnswers
* @param Frappant\FrpFormAnswers\Domain\Model\FormEntryDemand $formEntryDemand
* @param boolean $useSubmitUid bollean check if export UID values should use uid or submitUid
* @return array Rows with formatted formAnswers
*/
public function getExport($rowAnswers, FormEntryDemand $formEntryDemand, $useSubmitUid)
{
$rows = array();
$header = array();
$headerKeys = (array)array_values($rowAnswers[0]->getAnswers());
// add header for crdate
$headerKeys[] = [
'value' => '',
'conf' => [
'label' => LocalizationUtility::translate('LLL:EXT:frp_form_answers/Resources/Private/Language/locallang_db.xlf:tx_frpformanswers_domain_model_formentry.crdate'),
'inputType' => 'DateTime',
],
];
$this->setHeaders($rowAnswers, $formEntryDemand, $headerKeys, $header);
foreach ($rowAnswers as $key => $entry) {
$uid = ($useSubmitUid) ? $entry->getSubmitUid() : $entry->getUid();
if ($formEntryDemand->getUidLabel()) {
$rows[$uid][$formEntryDemand->getUidLabel()] = $uid;
}
foreach ($entry->getAnswers() as $fieldName => $field) {
if ($this->isExportableType($field['conf']['inputType'])) {
$rows[$uid][$fieldName] = (is_array($field['value']) ? implode(",", $field['value']) : $field['value']);
}
}
$rows[$uid]['crdate'] = $entry->_getProperty('crdate');
}
array_unshift($rows, $header);
return $rows;
}
/**
* Set header labels in an array
* @param array $rowAnswers
* @param FormEntryDemand $formEntryDemand
* @param array $headerKeys
* @param array &$header
*/
protected function setHeaders($rowAnswers, FormEntryDemand $formEntryDemand, $headerKeys, &$header)
{
if ($formEntryDemand->getUidLabel()) {
$header[] = $formEntryDemand->getUidLabel();
}
foreach ($headerKeys as $field => $val) {
if ($this->isExportableType($val['conf']['inputType'])) {
$header[] = ($val['conf']['label'] ? $val['conf']['label'] : $field);
}
}
}
private function isExportableType(string $inputType): bool
{
$typesToSkip = [
'Fieldset',
'StaticText',
'GridRow'
];
return !\in_array($inputType, $typesToSkip);
}
}
@@ -0,0 +1,110 @@
<?php
namespace Frappant\FrpFormAnswers\Domain\Finishers;
use Frappant\FrpFormAnswers\Domain\Model\FormEntry;
use TYPO3\CMS\Form\Domain\Finishers;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Domain\Model\FileReference;
use TYPO3\CMS\Form\Domain\Finishers\AbstractFinisher;
use TYPO3\CMS\Form\Domain\Finishers\Exception\FinisherException;
use TYPO3\CMS\Form\Domain\Model\FormElements\FormElementInterface;
class SaveFormToDatabaseFinisher extends AbstractFinisher
{
/**
* formEntryRepository
*
* @var \Frappant\FrpFormAnswers\Domain\Repository\FormEntryRepository
* @TYPO3\CMS\Extbase\Annotation\Inject
*/
protected $formEntryRepository = null;
/**
* signalSlotDispatcher
*
* @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
* @TYPO3\CMS\Extbase\Annotation\Inject
*/
protected $signalSlotDispatcher = null;
/**
* Executes this finisher
* @see AbstractFinisher::execute()
*/
protected function executeInternal()
{
// Values of all fields, getFormValues() also gives pages,
// so it will be filled in foreach
$values = $this->getFormValues();
// Identifier for the yaml file of the form
$identifier = $this->finisherContext->getFormRuntime()->getIdentifier();
// Default Value is new Form
$lastFormUid = 1;
$this->signalSlotDispatcher->dispatch(__CLASS__, 'preInsertSignal', array(&$values));
$formEntry = $this->objectManager->get(FormEntry::class);
$formEntry->setExported(false);
$formEntry->setAnswers($values);
$formEntry->setForm($identifier);
$formEntry->setPid($GLOBALS['TSFE']->id);
$lastForm = $this->formEntryRepository->getLastFormAnswerByIdentifyer($identifier);
// If there already exists a formAnswers, override lastFormUid
if ($lastForm instanceof FormEntry) {
$lastFormUid += $lastForm->getSubmitUid();
}
$formEntry->setSubmitUid($lastFormUid);
$this->formEntryRepository->add($formEntry);
}
/**
* Returns the values of the submitted form
*
* @return []
*/
protected function getFormValues(): array
{
// All values, with pages
$valuesWithPages = $this->finisherContext->getFormValues();
$values = [];
// Goes trough all form-pages - and there trough all PageElements (Questions)
foreach ($this->finisherContext->getFormRuntime()->getPages() as $page) {
foreach ($page->getElementsRecursively() as $pageElem) {
if ($pageElem->getType() !== 'Honeypot') {
if($pageElem->getType() !== 'FileUpload' && $pageElem->getType() !== 'ImageUpload'){
$values[$pageElem->getIdentifier()]['value'] = $valuesWithPages[$pageElem->getIdentifier()];
}else{
if($valuesWithPages[$pageElem->getIdentifier()]){
$values[$pageElem->getIdentifier()]['value'] = $valuesWithPages[$pageElem->getIdentifier()]->getOriginalResource()->getName();
}
}
$values[$pageElem->getIdentifier()]['conf']['label'] = $pageElem->getLabel();
$values[$pageElem->getIdentifier()]['conf']['inputType'] = $pageElem->getType();
}
}
}
return $values;
}
/**
* Returns a form element object for a given identifier.
*
* @param string $elementIdentifier
* @return NULL|FormElementInterface
*/
protected function getElementByIdentifier(string $elementIdentifier)
{
return $this
->finisherContext
->getFormRuntime()
->getFormDefinition()
->getElementByIdentifier($elementIdentifier);
}
}
@@ -0,0 +1,201 @@
<?php
namespace Frappant\FrpFormAnswers\Domain\Model;
/***
*
* This file is part of the "Form Answer Saver" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2017 !frappant <[email protected]>
*
***/
/**
* FormEntry
*/
class FormEntry extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
/**
* answers
*
* @var string
*/
protected $answers = '';
/**
* fieldHash
*
* @var string
*/
protected $fieldHash = '';
/**
* form
*
* @var string
*/
protected $form = '';
/**
* exported
*
* @var bool
*/
protected $exported = false;
/**
* @var \DateTime
*/
protected $crdate;
/**
* exported
*
* @var int
*/
protected $submitUid = '';
/**
* Returns the answers
*
* @return array $answers
*/
public function getAnswers()
{
return json_decode($this->answers, 1);
}
/**
* Sets the answers
*
* @param array $answers
* @return void
*/
public function setAnswers(array $answers)
{
$this->answers = json_encode($answers);
ksort($answers);
$fields = "";
foreach ($answers as $field => $value) {
$fields .= $field;
}
$this->fieldHash = md5($fields);
}
/**
* Returns the fieldHash
*
* @return string $fieldHash
*/
public function getFieldHash()
{
return $this->fieldHash;
}
/**
* Sets the fieldHash
*
* @param string $fieldHash
* @return void
*/
public function setFieldHash($fieldHash)
{
$this->fieldHash = md5($fieldHash);
}
/**
* Returns the form
*
* @return string $form
*/
public function getForm()
{
return $this->form;
}
/**
* Sets the form
*
* @param string $form
* @return void
*/
public function setForm($form)
{
$this->form = $form;
}
/**
* Returns the exported
*
* @return bool $exported
*/
public function getExported()
{
return $this->exported;
}
/**
* Sets the exported
*
* @param bool $exported
* @return void
*/
public function setExported($exported)
{
$this->exported = $exported;
}
/**
* Returns the boolean state of exported
*
* @return bool
*/
public function isExported()
{
return $this->exported;
}
/**
* Set creation date
*
* @param int $crdate
*/
public function setCrdate($crdate)
{
$this->crdate = $crdate;
}
/**
* Get creation date
*
* @return int
*/
public function getCrdate()
{
return $this->crdate;
}
/**
* Sets the submitUid
*
* @param int $submitUid
* @return void
*/
public function setSubmitUid($submitUid)
{
$this->submitUid = $submitUid;
}
/**
* Returns the submitUid
*
* @return int
*/
public function getSubmitUid()
{
return $this->submitUid;
}
}
@@ -0,0 +1,347 @@
<?php
namespace Frappant\FrpFormAnswers\Domain\Model;
/***
*
* This file is part of the "Form Answer Saver" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2017 !frappant <[email protected]>
*
***/
/**
* FormEntry
*/
class FormEntryDemand extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
/**
* selectAll
*
* @var bool
*/
protected $selectAll = false;
/**
* allPids
*
* @var bool
*/
protected $allPids = false;
/**
* exportType
*
* @var string
*/
protected $exportType = '';
/**
* uidLabel
*
* @var string
*/
protected $uidLabel = 'uid';
/**
* form
*
* @var string
*/
protected $form = '';
/**
* formName
*
* @var string
*/
protected $formName = '';
/**
* fileName
*
* @var string
*/
protected $fileName = '';
/**
* charset
*
* @var string
*/
protected $charset = '';
/**
* delimiter
*
* @var string
*/
protected $delimiter = '';
/**
* enclosure
*
* @var string
*/
protected $enclosure = '';
/**
* uidField
*
* @var string
*/
protected $uidField = '';
/**
* Returns the selectAll
*
* @return bool $selectAll
*/
public function getSelectAll()
{
return $this->selectAll;
}
/**
* Sets the selectAll
*
* @param bool $selectAll
* @return void
*/
public function setSelectAll($selectAll)
{
$this->selectAll = $selectAll;
}
/**
* Returns the boolean state of selectAll
*
* @return bool
*/
public function isSelectAll()
{
return $this->selectAll;
}
/**
* Returns the allPids
*
* @return bool $allPids
*/
public function getAllPids()
{
return $this->allPids;
}
/**
* Sets the allPids
*
* @param bool $allPids
* @return void
*/
public function setAllPids($allPids)
{
$this->allPids = $allPids;
}
/**
* Returns the boolean state of allPids
*
* @return bool
*/
public function isAllPids()
{
return $this->allPids;
}
/**
* Returns the exportType
*
* @return string $exportType
*/
public function getExportType()
{
return $this->exportType;
}
/**
* Sets the exportType
*
* @param string $exportType
* @return void
*/
public function setExportType($exportType)
{
$this->exportType = $exportType;
}
/**
* Returns the uidLabel
*
* @return string $uidLabel
*/
public function getUidLabel()
{
return $this->uidLabel;
}
/**
* Sets the uidLabel
*
* @param string $uidLabel
* @return void
*/
public function setUidLabel($uidLabel)
{
$this->uidLabel = $uidLabel;
}
/**
* Returns the form
*
* @return string $form
*/
public function getForm()
{
return $this->form;
}
/**
* Sets the form
*
* @param string $form
* @return void
*/
public function setForm($form)
{
$this->form = $form;
}
/**
* Returns the formName
*
* @return string $formName
*/
public function getFormName()
{
return $this->formName;
}
/**
* Sets the formName
*
* @param string $formName
* @return void
*/
public function setFormName($formName)
{
$this->formName = $formName;
}
/**
* Returns the fileName
*
* @return string $fileName
*/
public function getFileName()
{
return $this->fileName;
}
/**
* Sets the fileName
*
* @param string $fileName
* @return void
*/
public function setFileName($fileName)
{
$this->fileName = $fileName;
}
/**
* Returns the charset
*
* @return string $charset
*/
public function getCharset()
{
return $this->charset;
}
/**
* Sets the charset
*
* @param string $charset
* @return void
*/
public function setCharset($charset)
{
$this->charset = $charset;
}
/**
* Returns the delimiter
*
* @return string $delimiter
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* Sets the delimiter
*
* @param string $delimiter
* @return void
*/
public function setDelimiter($delimiter)
{
$this->delimiter = $delimiter;
}
/**
* Returns the enclosure
*
* @return string $enclosure
*/
public function getEnclosure()
{
return $this->enclosure;
}
/**
* Sets the enclosure
*
* @param string $enclosure
* @return void
*/
public function setEnclosure($enclosure)
{
$this->enclosure = $enclosure;
}
/**
* Returns the uidField
*
* @return string $uidField
*/
public function getUidField()
{
return $this->uidField;
}
/**
* Sets the uidField
*
* @param string $uidField
* @return void
*/
public function setUidField($uidField)
{
$this->uidField = $uidField;
}
}
@@ -0,0 +1,143 @@
<?php
namespace Frappant\FrpFormAnswers\Domain\Repository;
use Frappant\FrpFormAnswers\Domain\Model\FormEntryDemand;
use TYPO3\CMS\Core\Database\QueryGenerator;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Persistence\Generic\QueryResult;
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
use Frappant\FrpFormAnswers\Utility\BackendUtility;
/***
*
* This file is part of the "Form Answer Saver" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2017 !frappant <[email protected]>
*
***/
/**
* The repository for FormEntries
*/
class FormEntryRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
public function initializeObject()
{
$querySettings = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setStoragePageIds(array((int)\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('id')));
$this->setDefaultQuerySettings($querySettings);
}
/**
* setRespectStoragePage description
* @param boolean $bool Check if respectStoragePage should be set or nor
*/
public function setRespectStoragePage($bool)
{
$querySettings = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setRespectStoragePage($bool);
$this->setDefaultQuerySettings($querySettings);
}
/**
* Finds all FormEntries given by conf Array
* @param \Frappant\FrpFormAnswers\Domain\Model\FormEntryDemand $formEntryDemand
* @return QueryResult
*/
public function findByDemand(FormEntryDemand $formEntryDemand)
{
$query = $this->createQuery();
if ($formEntryDemand->getAllPids()) {
$settings = $query->getQuerySettings();
$settings->setRespectStoragePage(false);
$query->setQuerySettings($settings);
}
$constraints = array();
if (!$formEntryDemand->getSelectAll()) {
$constraints[] = $query->equals('exported', false);
}
if ($formEntryDemand->getForm()) {
$constraints[] = $query->equals('fieldHash', $formEntryDemand->getForm());
}
if ($formEntryDemand->getFormName()) {
$constraints[] = $query->equals('form', $formEntryDemand->getFormName());
}
if (count($constraints)) {
$query->matching($query->logicalAnd($constraints));
}
return $query->execute();
}
/**
* Find all within a Page and all subpages
*
* @param int $pid start page identifier
* @return QueryResult
*/
public function findAllInPidAndRootline($pid)
{
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(false);
$queryGenerator = GeneralUtility::makeInstance(QueryGenerator::class);
$pids = GeneralUtility::trimExplode(',', $queryGenerator->getTreeList($pid, 20, 0, 1), true);
if (!BackendUtility::isBackendAdmin()) {
$pids = BackendUtility::filterPagesForAccess($pids);
}
if (is_array($pids) && count($pids)) {
$query->matching($query->in('pid', $pids));
}
$query->setOrderings(['pid' => QueryInterface::ORDER_ASCENDING]);
return $query->execute();
}
/**
* Finds the last Form Entry of a given yaml File (form) - used to set the submitUid in SaveFormToDatabaseFinisher
*
* @param String $form
* @return QueryResult
*/
public function getLastFormAnswerByIdentifyer($form)
{
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(false);
$query->setOrderings(
array(
'submitUid' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
)
);
$query->matching($query->equals('form', $form));
$query->setLimit(1);
return $query->execute()->getFirst();
}
public function setFormsToExported($forms)
{
foreach ($forms as $entry) {
$entry->setExported(true);
$this->update($entry);
}
$persistenceManager = $this->objectManager->get("TYPO3\\CMS\\Extbase\\Persistence\\Generic\\PersistenceManager");
$persistenceManager->persistAll();
}
}
@@ -0,0 +1,17 @@
<?php
namespace Frappant\FrpFormAnswers\ExpressionLanguage;
use TYPO3\CMS\Core\ExpressionLanguage\AbstractProvider;
class CustomTypoScriptConditionProvider extends AbstractProvider
{
public function __construct()
{
$this->expressionLanguageProviders = [
\Frappant\FrpFormAnswers\TypoScript\CustomConditionFunctionsProvider::class,
];
}
}
@@ -0,0 +1,33 @@
<?php
namespace Frappant\FrpFormAnswers\Form;
use TYPO3\CMS\Backend\Form\Element\AbstractFormElement;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;
class FormAnswersJsonElement extends AbstractFormElement
{
public function render()
{
// Custom TCA properties and other data can be found in $this->data, for example the above
// parameters are available in $this->data['parameterArray']['fieldConf']['config']['parameters']
$resultArray = $this->initializeResultArray();
$fieldValues = json_decode($this->data['databaseRow']['answers'], true);
$out = '<ul>';
if (is_array($fieldValues)) {
foreach ($fieldValues as $fieldKey => $fieldValue) {
if ($fieldValue['conf']['label']) {
$out .= '<li>'.$fieldValue['conf']['label'].' - '.(is_array($fieldValue['value']) ? implode(",", htmlspecialchars($fieldValue['value'])) : htmlspecialchars($fieldValue['value'])).'</li>';
} else {
$out .= '<li>'.$fieldKey.' - '.(is_array($fieldValue['value']) ? implode(",", htmlspecialchars($fieldValue['value'])) : htmlspecialchars($fieldValue['value'])).'</li>';
}
}
}
$out .= '</ul>';
$resultArray['html'] = $out;
return $resultArray;
}
}
@@ -0,0 +1,27 @@
<?php
namespace Frappant\FrpFormAnswers\TypoScript;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
class CustomConditionFunctionsProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions()
{
return [
$this->getWebserviceFunction(),
];
}
protected function getWebserviceFunction(): ExpressionFunction
{
return new ExpressionFunction('BeUserHasAccessRights', function () {
// Not implemented, we only use the evaluator
}, function () {
return (is_object($GLOBALS['BE_USER']) ? ($GLOBALS['BE_USER']->isAdmin() || $GLOBALS['BE_USER']->check('modules', 'web_FrpFormAnswersFormanswers')) : false);
});
}
}
@@ -0,0 +1,109 @@
<?php
namespace Frappant\FrpFormAnswers\Utility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Backend\Utility\BackendUtility as BackendUtilityCore;
use TYPO3\CMS\Frontend\Page\PageRepository;
/**
* Class BackendUtility
*/
class BackendUtility extends BackendUtilityCore
{
/**
* Check if backend user is admin
*
* @return bool
*/
public static function isBackendAdmin()
{
if (isset(self::getBackendUserAuthentication()->user)) {
return self::getBackendUserAuthentication()->user['admin'] === 1;
}
return false;
}
/**
* Filter a pid array with only the pages that are allowed to be viewed from the backend user.
* If the backend user is an admin, show all of course - so ignore this filter.
*
* @param array $pids
* @return array
*/
public static function filterPagesForAccess(array $pids)
{
if (!self::isBackendAdmin()) {
$pageRepository = GeneralUtility::makeInstance(PageRepository::class);
if (version_compare(TYPO3_branch, '10', '<')) {
$expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('pages')
->expr()
;
$oldExpression = $expressionBuilder->lt('pages.doktype', 200);
$newExpression = $expressionBuilder->neq('pages.doktype', PageRepository::DOKTYPE_RECYCLER);
$pageRepository->where_hid_del = str_replace(
$oldExpression,
$newExpression,
$pageRepository->where_hid_del
);
}
$newPids = [];
foreach ($pids as $pid) {
$page = $pageRepository->getPage($pid);
if (self::getBackendUserAuthentication()->doesUserHaveAccess($page, 1)) {
$newPids[] = $pid;
}
}
$pids = $newPids;
}
return $pids;
}
/**
* @return BackendUserAuthentication
* @SuppressWarnings(PHPMD.Superglobals)
*/
protected static function getBackendUserAuthentication()
{
return $GLOBALS['BE_USER'];
}
/**
* Get current PID in backend.
* Uses various fallbacks depending on current view and backend module.
* ToDo: Ask somebody, how this can be done simple :)
*/
public static function getCurrentPid($pageUid = null)
{
if (!$pageUid) {
$pageUid = (int) $GLOBALS['_REQUEST']['popViewId'];
}
if (!$pageUid) {
$pageUid = (int) preg_replace('/(.*)(id=)([0-9]*)(.*)/i', '\\3', $GLOBALS['_REQUEST']['returnUrl']);
}
if (!$pageUid) {
$pageUid = (int) preg_replace('/(.*)(id=)([0-9]*)(.*)/i', '\\3', $GLOBALS['_POST']['returnUrl']);
}
if (!$pageUid) {
$pageUid = (int) preg_replace('/(.*)(id=)([0-9]*)(.*)/i', '\\3', $GLOBALS['_GET']['returnUrl']);
}
if (!$pageUid) {
$pageUid = (int) $GLOBALS['TSFE']->id;
}
if (!$pageUid) {
$pageUid = (int) $_GET['id'];
}
if (!$pageUid) {
//$pageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Domain\Repository\PageRepository::class);
//list($page) = $pageRepository->getSubpagesForPages([0]);
//$pageUid = intval($page['uid']);
$pageUid = 0;
}
return $pageUid;
}
}
@@ -0,0 +1,79 @@
<?php
namespace Frappant\FrpFormAnswers\Utility;
class FormAnswersUtility
{
/**
* formEntryRepository
*
* @var \Frappant\FrpFormAnswers\Domain\Repository\FormEntryRepository
* @TYPO3\CMS\Extbase\Annotation\Inject
*/
protected $formEntryRepository = null;
/**
* pageRepository
*
* @var \TYPO3\CMS\Frontend\Page\PageRepository
* @TYPO3\CMS\Extbase\Annotation\Inject
*/
protected $pageRepository = null;
/**
* [prepareFormAnswersArray description]
* @return [type] [description]
*/
public function prepareFormAnswersArray()
{
$act_pid = (int)\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('id');
$pageIds = array();
// Get a List from FormEntries in subpages
$startPointPids = ($act_pid > 0 ? [$act_pid] : $GLOBALS['BE_USER']->returnWebmounts());
// Get all Pids with a formEntry list
foreach ($startPointPids as $pageId) {
foreach ($this->formEntryRepository->findAllInPidAndRootline($pageId) as $formEntry) {
$pageIds[$formEntry->getPid()][$formEntry->getForm()]['tot'] += 1;
if (!$formEntry->isExported()) {
$pageIds[$formEntry->getPid()][$formEntry->getForm()]['new'] += 1;
}
}
}
unset($pageIds[(int)\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('id')]);
return $pageIds;
}
/**
* Get all names of the saved Forms
* @return array Formnames
*/
public function getAllFormNames()
{
$allFormAnswers = $this->formEntryRepository->findAll();
$formNames = [];
// Get FormNames from this page. We will separate them in the list View
foreach ($allFormAnswers as $answer) {
$formNames[$answer->getForm()] = $answer->getForm();
}
return array_keys($formNames);
}
/**
* Get all hashes of the saved Forms
* @return array Formhashes
*/
public function getAllFormHashes()
{
$allFormAnswers = $this->formEntryRepository->findAll();
$formHashes = [];
// Get FormNames from this page. We will separate them in the list View
foreach ($allFormAnswers as $answer) {
$formHashes[$answer->getFieldHash()] = $answer->getFieldHash();
}
return array_keys($formHashes);
}
}
@@ -0,0 +1,59 @@
<?php
namespace Frappant\FrpFormAnswers\Utility;
class FormExportUtility
{
/**
* tableName
*
* @var \PHPExcel
*/
private static $phpExcel = null;
public function __construct()
{
$this -> phpExcel = new \PHPExcel();
}
/**
* function export
* @var array $formEntries
*/
public function export($formEntries)
{
$rows = array();
$header = array();
foreach ($formEntries as $entry) {
$rows[$entry->getUid()] = (array)json_decode($entry->getAnswers());
}
$header = array_keys(array_values($rows)[0]);
// PHPExcel does not work with associative arrays - then to indexed array
foreach ($rows as $key => $value) {
self::setIndexedArray($rows[$key]);
}
array_unshift($rows, $header);
$this->phpExcel->setActiveSheetIndex(0);
$this->phpExcel->getActiveSheet()->fromArray($rows, null, 'A1');
$objWriter = \PHPExcel_IOFactory::createWriter($this->phpExcel, 'Excel2007');
$objWriter->save('php://output');
}
/**
* function setIndexedArray
* Sets an associative array to an indexed array
* @var array $arr
*/
private function setIndexedArray(&$arr)
{
$arr = array_values($arr);
}
}
@@ -0,0 +1,105 @@
<?php
namespace Frappant\FrpFormAnswers\View\FormEntry;
/***************************************************************
*
* Copyright notice
*
* (c) 2016 !frappant <[email protected]>
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* ExportCSV
*/
class ExportCsv extends \TYPO3\CMS\Extbase\Mvc\View\AbstractView
{
/**
* Delimiter Array
* @var array
*/
protected $delimiter = array(
'komma' => ',',
'semikolon' => ';',
'tab' => '\t'
);
/**
* Enclosure Array
* @var array
*/
protected $enclosure = array(
'single' => '\'',
'double' => '"'
);
public function initializeView()
{
$this->controllerContext->getResponse()->setHeader('Content-Type', 'application/force-download');
$this->controllerContext->getResponse()->setHeader('Content-Type', 'text/csv');
$this->controllerContext->getResponse()->setHeader('Content-Disposition', 'attachment;filename=export.csv');
$this->controllerContext->getResponse()->setHeader('Content-Transfer-Encoding', 'binary');
$this->controllerContext->getResponse()->setHeader("Content-Type", "application/download; charset=$this->variables['formEntryDemand']->getCharset()");
}
public function render()
{
foreach ($this->variables['rows'] as $fields) {
$this->fputcsv2(
$fields,
$this->delimiter[$this->variables['formEntryDemand']->getDelimiter()],
$this->enclosure[$this->variables['formEntryDemand']->getEnclosure()]
);
}
}
/**
* function fputscv2
* Funktion gem. php.net
* Behebt mögliche Fehlerfälle der ursprünglichen Funktion fputcsv
* @param array $fields
* @param string $delimiter
* @param string $enclosure
* @param boolean $mysql_null
* @return void
*/
private function fputcsv2(array $fields, $delimiter = ';', $enclosure = '"', $mysql_null = false)
{
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ($fields as $field) {
if ($field === null && $mysql_null) {
$output[] = 'NULL';
continue;
}
if ($field instanceof \DateTime) {
$field = $field->format('r');
}
$output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? (
$enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure
) : $field;
}
echo join($delimiter, $output) . "\n";
}
}
@@ -0,0 +1,81 @@
<?php
namespace Frappant\FrpFormAnswers\View\FormEntry;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use TYPO3\CMS\Extbase\Mvc\View\AbstractView;
/***************************************************************
*
* Copyright notice
*
* (c) 2016 !frappant <[email protected]>
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* ExportXls
*/
class ExportXls extends AbstractView
{
/**
* Spreadsheet
*
* @var \PhpOffice\PhpSpreadsheet\Spreadsheet
* @TYPO3\CMS\Extbase\Annotation\Inject
*/
private $spreadsheet;
public function initializeView()
{
$this->controllerContext->getResponse()->setHeader('Content-Type', 'application/force-download');
$this->controllerContext->getResponse()->setHeader('Content-Disposition', 'attachment;filename=export.xlsx');
$this->controllerContext->getResponse()->setHeader('Content-Type', 'application/download; charset=$this->variables[\'formEntryDemand\']->getCharset()');
}
/**
* @return string|void
* @throws \PhpOffice\PhpSpreadsheet\Exception
* @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
*/
public function render()
{
$rows = $this->variables['rows'];
// PHPExcel does not work with associative arrays - then to indexed array
foreach ($rows as $key => $value) {
$this->setIndexedArray($rows[$key]);
}
$this->spreadsheet->getActiveSheet()->fromArray($rows, null, 'A1');
$objWriter = new Xlsx($this->spreadsheet);
$objWriter->save('php://output');
}
/**
* function setIndexedArray
* Sets an associative array to an indexed array
*/
private function setIndexedArray(&$arr)
{
$arr = array_values($arr);
}
}
@@ -0,0 +1,104 @@
<?php
namespace Frappant\FrpFormAnswers\View\FormEntry;
/***************************************************************
*
* Copyright notice
*
* (c) 2016 !frappant <[email protected]>
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* ExportXls
*/
class ExportXml extends \TYPO3\CMS\Extbase\Mvc\View\AbstractView
{
public function initializeView()
{
$this->controllerContext->getResponse()->setHeader('Content-Type', 'application/force-download');
$this->controllerContext->getResponse()->setHeader('Content-Type', 'application/xml');
$this->controllerContext->getResponse()->setHeader('Content-Disposition', 'attachment;filename=export.xml');
$this->controllerContext->getResponse()->setHeader('Content-Transfer-Encoding', 'binary');
$this->controllerContext->getResponse()->setHeader("Content-Type", "application/download; charset=$this->variables['formEntryDemand']->getCharset()");
}
public function render()
{
$rows = $this->variables['rows'];
// remove header line
$this->array_shift($rows);
// write xml header
echo "<?xml version='1.0' standalone='yes'?>\n";
// write tableName
echo "<tx_frpformanswers_domain_model_formentry>\n";
// write all array rows - inner Array in separated function
for ($i = 0; $i < count($rows); $i++) {
echo $this->arr2xml($rows[$i], $i);
}
// close tableName
echo "</tx_frpformanswers_domain_model_formentry>\n";
}
/**
* function array_shift
* Function array_shift with resetting the key values (Indexed!)
* @param array $arr
*/
protected function array_shift(&$arr)
{
array_shift($arr);
$rows = array_values($arr);
}
/**
* function arr2xml
* Sets an associative Array into an XML Element
* @var array $arr
* @param int $index
* @return string The xml Tag
*/
protected function arr2xml($arr, $index)
{
// open row
$str = "\t<row index=\"".$index."\" type=\"array\">\n";
// put value in row
foreach ($arr as $field => $value) {
// consider crdate
if ($value instanceof \DateTime) {
$value = $value->format('c');
}
$str .= "\t\t<".$field.">".htmlspecialchars(stripslashes($value))."</".$field.">\n";
}
// close row
$str .= "\t</row>\n";
return $str;
}
}
@@ -0,0 +1,85 @@
<?php
namespace Frappant\FrpFormAnswers\ViewHelpers\Be\Link;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Backend\Routing\UriBuilder;
/***************************************************************
*
* Copyright notice
*
* (c) 2016 !frappant <[email protected]>
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* Renders a link for a new record.
*
* /typo3/index.php?route=/record/edit&token=d7b2e14e24824711081ee8731549ca58afac0648&edit[tx_frpredirects_domain_model_redirect][2]=edit&returnUrl=/typo3/index.php?M=web_list&moduleToken=ae0ea6fabda3a2a34a8873319b91f8dc6010bf2f&id=0&imagemode=1
*/
class BeLinkViewHelper extends \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper
{
/**
* @var string
*/
protected $tagName = 'a';
/**
* Arguments initialization
*
* @return void
*/
public function initializeArguments()
{
$this->registerUniversalTagAttributes();
$this->registerTagAttribute('name', 'string', 'Specifies the name of an anchor');
$this->registerTagAttribute('rel', 'string', 'Specifies the relationship between the current document and the linked document');
$this->registerTagAttribute('rev', 'string', 'Specifies the relationship between the linked document and the current document');
$this->registerTagAttribute('target', 'string', 'Specifies where to open the linked document');
$this->registerTagAttribute('pageUid', 'int', 'Page Uid');
}
public function render()
{
$returnUrl = $this->getRequestUri();
$urlParameters = [
'returnUrl' => $returnUrl,
'id' => $this->arguments['pageUid']
];
$uri = $this->getModuleUrl($urlParameters);
$this->tag->addAttribute('href', $uri);
$this->tag->setContent($this->renderChildren());
$this->tag->forceClosingTag(true);
return $this->tag->render();
}
protected function getRequestUri()
{
return GeneralUtility::getIndpEnv('REQUEST_URI');
}
protected function getModuleUrl(array $urlParameters)
{
$uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
return $uriBuilder->buildUriFromRoute('web_FrpFormAnswersFormanswers',$urlParameters);
}
}