Esempio n. 1
0
 /**
  * Create a webhook from request data.
  *
  * https://apidocs.mailchimp.com/webhooks/
  *
  * @param  array                             $data Request data
  * @return \Tev\TevMailchimp\Webhook\Webhook
  *
  * @throws \Exception If failed to instantiate webhook due to invalid data
  */
 public function create($data)
 {
     try {
         return new Webhook($this->getType($data), $this->getFiredAt($data), $this->getData($data), $this->getMergeFields($data));
     } catch (Exception $e) {
         $this->logger->error('Hook parsing failed', ['error' => $e->getMessage(), 'hook_data' => $data]);
         throw $e;
     }
 }
 /**
  * Download all lists from Mailchimp.
  *
  * @return void
  */
 public function listsCommand()
 {
     $this->outputLine('<info>Downloading lists...</info>');
     try {
         $lists = $this->mailchimpService->downloadLists();
         foreach ($lists as $l) {
             $this->outputLine("<comment>- {$l->getMcListId()} downloaded</comment>");
         }
         $this->outputLine('<info>complete</info>');
         $this->logger->info('Lists downloaded successfully via CLI');
     } catch (Exception $e) {
         $this->outputLine("<error>Error: {$e->getMessage()}</error>");
         $this->logger->error('Lists failed to download via CLI', ['message' => $e->getMessage()]);
     }
 }
 /**
  * The actual processing TASK
  *
  * Should return an array with database properties for sys_file_metadata to write
  *
  * @param File $file
  * @param array $previousExtractedData optional, contains the array of already extracted data
  * @return array
  */
 public function extractMetaData(File $file, array $previousExtractedData = [])
 {
     $metadata = [];
     try {
         if (!class_exists('ColorThief\\ColorThief')) {
             throw new \RuntimeException('Class ColorThief\\ColorThief does not exist', 1470749087524);
         }
         $path = $file->getForLocalProcessing();
         $averageColor = ColorThief::getColor($path);
         if (!is_array($averageColor)) {
             throw new \RuntimeException('$averageColor is not an array', 1470749109020);
         }
         if (count($averageColor) !== 3) {
             throw new \RuntimeException('$averageColor is an array, but has less than 3 items', 1470749136303);
         }
         $r = dechex((int) $averageColor[0]);
         $g = dechex((int) $averageColor[1]);
         $b = dechex((int) $averageColor[2]);
         $metadata['average_color'] = '#' . $r . $g . $b;
         $this->logger->debug(sprintf('Extracted average color "%s"', $metadata['average_color']), ['file' => $file->getUid()]);
     } catch (\Exception $e) {
         $this->logger->error($e->getCode() . ': ' . $e->getMessage(), ['file' => $file->getUid()]);
     }
     return $metadata;
 }
 /**
  * Returns a list of mountpoints that are available in the VFS.
  * In case no storage exists this automatically created a storage for fileadmin/
  *
  * @return \TYPO3\CMS\Core\Resource\ResourceStorage[]
  */
 public function findAll()
 {
     // check if we have never created a storage before (no records, regardless of the enableFields),
     // only fetch one record for that (is enough). If no record is found, create the fileadmin/ storage
     $storageObjectsCount = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', $this->table, '1=1');
     if ($storageObjectsCount === 0) {
         $this->createLocalStorage('fileadmin/ (auto-created)', $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], 'relative', 'This is the local fileadmin/ directory. This storage mount has been created automatically by TYPO3.');
     }
     $storageObjects = array();
     $whereClause = NULL;
     if ($this->type != '') {
         $whereClause = $this->typeField . ' = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->type, $this->table);
     }
     $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->table, ($whereClause ? $whereClause : '1=1') . $this->getWhereClauseForEnabledFields());
     /** @var $driverRegistry \TYPO3\CMS\Core\Resource\Driver\DriverRegistry */
     $driverRegistry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Driver\\DriverRegistry');
     while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
         if ($driverRegistry->driverExists($row['driver'])) {
             $storageObjects[] = $this->createDomainObject($row);
         } else {
             $this->logger->warning(sprintf('Could not instantiate storage "%s" because of missing driver.', array($row['name'])), $row);
         }
     }
     $GLOBALS['TYPO3_DB']->sql_free_result($res);
     return $storageObjects;
 }
 /**
  * Clear all caches except the page cache.
  * This is especially useful on big sites when you can't just drop the page cache.
  *
  * @return void
  */
 public function clearAllExceptPageCacheCommand()
 {
     $clearedCaches = $this->cacheApiService->clearAllExceptPageCache();
     $message = 'Cleared caches: ' . implode(', ', $clearedCaches);
     $this->logger->info($message);
     $this->outputLine($message);
 }
 /**
  * Performs the database update.
  *
  * @param array $dbQueries queries done in this update
  * @param mixed $customMessages custom messages
  * @return boolean TRUE on success, FALSE on error
  */
 public function performUpdate(array &$dbQueries, &$customMessages)
 {
     $this->init();
     if (!PATH_site) {
         throw new \Exception('PATH_site was undefined.');
     }
     $fileadminDirectory = rtrim($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/');
     $targetDirectory = '/_migrated/RTE/';
     $fullTargetDirectory = PATH_site . $fileadminDirectory . $targetDirectory;
     // Create the directory, if necessary
     if (!is_dir($fullTargetDirectory)) {
         \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep($fullTargetDirectory);
     }
     $oldRecords = $this->findMagicImagesInOldLocation();
     foreach ($oldRecords as $refRecord) {
         // Is usually uploads/RTE_magicC_123423324.png.png
         $sourceFileName = $refRecord['ref_string'];
         // Absolute path/filename
         $fullSourceFileName = PATH_site . $refRecord['ref_string'];
         $targetFileName = $targetDirectory . \TYPO3\CMS\Core\Utility\PathUtility::basename($refRecord['ref_string']);
         // Full directory
         $fullTargetFileName = $fullTargetDirectory . \TYPO3\CMS\Core\Utility\PathUtility::basename($refRecord['ref_string']);
         // maybe the file has been moved previously
         if (!file_exists($fullTargetFileName)) {
             // If the source file does not exist, we should just continue, but leave a message in the docs;
             // ideally, the user would be informed after the update as well.
             if (!file_exists(PATH_site . $sourceFileName)) {
                 $this->logger->notice('File ' . $sourceFileName . ' does not exist. Reference was not migrated.', array());
                 $format = 'File \'%s\' does not exist. Referencing field: %s.%d.%s. The reference was not migrated.';
                 $message = sprintf($format, $sourceFileName, $refRecord['tablename'], $refRecord['recuid'], $refRecord['field']);
                 $customMessages .= PHP_EOL . $message;
                 continue;
             }
             rename($fullSourceFileName, $fullTargetFileName);
         }
         // Get the File object
         $file = $this->storage->getFile($targetFileName);
         if ($file instanceof \TYPO3\CMS\Core\Resource\File) {
             // And now update the referencing field
             $targetFieldName = $refRecord['field'];
             $targetRecord = $this->db->exec_SELECTgetSingleRow('uid, ' . $targetFieldName, $refRecord['tablename'], 'uid=' . (int) $refRecord['recuid']);
             if ($targetRecord) {
                 // Replace the old filename with the new one, and add data-* attributes used by the RTE
                 $searchString = 'src="' . $sourceFileName . '"';
                 $replacementString = 'src="' . $fileadminDirectory . $targetFileName . '"';
                 $replacementString .= ' data-htmlarea-file-uid="' . $file->getUid() . '"';
                 $replacementString .= ' data-htmlarea-file-table="sys_file"';
                 $targetRecord[$targetFieldName] = str_replace($searchString, $replacementString, $targetRecord[$targetFieldName]);
                 // Update the record
                 $this->db->exec_UPDATEquery($refRecord['tablename'], 'uid=' . (int) $refRecord['recuid'], array($targetFieldName => $targetRecord[$targetFieldName]));
                 $queries[] = str_replace(LF, ' ', $this->db->debug_lastBuiltQuery);
                 // Finally, update the sys_refindex table as well
                 $this->db->exec_UPDATEquery('sys_refindex', 'hash=' . $this->db->fullQuoteStr($refRecord['hash'], 'sys_refindex'), array('ref_table' => 'sys_file', 'softref_key' => 'rtehtmlarea_images', 'ref_uid' => $file->getUid(), 'ref_string' => $fileadminDirectory . $targetFileName));
                 $queries[] = str_replace(LF, ' ', $this->db->debug_lastBuiltQuery);
             }
         }
     }
     return TRUE;
 }
 /**
  * Basic information about the system.
  *
  * @return void
  */
 public function infoCommand()
 {
     $data = $this->siteApiService->getSiteInfo();
     foreach ($data as $key => $value) {
         $line = wordwrap($value, self::MAXIMUM_LINE_LENGTH - 43, PHP_EOL . str_repeat(' ', 43), TRUE);
         $this->outputLine('%-2s%-40s %s', array(' ', $key, $line));
     }
     $this->logger->info('siteApi:info executes successfully.');
 }
Esempio n. 8
0
 /**
  * Geocode a raw string to a lat/lng value.
  *
  * @param  string  $details  Geocode string
  * @return  array  Hash containing lat and lng. Both will be null if geocoding failed
  * @throws  \Exception  If API key is not set
  */
 public function geocode($details)
 {
     $geo = $this->createGeocoder();
     try {
         $coords = $geo->geocode($details)->first()->getCoordinates();
         return ['lat' => $coords->getLatitude(), 'lng' => $coords->getLongitude()];
     } catch (Exception $e) {
         $this->logger->error('Error geocoding details', ['exception_message' => $e->getMessage(), 'submitted_details' => $details]);
         return ['lat' => null, 'lng' => null];
     }
 }
Esempio n. 9
0
 /**
  * Unsubcribe the given email address from the given list.
  *
  * @param  string                               $email Email to unsubscribe from list
  * @param  \Tev\TevMailchimp\Domain\Model\Mlist $list  List to unsubscribe email from
  * @return void
  */
 public function unsubscribeFromList($email, Mlist $list)
 {
     try {
         $curStatus = $this->getSubscriptionStatus($email, $list);
         if ($curStatus === 'subscribed' || $curStatus === 'pending' || $curStatus === 'cleaned') {
             $this->mc->updateMember($list->getMcListId(), $this->getMailchimpId($email), ['status' => 'unsubscribed']);
         }
     } catch (Exception $e) {
         $this->logger->error('MC API exception during unsubscribeFromList', ['message' => $e->getMessage(), 'email' => $email, 'list_uid' => $list->getUid(), 'mc_list_id' => $list->getMcListId()]);
         throw $e;
     }
 }
 /**
  * Import extension from file.
  *
  * @param string  $file      Path to t3x file
  * @param string  $location  Where to import the extension. System = typo3/sysext, Global = typo3/ext, Local = typo3conf/ext
  * @param boolean $overwrite Overwrite the extension if already exists
  *
  * @return void
  */
 public function importCommand($file, $location = 'Local', $overwrite = FALSE)
 {
     try {
         $data = $this->extensionApiService->importExtension($file, $location, $overwrite);
         $message = sprintf('Extension "%s" has been imported!', $data['extKey']);
         $this->outputLine($message);
         $this->logger->info($message);
     } catch (Exception $e) {
         $this->outputLine($e->getMessage());
         $this->logger->error($e->getMessage());
         $this->quit(1);
     }
 }
 /**
  * Start password reset
  *
  * @param string $username Username of a user
  * @return void
  *
  * @validate $username NotEmpty
  */
 public function startPasswordResetAction($username)
 {
     $user = $this->frontendUserRepository->findOneByUsername($username);
     // Forbid password reset if there is no password or password property,
     // e.g. if the user has not completed a special registration process
     // or is supposed to authenticate in some other way
     $password = ObjectAccess::getPropertyPath($user, 'password');
     if ($password === NULL) {
         $this->logger->error('Failed to initiate password reset for user "' . $username . '": no password present');
         $this->addLocalizedFlashMessage('resetPassword.failed.nopassword', NULL, FlashMessage::ERROR);
         $this->redirect('showPasswordResetForm');
     }
     $hash = md5(GeneralUtility::generateRandomBytes(64));
     $token = array('uid' => $user->getUid(), 'hmac' => $this->hashService->generateHmac($password));
     $tokenLifetime = $this->getSettingValue('passwordReset.token.lifetime');
     // Remove possibly existing reset tokens and store new one
     $this->tokenCache->flushByTag($user->getUid());
     $this->tokenCache->set($hash, $token, array($user->getUid()), $tokenLifetime);
     $expiryDate = new \DateTime(sprintf('now + %d seconds', $tokenLifetime));
     $hashUri = $this->uriBuilder->setTargetPageUid($this->getSettingValue('passwordReset.page'))->setUseCacheHash(FALSE)->setCreateAbsoluteUri(TRUE)->uriFor('showPasswordResetForm', array('hash' => $hash));
     /** @var \PAGEmachine\Hairu\Domain\DTO\PasswordResetRequestTransferObject $passwordResetRequestTransferObject */
     $passwordResetRequestTransferObject = GeneralUtility::makeInstance('PAGEmachine\\Hairu\\Domain\\DTO\\PasswordResetRequestTransferObject');
     $passwordResetRequestTransferObject->setUser($user);
     $passwordResetRequestTransferObject->setHash($hash);
     $passwordResetRequestTransferObject->setHashUri($hashUri);
     $passwordResetRequestTransferObject->setExpiryDate($expiryDate);
     $actionVariables = array('user' => $user, 'hash' => $hash, 'hashUri' => $hashUri, 'expiryDate' => $expiryDate);
     $this->view->assignMultiple($actionVariables);
     /** @var \TYPO3\CMS\Core\Mail\MailMessage $message */
     $message = $this->objectManager->get('TYPO3\\CMS\\Core\\Mail\\MailMessage');
     $message->setFrom($this->getSettingValue('passwordReset.mail.from'))->setTo($user->getEmail())->setSubject($this->getSettingValue('passwordReset.mail.subject'));
     $this->request->setFormat('txt');
     $message->setBody($this->view->render('passwordResetMail'), 'text/plain');
     $this->request->setFormat('html');
     $message->addPart($this->view->render('passwordResetMail'), 'text/html');
     $mailSent = FALSE;
     $passwordResetRequestTransferObject->setMessage($message);
     $this->emitBeforePasswordResetMailSendSignal($passwordResetRequestTransferObject);
     try {
         $mailSent = $message->send();
     } catch (\Swift_SwiftException $e) {
         $this->logger->error($e->getMessage());
     }
     if ($mailSent) {
         $this->addLocalizedFlashMessage('resetPassword.started', NULL, FlashMessage::INFO);
     } else {
         $this->addLocalizedFlashMessage('resetPassword.failed.sending', NULL, FlashMessage::ERROR);
     }
     $this->redirect('showPasswordResetForm');
 }
 /**
  * Returns a list of mountpoints that are available in the VFS.
  * In case no storage exists this automatically created a storage for fileadmin/
  *
  * @return ResourceStorage[]
  */
 public function findAll()
 {
     $this->initializeLocalCache();
     /** @var $driverRegistry Driver\DriverRegistry */
     $driverRegistry = GeneralUtility::makeInstance(Driver\DriverRegistry::class);
     $storageObjects = array();
     foreach (static::$storageRowCache as $storageRow) {
         if ($driverRegistry->driverExists($storageRow['driver'])) {
             $storageObjects[] = $this->factory->getStorageObject($storageRow['uid'], $storageRow);
         } else {
             $this->logger->warning(sprintf('Could not instantiate storage "%s" because of missing driver.', array($storageRow['name'])), $storageRow);
         }
     }
     return $storageObjects;
 }
 /**
  * Create an empty record below the existing one
  *
  * @param array $row old plugin row
  * @return int uid of the new record
  */
 protected function createPluginBelowExisting(array $row)
 {
     $data = array();
     $data['tt_content']['NEW'] = array('hidden' => 1, 'pid' => $row['uid'] * -1);
     /** @var \TYPO3\CMS\Core\DataHandling\DataHandler $dataHandler */
     $dataHandler = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
     $dataHandler->start($data, array());
     $dataHandler->admin = 1;
     $dataHandler->process_datamap();
     if (!empty($dataHandler->errorLog)) {
         $this->logger->error('Error(s) while creating the empty content element');
         foreach ($dataHandler->errorLog as $log) {
             $this->logger->error($log);
         }
     }
     return (int) $dataHandler->substNEWwithIDs['NEW'];
 }
 /**
  * Unlocks the backend access by deleting the lock file
  */
 public function unlockCommand()
 {
     if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
         unlink(PATH_typo3conf . 'LOCK_BACKEND');
         if (@is_file(PATH_typo3conf . 'LOCK_BACKEND')) {
             $message = 'ERROR: Could not remove lock file \'typo3conf/LOCK_BACKEND\'!';
             $this->outputLine($message);
             $this->logger->error($message);
             $this->quit(1);
         } else {
             $message = 'Removed lock file \'typo3conf/LOCK_BACKEND\'';
             $this->outputLine($message);
             $this->logger->info($message);
         }
     } else {
         $message = 'No lock file \'typo3conf/LOCK_BACKEND\' was found, hence no lock could be removed.';
         $this->outputLine($message);
         $this->logger->info($message);
         $this->quit(1);
     }
 }
 /**
  * Database compare.
  * Leave the argument 'actions' empty or use "help" to see the available ones
  *
  * @param string $actions List of actions which will be executed
  * @param bool   $dry
  */
 public function databaseCompareCommand($actions = '', $dry = FALSE)
 {
     if ($actions === 'help' || strlen($actions) === 0) {
         $actions = $this->databaseApiService->databaseCompareAvailableActions();
         foreach ($actions as $number => $action) {
             $this->outputLine('  - ' . $action . ' => ' . $number);
         }
         $this->quit();
     }
     $result = $this->databaseApiService->databaseCompare($actions, $dry);
     if ($dry) {
         $this->outputLine('DB compare would execute the following queries:');
         foreach ($result as $key => $set) {
             $this->outputLine(sprintf('### Action: %s ###', $key));
             $this->outputLine('===================================');
             $this->logger->info(sprintf('### Action: %s ###', $key));
             $this->logger->info('===================================');
             foreach ($set as $line) {
                 $this->outputLine($line);
                 $this->logger->info($line);
             }
             $this->outputLine(LF);
         }
         $this->logger->info('DB compare executed in dry mode');
     } else {
         if (empty($result)) {
             $message = 'DB has been compared';
             $this->outputLine($message);
             $this->logger->info($message);
         } else {
             $message = sprintf('DB could not be compared, Error(s): %s', array(LF . implode(LF, $result)));
             $this->outputLine($message);
             $this->logger->error($message);
             $this->quit(1);
         }
     }
 }
Esempio n. 16
0
 /**
  * Logs alert-leveled events
  *
  * @param string $message Log message
  * @param array $context Context data
  *
  * @return void
  */
 public function alert($message, array $context = [])
 {
     $this->logger->alert($message, $context);
 }
 /**
  * Migrates a single field.
  *
  * @param string $table
  * @param array $row
  * @param string $fieldname
  * @param array $fieldConfiguration
  * @param string $customMessages
  * @return array A list of performed database queries
  * @throws \Exception
  */
 protected function migrateField($table, $row, $fieldname, $fieldConfiguration, &$customMessages)
 {
     $titleTextContents = [];
     $alternativeTextContents = [];
     $captionContents = [];
     $linkContents = [];
     $fieldItems = GeneralUtility::trimExplode(',', $row[$fieldname], true);
     if (empty($fieldItems) || is_numeric($row[$fieldname])) {
         return [];
     }
     if (isset($fieldConfiguration['titleTexts'])) {
         $titleTextField = $fieldConfiguration['titleTexts'];
         $titleTextContents = explode(LF, $row[$titleTextField]);
     }
     if (isset($fieldConfiguration['alternativeTexts'])) {
         $alternativeTextField = $fieldConfiguration['alternativeTexts'];
         $alternativeTextContents = explode(LF, $row[$alternativeTextField]);
     }
     if (isset($fieldConfiguration['captions'])) {
         $captionField = $fieldConfiguration['captions'];
         $captionContents = explode(LF, $row[$captionField]);
     }
     if (isset($fieldConfiguration['links'])) {
         $linkField = $fieldConfiguration['links'];
         $linkContents = explode(LF, $row[$linkField]);
     }
     $fileadminDirectory = rtrim($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/') . '/';
     $queries = [];
     $i = 0;
     if (!PATH_site) {
         throw new \Exception('PATH_site was undefined.');
     }
     $storageUid = (int) $this->storage->getUid();
     foreach ($fieldItems as $item) {
         $fileUid = null;
         $sourcePath = PATH_site . $fieldConfiguration['sourcePath'] . $item;
         $targetDirectory = PATH_site . $fileadminDirectory . $fieldConfiguration['targetPath'];
         $targetPath = $targetDirectory . basename($item);
         // maybe the file was already moved, so check if the original file still exists
         if (file_exists($sourcePath)) {
             if (!is_dir($targetDirectory)) {
                 GeneralUtility::mkdir_deep($targetDirectory);
             }
             // see if the file already exists in the storage
             $fileSha1 = sha1_file($sourcePath);
             $existingFileRecord = $this->database->exec_SELECTgetSingleRow('uid', 'sys_file', 'sha1=' . $this->database->fullQuoteStr($fileSha1, 'sys_file') . ' AND storage=' . $storageUid);
             // the file exists, the file does not have to be moved again
             if (is_array($existingFileRecord)) {
                 $fileUid = $existingFileRecord['uid'];
             } else {
                 // just move the file (no duplicate)
                 rename($sourcePath, $targetPath);
             }
         }
         if ($fileUid === null) {
             // get the File object if it hasn't been fetched before
             try {
                 // if the source file does not exist, we should just continue, but leave a message in the docs;
                 // ideally, the user would be informed after the update as well.
                 /** @var File $file */
                 $file = $this->storage->getFile($fieldConfiguration['targetPath'] . $item);
                 $fileUid = $file->getUid();
             } catch (\InvalidArgumentException $e) {
                 // no file found, no reference can be set
                 $this->logger->notice('File ' . $fieldConfiguration['sourcePath'] . $item . ' does not exist. Reference was not migrated.', ['table' => $table, 'record' => $row, 'field' => $fieldname]);
                 $format = 'File \'%s\' does not exist. Referencing field: %s.%d.%s. The reference was not migrated.';
                 $message = sprintf($format, $fieldConfiguration['sourcePath'] . $item, $table, $row['uid'], $fieldname);
                 $customMessages .= PHP_EOL . $message;
                 continue;
             }
         }
         if ($fileUid > 0) {
             $fields = ['fieldname' => $fieldname, 'table_local' => 'sys_file', 'pid' => $table === 'pages' ? $row['uid'] : $row['pid'], 'uid_foreign' => $row['uid'], 'uid_local' => $fileUid, 'tablenames' => $table, 'crdate' => time(), 'tstamp' => time(), 'sorting' => $i + 256, 'sorting_foreign' => $i];
             if (isset($titleTextField)) {
                 $fields['title'] = trim($titleTextContents[$i]);
             }
             if (isset($alternativeTextField)) {
                 $fields['alternative'] = trim($alternativeTextContents[$i]);
             }
             if (isset($captionField)) {
                 $fields['description'] = trim($captionContents[$i]);
             }
             if (isset($linkField)) {
                 $fields['link'] = trim($linkContents[$i]);
             }
             $this->database->exec_INSERTquery('sys_file_reference', $fields);
             $queries[] = str_replace(LF, ' ', $this->database->debug_lastBuiltQuery);
             ++$i;
         }
     }
     // Update referencing table's original field to now contain the count of references,
     // but only if all new references could be set
     if ($i === count($fieldItems)) {
         $this->database->exec_UPDATEquery($table, 'uid=' . $row['uid'], [$fieldname => $i]);
         $queries[] = str_replace(LF, ' ', $this->database->debug_lastBuiltQuery);
     } else {
         $this->recordOffset[$table]++;
     }
     return $queries;
 }
 /**
  * @return LoggerInterface
  */
 protected function createNullLogger()
 {
     $logger = new Logger(__CLASS__);
     $logger->addWriter(LogLevel::EMERGENCY, new NullWriter());
     return $logger;
 }
Esempio n. 19
0
 /**
  * Process an email change webhook.
  *
  * @param  \Tev\TevMailchimp\Webhook\Webhook $hook Incoming webhook
  * @return void
  */
 private function processEmailChange(Webhook $hook)
 {
     $this->unsubscribe($hook->getData('old_email'), $hook->getData('list_id'));
     $this->subscribe($hook->getData('new_email'), $hook->getData('list_id'));
     $this->logger->info('Processed email change hook', ['old_email' => $hook->getData('old_email'), 'new_email' => $hook->getData('new_email'), 'list_id' => $hook->getData('list_id')]);
 }
 /**
  * Creates a logger which outputs to the console
  *
  * @param int $minimumLevel Minimum log level that should trigger output
  * @param array $options Additional options for the console writer
  * @return LoggerInterface
  */
 protected function createDefaultLogger($minimumLevel = LogLevel::DEBUG, $options = array())
 {
     $options['output'] = new SymfonyConsoleOutput();
     $logger = new Logger(get_class($this));
     $logger->addWriter($minimumLevel, new ConsoleWriter($options));
     return $logger;
 }
Esempio n. 21
0
 /**
  * Logs info-leveled events
  *
  * @param string $message Log message
  * @param array $context Context data
  *
  * @return void
  */
 public function info($message, array $context = array())
 {
     $this->logger->info($message, $context);
 }
Esempio n. 22
0
 /**
  * @test
  */
 public function addWriterAddsWriterAlsoToHigherLevelsThanSpecified()
 {
     $logger = new Logger('test.core.log');
     $writer = new Fixtures\WriterFixture();
     $logger->addWriter(LogLevel::NOTICE, $writer);
     $writers = $logger->getWriters();
     $this->assertContains($writer, $writers[LogLevel::EMERGENCY]);
 }
Esempio n. 23
0
 /**
  * Appends the processors to the given logger as configured.
  *
  * @param \TYPO3\CMS\Core\Log\Logger $logger Logger to configure
  * @return void
  * @throws \RangeException
  */
 protected function setProcessorsForLogger(\TYPO3\CMS\Core\Log\Logger $logger)
 {
     $configuration = $this->getConfigurationForLogger(self::CONFIGURATION_TYPE_PROCESSOR, $logger->getName());
     foreach ($configuration as $severityLevel => $processor) {
         foreach ($processor as $logProcessorClassName => $logProcessorOptions) {
             /** @var $logProcessor \TYPO3\CMS\Core\Log\Processor\ProcessorInterface */
             $logProcessor = NULL;
             try {
                 $logProcessor = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($logProcessorClassName, $logProcessorOptions);
                 $logger->addProcessor($severityLevel, $logProcessor);
             } catch (\RangeException $e) {
                 $logger->warning('Instantiation of LogProcessor "' . $logProcessorClassName . '" failed for logger ' . $logger->getName() . ' (' . $e->getMessage() . ')');
             }
         }
     }
 }
Esempio n. 24
0
 /**
  * Migrates a single field.
  *
  * @param array $row
  * @param string $customMessages
  * @param array $dbQueries
  *
  * @throws \Exception
  */
 protected function migrateField($row, &$customMessages, &$dbQueries)
 {
     $fieldItems = GeneralUtility::trimExplode(',', $row[$this->fieldToMigrate], true);
     if (empty($fieldItems) || is_numeric($row[$this->fieldToMigrate])) {
         return;
     }
     $fileadminDirectory = rtrim($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/') . '/';
     $i = 0;
     if (!PATH_site) {
         throw new \Exception('PATH_site was undefined.', 1476107387);
     }
     $storageUid = (int) $this->storage->getUid();
     $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
     foreach ($fieldItems as $item) {
         $fileUid = null;
         $sourcePath = PATH_site . $this->sourcePath . $item;
         $targetDirectory = PATH_site . $fileadminDirectory . $this->targetPath;
         $targetPath = $targetDirectory . basename($item);
         // maybe the file was already moved, so check if the original file still exists
         if (file_exists($sourcePath)) {
             if (!is_dir($targetDirectory)) {
                 GeneralUtility::mkdir_deep($targetDirectory);
             }
             // see if the file already exists in the storage
             $fileSha1 = sha1_file($sourcePath);
             $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
             $queryBuilder->getRestrictions()->removeAll();
             $existingFileRecord = $queryBuilder->select('uid')->from('sys_file')->where($queryBuilder->expr()->eq('sha1', $queryBuilder->createNamedParameter($fileSha1, \PDO::PARAM_STR)), $queryBuilder->expr()->eq('storage', $queryBuilder->createNamedParameter($storageUid, \PDO::PARAM_INT)))->execute()->fetch();
             // the file exists, the file does not have to be moved again
             if (is_array($existingFileRecord)) {
                 $fileUid = $existingFileRecord['uid'];
             } else {
                 // just move the file (no duplicate)
                 rename($sourcePath, $targetPath);
             }
         }
         if ($fileUid === null) {
             // get the File object if it hasn't been fetched before
             try {
                 // if the source file does not exist, we should just continue, but leave a message in the docs;
                 // ideally, the user would be informed after the update as well.
                 $file = $this->storage->getFile($this->targetPath . $item);
                 $fileUid = $file->getUid();
             } catch (\InvalidArgumentException $e) {
                 // no file found, no reference can be set
                 $this->logger->notice('File ' . $this->sourcePath . $item . ' does not exist. Reference was not migrated.', ['table' => $this->table, 'record' => $row, 'field' => $this->fieldToMigrate]);
                 $format = 'File \'%s\' does not exist. Referencing field: %s.%d.%s. The reference was not migrated.';
                 $message = sprintf($format, $this->sourcePath . $item, $this->table, $row['uid'], $this->fieldToMigrate);
                 $customMessages .= PHP_EOL . $message;
                 continue;
             }
         }
         if ($fileUid > 0) {
             $fields = ['fieldname' => $this->fieldToMigrate, 'table_local' => 'sys_file', 'pid' => $this->table === 'pages' ? $row['uid'] : $row['pid'], 'uid_foreign' => $row['uid'], 'uid_local' => $fileUid, 'tablenames' => $this->table, 'crdate' => time(), 'tstamp' => time(), 'sorting' => $i + 256, 'sorting_foreign' => $i];
             $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file_reference');
             $queryBuilder->insert('sys_file_reference')->values($fields)->execute();
             $dbQueries[] = str_replace(LF, ' ', $queryBuilder->getSQL());
             ++$i;
         }
     }
     // Update referencing table's original field to now contain the count of references,
     // but only if all new references could be set
     if ($i === count($fieldItems)) {
         $queryBuilder = $connectionPool->getQueryBuilderForTable($this->table);
         $queryBuilder->update($this->table)->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)))->set($this->fieldToMigrate, $i)->execute();
         $dbQueries[] = str_replace(LF, ' ', $queryBuilder->getSQL());
     } else {
         $this->recordOffset[$this->table]++;
     }
 }
Esempio n. 25
0
 /**
  * Remove temporary file.
  *
  * @param string $filePath
  */
 protected function removeTemporaryFile($filePath)
 {
     if (!GeneralUtility::unlink_tempfile($filePath)) {
         $this->logger->error('Failed to remove file', array('filepath' => $filePath));
     }
 }
Esempio n. 26
0
 /**
  * Log a mail message.
  *
  * @param  \TYPO3\CMS\Core\Mail\MailMessage $mail   Mail message
  * @param  boolean                          $result Whether or not the messag was sent successfully
  * @return void
  */
 public function logMessage(MailMessage $mail, $result = true)
 {
     $this->logger->log($result ? LogLevel::INFO : LogLevel::ERROR, $result ? 'Email sent' : 'Email failed to send', ['from' => $mail->getFrom(), 'to' => $mail->getTo(), 'subject' => $mail->getSubject(), 'body' => $mail->getBody()]);
 }
 public function searchResultAction()
 {
     $this->logger = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Log\\LogManager')->getLogger(__CLASS__);
     //$this->logger->warning('hallo hier der logger' . __METHOD__);
     $debug = false;
     $isAjax = true;
     if ($this->request->hasArgument('ajax')) {
         $isAjax = true;
     }
     $args = $this->request->getArguments();
     /** @var  $searchForm \MUM\BjrFreizeit\Utility\LeisureSearchForm */
     $searchForm = GeneralUtility::makeInstance('MUM\\BjrFreizeit\\Utility\\LeisureSearchForm', $args);
     if ($debug) {
         return json_encode(array('html' => print_r($searchForm, true), 'args' => $args));
     }
     $leisures = $this->leisureRepository->findAllBySearchForm($searchForm);
     if ($leisures->count() > 0) {
         //$this->typoScript = $this->getFullTypoScript();
         $this->view->assign('found', true);
         $this->view->assign('leisures', $leisures);
         $this->view->assign('imagePath', $this->settings['leisureImagePath']);
         $this->view->assign('detailPage', $this->settings['detailPage']);
     } else {
         $this->view->assign('found', false);
     }
     if ($isAjax) {
         $renderer = $this->getPlainRenderer('SearchResult', 'html');
         $renderer->assign('found', $leisures->count() > 0);
         $renderer->assign('leisures', $leisures);
         $renderer->assign('imagePath', $this->settings['leisureImagePath']);
         $renderer->assign('detailPage', $this->settings['detailPage']);
         $html = $renderer->render();
         //$html = $this->view->render();
         $success = true;
         $this->logger->alert('SearchManager ', array('keyword' => $searchForm->getDescription()));
         $this->logger->alert('Arguments ', $args);
         return json_encode(array('html' => $html, 'success' => $success, 'arguments' => $args, 'searchManagerCategory' => $searchForm->getCategory(), 'number' => $leisures->count()));
     } else {
     }
 }