public function onBeforeWrite() { parent::onBeforeWrite(); // Create the base folder if (!$this->owner->BaseFolder && $this->owner->Title) { $filter = new FileNameFilter(); $this->owner->BaseFolder = $filter->filter($this->owner->getTitle()); $this->owner->BaseFolder = str_replace(' ', '', ucwords(str_replace('-', ' ', $this->owner->BaseFolder))); } // If name has changed, rename existing groups $changes = $this->owner->getChangedFields(); if (isset($changes['Title']) && !empty($changes['Title']['before'])) { $filter = new URLSegmentFilter(); $groupName = $this->getAdministratorGroupName($changes['Title']['before']); $group = self::getGroupByName($groupName); if ($group) { $group->Title = $this->getAdministratorGroupName($changes['Title']['after']); $group->Code = $filter->filter($group->Title); $group->write(); } $membersGroupName = $this->getMembersGroupName($changes['Title']['before']); $membersGroup = self::getGroupByName($membersGroupName); if ($membersGroup) { $membersGroup->Title = $this->getMembersGroupName($changes['Title']['after']); $membersGroup->Code = $filter->filter($membersGroup->Title); $membersGroup->write(); } } }
function testFilterWithEmptyString() { $name = 'ö ö ö.jpg'; $filter = new FileNameFilter(); $result = $filter->filter($name); $this->assertFalse(empty($result)); $this->assertStringEndsWith('.jpg', $result); $this->assertGreaterThan(strlen('.jpg'), strlen($result)); }
public function run($request) { $filesWithSpaces = File::get()->where('"Filename" LIKE \'% %\''); $filter = new FileNameFilter(); foreach ($filesWithSpaces as $file) { DB::alteration_message("Updating file #" . $file->ID . " with filename " . $file->Filename); $parts = explode('/', $file->Filename); $filtered = array_map(function ($item) use($filter) { return $filter->filter($item); }, $parts); $file->Filename = implode('/', $filtered); $file->write(); } DB::alteration_message("All done!"); }
function checkFolder() { if (!$this->exists()) { return; } if (!$this->URLSegment) { return; } $baseFolder = ''; if (class_exists('Subsite') && self::config()->use_subsite_integration) { if ($this->SubsiteID) { $subsite = $this->Subsite(); if ($subsite->hasField('BaseFolder')) { $baseFolder = $subsite->BaseFolder; } else { $filter = new FileNameFilter(); $baseFolder = $filter->filter($subsite->getTitle()); $baseFolder = str_replace(' ', '', ucwords(str_replace('-', ' ', $baseFolder))); } $baseFolder .= '/'; } } $folderPath = $baseFolder . "galleries/{$this->URLSegment}"; $folder = Folder::find_or_make($folderPath); if ($this->RootFolderID && $folder->ID != $this->RootFolderID) { if ($this->RootFolder()->exists()) { // We need to rename current folder $this->RootFolder()->setFilename($folder->Filename); $this->RootFolder()->write(); $folder->deleteDatabaseOnly(); //Otherwise we keep a stupid clone that will be used as the parent } else { $this->RootFolderID = $folder->ID; } } else { $this->RootFolderID = $folder->ID; } }
/** * Send the email through mandrill * * @param string|array $to * @param string $from * @param string $subject * @param string $plainContent * @param array $attachedFiles * @param array $customheaders * @param bool $inlineImages * @return array|bool */ protected function send($to, $from, $subject, $htmlContent, $attachedFiles = false, $customheaders = false, $plainContent = false, $inlineImages = false) { $original_to = $to; // Process recipients $to_array = array(); $to_array = $this->appendTo($to_array, $to, 'to'); if (isset($customheaders['Cc'])) { $to_array = $this->appendTo($to_array, $customheaders['Cc'], 'cc'); unset($customheaders['Cc']); } if (isset($customheaders['Bcc'])) { $to_array = $this->appendTo($to_array, $customheaders['Bcc'], 'bcc'); unset($customheaders['Bcc']); } // Process sender $fromArray = $this->processRecipient($from); $fromEmail = $fromArray['email']; $fromName = $fromArray['name']; // Create params to send to mandrill message api $default_params = array(); if (self::getDefaultParams()) { $default_params = self::getDefaultParams(); } $params = array_merge($default_params, array("subject" => $subject, "from_email" => $fromEmail, "to" => $to_array)); if ($fromName) { $params['from_name'] = $fromName; } // Inject additional params into message if (isset($customheaders['X-MandrillMailer'])) { $params = array_merge($params, $customheaders['X-MandrillMailer']); unset($customheaders['X-MandrillMailer']); } if ($plainContent) { $params['text'] = $plainContent; } if ($htmlContent) { $params['html'] = $htmlContent; } // Attach tags to params if (self::getGlobalTags()) { if (!isset($params['tags'])) { $params['tags'] = array(); } $params['tags'] = array_merge($params['tags'], self::getGlobalTags()); } // Attach subaccount to params if (self::getSubaccount()) { $params['subaccount'] = self::getSubaccount(); } $bcc_email = Config::inst()->get('Email', 'bcc_all_emails_to'); if ($bcc_email) { if (is_string($bcc_email)) { $params['bcc_address'] = $bcc_email; } } // Google analytics domains if (self::getUseGoogleAnalytics() && !Director::isDev()) { if (!isset($params['google_analytics_domains'])) { // Compute host $host = str_replace(Director::protocol(), '', Director::protocolAndHost()); // Define in params $params['google_analytics_domains'] = array($host); } } // Handle files attachments if ($attachedFiles) { $attachments = array(); // Include any specified attachments as additional parts foreach ($attachedFiles as $file) { if (isset($file['tmp_name']) && isset($file['name'])) { $attachments[] = $this->encodeFileForEmail($file['tmp_name'], $file['name']); } else { $attachments[] = $this->encodeFileForEmail($file); } } $params['attachments'] = $attachments; } if ($customheaders) { $params['headers'] = $customheaders; } if (self::getEnableLogging()) { // Append some extra information at the end $logContent = $htmlContent; $logContent .= '<pre>'; $logContent .= 'To : ' . print_r($original_to, true) . "\n"; $logContent .= 'Subject : ' . $subject . "\n"; $logContent .= 'Headers : ' . print_r($customheaders, true) . "\n"; if (!empty($params['from_email'])) { $logContent .= 'From email : ' . $params['from_email'] . "\n"; } if (!empty($params['from_name'])) { $logContent .= 'From name : ' . $params['from_name'] . "\n"; } if (!empty($params['to'])) { $logContent .= 'Recipients : ' . print_r($params['to'], true) . "\n"; } $logContent .= '</pre>'; // Store it $logFolder = BASE_PATH . '/' . self::getLogFolder(); if (!is_dir($logFolder)) { mkdir($logFolder, 0777, true); } $filter = new FileNameFilter(); $title = substr($filter->filter($subject), 0, 20); $r = file_put_contents($logFolder . '/' . time() . '-' . $title . '.html', $logContent); if (!$r) { throw new Exception('Failed to store email in ' . $logFolder); } } if (self::getSendingDisabled()) { $customheaders['X-SendingDisabled'] = true; return array($original_to, $subject, $htmlContent, $customheaders); } try { $ret = $this->getMandrill()->messages->send($params); } catch (Exception $ex) { $ret = array(array('status' => 'rejected', 'reject_reason' => $ex->getMessage())); } $this->last_result = $ret; $sent = 0; $failed = 0; $reasons = array(); if ($ret) { foreach ($ret as $result) { if (in_array($result['status'], array('rejected', 'invalid'))) { $failed++; if (!empty($result['reject_reason'])) { $reasons[] = $result['reject_reason']; } else { if ($result['status'] == 'invalid') { $reasons[] = 'Email "' . $result['email'] . '" is invalid'; } } continue; } $sent++; } } if ($sent) { $this->last_is_error = false; return array($original_to, $subject, $htmlContent, $customheaders); } else { $this->last_is_error = true; $this->last_error = $ret; SS_Log::log("Failed to send {$failed} emails", SS_Log::DEBUG); foreach ($reasons as $reason) { SS_Log::log("Failed to send because: {$reason}", SS_Log::DEBUG); } return false; } }
/** * Generate export fields for Excel. * * @param GridField $gridField * @return PHPExcel */ public function generateExportFileData($gridField) { $class = $gridField->getModelClass(); $columns = $this->exportColumns ? $this->exportColumns : ExcelImportExport::exportFieldsForClass($class); $fileData = ''; $singl = singleton($class); $singular = $class ? $singl->i18n_singular_name() : ''; $plural = $class ? $singl->i18n_plural_name() : ''; $filter = new FileNameFilter(); if ($this->exportName) { $this->exportName = $filter->filter($this->exportName); } else { $this->exportName = $filter->filter('export-' . $plural); } $excel = new PHPExcel(); $excelProperties = $excel->getProperties(); $excelProperties->setTitle($this->exportName); $sheet = $excel->getActiveSheet(); if ($plural) { $sheet->setTitle($plural); } $row = 1; $col = 0; if ($this->hasHeader) { $headers = array(); // determine the headers. If a field is callable (e.g. anonymous function) then use the // source name as the header instead foreach ($columns as $columnSource => $columnHeader) { $headers[] = !is_string($columnHeader) && is_callable($columnHeader) ? $columnSource : $columnHeader; } foreach ($headers as $header) { $sheet->setCellValueByColumnAndRow($col, $row, $header); $col++; } $endcol = PHPExcel_Cell::stringFromColumnIndex($col - 1); $sheet->setAutoFilter("A1:{$endcol}1"); $sheet->getStyle("A1:{$endcol}1")->getFont()->setBold(true); $col = 0; $row++; } // Autosize $cellIterator = $sheet->getRowIterator()->current()->getCellIterator(); try { $cellIterator->setIterateOnlyExistingCells(true); } catch (Exception $ex) { continue; } foreach ($cellIterator as $cell) { $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true); } //Remove GridFieldPaginator as we're going to export the entire list. $gridField->getConfig()->removeComponentsByType('GridFieldPaginator'); $items = $gridField->getManipulatedList(); // @todo should GridFieldComponents change behaviour based on whether others are available in the config? foreach ($gridField->getConfig()->getComponents() as $component) { if ($component instanceof GridFieldFilterHeader || $component instanceof GridFieldSortableHeader) { $items = $component->getManipulatedData($gridField, $items); } } foreach ($items->limit(null) as $item) { if (!$item->hasMethod('canView') || $item->canView()) { foreach ($columns as $columnSource => $columnHeader) { if (!is_string($columnHeader) && is_callable($columnHeader)) { if ($item->hasMethod($columnSource)) { $relObj = $item->{$columnSource}(); } else { $relObj = $item->relObject($columnSource); } $value = $columnHeader($relObj); } else { $value = $gridField->getDataFieldValue($item, $columnSource); if ($value === null) { $value = $gridField->getDataFieldValue($item, $columnHeader); } } $value = str_replace(array("\r", "\n"), "\n", $value); $sheet->setCellValueByColumnAndRow($col, $row, $value); $col++; } } if ($item->hasMethod('destroy')) { $item->destroy(); } $col = 0; $row++; } return $excel; }
public function testDuplicateDashesRemoved() { $name = 'test--document.txt'; $filter = new FileNameFilter(); $this->assertEquals('test-document.txt', $filter->filter($name)); }
/** * Get a random image * @return Image */ public static function image() { $images = DataObject::get('Image', "Filename LIKE 'assets/Faker/%'"); if (!count($images)) { $rss = file_get_contents(self::$imageRss); $xml = simplexml_load_string($rss); $nodes = $xml->xpath("//image"); $i = 0; $folder = Folder::find_or_make('Faker'); $dir = $folder->getFullPath(); $filter = new FileNameFilter(); foreach ($nodes as $node) { $i++; $image = file_get_contents((string) $node->url); $filename = $dir . '/' . basename($filter->filter((string) $node->title) . '.jpg'); file_put_contents($filename, $image); } $folder->syncChildren(); $images = DataObject::get('Image', "Filename LIKE 'assets/Faker/%'"); } $rand = rand(0, count($images)); foreach ($images as $key => $image) { if ($key == $rand) { return $image; } } return $images->First(); }
/** * Send the email through SparkPost * * @param string|array $to * @param string $from * @param string $subject * @param string $plainContent * @param array $attachedFiles * @param array $customheaders * @param bool $inlineImages * @return array|bool */ protected function send($to, $from, $subject, $htmlContent, $attachedFiles = false, $customheaders = false, $plainContent = false, $inlineImages = false) { $original_to = $to; // Process recipients $to_array = []; $to_array = $this->appendTo($to_array, $to); // Handle CC/BCC/BCC ALL if (isset($customheaders['Cc'])) { $to_array = $this->appendTo($to_array, $customheaders['Cc']); unset($customheaders['Cc']); } if (isset($customheaders['Bcc'])) { $to_array = $this->appendTo($to_array, $customheaders['Bcc']); unset($customheaders['Bcc']); } $bcc_email = Email::config()->bcc_all_emails_to; if ($bcc_email) { $to_array = $this->appendTo($to_array, $bcc_email); } // Process sender $from = $this->resolveDefaultFromEmail($from); // Create params $default_params = []; if (self::config()->default_params) { $default_params = self::config()->default_params; } $params = array_merge($default_params, ["subject" => $subject, "from" => $from, "recipients" => $to_array]); // Inject additional params into message if (isset($customheaders['X-SparkPostMailer'])) { $params = array_merge($params, $customheaders['X-SparkPostMailer']); unset($customheaders['X-SparkPostMailer']); } // Always set some default content if (!$plainContent && $htmlContent && self::config()->provide_plain) { $plainContent = $this->convertHtmlToText($htmlContent); } if ($plainContent) { $params['text'] = $plainContent; } if ($htmlContent) { if (self::config()->inline_styles) { try { $html = $this->inlineStyles($htmlContent); // Prevent SparkPost from inlining twice $params['default_params']['inlineCss'] = false; } catch (Exception $ex) { // If it fails, let SparkPost do the job $params['default_params']['inlineCss'] = true; } } $params['html'] = $htmlContent; } // Handle files attachments if ($attachedFiles) { $attachments = []; // Include any specified attachments as additional parts foreach ($attachedFiles as $file) { if (isset($file['tmp_name']) && isset($file['name'])) { $attachments[] = $this->encodeFileForEmail($file['tmp_name'], $file['name']); } else { $attachments[] = $this->encodeFileForEmail($file); } } $params['attachments'] = $attachments; } // Handle Reply-To custom header properly if (isset($customheaders['Reply-To'])) { $params['replyTo'] = $customheaders['Reply-To']; unset($customheaders['Reply-To']); } if ($customheaders) { $params['customHeaders'] = $customheaders; } if (self::config()->enable_logging) { // Append some extra information at the end $logContent = $htmlContent; $logContent .= '<hr><pre>Debug infos:' . "\n\n"; $logContent .= 'To : ' . print_r($original_to, true) . "\n"; $logContent .= 'Subject : ' . $subject . "\n"; $logContent .= 'Headers : ' . print_r($customheaders, true) . "\n"; if (!empty($params['from'])) { $logContent .= 'From : ' . $params['from'] . "\n"; } if (!empty($params['recipients'])) { $logContent .= 'Recipients : ' . print_r($params['recipients'], true) . "\n"; } $logContent .= '</pre>'; // Store it $logFolder = $this->getLogFolder(); $filter = new FileNameFilter(); $title = substr($filter->filter($subject), 0, 35); $ext = empty($htmlContent) ? 'txt' : 'html'; $r = file_put_contents($logFolder . '/' . date('Ymd') . '_' . $title . '_' . uniqid() . '.' . $ext, $logContent); if (!$r && Director::isDev()) { throw new Exception('Failed to store email in ' . $logFolder); } } if (self::config()->disable_sending) { $customheaders['X-SendingDisabled'] = true; return [$original_to, $subject, $htmlContent, $customheaders]; } $logLevel = self::config()->log_level ? self::config()->log_level : 7; try { $result = $this->getClient()->createTransmissions($params); if (!empty($result['total_accepted_recipients'])) { return [$original_to, $subject, $htmlContent, $customheaders]; } SS_Log::log("No recipient was accepted for transmission " . $result['id'], $logLevel); } catch (Exception $ex) { $this->lastException = $ex; SS_Log::log($ex->getMessage(), $logLevel); } return false; }