| Total Complexity | 140 |
| Total Lines | 1010 |
| Duplicated Lines | 0 % |
| Changes | 3 | ||
| Bugs | 0 | Features | 2 |
Complex classes like SparkPostAdmin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SparkPostAdmin, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 50 | class SparkPostAdmin extends LeftAndMain implements PermissionProvider |
||
| 51 | { |
||
| 52 | |||
| 53 | const MESSAGE_CACHE_MINUTES = 5; |
||
| 54 | const WEBHOOK_CACHE_MINUTES = 1440; // 1 day |
||
| 55 | const SENDINGDOMAIN_CACHE_MINUTES = 1440; // 1 day |
||
| 56 | |||
| 57 | private static $menu_title = "SparkPost"; |
||
|
|
|||
| 58 | private static $url_segment = "sparkpost"; |
||
| 59 | private static $menu_icon = "sparkpost/images/sparkpost-icon.png"; |
||
| 60 | private static $url_rule = '/$Action/$ID/$OtherID'; |
||
| 61 | private static $allowed_actions = [ |
||
| 62 | 'settings', |
||
| 63 | 'SearchForm', |
||
| 64 | 'doSearch', |
||
| 65 | "doInstallHook", |
||
| 66 | "doUninstallHook", |
||
| 67 | "doInstallDomain", |
||
| 68 | "doUninstallDomain", |
||
| 69 | "send_test", |
||
| 70 | ]; |
||
| 71 | |||
| 72 | private static $cache_enabled = true; |
||
| 73 | |||
| 74 | /** |
||
| 75 | * @var bool |
||
| 76 | */ |
||
| 77 | protected $subaccountKey = false; |
||
| 78 | |||
| 79 | /** |
||
| 80 | * @var Exception |
||
| 81 | */ |
||
| 82 | protected $lastException; |
||
| 83 | |||
| 84 | /** |
||
| 85 | * @var ViewableData |
||
| 86 | */ |
||
| 87 | protected $currentMessage; |
||
| 88 | |||
| 89 | /** |
||
| 90 | * Inject public dependencies into the controller |
||
| 91 | * |
||
| 92 | * @var array |
||
| 93 | */ |
||
| 94 | private static $dependencies = [ |
||
| 95 | 'logger' => '%$Psr\Log\LoggerInterface', |
||
| 96 | 'cache' => '%$Psr\SimpleCache\CacheInterface.sparkpost', // see _config/cache.yml |
||
| 97 | ]; |
||
| 98 | |||
| 99 | /** |
||
| 100 | * @var Psr\Log\LoggerInterface |
||
| 101 | */ |
||
| 102 | public $logger; |
||
| 103 | |||
| 104 | /** |
||
| 105 | * @var Psr\SimpleCache\CacheInterface |
||
| 106 | */ |
||
| 107 | public $cache; |
||
| 108 | |||
| 109 | public function init() |
||
| 110 | { |
||
| 111 | parent::init(); |
||
| 112 | |||
| 113 | if (isset($_GET['refresh'])) { |
||
| 114 | $this->getCache()->clear(); |
||
| 115 | } |
||
| 116 | } |
||
| 117 | |||
| 118 | public function index($request) |
||
| 119 | { |
||
| 120 | return parent::index($request); |
||
| 121 | } |
||
| 122 | |||
| 123 | public function settings($request) |
||
| 124 | { |
||
| 125 | return parent::index($request); |
||
| 126 | } |
||
| 127 | |||
| 128 | public function send_test($request) |
||
| 129 | { |
||
| 130 | if (!$this->CanConfigureApi()) { |
||
| 131 | return $this->httpError(404); |
||
| 132 | } |
||
| 133 | $service = DefaultAdminService::create(); |
||
| 134 | $to = $request->getVar('to'); |
||
| 135 | if (!$to) { |
||
| 136 | $to = $service->findOrCreateDefaultAdmin()->Email; |
||
| 137 | } |
||
| 138 | $email = Email::create(); |
||
| 139 | $email->setSubject("Test email"); |
||
| 140 | $email->setBody("Test " . date('Y-m-d H:i:s')); |
||
| 141 | $email->setTo($to); |
||
| 142 | |||
| 143 | $result = $email->send(); |
||
| 144 | var_dump($result); |
||
| 145 | } |
||
| 146 | |||
| 147 | /** |
||
| 148 | * @return Session |
||
| 149 | */ |
||
| 150 | public function getSession() |
||
| 151 | { |
||
| 152 | return $this->getRequest()->getSession(); |
||
| 153 | } |
||
| 154 | |||
| 155 | /** |
||
| 156 | * Returns a GridField of messages |
||
| 157 | * @return CMSForm |
||
| 158 | */ |
||
| 159 | public function getEditForm($id = null, $fields = null) |
||
| 160 | { |
||
| 161 | if (!$id) { |
||
| 162 | $id = $this->currentPageID(); |
||
| 163 | } |
||
| 164 | |||
| 165 | $form = parent::getEditForm($id); |
||
| 166 | |||
| 167 | $record = $this->getRecord($id); |
||
| 168 | |||
| 169 | // Check if this record is viewable |
||
| 170 | if ($record && !$record->canView()) { |
||
| 171 | $response = Security::permissionFailure($this); |
||
| 172 | $this->setResponse($response); |
||
| 173 | return null; |
||
| 174 | } |
||
| 175 | |||
| 176 | // Build gridfield |
||
| 177 | $messageListConfig = GridFieldConfig::create()->addComponents( |
||
| 178 | new GridFieldSortableHeader(), |
||
| 179 | new GridFieldDataColumns(), |
||
| 180 | new GridFieldFooter() |
||
| 181 | ); |
||
| 182 | |||
| 183 | $messages = $this->Messages(); |
||
| 184 | if (is_string($messages)) { |
||
| 185 | // The api returned an error |
||
| 186 | $messagesList = new LiteralField("MessageAlert", $this->MessageHelper($messages, 'bad')); |
||
| 187 | } else { |
||
| 188 | $messagesList = GridField::create( |
||
| 189 | 'Messages', |
||
| 190 | false, |
||
| 191 | $messages, |
||
| 192 | $messageListConfig |
||
| 193 | )->addExtraClass("messages_grid"); |
||
| 194 | |||
| 195 | /** @var GridFieldDataColumns $columns */ |
||
| 196 | $columns = $messageListConfig->getComponentByType(GridFieldDataColumns::class); |
||
| 197 | $columns->setDisplayFields([ |
||
| 198 | 'transmission_id' => _t('SparkPostAdmin.EventTransmissionId', 'Id'), |
||
| 199 | 'timestamp' => _t('SparkPostAdmin.EventDate', 'Date'), |
||
| 200 | 'type' => _t('SparkPostAdmin.EventType', 'Type'), |
||
| 201 | 'rcpt_to' => _t('SparkPostAdmin.EventRecipient', 'Recipient'), |
||
| 202 | 'subject' => _t('SparkPostAdmin.EventSubject', 'Subject'), |
||
| 203 | 'friendly_from' => _t('SparkPostAdmin.EventSender', 'Sender'), |
||
| 204 | ]); |
||
| 205 | |||
| 206 | $columns->setFieldFormatting([ |
||
| 207 | 'timestamp' => function ($value, &$item) { |
||
| 208 | return date('Y-m-d H:i:s', strtotime($value)); |
||
| 209 | }, |
||
| 210 | ]); |
||
| 211 | |||
| 212 | // Validator setup |
||
| 213 | $validator = null; |
||
| 214 | if ($record && method_exists($record, 'getValidator')) { |
||
| 215 | $validator = $record->getValidator(); |
||
| 216 | } |
||
| 217 | |||
| 218 | if ($validator) { |
||
| 219 | /** @var GridFieldDetailForm $detailForm */ |
||
| 220 | $detailForm = $messageListConfig->getComponentByType(GridFieldDetailForm::class); |
||
| 221 | if ($detailForm) { |
||
| 222 | $detailForm->setValidator($validator); |
||
| 223 | } |
||
| 224 | } |
||
| 225 | } |
||
| 226 | |||
| 227 | // Create tabs |
||
| 228 | $messagesTab = new Tab( |
||
| 229 | 'Messages', |
||
| 230 | _t('SparkPostAdmin.Messages', 'Messages'), |
||
| 231 | $this->SearchFields(), |
||
| 232 | $messagesList, |
||
| 233 | // necessary for tree node selection in LeftAndMain.EditForm.js |
||
| 234 | new HiddenField('ID', false, 0) |
||
| 235 | ); |
||
| 236 | |||
| 237 | $fields = new FieldList([ |
||
| 238 | $root = new TabSet('Root', $messagesTab) |
||
| 239 | ]); |
||
| 240 | |||
| 241 | if ($this->CanConfigureApi()) { |
||
| 242 | $settingsTab = new Tab('Settings', _t('SparkPostAdmin.Settings', 'Settings')); |
||
| 243 | |||
| 244 | $domainTabData = $this->DomainTab(); |
||
| 245 | $settingsTab->push($domainTabData); |
||
| 246 | |||
| 247 | // Show webhook options if not using a subaccount key |
||
| 248 | if (!$this->subaccountKey) { |
||
| 249 | $webhookTabData = $this->WebhookTab(); |
||
| 250 | $settingsTab->push($webhookTabData); |
||
| 251 | } |
||
| 252 | |||
| 253 | $toolsHtml = '<h2>Tools</h2>'; |
||
| 254 | |||
| 255 | // Show default from email |
||
| 256 | $defaultEmail = SparkPostHelper::resolveDefaultFromEmail(); |
||
| 257 | $toolsHtml .= "<p>Default sending email: " . $defaultEmail . " (" . SparkPostHelper::resolveDefaultFromEmailType() . ")</p>"; |
||
| 258 | if (!SparkPostHelper::isEmailDomainReady($defaultEmail)) { |
||
| 259 | $toolsHtml .= '<p style="color:red">The default email is not ready to send emails</p>'; |
||
| 260 | } |
||
| 261 | |||
| 262 | // Show constants |
||
| 263 | if (SparkPostHelper::getEnvSendingDisabled()) { |
||
| 264 | $toolsHtml .= '<p style="color:red">Sending is disabled by .env configuration</p>'; |
||
| 265 | } |
||
| 266 | if (SparkPostHelper::getEnvEnableLogging()) { |
||
| 267 | $toolsHtml .= '<p style="color:orange">Logging is enabled by .env configuration</p>'; |
||
| 268 | } |
||
| 269 | if (SparkPostHelper::getEnvSubaccountId()) { |
||
| 270 | $toolsHtml .= '<p style="color:orange">Using subaccount id</p>'; |
||
| 271 | } |
||
| 272 | if (SparkPostHelper::getEnvForceSender()) { |
||
| 273 | $toolsHtml .= '<p style="color:orange">Sender is forced to ' . SparkPostHelper::getEnvForceSender() . '</p>'; |
||
| 274 | } |
||
| 275 | |||
| 276 | // Add a refresh button |
||
| 277 | $toolsHtml .= $this->ButtonHelper( |
||
| 278 | $this->Link() . '?refresh=true', |
||
| 279 | _t('SparkPostAdmin.REFRESH', 'Force data refresh from the API') |
||
| 280 | ); |
||
| 281 | |||
| 282 | $toolsHtml = $this->FormGroupHelper($toolsHtml); |
||
| 283 | $Tools = new LiteralField('Tools', $toolsHtml); |
||
| 284 | $settingsTab->push($Tools); |
||
| 285 | |||
| 286 | $fields->addFieldToTab('Root', $settingsTab); |
||
| 287 | } |
||
| 288 | |||
| 289 | // Tab nav in CMS is rendered through separate template |
||
| 290 | $root->setTemplate('SilverStripe\\Forms\\CMSTabSet'); |
||
| 291 | |||
| 292 | // Manage tabs state |
||
| 293 | $actionParam = $this->getRequest()->param('Action'); |
||
| 294 | if ($actionParam == 'setting') { |
||
| 295 | $settingsTab->addExtraClass('ui-state-active'); |
||
| 296 | } elseif ($actionParam == 'messages') { |
||
| 297 | $messagesTab->addExtraClass('ui-state-active'); |
||
| 298 | } |
||
| 299 | |||
| 300 | $actions = new FieldList(); |
||
| 301 | |||
| 302 | |||
| 303 | // Build replacement form |
||
| 304 | $form = Form::create( |
||
| 305 | $this, |
||
| 306 | 'EditForm', |
||
| 307 | $fields, |
||
| 308 | new FieldList() |
||
| 309 | )->setHTMLID('Form_EditForm'); |
||
| 310 | $form->addExtraClass('cms-edit-form fill-height'); |
||
| 311 | $form->setTemplate($this->getTemplatesWithSuffix('_EditForm')); |
||
| 312 | $form->addExtraClass('ss-tabset cms-tabset ' . $this->BaseCSSClasses()); |
||
| 313 | $form->setAttribute('data-pjax-fragment', 'CurrentForm'); |
||
| 314 | |||
| 315 | $this->extend('updateEditForm', $form); |
||
| 316 | |||
| 317 | return $form; |
||
| 318 | } |
||
| 319 | |||
| 320 | /** |
||
| 321 | * Get logger |
||
| 322 | * |
||
| 323 | * @return Psr\Log\LoggerInterface |
||
| 324 | */ |
||
| 325 | public function getLogger() |
||
| 326 | { |
||
| 327 | return $this->logger; |
||
| 328 | } |
||
| 329 | |||
| 330 | /** |
||
| 331 | * Get the cache |
||
| 332 | * |
||
| 333 | * @return Psr\SimpleCache\CacheInterface |
||
| 334 | */ |
||
| 335 | public function getCache() |
||
| 336 | { |
||
| 337 | return $this->cache; |
||
| 338 | } |
||
| 339 | |||
| 340 | /** |
||
| 341 | * @return boolean |
||
| 342 | */ |
||
| 343 | public function getCacheEnabled() |
||
| 344 | { |
||
| 345 | if (isset($_GET['disable_cache'])) { |
||
| 346 | return false; |
||
| 347 | } |
||
| 348 | if (Environment::getEnv('SPARKPOST_DISABLE_CACHE')) { |
||
| 349 | return false; |
||
| 350 | } |
||
| 351 | $v = $this->config()->cache_enabled; |
||
| 352 | if ($v === null) { |
||
| 353 | $v = self::$cache_enabled; |
||
| 354 | } |
||
| 355 | return $v; |
||
| 356 | } |
||
| 357 | |||
| 358 | /** |
||
| 359 | * A simple cache helper |
||
| 360 | * |
||
| 361 | * @param string $method |
||
| 362 | * @param array $params |
||
| 363 | * @param int $expireInSeconds |
||
| 364 | * @return array |
||
| 365 | */ |
||
| 366 | protected function getCachedData($method, $params, $expireInSeconds = 60) |
||
| 367 | { |
||
| 368 | $enabled = $this->getCacheEnabled(); |
||
| 369 | if ($enabled) { |
||
| 370 | $cache = $this->getCache(); |
||
| 371 | $key = md5(serialize($params)); |
||
| 372 | $cacheResult = $cache->get($key); |
||
| 373 | } |
||
| 374 | if ($enabled && $cacheResult) { |
||
| 375 | $data = unserialize($cacheResult); |
||
| 376 | } else { |
||
| 377 | try { |
||
| 378 | $client = SparkPostHelper::getClient(); |
||
| 379 | $data = $client->$method($params); |
||
| 380 | } catch (Exception $ex) { |
||
| 381 | $this->lastException = $ex; |
||
| 382 | $this->getLogger()->debug($ex); |
||
| 383 | $data = false; |
||
| 384 | } |
||
| 385 | |||
| 386 | //5 minutes cache |
||
| 387 | if ($enabled) { |
||
| 388 | $cache->set($key, serialize($data), $expireInSeconds); |
||
| 389 | } |
||
| 390 | } |
||
| 391 | |||
| 392 | return $data; |
||
| 393 | } |
||
| 394 | |||
| 395 | public function getParams() |
||
| 396 | { |
||
| 397 | $params = $this->config()->default_search_params; |
||
| 398 | if (!$params) { |
||
| 399 | $params = []; |
||
| 400 | } |
||
| 401 | $data = $this->getSession()->get(__class__ . '.Search'); |
||
| 402 | if (!$data) { |
||
| 403 | $data = []; |
||
| 404 | } |
||
| 405 | |||
| 406 | $params = array_merge($params, $data); |
||
| 407 | |||
| 408 | // Respect api formats |
||
| 409 | if (!empty($params['to'])) { |
||
| 410 | $params['to'] = date('Y-m-d', strtotime(str_replace('/', '-', $params['to']))) . 'T00:00'; |
||
| 411 | } |
||
| 412 | if (!empty($params['from'])) { |
||
| 413 | $params['from'] = date('Y-m-d', strtotime(str_replace('/', '-', $params['from']))) . 'T23:59'; |
||
| 414 | } |
||
| 415 | |||
| 416 | $params = array_filter($params); |
||
| 417 | |||
| 418 | return $params; |
||
| 419 | } |
||
| 420 | |||
| 421 | public function getParam($name, $default = null) |
||
| 428 | } |
||
| 429 | |||
| 430 | public function SearchFields() |
||
| 431 | { |
||
| 432 | $disabled_filters = $this->config()->disabled_search_filters; |
||
| 433 | if (!$disabled_filters) { |
||
| 434 | $disabled_filters = []; |
||
| 435 | } |
||
| 436 | |||
| 437 | $fields = new CompositeField(); |
||
| 438 | $fields->push($from = new DateField('params[from]', _t('SparkPostAdmin.DATEFROM', 'From'), $this->getParam('from'))); |
||
| 439 | // $from->setConfig('min', date('Y-m-d', strtotime('-10 days'))); |
||
| 440 | |||
| 441 | $fields->push(new DateField('params[to]', _t('SparkPostAdmin.DATETO', 'To'), $to = $this->getParam('to'))); |
||
| 442 | |||
| 443 | if (!in_array('friendly_froms', $disabled_filters)) { |
||
| 444 | $fields->push($friendly_froms = new TextField('params[friendly_froms]', _t('SparkPostAdmin.FRIENDLYFROM', 'Sender'), $this->getParam('friendly_froms'))); |
||
| 445 | $friendly_froms->setAttribute('placeholder', '[email protected],[email protected]'); |
||
| 446 | } |
||
| 447 | |||
| 448 | if (!in_array('recipients', $disabled_filters)) { |
||
| 449 | $fields->push($recipients = new TextField('params[recipients]', _t('SparkPostAdmin.RECIPIENTS', 'Recipients'), $this->getParam('recipients'))); |
||
| 450 | $recipients->setAttribute('placeholder', '[email protected],[email protected]'); |
||
| 451 | } |
||
| 452 | |||
| 453 | // Only allow filtering by subaccount if a master key is defined |
||
| 454 | if (SparkPostHelper::config()->master_api_key && !in_array('subaccounts', $disabled_filters)) { |
||
| 455 | $fields->push($subaccounts = new TextField('params[subaccounts]', _t('SparkPostAdmin.SUBACCOUNTS', 'Subaccounts'), $this->getParam('subaccounts'))); |
||
| 456 | $subaccounts->setAttribute('placeholder', '101,102'); |
||
| 457 | } |
||
| 458 | |||
| 459 | $fields->push(new DropdownField('params[per_page]', _t('SparkPostAdmin.PERPAGE', 'Number of results'), array( |
||
| 460 | 100 => 100, |
||
| 461 | 500 => 500, |
||
| 462 | 1000 => 1000, |
||
| 463 | 10000 => 10000, |
||
| 464 | ), $this->getParam('per_page', 100))); |
||
| 465 | |||
| 466 | foreach ($fields->FieldList() as $field) { |
||
| 467 | $field->addExtraClass('no-change-track'); |
||
| 468 | } |
||
| 469 | |||
| 470 | // This is a ugly hack to allow embedding a form into another form |
||
| 471 | $fields->push($doSearch = new FormAction('doSearch', _t('SparkPostAdmin.DOSEARCH', 'Search'))); |
||
| 472 | $doSearch->addExtraClass("btn-primary"); |
||
| 473 | $doSearch->setAttribute('onclick', "jQuery('#Form_SearchForm').append(jQuery('#Form_EditForm input,#Form_EditForm select').clone()).submit();"); |
||
| 474 | |||
| 475 | return $fields; |
||
| 476 | } |
||
| 477 | |||
| 478 | public function SearchForm() |
||
| 479 | { |
||
| 480 | $SearchForm = new Form($this, 'SearchForm', new FieldList(), new FieldList([ |
||
| 481 | new FormAction('doSearch') |
||
| 482 | ])); |
||
| 483 | $SearchForm->setAttribute('style', 'display:none'); |
||
| 484 | return $SearchForm; |
||
| 485 | } |
||
| 486 | |||
| 487 | public function doSearch($data, Form $form) |
||
| 488 | { |
||
| 489 | $post = $this->getRequest()->postVar('params'); |
||
| 490 | if (!$post) { |
||
| 491 | return $this->redirectBack(); |
||
| 492 | } |
||
| 493 | $params = []; |
||
| 494 | |||
| 495 | $validFields = []; |
||
| 496 | foreach ($this->SearchFields()->FieldList()->dataFields() as $field) { |
||
| 497 | $validFields[] = str_replace(['params[', ']'], '', $field->getName()); |
||
| 498 | } |
||
| 499 | |||
| 500 | foreach ($post as $k => $v) { |
||
| 501 | if (in_array($k, $validFields)) { |
||
| 502 | $params[$k] = $v; |
||
| 503 | } |
||
| 504 | } |
||
| 505 | |||
| 506 | $this->getSession()->set(__class__ . '.Search', $params); |
||
| 507 | $this->getSession()->save($this->getRequest()); |
||
| 508 | |||
| 509 | return $this->redirectBack(); |
||
| 510 | } |
||
| 511 | |||
| 512 | /** |
||
| 513 | * List of messages events |
||
| 514 | * |
||
| 515 | * Messages are cached to avoid hammering the api |
||
| 516 | * |
||
| 517 | * @return ArrayList|string |
||
| 518 | */ |
||
| 519 | public function Messages() |
||
| 520 | { |
||
| 521 | $params = $this->getParams(); |
||
| 522 | |||
| 523 | $messages = $this->getCachedData('searchEvents', $params, 60 * self::MESSAGE_CACHE_MINUTES); |
||
| 524 | if ($messages === false) { |
||
| 525 | if ($this->lastException) { |
||
| 526 | return $this->lastException->getMessage(); |
||
| 527 | } |
||
| 528 | return _t('SparkpostAdmin.NO_MESSAGES', 'No messages'); |
||
| 529 | } |
||
| 530 | |||
| 531 | // Consolidate Subject/Sender for open and click events |
||
| 532 | $transmissions = []; |
||
| 533 | foreach ($messages as $message) { |
||
| 534 | if (empty($message['transmission_id']) || empty($message['subject'])) { |
||
| 535 | continue; |
||
| 536 | } |
||
| 537 | if (isset($transmissions[$message['transmission_id']])) { |
||
| 538 | continue; |
||
| 539 | } |
||
| 540 | $transmissions[$message['transmission_id']] = $message; |
||
| 541 | } |
||
| 542 | |||
| 543 | $list = new ArrayList(); |
||
| 544 | if ($messages) { |
||
| 545 | foreach ($messages as $message) { |
||
| 546 | // If we have a transmission id but no subject, try to find the transmission details |
||
| 547 | if (isset($message['transmission_id']) && empty($message['subject']) && isset($transmissions[$message['transmission_id']])) { |
||
| 548 | $message = array_merge($transmissions[$message['transmission_id']], $message); |
||
| 549 | } |
||
| 550 | // In some case (errors, etc) we don't have a friendly from |
||
| 551 | if (empty($message['friendly_from']) && isset($message['msg_from'])) { |
||
| 552 | $message['friendly_from'] = $message['msg_from']; |
||
| 553 | } |
||
| 554 | $m = new ArrayData($message); |
||
| 555 | $list->push($m); |
||
| 556 | } |
||
| 557 | } |
||
| 558 | |||
| 559 | return $list; |
||
| 560 | } |
||
| 561 | |||
| 562 | /** |
||
| 563 | * Provides custom permissions to the Security section |
||
| 564 | * |
||
| 565 | * @return array |
||
| 566 | */ |
||
| 567 | public function providePermissions() |
||
| 568 | { |
||
| 569 | $title = _t("SparkPostAdmin.MENUTITLE", LeftAndMain::menu_title_for_class('SparkPost')); |
||
| 570 | return [ |
||
| 571 | "CMS_ACCESS_SparkPost" => [ |
||
| 572 | 'name' => _t('SparkPostAdmin.ACCESS', "Access to '{title}' section", ['title' => $title]), |
||
| 573 | 'category' => _t('Permission.CMS_ACCESS_CATEGORY', 'CMS Access'), |
||
| 574 | 'help' => _t( |
||
| 575 | 'SparkPostAdmin.ACCESS_HELP', |
||
| 576 | 'Allow use of SparkPost admin section' |
||
| 577 | ) |
||
| 578 | ], |
||
| 579 | ]; |
||
| 580 | } |
||
| 581 | |||
| 582 | /** |
||
| 583 | * Message helper |
||
| 584 | * |
||
| 585 | * @param string $message |
||
| 586 | * @param string $status |
||
| 587 | * @return string |
||
| 588 | */ |
||
| 589 | protected function MessageHelper($message, $status = 'info') |
||
| 590 | { |
||
| 591 | return '<div class="message ' . $status . '">' . $message . '</div>'; |
||
| 592 | } |
||
| 593 | |||
| 594 | /** |
||
| 595 | * Button helper |
||
| 596 | * |
||
| 597 | * @param string $link |
||
| 598 | * @param string $text |
||
| 599 | * @param boolean $confirm |
||
| 600 | * @return string |
||
| 601 | */ |
||
| 602 | protected function ButtonHelper($link, $text, $confirm = false) |
||
| 603 | { |
||
| 604 | $link = '<a class="btn btn-primary" href="' . $link . '"'; |
||
| 605 | if ($confirm) { |
||
| 606 | $link .= ' onclick="return confirm(\'' . _t('SparkPostAdmin.CONFIRM_MSG', 'Are you sure?') . '\')"'; |
||
| 607 | } |
||
| 608 | $link .= '>' . $text . '</a>'; |
||
| 609 | return $link; |
||
| 610 | } |
||
| 611 | |||
| 612 | /** |
||
| 613 | * Wrap html in a form group |
||
| 614 | * |
||
| 615 | * @param string $html |
||
| 616 | * @return string |
||
| 617 | */ |
||
| 618 | protected function FormGroupHelper($html) |
||
| 619 | { |
||
| 620 | return '<div class="form-group"><div class="form__fieldgroup form__field-holder form__field-holder--no-label">' . $html . '</div></div>'; |
||
| 621 | } |
||
| 622 | |||
| 623 | /** |
||
| 624 | * A template accessor to check the ADMIN permission |
||
| 625 | * |
||
| 626 | * @return bool |
||
| 627 | */ |
||
| 628 | public function IsAdmin() |
||
| 631 | } |
||
| 632 | |||
| 633 | /** |
||
| 634 | * Check the permission for current user |
||
| 635 | * |
||
| 636 | * @return bool |
||
| 637 | */ |
||
| 638 | public function canView($member = null) |
||
| 639 | { |
||
| 640 | $mailer = SparkPostHelper::getMailer(); |
||
| 641 | // Another custom mailer has been set |
||
| 642 | if (!$mailer instanceof SwiftMailer) { |
||
| 643 | return false; |
||
| 644 | } |
||
| 645 | // Doesn't use the proper transport |
||
| 646 | if (!$mailer->getSwiftMailer()->getTransport() instanceof SparkPostSwiftTransport) { |
||
| 647 | return false; |
||
| 648 | } |
||
| 649 | return Permission::check("CMS_ACCESS_SparkPost", 'any', $member); |
||
| 650 | } |
||
| 651 | |||
| 652 | /** |
||
| 653 | * |
||
| 654 | * @return bool |
||
| 655 | */ |
||
| 656 | public function CanConfigureApi() |
||
| 657 | { |
||
| 658 | return Permission::check('ADMIN') || Director::isDev(); |
||
| 659 | } |
||
| 660 | |||
| 661 | /** |
||
| 662 | * Check if webhook is installed |
||
| 663 | * |
||
| 664 | * @return array |
||
| 665 | */ |
||
| 666 | public function WebhookInstalled() |
||
| 667 | { |
||
| 668 | $list = $this->getCachedData('listAllWebhooks', null, 60 * self::WEBHOOK_CACHE_MINUTES); |
||
| 669 | |||
| 670 | if (empty($list)) { |
||
| 671 | return false; |
||
| 672 | } |
||
| 673 | $url = $this->WebhookUrl(); |
||
| 674 | foreach ($list as $el) { |
||
| 675 | if (!empty($el['target']) && $el['target'] === $url) { |
||
| 676 | return $el; |
||
| 677 | } |
||
| 678 | } |
||
| 679 | return false; |
||
| 680 | } |
||
| 681 | |||
| 682 | /** |
||
| 683 | * Hook details for template |
||
| 684 | * @return \ArrayData |
||
| 685 | */ |
||
| 686 | public function WebhookDetails() |
||
| 687 | { |
||
| 688 | $el = $this->WebhookInstalled(); |
||
| 689 | if ($el) { |
||
| 690 | return new ArrayData($el); |
||
| 691 | } |
||
| 692 | } |
||
| 693 | |||
| 694 | /** |
||
| 695 | * Get content of the tab |
||
| 696 | * |
||
| 697 | * @return FormField |
||
| 698 | */ |
||
| 699 | public function WebhookTab() |
||
| 700 | { |
||
| 701 | if ($this->WebhookInstalled()) { |
||
| 702 | return $this->UninstallHookForm(); |
||
| 703 | } |
||
| 704 | return $this->InstallHookForm(); |
||
| 705 | } |
||
| 706 | |||
| 707 | /** |
||
| 708 | * @return string |
||
| 709 | */ |
||
| 710 | public function WebhookUrl() |
||
| 711 | { |
||
| 712 | if (self::config()->webhook_base_url) { |
||
| 713 | return rtrim(self::config()->webhook_base_url, '/') . '/sparkpost/incoming'; |
||
| 714 | } |
||
| 715 | if (Director::isLive()) { |
||
| 716 | return Director::absoluteURL('/sparkpost/incoming'); |
||
| 717 | } |
||
| 718 | $protocol = Director::protocol(); |
||
| 719 | return $protocol . $this->getDomain() . '/sparkpost/incoming'; |
||
| 720 | } |
||
| 721 | |||
| 722 | /** |
||
| 723 | * Install hook form |
||
| 724 | * |
||
| 725 | * @return FormField |
||
| 726 | */ |
||
| 727 | public function InstallHookForm() |
||
| 728 | { |
||
| 729 | $fields = new CompositeField(); |
||
| 730 | $fields->push(new LiteralField('Info', $this->MessageHelper( |
||
| 731 | _t('SparkPostAdmin.WebhookNotInstalled', 'Webhook is not installed. It should be configured using the following url {url}. This url must be publicly visible to be used as a hook.', ['url' => $this->WebhookUrl()]), |
||
| 732 | 'bad' |
||
| 733 | ))); |
||
| 734 | $fields->push(new LiteralField('doInstallHook', $this->ButtonHelper( |
||
| 735 | $this->Link('doInstallHook'), |
||
| 736 | _t('SparkPostAdmin.DOINSTALL_WEBHOOK', 'Install webhook') |
||
| 737 | ))); |
||
| 738 | return $fields; |
||
| 739 | } |
||
| 740 | |||
| 741 | public function doInstallHook() |
||
| 742 | { |
||
| 743 | if (!$this->CanConfigureApi()) { |
||
| 744 | return $this->redirectBack(); |
||
| 745 | } |
||
| 746 | |||
| 747 | $client = SparkPostHelper::getClient(); |
||
| 748 | |||
| 749 | $url = $this->WebhookUrl(); |
||
| 750 | $description = SiteConfig::current_site_config()->Title; |
||
| 751 | |||
| 752 | $defaultAdmin = Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME'); |
||
| 753 | $defaultPassword = Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD'); |
||
| 754 | |||
| 755 | try { |
||
| 756 | if ($defaultAdmin) { |
||
| 757 | $client->createSimpleWebhook($description, $url, null, true, ['username' => $defaultAdmin, 'password' => $defaultPassword]); |
||
| 758 | } else { |
||
| 759 | $client->createSimpleWebhook($description, $url); |
||
| 760 | } |
||
| 761 | $this->getCache()->clear(); |
||
| 762 | } catch (Exception $ex) { |
||
| 763 | $this->getLogger()->debug($ex); |
||
| 764 | } |
||
| 765 | |||
| 766 | return $this->redirectBack(); |
||
| 767 | } |
||
| 768 | |||
| 769 | /** |
||
| 770 | * Uninstall hook form |
||
| 771 | * |
||
| 772 | * @return FormField |
||
| 773 | */ |
||
| 774 | public function UninstallHookForm() |
||
| 775 | { |
||
| 776 | $fields = new CompositeField(); |
||
| 777 | $fields->push(new LiteralField('Info', $this->MessageHelper( |
||
| 778 | _t('SparkPostAdmin.WebhookInstalled', 'Webhook is installed and accessible at the following url {url}.', ['url' => $this->WebhookUrl()]), |
||
| 779 | 'good' |
||
| 780 | ))); |
||
| 781 | $fields->push(new LiteralField('doUninstallHook', $this->ButtonHelper( |
||
| 782 | $this->Link('doUninstallHook'), |
||
| 783 | _t('SparkPostAdmin.DOUNINSTALL_WEBHOOK', 'Uninstall webhook'), |
||
| 784 | true |
||
| 785 | ))); |
||
| 786 | return $fields; |
||
| 787 | } |
||
| 788 | |||
| 789 | public function doUninstallHook($data, Form $form) |
||
| 790 | { |
||
| 791 | if (!$this->CanConfigureApi()) { |
||
| 792 | return $this->redirectBack(); |
||
| 793 | } |
||
| 794 | |||
| 795 | $client = SparkPostHelper::getClient(); |
||
| 796 | |||
| 797 | try { |
||
| 798 | $el = $this->WebhookInstalled(); |
||
| 799 | if ($el && !empty($el['id'])) { |
||
| 800 | $client->deleteWebhook($el['id']); |
||
| 801 | } |
||
| 802 | $this->getCache()->clear(); |
||
| 803 | } catch (Exception $ex) { |
||
| 804 | $this->getLogger()->debug($ex); |
||
| 805 | } |
||
| 806 | |||
| 807 | return $this->redirectBack(); |
||
| 808 | } |
||
| 809 | |||
| 810 | /** |
||
| 811 | * Check if sending domain is installed |
||
| 812 | * |
||
| 813 | * @return array |
||
| 814 | */ |
||
| 815 | public function SendingDomainInstalled() |
||
| 816 | { |
||
| 817 | $domain = $this->getCachedData('getSendingDomain', $this->getDomain(), 60 * self::SENDINGDOMAIN_CACHE_MINUTES); |
||
| 818 | |||
| 819 | if (empty($domain)) { |
||
| 820 | return false; |
||
| 821 | } |
||
| 822 | return $domain; |
||
| 823 | } |
||
| 824 | |||
| 825 | /** |
||
| 826 | * Trigger request to check if sending domain is verified |
||
| 827 | * |
||
| 828 | * @return array |
||
| 829 | */ |
||
| 830 | public function VerifySendingDomain() |
||
| 831 | { |
||
| 832 | $client = SparkPostHelper::getClient(); |
||
| 833 | |||
| 834 | $host = $this->getDomain(); |
||
| 835 | |||
| 836 | $verification = $client->verifySendingDomain($host); |
||
| 837 | |||
| 838 | if (empty($verification)) { |
||
| 839 | return false; |
||
| 840 | } |
||
| 841 | return $verification; |
||
| 842 | } |
||
| 843 | |||
| 844 | /** |
||
| 845 | * Get content of the tab |
||
| 846 | * |
||
| 847 | * @return FormField |
||
| 848 | */ |
||
| 849 | public function DomainTab() |
||
| 850 | { |
||
| 851 | $defaultDomain = $this->getDomain(); |
||
| 852 | $defaultDomainInfos = null; |
||
| 853 | |||
| 854 | $domains = $this->getCachedData('listAllSendingDomains', null, 60 * self::SENDINGDOMAIN_CACHE_MINUTES); |
||
| 855 | |||
| 856 | $fields = new CompositeField(); |
||
| 857 | |||
| 858 | $list = new ArrayList(); |
||
| 859 | if ($domains) { |
||
| 860 | foreach ($domains as $domain) { |
||
| 861 | // We are using a subaccount api key |
||
| 862 | if (!isset($domain['shared_with_subaccounts'])) { |
||
| 863 | $this->subaccountKey = true; |
||
| 864 | } |
||
| 865 | |||
| 866 | $list->push(new ArrayData([ |
||
| 867 | 'Domain' => $domain['domain'], |
||
| 868 | 'SPF' => $domain['status']['spf_status'], |
||
| 869 | 'DKIM' => $domain['status']['dkim_status'], |
||
| 870 | 'Compliance' => $domain['status']['compliance_status'], |
||
| 871 | 'Verified' => $domain['status']['ownership_verified'], |
||
| 872 | ])); |
||
| 873 | |||
| 874 | if ($domain['domain'] == $defaultDomain) { |
||
| 875 | $defaultDomainInfos = $domain; |
||
| 876 | } |
||
| 877 | } |
||
| 878 | } |
||
| 879 | |||
| 880 | $config = GridFieldConfig::create(); |
||
| 881 | $config->addComponent(new GridFieldToolbarHeader()); |
||
| 882 | $config->addComponent(new GridFieldTitleHeader()); |
||
| 883 | $config->addComponent($columns = new GridFieldDataColumns()); |
||
| 884 | $columns->setDisplayFields(ArrayLib::valuekey(['Domain', 'SPF', 'DKIM', 'Compliance', 'Verified'])); |
||
| 885 | $domainsList = new GridField('SendingDomains', _t('SparkPostAdmin.ALL_SENDING_DOMAINS', 'Configured sending domains'), $list, $config); |
||
| 886 | $domainsList->addExtraClass('mb-2'); |
||
| 887 | $fields->push($domainsList); |
||
| 888 | |||
| 889 | if (!$defaultDomainInfos) { |
||
| 890 | $this->InstallDomainForm($fields); |
||
| 891 | } else { |
||
| 892 | $this->UninstallDomainForm($fields); |
||
| 893 | } |
||
| 894 | |||
| 895 | return $fields; |
||
| 896 | } |
||
| 897 | |||
| 898 | /** |
||
| 899 | * @return string |
||
| 900 | */ |
||
| 901 | public function InboundUrl() |
||
| 902 | { |
||
| 903 | $subdomain = self::config()->inbound_subdomain; |
||
| 904 | $domain = $this->getDomain(); |
||
| 905 | if ($domain) { |
||
| 906 | return $subdomain . '.' . $domain; |
||
| 907 | } |
||
| 908 | return false; |
||
| 909 | } |
||
| 910 | |||
| 911 | /** |
||
| 912 | * Get domain name from current host |
||
| 913 | * |
||
| 914 | * @return boolean|string |
||
| 915 | */ |
||
| 916 | public function getDomainFromHost() |
||
| 917 | { |
||
| 918 | $base = Environment::getEnv('SS_BASE_URL'); |
||
| 919 | if (!$base) { |
||
| 920 | $base = Director::protocolAndHost(); |
||
| 921 | } |
||
| 922 | $host = parse_url($base, PHP_URL_HOST); |
||
| 923 | $hostParts = explode('.', $host); |
||
| 924 | $parts = count($hostParts); |
||
| 925 | if ($parts < 2) { |
||
| 926 | return false; |
||
| 927 | } |
||
| 928 | $domain = $hostParts[$parts - 2] . "." . $hostParts[$parts - 1]; |
||
| 929 | return $domain; |
||
| 930 | } |
||
| 931 | |||
| 932 | /** |
||
| 933 | * Get domain from admin email |
||
| 934 | * |
||
| 935 | * @return boolean|string |
||
| 936 | */ |
||
| 937 | public function getDomainFromEmail() |
||
| 938 | { |
||
| 939 | $email = SparkPostHelper::resolveDefaultFromEmail(null, false); |
||
| 940 | if ($email) { |
||
| 941 | $domain = substr(strrchr($email, "@"), 1); |
||
| 942 | return $domain; |
||
| 943 | } |
||
| 944 | return false; |
||
| 945 | } |
||
| 946 | |||
| 947 | /** |
||
| 948 | * Get domain |
||
| 949 | * |
||
| 950 | * @return boolean|string |
||
| 951 | */ |
||
| 952 | public function getDomain() |
||
| 953 | { |
||
| 954 | $domain = $this->getDomainFromEmail(); |
||
| 955 | if (!$domain) { |
||
| 956 | return $this->getDomainFromHost(); |
||
| 957 | } |
||
| 958 | return $domain; |
||
| 959 | } |
||
| 960 | |||
| 961 | /** |
||
| 962 | * Install domain form |
||
| 963 | * |
||
| 964 | * @param CompositeField $fieldsd |
||
| 965 | * @return FormField |
||
| 966 | */ |
||
| 967 | public function InstallDomainForm(CompositeField $fields) |
||
| 978 | ))); |
||
| 979 | } |
||
| 980 | |||
| 981 | public function doInstallDomain() |
||
| 1003 | } |
||
| 1004 | |||
| 1005 | /** |
||
| 1006 | * Uninstall domain form |
||
| 1007 | * |
||
| 1008 | * @param CompositeField $fieldsd |
||
| 1009 | * @return FormField |
||
| 1010 | */ |
||
| 1011 | public function UninstallDomainForm(CompositeField $fields) |
||
| 1012 | { |
||
| 1013 | $domainInfos = $this->SendingDomainInstalled(); |
||
| 1014 | |||
| 1015 | $domain = $this->getDomain(); |
||
| 1016 | |||
| 1017 | if ($domainInfos && $domainInfos['status']['ownership_verified']) { |
||
| 1018 | $fields->push(new LiteralField('Info', $this->MessageHelper( |
||
| 1019 | _t('SparkPostAdmin.DomainInstalled', 'Default domain {domain} is installed.', ['domain' => $domain]), |
||
| 1020 | 'good' |
||
| 1032 | ))); |
||
| 1033 | } |
||
| 1034 | |||
| 1035 | public function doUninstallDomain($data, Form $form) |
||
| 1036 | { |
||
| 1037 | if (!$this->CanConfigureApi()) { |
||
| 1038 | return $this->redirectBack(); |
||
| 1039 | } |
||
| 1040 | |||
| 1041 | $client = SparkPostHelper::getClient(); |
||
| 1042 | |||
| 1043 | $domain = $this->getDomain(); |
||
| 1044 | |||
| 1045 | if (!$domain) { |
||
| 1046 | return $this->redirectBack(); |
||
| 1060 | } |
||
| 1061 | } |
||
| 1062 |