1: <?php
2: namespace TIC\MailBundle\Controller;
3:
4: use TIC\CoreBundle\Base\TICController as BaseController;
5: #use TIC\DormBundle\Traits\ControllerCrudable;
6: use TIC\DormBundle\Traits\ControllerItemable;
7: use TIC\TwigBundle\Traits\ControllerViewable;
8:
9: use Symfony\Component\Routing\Annotation\Route;
10: use Symfony\Component\HttpFoundation\Request;
11: use Symfony\Component\HttpFoundation\Response;
12: use Symfony\Component\HttpFoundation\RedirectResponse;
13: use Symfony\Component\HttpFoundation\StreamedResponse;
14: use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
15: use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
16:
17: use TIC\MailBundle\Service\MailerService;
18:
19: /**
20: * Administration des modèles de notification par email.
21: *
22: * @Route("/")
23: * @IsGranted("ROLE_ADMIN")
24: */
25: class TemplateController extends BaseController
26: {
27: # use ControllerCrudable;
28: use ControllerItemable, ControllerViewable;
29:
30: /**
31: * Liste des modèles de notification existants.
32: *
33: * @Route("/list", name="ticmail_template_list")
34: * @Security("is_granted('ROLE_TICMAIL_VIEW')")
35: */
36: public function list(Request $request): Response
37: {
38: // recherche si des modèles restent à définir
39: $missings = $this->getRepo()->listAvailableRefs($this->getParameter('tic_mail.templates'));
40: if (\count($missings)) $this->alert('warning', array(
41: 'title' => 'ticmail.alert.undefined_templates',
42: 'extra' => \implode(", ", $missings),
43: ));
44:
45: // génération du formulaire (modal import)
46: $form_import = null;
47: if ($this->checkRole('TICMAIL_EDIT')) {
48: $this->ctxForm = 'TIC\MailBundle\Form\TemplateImportType';
49: $form_import = $this->getForm(null, $request, array(
50: 'action' => $this->generateUrl('ticmail_template_import'),
51: ));
52: }
53:
54: // affichage de la liste
55: return $this->renderAction('list', array(
56: 'items' => $this->getRepo()->listAll(),
57: 'missings' => $missings,
58: 'form_import' => $form_import,
59: ));
60: }
61:
62: /**
63: * Fiche détaillée d'un modèle de notification.
64: *
65: * @Route("/show/{id}", name="ticmail_template_show")
66: * @Security("is_granted('ROLE_TICMAIL_VIEW')")
67: */
68: public function show(Request $request, MailerService $mailer, $id): Response
69: {
70: $config = $this->getParameter('tic_mail.config');
71: return $this->renderAction('show', array(
72: 'item' => $this->getItem($id),
73: 'admins' => $config['admins'],
74: 'return' => $config['return'],
75: 'sender' => \sprintf('"%s" <%s>', $config['fromname'], $config['fromaddr']),
76: 'locales' => $mailer->getLocales(),
77: 'deflocale' => $this->getParameter('kernel.default_locale'),
78: ));
79: }
80:
81: /**
82: * Formulaire d'édition d'un modèle (création ou modification).
83: *
84: * @Route("/create", name="ticmail_template_create")
85: * @Route("/update/{id}", name="ticmail_template_update")
86: * @Security("is_granted('ROLE_TICMAIL_EDIT')")
87: */
88: public function form(Request $request, MailerService $mailer, $id = null): Response
89: {
90: $item = $this->getItem($id);
91:
92: // génération du formulaire
93: $config = $this->getParameter('tic_mail.config');
94: $form = $this->getForm($item, $request, array(
95: 'list_refs' => $this->getRepo()->listAvailableRefs($this->getParameter('tic_mail.templates'), $item->getRef()),
96: 'admins' => $config['admins'],
97: 'return' => $config['return'],
98: 'sender' => \sprintf('"%s" &lt;%s&gt;', $config['fromname'], $config['fromaddr']),
99: 'targets' => $this->getRepo()->getTargets(),
100: 'formats' => $config['formats'],
101: 'locales' => $mailer->getLocales(),
102: 'deflocale' => $this->getParameter('kernel.default_locale'),
103: ));
104:
105: // validation du formulaire
106: if ($form->isSubmitted() and $form->isValid()) return $this->saveItem($item, true);
107:
108: // affichage du formulaire
109: return $this->renderAction('form', array(
110: 'form' => $form,
111: 'item' => $item,
112: 'vars' => $this->getVars($item->getRef()),
113: ));
114: }
115:
116: /**
117: * Action d'activation/désactivation de propriétés.
118: *
119: * @Route("/{id}/toggle/{field}/{state}", name="ticmail_template_toggle", defaults={"state":null},
120: * requirements={"field":"enabled|bccAdmins"})
121: * @Security("is_granted('ROLE_TICMAIL_EDIT')")
122: */
123: public function toggle(Request $request, $id, $field, $state = null): Response
124: {
125: // modification de la propriété, enregistrement avec message et redirection par défaut (referer)
126: return $this->toggleItem($this->getItem($id), $field, $state);
127: }
128:
129: /**
130: * Suppression d'un modèle de notification existant.
131: *
132: * @Route("/delete/{id}", name="ticmail_template_delete")
133: * @Security("is_granted('ROLE_TICMAIL_FULL')")
134: */
135: public function delete(Request $request, $id): Response
136: {
137: # return $this->crudDelete($request, $id);
138: $item = $this->getItem($id);
139:
140: if (false === $this->checkCSRF('delete'.$id, $request))
141: return $this->alert('danger', "error.csrf.invalid_token", $item);
142:
143: return $this->deleteItem($item, true);
144: }
145:
146: /**
147: * Export des données d'un modèle donné ou de tous les modèles.
148: * Note : utilisation des formats Mail (MIME) et Mbox pour la concaténation des messages
149: *
150: * @Route("/export/{id}", name="ticmail_template_export", defaults={"id"="0"})
151: * @Security("is_granted('ROLE_TICMAIL_VIEW')")
152: */
153: public function export(Request $request, $id = null)
154: {
155: return new StreamedResponse(function() use ($id) {
156: if (empty($id)) {
157: foreach ($this->getRepo()->listAll() as $item) echo $item->exportMail();
158: } else {
159: $item = $this->getItem($id);
160: if ($item) echo $item->exportMail();
161: }
162: }, 200, array(
163: 'Content-Disposition' => \sprintf('attachment; filename="templates-%s.eml";', \date('Ymd_His')),
164: ));
165: }
166:
167: /**
168: * Import des données de modèles uploadés au format Mail/Mbox (cf export).
169: *
170: * @Route("/import", name="ticmail_template_import")
171: * @Security("is_granted('ROLE_TICMAIL_EDIT')")
172: */
173: public function import(Request $request): RedirectResponse
174: {
175: // génération du formulaire d'import
176: $this->ctxForm = 'TIC\MailBundle\Form\TemplateImportType';
177: $form = $this->getForm(null, $request);
178:
179: // validation du formulaire d'import
180: if ($form->isValid()) {
181: $file = $form->get('messages')->getData()->openFile('r');
182: $rc = $this->getRepo()->importMail($file);
183: if ($rc === true) return $this->alert('success', 'ticmail.alert.templates_import_ok', true);
184: if ($rc === null) return $this->alert('warning', 'ticmail.alert.templates_import_no', true);
185: return $this->alert('danger', array('title'=>'ticmail.alert.templates_import_err', 'text'=>$rc), true);
186: }
187:
188: // affichage de la liste (contenant le formulaire d'import en modal)
189: return $this->alert('warning', 'ticmail.alert.templates_import_no', true);
190: }
191:
192: /**
193: * Récupération des variables utilisables pour un modèle donnée.
194: *
195: * @param string $ref Référence du modèle édité.
196: * @return array Liste des variables rangées par groupes
197: */
198: protected function getVars(string $ref = null): ?array
199: {
200: if ($ref === null) return null;
201:
202: $vargroups = $this->getParameter('tic_mail.vargroups');
203: $variables = $this->getParameter('tic_mail.variables');
204:
205: if (! \is_array($vargroups)) return null;
206: if (! \is_array($variables)) return null;
207: if (! \array_key_exists($ref, $vargroups)) return null;
208: if (! \is_array($vargroups[ $ref ])) return null;
209:
210: $vars = array();
211: foreach ($vargroups[ $ref ] as $group) {
212: if (\is_array($group)) $vars['_'] = $group;
213: elseif (\array_key_exists($group, $variables)) $vars[ $group ] = $variables[ $group ];
214: }
215: return $vars;
216: }
217:
218: }
219: