/** * The main method of the PlugIn * * @access public * * @param string $content: The PlugIn content * @param array $conf: The PlugIn configuration * * @return string The content that is displayed on the website */ public function main($content, $conf) { $this->init($conf); // Turn cache on. $this->setCache(TRUE); // Quit without doing anything if required configuration variables are not set. if (empty($this->conf['pages'])) { if (TYPO3_DLOG) { t3lib_div::devLog('[tx_dlf_statistics->main(' . $content . ', [data])] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf); } return $content; } // Get description. $content .= $this->pi_RTEcssText($this->conf['description']); // Check for selected collections. if ($this->conf['collections']) { // Include only selected collections. $resultTitles = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query('tx_dlf_documents.uid AS uid', 'tx_dlf_documents', 'tx_dlf_relations', 'tx_dlf_collections', 'AND tx_dlf_documents.pid=' . intval($this->conf['pages']) . ' AND tx_dlf_collections.pid=' . intval($this->conf['pages']) . ' AND tx_dlf_documents.partof=0 AND tx_dlf_collections.uid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']) . ') AND tx_dlf_relations.ident=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations') . tx_dlf_helper::whereClause('tx_dlf_documents') . tx_dlf_helper::whereClause('tx_dlf_collections'), 'tx_dlf_documents.uid', '', ''); $resultVolumes = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query('tx_dlf_documents.uid AS uid', 'tx_dlf_documents', 'tx_dlf_relations', 'tx_dlf_collections', 'AND tx_dlf_documents.pid=' . intval($this->conf['pages']) . ' AND tx_dlf_collections.pid=' . intval($this->conf['pages']) . ' AND NOT tx_dlf_documents.uid IN (SELECT DISTINCT tx_dlf_documents.partof FROM tx_dlf_documents WHERE NOT tx_dlf_documents.partof=0' . tx_dlf_helper::whereClause('tx_dlf_documents') . ') AND tx_dlf_collections.uid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($this->conf['collections']) . ') AND tx_dlf_relations.ident=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('docs_colls', 'tx_dlf_relations') . tx_dlf_helper::whereClause('tx_dlf_documents') . tx_dlf_helper::whereClause('tx_dlf_collections'), 'tx_dlf_documents.uid', '', ''); } else { // Include all collections. $resultTitles = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_documents.uid AS uid', 'tx_dlf_documents', 'tx_dlf_documents.pid=' . intval($this->conf['pages']) . ' AND tx_dlf_documents.partof=0' . tx_dlf_helper::whereClause('tx_dlf_documents'), '', '', ''); $resultVolumes = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_documents.uid AS uid', 'tx_dlf_documents', 'tx_dlf_documents.pid=' . intval($this->conf['pages']) . ' AND NOT tx_dlf_documents.uid IN (SELECT DISTINCT tx_dlf_documents.partof FROM tx_dlf_documents WHERE NOT tx_dlf_documents.partof=0' . tx_dlf_helper::whereClause('tx_dlf_documents') . ')' . tx_dlf_helper::whereClause('tx_dlf_documents'), '', '', ''); } $countTitles = $GLOBALS['TYPO3_DB']->sql_num_rows($resultTitles); $countVolumes = $GLOBALS['TYPO3_DB']->sql_num_rows($resultVolumes); // Set replacements. $replace = array('key' => array('###TITLES###', '###VOLUMES###'), 'value' => array($countTitles . ($countTitles > 1 ? $this->pi_getLL('titles', '', TRUE) : $this->pi_getLL('title', '', TRUE)), $countVolumes . ($countVolumes > 1 ? $this->pi_getLL('volumes', '', TRUE) : $this->pi_getLL('volume', '', TRUE)))); // Apply replacements. $content = str_replace($replace['key'], $replace['value'], $content); return $this->pi_wrapInBaseClass($content); }
/** * Writes exception to different logs * * @param Exception $exception The exception * @param string the context where the exception was thrown, WEB or CLI * @return void * @see t3lib_div::sysLog(), t3lib_div::devLog() */ protected function writeLogEntries(Exception $exception, $context) { $filePathAndName = $exception->getFile(); $exceptionCodeNumber = $exception->getCode() > 0 ? '#' . $exception->getCode() . ': ' : ''; $logTitle = 'Core: Exception handler (' . $context . ')'; $logMessage = 'Uncaught TYPO3 Exception: ' . $exceptionCodeNumber . $exception->getMessage() . ' | ' . get_class($exception) . ' thrown in file ' . $filePathAndName . ' in line ' . $exception->getLine(); $backtrace = $exception->getTrace(); // write error message to the configured syslogs t3lib_div::sysLog($logMessage, $logTitle, 4); // When database credentials are wrong, the exception is probably // caused by this. Therefor we cannot do any database operation, // otherwise this will lead into recurring exceptions. try { // In case an error occurs before a database connection exists, try // to connect to the DB to be able to write the devlog/sys_log entry if (isset($GLOBALS['TYPO3_DB']) && is_object($GLOBALS['TYPO3_DB']) && empty($GLOBALS['TYPO3_DB']->link)) { $GLOBALS['TYPO3_DB']->connectDB(); } // write error message to devlog // see: $TYPO3_CONF_VARS['SYS']['enable_exceptionDLOG'] if (TYPO3_EXCEPTION_DLOG) { t3lib_div::devLog($logMessage, $logTitle, 3, array('TYPO3_MODE' => TYPO3_MODE, 'backtrace' => $backtrace)); } // write error message to sys_log table $this->writeLog($logTitle . ': ' . $logMessage); } catch (Exception $exception) { // Nothing happens here. It seems the database credentials are wrong } }
/** * The main method of the PlugIn * * @access public * * @param string $content: The PlugIn content * @param array $conf: The PlugIn configuration * * @return string The content that is displayed on the website */ public function main($content, $conf) { $this->init($conf); // Turn cache on. $this->setCache(TRUE); // Quit without doing anything if required configuration variables are not set. if (empty($this->conf['pages'])) { if (TYPO3_DLOG) { t3lib_div::devLog('[tx_dlf_collection->main(' . $content . ', [data])] Incomplete plugin configuration', $this->extKey, SYSLOG_SEVERITY_WARNING, $conf); } return $content; } // Load template file. if (!empty($this->conf['templateFile'])) { $this->template = $this->cObj->getSubpart($this->cObj->fileResource($this->conf['templateFile']), '###TEMPLATE###'); } else { $this->template = $this->cObj->getSubpart($this->cObj->fileResource('EXT:dlf/plugins/collection/template.tmpl'), '###TEMPLATE###'); } // Get hook objects. $this->hookObjects = tx_dlf_helper::getHookObjects($this->scriptRelPath); if (!empty($this->piVars['collection'])) { $this->showSingleCollection(intval($this->piVars['collection'])); } else { $content .= $this->showCollectionList(); } return $this->pi_wrapInBaseClass($content); }
/** * Workaround for missing support of typeHints in parameters * the typeHint is parsed from a the casted string representation of the * reflectionParameter * The string has the format 'Parameter #index [ <required/optional> typeHint $parameterName ]' * where index is the sort number and typeHint is optional * The parts in the brackets are splitted and counted * * @param $reflectionParameter * @return string typeHint */ protected function getTypeHintFromReflectionParameter($reflectionParameter) { $paramAsString = (string) $reflectionParameter; $paramRegex = '/^Parameter\\s\\#[0-9]\\s\\[\\s<(required|optional)>\\s*.*\\$.*]$/'; //t3lib_div::devLog('ReflectionParameter in method '.$this->getName().' : '.$paramAsString,'extension_builder',2); if (!preg_match($paramRegex, $paramAsString)) { // since the approach to cast the reflection parameter as a string is not part of the official PHP API // this might not work anymore in future versions t3lib_div::devLog('ReflectionParameter in method ' . $this->getName() . ' casted as string has not the expected format: ' . $paramAsString, 'extension_builder', 2); return ''; } $typeHintRegex = '/>\\s*([a-zA-Z0-9_&\\s]*)\\s*\\$/'; $matches = array(); if (preg_match($typeHintRegex, $paramAsString, $matches)) { if (!empty($matches[1])) { $typeHint = $matches[1]; if ($reflectionParameter->isPassedByReference()) { // remove the & from typeHint $typeHint = str_replace('&', '', $typeHint); } $typeHint = trim($typeHint); return $typeHint; } } return ''; }
/** * Handles the indexing of the page content during post processing of * a generated page. * * @param tslib_fe Typoscript frontend */ public function hook_indexContent(tslib_fe $page) { $this->page = $page; // determine if the current page should be indexed if ($this->indexingEnabled()) { try { // do some checks first if ($page->page['no_search']) { throw new Exception('Index page? No, The "No Search" flag has been set in the page properties!', 1234523946); } if ($page->no_cache) { throw new Exception('Index page? No, page was set to "no_cache" and so cannot be indexed.', 1234524030); } if ($page->sys_language_uid != $page->sys_language_content) { throw new Exception('Index page? No, ->sys_language_uid was different from sys_language_content which indicates that the page contains fall-back content and that would be falsely indexed as localized content.', 1234524095); } if ($GLOBALS['TSFE']->beUserLogin && !$GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['index.']['enableIndexingWhileBeUserLoggedIn']) { throw new Exception('Index page? No, Detected a BE user being logged in.', 1246444055); } // everything ready, let's do it $indexer = t3lib_div::makeInstance('tx_solr_Typo3PageIndexer', $page); $indexer->setPageAccessRootline($this->getAccessRootline()); $indexer->indexPage(); } catch (Exception $e) { # $this->log($e->getMessage() . ' Error code: ' . $e->getCode(), 3); if ($GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['logging.']['exceptions']) { t3lib_div::devLog('Exception while trying to index a page', 'tx_solr', 3, array($e->__toString())); } } } }
/** * Starts the execution of a frontend helper. * * @param Tx_Solr_IndexQueue_PageIndexerRequest $request Page indexer request * @param Tx_Solr_IndexQueue_PageIndexerResponse $response Page indexer response */ public function processRequest(Tx_Solr_IndexQueue_PageIndexerRequest $request, Tx_Solr_IndexQueue_PageIndexerResponse $response) { $this->request = $request; $this->response = $response; if ($request->getParameter('loggingEnabled')) { t3lib_div::devLog('Page indexer request received', 'solr', 0, array('request' => (array) $request)); } }
/** * action doMigrateData * * @return void */ public function doMigrateDataAction() { t3lib_div::devLog('doMigrateDataAction', " universal_content_lists", -1, array()); #$this->migrateEmails(); t3lib_div::devLog("doMigrateDataAction Data Migration complete", " universal_content_lists", -1); $this->flashMessageContainer->add('Data Migration complete'); # $this->redirect('migrateData'); }
/** * Extracts the markup wrapped with TYPO3SEARCH_begin and TYPO3SEARCH_end * markers. * * @param string HTML markup with TYPO3SEARCH markers for content that should be indexed * @return string HTML markup found between TYPO3SEARCH markers */ protected function extractContentMarkedForIndexing($html) { preg_match_all('/<!--\\s*?TYPO3SEARCH_begin\\s*?-->.*?<!--\\s*?TYPO3SEARCH_end\\s*?-->/mis', $html, $indexableContents); $indexableContent = implode($indexableContents[0], ''); if (empty($indexableContent) && $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['logging.']['indexing.']['missingTypo3SearchMarkers']) { t3lib_div::devLog('No TYPO3SEARCH markers found.', 'solr', 2); } return $indexableContent; }
/** * Logs the given values. * * @return void */ public function process() { $message = 'Form on page ' . $GLOBALS['TSFE']->id . ' was submitted!'; $severity = 1; if (intval($this->settings['markAsSpam']) === 1) { $message = 'Caught possible spamming on page ' . $GLOBALS['TSFE']->id . '!'; $severity = 2; } t3lib_div::devLog($message, 'formhandler', $severity, $this->gp); }
/** * Make the given contexts active (available in this container) * * @param array $arContexts Array of context objects * * @return Tx_Contexts_Context_Container */ protected function setActive($arContexts) { $this->exchangeArray($arContexts); $aliases = array(); foreach ($arContexts as $context) { $aliases[] = $context->getAlias(); } t3lib_div::devLog(count($this) . ' active contexts: ' . implode(', ', $aliases), 'tx_contexts', 0); return $this; }
/** * Return URL from pageID. * Will look through all registered services, and use the first one that finds the URL. * It returns an array where each entry is an associative array with domain and pagepath. * If the service that locates the URL is unable to determine from which domain this URL is found from, the * domain key is not set. * * @param integer $uid * @return array An array of all found URL for this page id. */ public function getUrlFromPageID($uid) { foreach ($this->URLFinders as $finder) { if ($urls = $finder->getURLFromPageID($uid)) { return $urls; } } t3lib_div::devLog('Unable to determine pageURL for page with uid ' . $uid, 'moc_varnish', 2); return array(); }
/** * Authenticates the request, runs the frontend helpers defined by the * request, and registers its own shutdown() method for execution at * hook_eofe in tslib/class.tslib_fe.php. * * @return void */ public function run() { if (!$this->request->isAuthenticated()) { t3lib_div::devLog('Invalid Index Queue Frontend Request detected!', 'solr', 3, array('page indexer request' => (array) $this->request, 'index queue header' => $_SERVER['HTTP_X_TX_SOLR_IQ'])); die('Invalid Index Queue Request!'); } $this->dispatcher->dispatch($this->request, $this->response); // register shutdown method here instead of in ext_localconf.php to // allow frontend helpers to execute at hook_eofe in // tslib/class.tslib_fe.php before shuting down $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe'][__CLASS__] = '&Tx_Solr_IndexQueue_PageIndexerRequestHandler->shutdown'; }
/** * Renders the size of a file using t3lib_div::formatSize * * @param string $file Path to the file * @param string $format Labels for bytes, kilo, mega and giga separated by vertical bar (|) and possibly encapsulated in "". Eg: " | K| M| G" (which is the default value) * @param boolean $hideError Define if an error should be displayed if file not found * @return string * @throws Tx_Fluid_Core_ViewHelper_Exception_InvalidVariableException */ public function render($file, $format = '', $hideError = FALSE) { if (!is_file($file)) { $errorMessage = sprintf('Given file "%s" for %s is not valid', htmlspecialchars($file), get_class()); t3lib_div::devLog($errorMessage, 'news', t3lib_div::SYSLOG_SEVERITY_WARNING); if (!$hideError) { throw new Tx_Fluid_Core_ViewHelper_Exception_InvalidVariableException('Given file is not a valid file: ' . htmlspecialchars($file)); } } $fileSize = t3lib_div::formatSize(filesize($file), $format); return $fileSize; }
public function outputDebugLog() { foreach ($this->debugLog as $section => $logData) { foreach ($logData as $messageData) { $message = $section . ': ' . $messageData['message']; $data = FALSE; if (is_array($messageData['data'])) { $data = $messageData['data']; } t3lib_div::devLog($message, 'formhandler', $severity, $data); } } }
/** * Writes log message. * Destination log depends on the current system mode. * For FE the function writes to the admin panel log. For BE messages are * sent to the system log. If developer log is enabled, messages are also * sent there. * * This function accepts variable number of arguments and can format * parameters. The syntax is the same as for sprintf() * * @param string $message: * to output * @return void * @see sprintf() * @see t3lib::divLog() * @see t3lib_div::sysLog() * @see t3lib_timeTrack::setTSlogMessage() */ public static function writeLogMessage($message) { if (func_num_args() > 1) { $params = func_get_args(); array_shift($params); $message = vsprintf($message, $params); } if (TYPO3_MODE === 'BE') { t3lib_div::sysLog($message, self::$extKey, 1); } if (TYPO3_DLOG) { t3lib_div::devLog($message, self::$extKey, 1); } }
/** * Indexes items from the Index Queue. * * @return void */ protected function indexItems() { $limit = $this->documentsToIndexLimit; $indexQueue = t3lib_div::makeInstance('Tx_Solr_IndexQueue_Queue'); // get items to index $itemsToIndex = $indexQueue->getItemsToIndex($this->site, $limit); foreach ($itemsToIndex as $itemToIndex) { try { // try indexing $itemIndexed = $this->indexItem($itemToIndex); } catch (Exception $e) { $indexQueue->markItemAsFailed($itemToIndex, $e->getCode() . ': ' . $e->__toString()); t3lib_div::devLog('Failed indexing Index Queue item ' . $itemToIndex->getIndexQueueUid(), 'solr', 3, array('code' => $e->getCode(), 'message' => $e->getMessage(), 'trace' => $e->getTrace(), 'item' => (array) $itemToIndex)); } } }
/** * @return boolean */ public function execute() { t3lib_div::devLog('[tx_scheduler_ImportMember]: execute', 't3o_membership', 0); $membershipRecords = $this->getDatabaseConnection()->exec_SELECTgetRows('uid, name', 'tx_t3omembership_domain_model_membership', 'NOT hidden AND NOT deleted'); foreach ($membershipRecords as $membershipRecord) { $this->memberships[$membershipRecord['name']] = (int) $membershipRecord['uid']; } // does the import file exist? $importFile = $this->getImportFile(); if (!t3lib_div::isAbsPath($importFile)) { $importFile = t3lib_div::getFileAbsFileName($importFile); } if (!file_exists($importFile)) { t3lib_div::devLog('[tx_scheduler_ImportMember]: no importfile - given value: ' . $importFile, 't3o_membership', 0); return false; } $this->initializeHookObjects(); $fileData = file($importFile); array_shift($fileData); foreach ($fileData as $key => $line) { $line = iconv('ISO-8859-15', 'UTF-8', $line); /** @noinspection PhpParamsInspection */ $fields = t3lib_div::trimExplode("\t", $line); $membershipUid = $this->getMembershipUid($fields[12]); // Skip records with unknown membership types. if (empty($membershipUid)) { continue; } $subscriptionNo = (int) $fields[14]; $endDate = $this->getMemberEndDate($fields[15]); // If the user has cancelled his membership "Gekündigt", we set the endtime enable field. $endTime = !empty($fields[17]) ? $endDate : 0; $hidden = false; if ($endTime > 0 && $endTime < time()) { $hidden = true; } $member = array('name' => $fields[6], 'subscription_no' => $subscriptionNo, 'external_id' => (int) $fields[0], 'address' => $fields[7] !== '' ? $fields[7] : $fields[8], 'zip' => $fields[10], 'city' => $fields[11], 'country' => $fields[13], 'end_date' => $endDate, 'endtime' => $endTime, 'hidden' => $hidden, 'starttime' => 0, 'membership' => $membershipUid, 'pid' => $this->getMembershipStoragePid(), 'crdate' => time(), 'tstamp' => time(), 'invoice_email' => $fields[84], 'email' => $fields[79], 'url' => $fields[80], 'firstname' => $fields[82], 'lastname' => $fields[83]); $memberUid = $this->createOrUpdateMember($subscriptionNo, $member); foreach ($this->hookObjects as $hookObject) { if (method_exists($hookObject, 'postUpdateMemberData')) { $hookObject->postUpdateMemberData($memberUid, $member); } } } return true; }
/** * Download a file * * @param string $file Path to the file * @param array $configuration configuration used to render the filelink cObject * @param boolean $hideError define if an error should be displayed if file not found * * @param string $class optional class * * @param string $target target * * @param string $alt alt text * * @param string $title title text * @return string * @throws Tx_Fluid_Core_ViewHelper_Exception_InvalidVariableException */ public function render($file, $configuration = array(), $hideError = FALSE, $class = '', $target = '', $alt = '', $title = '') { if (!is_file($file)) { $errorMessage = sprintf('Given file "%s" for %s is not valid', htmlspecialchars($file), get_class()); t3lib_div::devLog($errorMessage, 'news', t3lib_div::SYSLOG_SEVERITY_WARNING); if (!$hideError) { throw new Tx_Fluid_Core_ViewHelper_Exception_InvalidVariableException('Given file is not a valid file: ' . htmlspecialchars($file)); } } $cObj = t3lib_div::makeInstance('tslib_cObj'); $fileInformation = pathinfo($file); $fileInformation['file'] = $file; $fileInformation['size'] = filesize($file); $cObj->data = $fileInformation; // set a basic configuration for cObj->filelink $tsConfiguration = array('path' => $fileInformation['dirname'] . '/', 'ATagParams' => 'class="download-link basic-class ' . strtolower($fileInformation['extension']) . '"', 'labelStdWrap.' => array('cObject.' => array('value' => $this->renderChildren()))); // Fallback if no configuration given if (!is_array($configuration)) { $configuration = array('labelStdWrap.' => array('cObject' => 'TEXT')); } else { if (class_exists('Tx_Extbase_Utility_TypoScript')) { $configuration = Tx_Extbase_Utility_TypoScript::convertPlainArrayToTypoScriptArray($configuration); } else { /** @var $typoscriptService Tx_Extbase_Service_TypoScriptService */ $typoscriptService = t3lib_div::makeInstance('Tx_Extbase_Service_TypoScriptService'); $configuration = $typoscriptService->convertPlainArrayToTypoScriptArray($configuration); } } // merge default configuration with optional configuration $tsConfiguration = t3lib_div::array_merge_recursive_overrule($tsConfiguration, $configuration); if (!empty($class)) { $tsConfiguration['ATagParams'] .= ' class="' . $class . '"'; } if (!empty($target)) { $tsConfiguration['target'] = $target; } if (!empty($alt)) { $tsConfiguration['altText'] = $alt; } if (!empty($title)) { $tsConfiguration['titleText'] = $title; } // generate link $link = $cObj->filelink($fileInformation['basename'], $tsConfiguration); return $link; }
/** * Set properties of an object/array in cobj->LOAD_REGISTER which can then * be used to be loaded via TS with register:name * * @param string $properties comma separated list of properties * @param mixed $object object or array to get the properties * @param string $prefix optional prefix * @return void */ public static function setRegisterProperties($properties, $object, $prefix = 'news') { if (!empty($properties) && !is_null($object)) { $cObj = t3lib_div::makeInstance('tslib_cObj'); $items = t3lib_div::trimExplode(',', $properties, TRUE); $register = array(); foreach ($items as $item) { $key = $prefix . ucfirst($item); try { $register[$key] = Tx_Extbase_Reflection_ObjectAccess::getProperty($object, $item); } catch (Exception $e) { t3lib_div::devLog($e->getMessage(), 'news', t3lib_div::SYSLOG_SEVERITY_WARNING); } } $cObj->LOAD_REGISTER($register, ''); } }
/** * @return void */ public function execute() { $curl_handles = array(); if (count($this->clearQueue) > 0) { $this->clearQueue = array_unique($this->clearQueue); t3lib_div::devLog('Clearing cache', 'moc_varnish', 0, $this->clearQueue); $mh = curl_multi_init(); $varnishHosts = array(); if (isset($this->extConf['varnishHosts']) && $this->extConf['varnishHosts'] !== '') { $varnishHosts = t3lib_div::trimExplode(',', $this->extConf['varnishHosts'], TRUE); } foreach ($this->clearQueue as $path) { if (count($varnishHosts) > 0) { foreach ($varnishHosts as $varnishHost) { $ch = $this->getCurlHandleForCacheClearing($path, $varnishHost); array_push($curl_handles, $ch); curl_multi_add_handle($mh, $ch); } } else { $ch = $this->getCurlHandleForCacheClearing($path); array_push($curl_handles, $ch); curl_multi_add_handle($mh, $ch); } } $active = NULL; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } foreach ($curl_handles as $ch) { curl_close($ch); curl_multi_remove_handle($mh, $ch); } curl_multi_close($mh); $this->clearQueue = array(); } }
/** * Gets a Solr connection. * * Instead of generating a new connection with each call, connections are * kept and checked whether the requested connection already exists. If a * connection already exists, it's reused. * * @param string $host Solr host (optional) * @param integer $port Solr port (optional) * @param string $path Solr path (optional) * @param string $scheme Solr scheme, defaults to http, can be https (optional) * @return Tx_Solr_SolrService A solr connection. */ public function getConnection($host = '', $port = 8080, $path = '/solr/', $scheme = 'http') { $connection = NULL; if (empty($host)) { t3lib_div::devLog('Tx_Solr_ConnectionManager::getConnection() called with empty host parameter. Using configuration from TSFE, might be inaccurate. Always provide a host or use the getConnectionBy* methods.', 'solr', 2); $solrConfiguration = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['solr.']; $host = $solrConfiguration['host']; $port = $solrConfiguration['port']; $path = $solrConfiguration['path']; $scheme = $solrConfiguration['scheme']; } $connectionHash = md5($scheme . '://' . $host . $port . $path); if (!isset(self::$connections[$connectionHash])) { $connection = t3lib_div::makeInstance('Tx_Solr_SolrService', $host, $port, $path, $scheme); self::$connections[$connectionHash] = $connection; } return self::$connections[$connectionHash]; }
/** * Extends a given list of categories by their subcategories * * @param string $catlist list of categories which will be extended by subcategories * @param string $addWhere additional WHERE restricion * @param int $cc counter to detect recursion in nested categories * @return string extended $catlist */ public static function getSubCategories($catlist, $addWhere = '', $cc = 0) { if (!$catlist) { t3lib_div::devLog('EMPTY $catlist (' . __CLASS__ . '::' . __FUNCTION__ . ')', 'tt_news', 3, array()); } $sCatArr = array(); $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'tt_news_cat', 'tt_news_cat.parent_category IN (' . $catlist . ') AND deleted=0 ' . $addWhere); while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) { $cc++; if ($cc > 10000) { $GLOBALS['TT']->setTSlogMessage('tt_news: one or more recursive categories where found'); return implode(',', $sCatArr); } $subcats = tx_ttnews_div::getSubCategories($row['uid'], $addWhere, $cc); $subcats = $subcats ? ',' . $subcats : ''; $sCatArr[] = $row['uid'] . $subcats; } $GLOBALS['TYPO3_DB']->sql_free_result($res); $catlist = implode(',', $sCatArr); return $catlist; }
/** * The main method of the plugin * * @param string The plugin content * @param array The plugin configuration * @return string The content that is displayed on the website */ public function main($content, $configuration) { $content = ''; try { $this->initialize($configuration); $this->preRender(); $actionResult = $this->performAction(); if ($this->solrAvailable) { $content = $this->render($actionResult); $content = $this->postRender($content); } else { $content = $this->renderError(); } } catch (Exception $e) { // TODO do something useful with the exception if ($GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['logging.']['exceptions']) { t3lib_div::devLog($e->getCode() . ': ' . $e->__toString(), 'tx_solr', 3, (array) $e); } $this->initializeTemplateEngine(); $content = $this->renderException(); } return $this->pi_wrapInBaseClass($content); }
/** * init static info tables to use with this view helper * * @return null */ protected static function init() { // check if class was already initialized if (!is_null(self::$staticInfoObject)) { return; } // check if static_info_tables is installed if (!t3lib_extMgm::isLoaded('static_info_tables')) { self::$staticInfoObject = false; t3lib_div::devLog('static_info_tables needs to be installed to use ' . get_class(self), get_class(self), 1); return; } require_once t3lib_extMgm::extPath('static_info_tables') . 'pi1/class.tx_staticinfotables_pi1.php'; // init class // code taken from the documentation self::$staticInfoObject =& t3lib_div::getUserObj('&tx_staticinfotables_pi1'); if (!self::$staticInfoObject) { self::$staticInfoObject = false; return null; } if (self::$staticInfoObject->needsInit()) { self::$staticInfoObject->init(); } }
/** * Find the right class for the context type and instantiate it * * @param array $arRow Database context row * * @return Tx_Contexts_Context_Abstract|null * @throws Tx_Contexts_Exception */ public static function createFromDb($arRow) { $classMap = Tx_Contexts_Api_Configuration::getContextTypes(); $type = $arRow['type']; if (!$type || !array_key_exists($type, $classMap)) { t3lib_div::devLog('No class found for context type "' . $type . '"', 'tx_contexts', 2); $type = 'default'; } if (!isset($classMap[$type]['class'])) { return null; } $class = $classMap[$type]['class']; if (!$class) { return null; } $instance = t3lib_div::makeInstance($class, $arRow); if ($instance instanceof t3lib_Singleton) { throw new Tx_Contexts_Exception($class . ' may not be singleton'); } if (!$instance instanceof Tx_Contexts_Context_Abstract) { throw new Tx_Contexts_Exception($class . ' must extend Tx_Contexts_Context_Abstract'); } return $instance; }
/** * displays a category rootline by extending either the first category of a record or the category * which is selected by piVars by their parent categories until a category with parent 0 is reached. * * @param array $categoryArray: list of categories which will be extended by subcategories * @return string the category rootline */ function getCategoryPath($categoryArray) { $catRootline = ''; if (is_array($categoryArray)) { $pTmp = $this->tsfe->ATagParams; $lConf = $this->conf['catRootline.']; if ($this->conf['catSelectorTargetPid']) { $catSelLinkParams = $this->conf['catSelectorTargetPid']; if ($this->conf['itemLinkTarget']) { $catSelLinkParams .= ' ' . $this->conf['itemLinkTarget']; } } else { $catSelLinkParams = $this->tsfe->id; } $mainCategory = array_shift($categoryArray); $uid = $mainCategory['catid']; if (intval($uid) != $uid) { t3lib_div::devLog('EMPTY category (' . __CLASS__ . '::' . __FUNCTION__ . ')', 'tt_news', 3, array($mainCategory, $this->SPaddWhere, $this->enableCatFields)); } $loopCheck = 100; $theRowArray = array(); $output = array(); while ($uid != 0 && $loopCheck > 0) { $loopCheck--; $res = $this->db->exec_SELECTquery('*', 'tt_news_cat', 'uid=' . intval($uid) . $this->SPaddWhere . $this->enableCatFields); if ($row = $this->db->sql_fetch_assoc($res)) { $this->db->sql_free_result($res); $uid = $row['parent_category']; $theRowArray[] = $row; } else { break; } } if (is_array($theRowArray)) { krsort($theRowArray); foreach ($theRowArray as $val) { if ($lConf['linkTitles'] && t3lib_div::inList('2,3', $this->config['catTextMode'])) { $this->tsfe->ATagParams = ($pTmp ? $pTmp . ' ' : '') . 'title="' . $val['title'] . '"'; if ($this->config['catTextMode'] == 2) { // link to category shortcut $target = $val['shortcut'] ? $val['shortcut_target'] : ''; $pageID = $val['shortcut'] ? $val['shortcut'] : $catSelLinkParams; $linkedTitle = $this->pi_linkToPage($val['title'], $pageID, $target); $output[] = $this->local_cObj->stdWrap($linkedTitle, $lConf['title_stdWrap.']); } elseif ($this->config['catTextMode'] == 3) { if ($this->conf['useHRDates']) { $output[] = $this->local_cObj->stdWrap($this->pi_linkTP_keepPIvars($val['title'], array('cat' => $val['uid'], 'year' => $this->piVars['year'] ? $this->piVars['year'] : null, 'month' => $this->piVars['month'] ? $this->piVars['month'] : null, 'backPid' => null, 'tt_news' => null, $this->pointerName => null), $this->allowCaching, 0, $catSelLinkParams), $lConf['title_stdWrap.']); } else { $output[] = $this->local_cObj->stdWrap($this->pi_linkTP_keepPIvars($val['title'], array('cat' => $val['uid'], 'backPid' => null, 'tt_news' => null, $this->pointerName => null), $this->allowCaching, 0, $catSelLinkParams), $lConf['title_stdWrap.']); } } } else { $output[] = $this->local_cObj->stdWrap($val['title'], $lConf['title_stdWrap.']); } } } $catRootline = implode($lConf['divider'], $output); if ($catRootline) { $catRootline = $this->local_cObj->stdWrap($catRootline, $lConf['catRootline_stdWrap.']); } $this->tsfe->ATagParams = $pTmp; } if ($this->debugTimes) { $this->hObj->getParsetime(__METHOD__); } return $catRootline; }
/** * Sends a ping to the solr server to see whether it is available. * * @return boolean Returns TRUE on successful ping. * @throws Exception Throws an exception in case ping was not successful. */ public function ping() { $solrAvailable = FALSE; try { if (!$this->solr->ping()) { throw new Exception('Solr Server not responding.', 1237475791); } $solrAvailable = TRUE; } catch (Exception $e) { if ($GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_solr.']['logging.']['exceptions']) { t3lib_div::devLog('exception while trying to ping the solr server', 'tx_solr', 3, array($e->__toString())); } } return $solrAvailable; }
/** * Loads the current document into $this->doc * * @access protected * * @return void */ protected function loadDocument() { // Check for required variable. if (!empty($this->piVars['id']) && !empty($this->conf['pages'])) { // Should we exclude documents from other pages than $this->conf['pages']? $pid = !empty($this->conf['excludeOther']) ? intval($this->conf['pages']) : 0; // Get instance of tx_dlf_document. $this->doc =& tx_dlf_document::getInstance($this->piVars['id'], $pid); if (!$this->doc->ready) { // Destroy the incomplete object. if (TYPO3_DLOG) { t3lib_div::devLog('[tx_dlf_plugin->loadDocument()] Failed to load document with UID "' . $this->piVars['id'] . '"', $this->extKey, SYSLOG_SEVERITY_ERROR); } $this->doc = NULL; } else { // Set configuration PID. $this->doc->cPid = $this->conf['pages']; } } elseif (!empty($this->piVars['recordId'])) { // Get UID of document with given record identifier. $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tx_dlf_documents.uid', 'tx_dlf_documents', 'tx_dlf_documents.record_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->piVars['recordId'], 'tx_dlf_documents') . tx_dlf_helper::whereClause('tx_dlf_documents'), '', '', '1'); if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) == 1) { list($this->piVars['id']) = $GLOBALS['TYPO3_DB']->sql_fetch_row($result); // Set superglobal $_GET array. $_GET[$this->prefixId]['id'] = $this->piVars['id']; // Unset variable to avoid infinite looping. unset($this->piVars['recordId'], $_GET[$this->prefixId]['recordId']); // Try to load document. $this->loadDocument(); } else { if (TYPO3_DLOG) { t3lib_div::devLog('[tx_dlf_plugin->loadDocument()] Failed to load document with record ID "' . $this->piVars['recordId'] . '"', $this->extKey, SYSLOG_SEVERITY_ERROR); } } } else { if (TYPO3_DLOG) { t3lib_div::devLog('[tx_dlf_plugin->loadDocument()] Invalid UID "' . $this->piVars['id'] . '" or PID "' . $this->conf['pages'] . '" for document loading', $this->extKey, SYSLOG_SEVERITY_ERROR); } } }
/** * This magic method is called each time an invisible property is referenced from the object * * @access public * * @param string $var: Name of variable to set * @param mixed $value: New value of variable * * @return void */ public function __set($var, $value) { $method = '_set' . ucfirst($var); if (!property_exists($this, $var) || !method_exists($this, $method)) { if (TYPO3_DLOG) { t3lib_div::devLog('[tx_dlf_solr->__set(' . $var . ', [data])] There is no setter function for property "' . $var . '"', self::$extKey, SYSLOG_SEVERITY_WARNING, $value); } } else { $this->{$method}($value); } }
/** * Finds the FE user groups used on a page including all groups of content * elements and groups of records of extensions that have correctly been * pushed through tslib_cObj during rendering. * * @param Tx_Solr_IndexQueue_Item $item Index queue item representing the current page to get the user groups from * @param integer $language The sys_language_uid language ID * @return array Array of user group IDs */ protected function getAccessGroupsFromContent(Tx_Solr_IndexQueue_Item $item, $language = 0) { static $accessGroupsCache; $accessGroupsCacheEntryId = $item->getRecordUid() . '|' . $language; if (!isset($accessGroupsCache[$accessGroupsCacheEntryId])) { $request = $this->buildBasePageIndexerRequest(); $request->setIndexQueueItem($item); $request->addAction('findUserGroups'); $indexRequestUrl = $this->getDataUrl($item, $language); $response = $request->send($indexRequestUrl); $groups = $response->getActionResult('findUserGroups'); if (is_array($groups)) { $accessGroupsCache[$accessGroupsCacheEntryId] = $groups; } if ($this->loggingEnabled) { t3lib_div::devLog('Page Access Groups', 'solr', 0, array('item' => (array) $item, 'language' => $language, 'index request url' => $indexRequestUrl, 'request' => (array) $request, 'response' => (array) $response, 'groups' => $groups)); } } return $accessGroupsCache[$accessGroupsCacheEntryId]; }