deblan.tv/vendor/trinity/src/Trinity/.svn/pristine/e1/e1b873511f1308978aecab5748930c16e930ddc9.svn-base
2015-03-02 21:57:49 +01:00

836 lines
28 KiB
Plaintext

<?php
namespace Trinity\Bundle\AdminBundle\Controller;
use \BasePeer;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\File\File;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Pagerfanta\Adapter\PropelAdapter;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Exception\NotValidCurrentPageException;
use Trinity\Bundle\AdminBundle\Exception\FilterMethodNotFoundException;
use Trinity\Bundle\AdminBundle\Form\Type\BatchType;
use Trinity\Bundle\AdminBundle\Form\Type\RankType;
use Trinity\Bundle\UserBundle\Flash\FlashError;
use Trinity\Bundle\UserBundle\Flash\FlashSuccess;
use Trinity\Bundle\UserBundle\Flash\FlashWarning;
use Trinity\Bundle\AdminBundle\Exception\RequestAdminException;
use Trinity\Component\Utils\Propel;
/**
* @Route("/admin")
*/
class BaseAdminController extends Controller
{
const UPLOAD_INTERFACE = 'Trinity\Component\File\FileUploadInterface';
const HISTORY_LIMIT = 10;
protected $configuration;
public function flashAction()
{
$user = $this->getSessionUser();
if (!$user->hasFlash('message', $this->getConfiguration()->getStorageNamespace())) {
return new Response();
}
$flash = $user->getFlash(
'message',
$this->getConfiguration()->getStorageNamespace()
);
return $this->render(
$flash->getTemplate(),
array(
'message' => $flash->getMessage()
)
);
}
public function filtersAction($route_prefix)
{
return $this->render(
'TrinityAdminBundle:BaseAdmin:filters.html.twig',
array(
'form_filter' => $this->getFormFilter()->createView(),
'filter_display_fields' => $this->getConfiguration()->getFilterDisplayFields(),
'filters_templates' => $this->getConfiguration()->getFiltersTemplates(),
'user_has_filter' => $this->getSessionUser()->getAttribute('filter', false, $this->getConfiguration()->getStorageNamespace()),
'route_prefix' => $route_prefix,
)
);
}
public function historyAction($route_prefix)
{
$query = $this->getQuery();
try {
$query->orderByUpdatedAt(\Criteria::DESC);
} catch (\PropelException $e) {
}
$query->limit(self::HISTORY_LIMIT);
return $this->render(
'TrinityAdminBundle:BaseAdmin:history.html.twig',
array(
'objects' => $query->find(),
'route_prefix' => $route_prefix,
)
);
}
protected function getQuery()
{
$model_query = $this->getConfiguration()->getModelQuery();
return $model_query::create();
}
protected function addSortToQuery(&$query)
{
if (!$this->getConfiguration()->getSortOrder()) {
return false;
}
$method = $this->getConfiguration()->getSort();
$method = $this->getConfiguration()->getRankable() ? 'orderByRank' : $this->configuration->getSort();
if (!$method) {
return false;
}
try {
call_user_func(array($query, $method), $this->getConfiguration()->getSortOrder());
} catch (\PropelException $e) {
}
return true;
}
protected function getFilters(Request $request, $filtersMethods = array())
{
$datas = [];
foreach($filtersMethods as $field => $filterMethod) {
if(isset($filterMethod['value'])) {
$datas[$field] = $filterMethod['value'];
}
}
$datas = array_merge(
$datas,
$request->request->get($this->getFormFilter(true)->getName(), array())
);
if (!empty($datas)) {
return $datas;
}
return $this->getSessionUser()->getAttribute(
'filter',
array(),
$this->getConfiguration()->getStorageNamespace()
);
}
protected function addFiltersToQuery(&$query, Request $request)
{
$form = $this->getFormFilter(true);
$filters_methods = $this->getConfiguration()->getFiltersMethods();
$datas = $this->getFilters($request, $filters_methods);
if (!is_array($datas)) {
return false;
}
$datas = $this->cleanFilterArray($datas);
foreach ($datas as $field => $value) {
$method = isset($filters_methods[$field]) ? $filters_methods[$field]['method'] : 'filterBy'.Propel::camelCase($field);
$criteria = isset($filters_methods[$field]) ? $filters_methods[$field]['criteria'] : (is_numeric($value) && intval($value) == $value ? null : 'like');
$params = isset($filters_methods[$field]) ? $filters_methods[$field]['value'] : null;
if(null !== $params) {
$value = $params;
}
;
if (!method_exists($this->getConfiguration()->getModelQuery(), $method)) {
throw new FilterMethodNotFoundException(sprintf('Filter method "%s" does not exist in class "%s"', $method, $this->getConfiguration()->getModelQuery()));
}
if (strtolower($criteria) == 'like') {
$value = '%'.$value.'%';
$criteria = null;
}
if ($value !== 'bool.both' && $value !== '%bool.both%') {
$bools = array(
'bool.true' => true,
'bool.false' => false,
'%bool.true%' => true,
'%bool.false%' => false,
);
if (isset($bools[$value])) {
$value = $bools[$value];
}
try {
$this->get('logger')->info(sprintf('Filter by "%s" with "%s", criteria: %s', $method, $value, $criteria ? $criteria : 'NULL'));
$call_params = array_merge($criteria !== null ? array($value, $criteria) : array($value), (array) $value);
call_user_func_array(array($query, $method), $call_params);
} catch (\PropelException $e) {
}
} else {
unset($datas[$field]);
}
}
$this->getSessionUser()->setAttribute('filter', $datas, $this->getConfiguration()->getStorageNamespace());
$form->bind($datas);
return $form;
}
protected function getPager(Request $request)
{
$query = $this->getQuery();
$query->distinct();
$this->addSortToQuery($query);
$this->addFiltersToQuery($query, $request);
$adapter = new PropelAdapter($query);
$pagerfanta = new Pagerfanta($adapter);
$pagerfanta->setMaxPerPage($this->getConfiguration()->getMaxPerPage());
try {
$pagerfanta->setCurrentPage($this->getConfiguration()->getCurrentPage(), false, true);
} catch (NotValidCurrentPageException $e) {
$pagerfanta->setCurrentPage(1, false, true);
}
return $pagerfanta;
}
protected function getFields()
{
$model_peer = $this->getConfiguration()->getModelPeer();
$peerFields = $model_peer::getFieldNames(BasePeer::TYPE_FIELDNAME);
$peerFieldsCb = $model_peer::getFieldNames();
$fields = array();
$final_fields = array();
$display_fields = $this->getConfiguration()->getDisplayFields();
$fields_templates = $this->getConfiguration()->getFieldsTemplates();
if (!empty($display_fields)) {
$array_push_before = function(array $array, $data, $pos){
return array_merge(array_slice($array, 0, $pos), array($data), array_slice($array, $pos));
};
foreach ($display_fields as $k => $display_field) {
if (!in_array($display_field, $peerFields)) {
$method = ucfirst($display_field);
$peerFields = $array_push_before($peerFields, $display_field, $k);
$peerFieldsCb = $array_push_before($peerFieldsCb, $method, $k);
}
}
}
$fieldNames = new \ArrayIterator($peerFields);
$fieldNamesCb = new \ArrayIterator($peerFieldsCb);
while ($fieldNames->valid()) {
if (empty($display_fields) || (!empty($display_fields) && in_array($fieldNames->current(), $display_fields))) {
$data = array(
'name' => $fieldNames->current(),
'method' => Propel::getGetter($fieldNamesCb->current()),
'template' => isset($fields_templates[$fieldNames->current()]) ? $fields_templates[$fieldNames->current()] : $this->getConfiguration()->getDefaultFieldTemplate()
);
if (empty($display_fields)) {
$fields[] = $data;
} else {
$keys = array_keys($display_fields, $fieldNames->current());
$fields[$keys[0]] = $data;
}
}
$fieldNames->next();
$fieldNamesCb->next();
}
$k = 0;
while (count($final_fields) !== count($fields)) {
if (isset($fields[$k])) {
$final_fields[] = $fields[$k];
}
$k++;
}
return $final_fields;
}
protected function redirectByRequest(Request $request, $object)
{
$list = array(
'edit_same' => $this->generateUrl(sprintf('%s_edit', $this->getConfiguration()->getRoutePrefix()), array('id' => $object->getId())),
'save_new' => $this->generateUrl(sprintf('%s_new', $this->getConfiguration()->getRoutePrefix())),
);
foreach ($list as $index => $uri) {
if ($request->request->has($index)) {
return $uri;
}
}
throw new RequestAdminException('No valid target (post submit) has been found.');
}
protected function getBatchType()
{
return $this->createForm(new BatchType());
}
protected function getRankType()
{
return $this->createForm(new RankType());
}
protected function processForm(&$form, &$object, Request $request)
{
$form->bind($request);
if ($form->isValid()) {
if ($object instanceof \FOS\UserBundle\Propel\User) {
if ($object->isNew()) {
$new_user = true;
} else {
$updated_user = true;
}
}
$this->preSave($object);
$object->save();
$this->postSave($object);
if (!empty($new_user)) {
$this->get('trinity.user_log')->created($object, $this->getUser());
}
if (!empty($updated_user)) {
$this->get('trinity.user_log')->updated($object, $this->getUser());
}
return $this->redirect($this->redirectByRequest($request, $object));
}
return false;
}
protected function removeObjects($query, array $pks)
{
foreach ($pks as $pk) {
$object = $query->findPK($pk);
$this->preRemove($object);
$object->delete();
$this->postRemove($object);
}
}
protected function copyObjects($query, array $pks)
{
foreach ($pks as $pk) {
$copy = $query->findPK($pk)->copy(true);
$this->preSave($copy);
$copy->save();
$this->postSave($copy);
}
}
protected function processBatchForm(&$form, Request $request)
{
$form->submit($request);
//if ($form->isValid()) {
$values = $request->request->get($form->getName());
if (!empty($values['objects'])) {
$model_query = $this->getConfiguration()->getModelQuery();
$query = new $model_query();
switch ($values['action']) {
case BatchType::BATCH_COPY: $this->copyObjects($query, $values['objects']); break;
case BatchType::BATCH_REMOVE: $this->removeObjects($query, $values['objects']); break;
}
$this->get('logger')->info(sprintf('Batch action (%s)', $values['action']));
return 2;
}
return 1;
//}
return 0;
}
protected function batchAction(Request $request)
{
$form = $this->getBatchType();
$redirect = $this->redirect(
$this->getSessionUser()->getAttribute(
'referer',
$this->generateUrl(sprintf('%s_index', $this->getConfiguration()->getRoutePrefix()), array('page' => 1))
)
);
$proccess = $this->processBatchForm($form, $request);
$namespace = $this->getConfiguration()->getStorageNamespace();
switch ($proccess) {
case 1: $this->getSessionUser()->setFlash('message', new FlashWarning('crud.flash.notselected'), false, $namespace); break;
case 2: $this->getSessionUser()->setFlash('message', new FlashSuccess('crud.flash.updated.plural'), false, $namespace); break;
}
return $redirect;
}
/**
* @Route("/", name="TrinityAdminBundle_index")
*/
public function indexAction($page, Request $request)
{
$this->getConfiguration()->setCurrentPage($page);
$this->getSessionUser()->setAttribute('referer', $request->getRequestUri());
$namespace = $this->getConfiguration()->getStorageNamespace();
$cookieName = $namespace.'_sort';
$sort = '';
if ($request->query->get('sort')) {
$sort = $request->query->get('sort');
} elseif ($cookie = $request->cookies->get($cookieName)) {
$sort = $cookie;
}
if (!empty($sort)) {
$parts = explode(':', $sort);
if (count($parts) == 2) {
list($field, $order) = $parts;
$method = 'orderBy'.Propel::camelCase($field);
$this->getConfiguration()->setSort($method, $order);
$this->get('logger')->info(sprintf('Order by "%s", "%s"', $method, $order));
$cookie = new Cookie($cookieName, $sort, time() + 3600 * 24 * 360);
$response = new Response();
$response->headers->setCookie($cookie);
$response->send();
}
}
if ($format = $request->query->get('format')) {
if ($this->isValidExportFormat($format)) {
return $this->exportTo($format);
}
}
$pager = $this->getPager($request);
if ($this->getFilters($request) && count($pager) === 1 && $this->getConfiguration()->getIndexListAction('edit')) {
$this->getSessionUser()->setAttribute('filter', null, $this->getConfiguration()->getStorageNamespace());
return $this->redirect($this->generateUrl(sprintf('%s_edit',$this->getConfiguration()->getRoutePrefix()), array('id' => $pager->getIterator()->offsetGet(0)->getId())));
}
return array(
'pager' => $pager,
'fields' => $this->getFields(),
'fields_templates' => $this->getConfiguration()->getFieldsTemplates(),
'fields_attrs' => $this->getConfiguration()->getDisplayFieldsAttrs(),
'list_actions' => $this->getConfiguration()->getIndexListActions(),
'index_actions' => $this->getConfiguration()->getIndexActions(),
'batch_actions' => $this->getConfiguration()->getBatchActions(),
'export' => $this->getConfiguration()->getExport(),
'rankable' => $this->getConfiguration()->getRankable(),
'remove_token' => $this->getRemoveToken(true),
'fieldsnames' => $this->getConfiguration()->getFieldsnames(),
'templating' => $this->container->get('templating'),
'form_batch' => $this->getBatchType()->createView(),
'form_rank' => $this->getRankType()->createView(),
'title' => $this->getConfiguration()->getListTitle(),
'i18n' => $this->getConfiguration()->getI18n(),
'i18n_cultures' => $this->getConfiguration()->getI18nCultures(),
'pager_sort' => $sort,
);
}
protected function exportTo($format)
{
$query = $this->getQuery();
$this->addSortToQuery($query);
$this->addFiltersToQuery($query, $this->getRequest());
$render = $this->render(
'TrinityAdminBundle:BaseAdmin:export.html.twig',
array(
'datas' => $query->find()->exportTo($format),
)
);
$render->headers->set('Content-Type', $this->getExportContentTypeByFormat($format));
$render->headers->set('Content-disposition', sprintf('filename="export-%s%s"', time(), $this->getExportExtensionByFormat($format)));
return $render;
}
public function clearFilterAction(Request $request)
{
$redirect = $this->redirect(
$this->getSessionUser()->getAttribute(
'referer',
$this->generateUrl(sprintf('%s_index', $this->getConfiguration()->getRoutePrefix()), array('page' => 1))
)
);
$this->getSessionUser()->setAttribute('filter', null, $this->getConfiguration()->getStorageNamespace());
return $redirect;
}
public function editAction($object, Request $request)
{
if (!$object) {
$this->getSessionUser()->setFlash('message', new FlashWarning('crud.flash.unknown'), false, $this->getConfiguration()->getStorageNamespace());
return $this->redirect($this->generateUrl(sprintf('%s_index',$this->getConfiguration()->getRoutePrefix())));
}
$form = $this->getConfiguration()->getFormEdit();
$form = $this->createForm(new $form($this->getConfiguration()->getFormEditOptions()), $object);
if ('POST' === $request->getMethod()) {
if (false !== $processForm = $this->processForm($form, $object, $request)) {
$this->getSessionUser()->setFlash('message', new FlashSuccess('crud.flash.updated.singular'), false, $this->getConfiguration()->getStorageNamespace());
return $processForm;
}
$this->getSessionUser()->setFlash('message', new FlashError('crud.flash.fail.update'), false, $this->getConfiguration()->getStorageNamespace());
}
return array(
'object' => $object,
'created_at' => (method_exists($object, 'getCreatedAt'))?$object->getCreatedAt('d/m/Y'):null,
'updated_at' => (method_exists($object, 'getUpdatedAt'))?$object->getUpdatedAt('d/m/Y'):null,
'form' => $form->createView(),
'fieldsets' => $this->getConfiguration()->getFieldsets(),
'fieldsnames' => $this->getConfiguration()->getFieldsnames(),
'fields_helpers' => $this->getConfiguration()->getFieldsHelpers(),
'remove_token' => $this->getRemoveToken(true),
'title' => $this->getConfiguration()->getEditTitle($object),
'i18n' => $this->getConfiguration()->getI18n(),
'i18n_cultures' => $this->getConfiguration()->getI18nCultures(),
'collections' => $this->getConfiguration()->getCollections(),
);
}
public function newAction(Request $request)
{
$model = $this->getConfiguration()->getModel();
$object = new $model();
$form = $this->getConfiguration()->getFormNew();
$form = $this->createForm(new $form($this->getConfiguration()->getFormNewOptions()), $object);
if ('POST' === $request->getMethod()) {
if (false !== $processForm = $this->processForm($form, $object, $request)) {
$this->getSessionUser()->setFlash('message', new FlashSuccess('crud.flash.updated.singular'), false, $this->getConfiguration()->getStorageNamespace());
return $processForm;
}
$this->getSessionUser()->setFlash('message', new FlashError('crud.flash.fail.new'), false, $this->getConfiguration()->getStorageNamespace());
}
return array(
'form' => $form->createView(),
'fieldsets' => $this->getConfiguration()->getFieldsets(),
'fieldsnames' => $this->getConfiguration()->getFieldsnames(),
'fields_helpers' => $this->getConfiguration()->getFieldsHelpers(),
'title' => $this->getConfiguration()->getNewTitle(),
'i18n' => $this->getConfiguration()->getI18n(),
'i18n_cultures' => $this->getConfiguration()->getI18nCultures(),
'collections' => $this->getConfiguration()->getCollections(),
);
}
public function removeAction($object, $token, Request $request)
{
if ($object) {
if ($this->getRemoveToken() !== $token) {
$this->getSessionUser()->setFlash('message', new FlashError('crud.flash.token'), false, $this->getConfiguration()->getStorageNamespace());
} else {
try {
$this->preRemove($object);
$object->delete();
$this->postRemove($object);
$this->getSessionUser()->setFlash('message', new FlashSuccess('crud.flash.removed'), false, $this->getConfiguration()->getStorageNamespace());
} catch (PropelException $e) {
$this->getSessionUser()->setFlash('message', new FlashError('crud.flash.fail.remove'), false, $this->getConfiguration()->getStorageNamespace());
}
}
} else {
$this->getSessionUser()->setFlash('message', new FlashWarning('crud.flash.unknown'), false, $this->getConfiguration()->getStorageNamespace());
}
return $this->redirect($this->generateUrl(sprintf('%s_index',$this->getConfiguration()->getRoutePrefix())));
}
public function rankAction(Request $request)
{
$form = $this->getRankType();
$form->bind($request);
if ($form->isValid()) {
$datas = $form->getData();
$ids = explode(' ', $datas['objects']);
$page = $datas['page'];
$query = $this->getQuery();
foreach ($ids as $k => $id) {
$rank = ($this->getConfiguration()->getMaxPerPage() * $page) + $k + 1;
$object = $query->findOneById($id);
if ($object) {
$object->setRank($rank)->save();
}
}
}
return null;
}
protected function getRemoveToken($get_new = false)
{
$attribute_name = 'remove_token_'.$this->getConfiguration()->getModel();
if ($get_new) {
$token = sha1(uniqid().time());
$this->getSessionUser()->setAttribute($attribute_name, $token);
return $token;
}
return $this->getSessionUser()->getAttribute($attribute_name);
}
protected function isValidExportFormat($format)
{
return in_array($format, array('XML', 'CSV', 'JSON', 'YAML'));
}
protected function getExportContentTypeByFormat($format)
{
if (!$this->isValidExportFormat($format)) {
return null;
}
$formats = array(
'XML' => 'text/xml',
'CSV' => 'text/csv',
'JSON' => 'text/json',
'YAML' => 'text/yaml',
);
return $formats[$format];
}
protected function getExportExtensionByFormat($format)
{
if (!$this->isValidExportFormat($format)) {
return null;
}
$formats = array(
'XML' => '.xml',
'CSV' => '.csv',
'JSON' => '.json',
'YAML' => '.yml',
);
return $formats[$format];
}
protected function getFormFilter($new = false)
{
$form = $this->getConfiguration()->getFormFilter() ? $this->configuration->getFormFilter() : $this->configuration->getFormNew();
$form = $this->createForm(new $form($this->getConfiguration()->getFormFilterOptions()));
if (!$new) {
$datas = $this->cleanFilterArray($this->getSessionUser()->getAttribute('filter', array(), $this->getConfiguration()->getStorageNamespace()));
$form->bind($datas);
}
return $form;
}
protected function cleanFilterArray(array $array)
{
foreach ($array as $k => $v) {
if (trim($v) === '') {
unset($array[$k]);
}
}
return $array;
}
public function getConfiguration()
{
if (empty($this->configuration)) {
throw new \LogicException('You must specify a crud configuration.');
}
if (null === $this->configuration->getStorageNamespace()) {
$this->configuration->setStorageNamespace(get_class($this));
}
return $this->configuration;
}
/**
* @Route("/jsTranslations.js", name="TrinityAdminBundle_jsTranslation")
* @Template("TrinityAdminBundle:BaseAdmin:jsTranslation.html.twig")
*/
public function jsTranslationAction(Request $request)
{
}
public function getUser()
{
if (!$this->container->has('security.context')) {
throw new \LogicException('The SecurityBundle is not registered in your application.');
}
if (null === $token = $this->container->get('security.context')->getToken()) {
return null;
}
if (!is_object($user = $token->getUser())) {
return null;
}
if (method_exists($user, 'setStorage')) {
$user->setStorage($this->container->get('trinity.storage'));
}
return $user;
}
public function getSessionUser()
{
return $this->container->get('trinity.session_user');
}
public function preSave($object)
{
}
public function postSave($object, $was_new = false)
{
}
public function preRemove($object)
{
}
public function postRemove($object)
{
}
public function postDelete($object)
{
return $this->postRemove($object);
}
public function preDelete($object)
{
return $this->preRemove($object);
}
public function cleanString($text)
{
$text = preg_replace('`</?[^>]+>`U', '', $text);
$encoding = mb_detect_encoding($text);
$text = str_replace(array('&nbsp;', '&rsquo;'), ' ',$text);
$text = html_entity_decode(strip_tags($text));
if ($encoding!='UTF-8') $text = utf8_encode($text);
$text = str_replace(
array(
'à', 'â', 'ä', 'á', 'ã', 'å',
'î', 'ï', 'ì', 'í',
'ô', 'ö', 'ò', 'ó', 'õ', 'ø',
'ù', 'û', 'ü', 'ú',
'é', 'è', 'ê', 'ë',
'ç', 'ÿ', 'ñ',
'À', 'Â', 'Ä', 'Á', 'Ã', 'Å',
'Î', 'Ï', 'Ì', 'Í',
'Ô', 'Ö', 'Ò', 'Ó', 'Õ', 'Ø',
'Ù', 'Û', 'Ü', 'Ú',
'É', 'È', 'Ê', 'Ë',
'Ç', 'Ÿ', 'Ñ',
'\'', '"',
' ', ' ', ' ', ' ', ' '
),
array(
'a', 'a', 'a', 'a', 'a', 'a',
'i', 'i', 'i', 'i',
'o', 'o', 'o', 'o', 'o', 'o',
'u', 'u', 'u', 'u',
'e', 'e', 'e', 'e',
'c', 'y', 'n',
'A', 'A', 'A', 'A', 'A', 'A',
'I', 'I', 'I', 'I',
'O', 'O', 'O', 'O', 'O', 'O',
'U', 'U', 'U', 'U',
'E', 'E', 'E', 'E',
'C', 'Y', 'N',
' ', ' ',
' ', ' ', ' ', ' ', ' '
),$text);
return strtolower($text);
}
}