function entities_to_7bit($str) { require_once LEPTON_PATH . '/framework/summary.utf8.php'; // convert to UTF-8 $str = charset_to_utf8($str); if (!utf8_check($str)) { return $str; } // replace some specials $str = utf8_stripspecials($str, '_'); // translate non-ASCII characters to ASCII $str = utf8_romanize($str); // missed some? - Many UTF-8-chars can't be romanized // convert to HTML-entities, and replace entites by hex-numbers $str = utf8_fast_umlauts_to_entities($str, false); $str = str_replace(''', ''', $str); // $str = preg_replace_callback('/&#([0-9]+);/', function($matches) {return "dechex($matches[1])";}, $str); // $str = preg_replace_callback('/&#([0-9]+);/', function($matches) {return dechex($matches[1]);}, $str); if (version_compare(PHP_VERSION, '5.3', '<')) { $str = preg_replace('/&#([0-9]+);/e', "dechex('\$1')", $str); } else { $str = preg_replace_callback('/&#([0-9]+);/', create_function('$aMatches', 'return dechex($aMatches[1]);'), $str); } // maybe there are some > < ' " & left, replace them too $str = str_replace(array('>', '<', ''', '\'', '"', '&'), '', $str); $str = str_replace('&', '', $str); return $str; }
/** * get Country-List */ public function getCountriesByContinent() { $return = array(); $countries = array(); $arrAux = array(); $arrTmp = array(); $this->loadLanguageFile('countries'); $this->loadLanguageFile('continents'); include TL_ROOT . '/system/config/countries.php'; include TL_ROOT . '/system/config/countriesByContinent.php'; foreach ($countriesByContinent as $strConKey => $arrCountries) { $strConKeyTranslated = strlen($GLOBALS['TL_LANG']['CONTINENT'][$strConKey]) ? utf8_romanize($GLOBALS['TL_LANG']['CONTINENT'][$strConKey]) : $strConKey; $arrAux[$strConKey] = $strConKeyTranslated; foreach ($arrCountries as $key => $strCounntry) { $arrTmp[$strConKeyTranslated][$key] = strlen($GLOBALS['TL_LANG']['CNT'][$key]) ? utf8_romanize($GLOBALS['TL_LANG']['CNT'][$key]) : $countries[$key]; } } ksort($arrTmp); foreach ($arrTmp as $strConKey => $arrCountries) { asort($arrCountries); //get original continent key $strOrgKey = array_search($strConKey, $arrAux); $strConKeyTranslated = strlen($GLOBALS['TL_LANG']['CONTINENT'][$strOrgKey]) ? $GLOBALS['TL_LANG']['CONTINENT'][$strOrgKey] : $strConKey; foreach ($arrCountries as $strKey => $strCountry) { $return[$strConKeyTranslated][$strKey] = strlen($GLOBALS['TL_LANG']['CNT'][$strKey]) ? $GLOBALS['TL_LANG']['CNT'][$strKey] : $countries[$strKey]; } } $return[$GLOBALS['TL_LANG']['CONTINENT']['other']]['xx'] = strlen($GLOBALS['TL_LANG']['CNT']['xx']) ? $GLOBALS['TL_LANG']['CNT']['xx'] : 'No Country'; return $return; }
/** * Generate module */ protected function compile() { $objTerm = $this->Database->execute("SELECT * FROM tl_glossary_term WHERE pid IN(" . implode(',', array_map('intval', $this->glossaries)) . ")" . " ORDER BY sortTerm"); if ($objTerm->numRows < 1) { $this->Template->terms = array(); return; } global $objPage; $this->import('String'); $arrTerms = array(); while ($objTerm->next()) { $objTemp = new stdClass(); $key = utf8_strtoupper(utf8_substr($objTerm->sortTerm, 0, 1)); $objTemp->term = $objTerm->term; $objTemp->anchor = 'gl' . utf8_romanize($key); $objTemp->id = standardize($objTerm->term); $objTemp->isParent = false; $objTemp->isReference = false; if ($objTerm->addReference) { if ($objTerm->referenceType == 'parent') { $objTemp->hasParent = true; } elseif ($objTerm->referenceType == 'reference') { $objTemp->isReference = true; $objTemp->referenceTerm = false; $objReference = $this->Database->prepare("SELECT `id`,`term` FROM `tl_glossary_term` WHERE `id`=?")->execute($objTerm->referenceTerm); if ($objReference->next()) { $objTemp->referenceTerm = $objReference->term; $objTemp->referenceAnchor = standardize($objReference->term); } } } // Clean the RTE output if ($objPage->outputFormat == 'xhtml') { $objTerm->definition = $this->String->toXhtml($objTerm->definition); } else { $objTerm->definition = $this->String->toHtml5($objTerm->definition); } $objTemp->definition = $this->String->encodeEmail($objTerm->definition); if ($objTerm->addExample) { $objTemp->addExample = true; $objTemp->example = $objPage->outputFormat == 'xhtml' ? $this->String->toXhtml($objTerm->example) : $this->String->toHtml5($objTerm->example); } else { $objTemp->addExample = false; } $objTemp->addImage = false; // Add image if ($objTerm->addImage && is_file(TL_ROOT . '/' . $objTerm->singleSRC)) { $this->addImageToTemplate($objTemp, $objTerm->row()); } $objTemp->enclosures = array(); // Add enclosures if ($objTerm->addEnclosure) { $this->addEnclosuresToTemplate($objTemp, $objTerm->row()); } $arrTerms[$key][] = $objTemp; } $this->Template->terms = $arrTerms; $this->Template->request = ampersand($this->Environment->request, true); $this->Template->topLink = $GLOBALS['TL_LANG']['MSC']['backToTop']; }
public function renderXml() { $nameSuffix = str_replace(' ', '-', utf8_romanize(utf8_deaccent(ucfirst($this->_params['name'])))); XenForo_Application::autoload('Zend_Debug'); $this->setDownloadFileName('BBM_BbCode_' . $nameSuffix . '.xml'); return $this->_params['xml']->saveXml(); }
/** * Check the uploaded files and move them to the target directory * @param string * @param string * @return array * @throws \Exception */ public function uploadTo($strTarget, $strKey) { if ($strTarget == '' || strpos($strTarget, '../') !== false) { throw new \Exception("Invalid target path {$strTarget}"); } if ($strKey == '') { throw new \Exception('The key must not be empty'); } $maxlength_kb = $this->getMaximumUploadSize(); $maxlength_kb_readable = $this->getReadableSize($maxlength_kb); $arrUploaded = array(); $arrFiles = $this->getFilesFromGlobal($strKey); foreach ($arrFiles as $file) { // Romanize the filename $file['name'] = strip_tags($file['name']); $file['name'] = utf8_romanize($file['name']); $file['name'] = str_replace('"', '', $file['name']); // File was not uploaded if (!is_uploaded_file($file['tmp_name'])) { if ($file['error'] == 1 || $file['error'] == 2) { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb_readable)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb_readable, 'Uploader uploadTo()', TL_ERROR); $this->blnHasError = true; } elseif ($file['error'] == 3) { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name'])); $this->log('File "' . $file['name'] . '" was only partially uploaded', 'Uploader uploadTo()', TL_ERROR); $this->blnHasError = true; } } elseif ($file['size'] > $maxlength_kb) { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb_readable)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb_readable, 'Uploader uploadTo()', TL_ERROR); $this->blnHasError = true; } else { $pathinfo = pathinfo($file['name']); $arrAllowedTypes = trimsplit(',', strtolower($GLOBALS['TL_CONFIG']['uploadTypes'])); // File type not allowed if (!in_array(strtolower($pathinfo['extension']), $arrAllowedTypes)) { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $pathinfo['extension'])); $this->log('File type "' . $pathinfo['extension'] . '" is not allowed to be uploaded (' . $file['name'] . ')', 'Uploader uploadTo()', TL_ERROR); $this->blnHasError = true; } else { $this->import('Files'); $strNewFile = $strTarget . '/' . $file['name']; // Set CHMOD and resize if neccessary if ($this->Files->move_uploaded_file($file['tmp_name'], $strNewFile)) { $this->Files->chmod($strNewFile, 0644); $blnResized = $this->resizeUploadedImage($strNewFile, $file); // Notify the user if (!$blnResized) { \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['MSC']['fileUploaded'], $file['name'])); $this->log('File "' . $file['name'] . '" uploaded successfully', 'Uploader uploadTo()', TL_FILES); } $arrUploaded[] = $strNewFile; } } } } return $arrUploaded; }
public function saveCookieName($strString, $ObjDataContainer) { $arrSearch = array('/[^a-zA-Z0-9 _-]+/', '/ +/', '/\\-+/'); $arrReplace = array('', '-', '-'); $strString = html_entity_decode($strString, ENT_QUOTES, $GLOBALS['TL_CONFIG']['characterSet']); $strString = strip_insert_tags($strString); $strString = utf8_romanize($strString); $strString = preg_replace($arrSearch, $arrReplace, $strString); return trim($strString, '-'); }
/** * Export a ZAD Send News manager to XML file. * @param \DataContainer */ public function exportManager($dc) { // get the manager data $manager = $this->Database->prepare("SELECT * FROM tl_zad_sendnews WHERE id=?")->execute($dc->id); if ($manager->numRows < 1) { // error, exit return; } // create a new XML document $xml = new \DOMDocument('1.0', 'UTF-8'); $xml->formatOutput = true; // root element $tables = $xml->createElement('tables'); $tables->setAttribute('version', '2.0'); $tables = $xml->appendChild($tables); // add manager table $this->exportTable('tl_zad_sendnews', $xml, $tables, $manager); // add rules table $rules = $this->Database->prepare("SELECT * FROM tl_zad_sendnews_rule WHERE pid=? ORDER BY sorting")->execute($manager->id); $this->exportTable('tl_zad_sendnews_rule', $xml, $tables, $rules); // add news_archive table $news = $this->Database->prepare("SELECT id,title FROM tl_news_archive WHERE id=?")->execute($manager->news_archive); $this->exportTable('tl_news_archive', $xml, $tables, $news); // add user table $user = $this->Database->prepare("SELECT id,username,name,email FROM tl_user WHERE id=?")->execute($manager->news_author); $this->exportTable('tl_user', $xml, $tables, $user); // create a zip archive $tmp = md5(uniqid(mt_rand(), true)); $zip = new \ZipWriter('system/tmp/' . $tmp); // add XML document $zip->addString($xml->saveXML(), 'sendnews.xml'); // close archive $zip->close(); // romanize the file name $name = utf8_romanize($manager->name); $name = strtolower(str_replace(' ', '_', $name)); $name = preg_replace('/[^A-Za-z0-9\\._-]/', '', $name); $name = basename($name); // open the "save as …" dialogue $file = new \File('system/tmp/' . $tmp, true); // send file header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: binary'); header('Content-Disposition: attachment; filename="' . $name . '.zip"'); header('Content-Length: ' . $file->filesize); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Expires: 0'); $fl = fopen(TL_ROOT . '/system/tmp/' . $tmp, 'rb'); fpassthru($fl); fclose($fl); exit; }
/** * Slugify a value. * * @param string $value Given value. * @param string $separator Separator string. * * @return string */ private function slugify($value, $separator) { $arrSearch = array('/[^a-zA-Z0-9 \\.\\&\\/_-]+/', '/[ \\.\\&\\/-]+/'); $arrReplace = array('', $separator); $value = html_entity_decode($value, ENT_QUOTES, $this->charset); $value = strip_insert_tags($value); $value = utf8_romanize($value); $value = preg_replace($arrSearch, $arrReplace, $value); if (!$this->preserveUppercase) { $value = strtolower($value); } return trim($value, $separator); }
/** * Generate module */ protected function compile() { $objTerm = $this->Database->execute("SELECT * FROM tl_glossary_term WHERE pid IN(" . implode(',', array_map('intval', $this->glossaries)) . ")" . " ORDER BY term"); if ($objTerm->numRows < 1) { return; } $arrAnchor = array(); while ($objTerm->next()) { $link = utf8_substr($objTerm->term, 0, 1); $key = 'gl' . utf8_romanize($link); $arrAnchor[$key] = $link; } $this->Template->request = ampersand($this->Environment->request, true); $this->Template->anchors = $arrAnchor; }
/** * Standardize a parameter (strip special characters and convert spaces) * * @param string $strString * @param boolean $blnPreserveUppercase * * @return string */ function standardize($strString, $blnPreserveUppercase = false) { $arrSearch = array('/[^a-zA-Z0-9 \\.\\&\\/_-]+/', '/[ \\.\\&\\/-]+/'); $arrReplace = array('', '-'); $strString = html_entity_decode($strString, ENT_QUOTES, $GLOBALS['TL_CONFIG']['characterSet']); $strString = strip_insert_tags($strString); $strString = utf8_romanize($strString); $strString = preg_replace($arrSearch, $arrReplace, $strString); if (is_numeric(substr($strString, 0, 1))) { $strString = 'id-' . $strString; } if (!$blnPreserveUppercase) { $strString = strtolower($strString); } return trim($strString, '-'); }
function cleanID($raw_id) { $sepchar = "_"; $sepcharpat = '#\\' . $sepchar . '+#'; $id = trim((string) $raw_id); $id = utf8_strtolower($id); //alternative namespace seperator $id = strtr($id, ';', ':'); $id = strtr($id, '/', $sepchar); $id = utf8_romanize($id); $id = utf8_deaccent($id, -1); //remove specials $id = utf8_stripspecials($id, $sepchar, '\\*'); $id = utf8_strip($id); $id = preg_replace($sepcharpat, $sepchar, $id); $id = preg_replace('#:+#', ':', $id); $id = preg_replace('#:[:\\._\\-]+#', ':', $id); return $id; }
/** * Generate module */ protected function compile() { $objTerm = $this->objResult; if ($objTerm->numRows < 1) { return ''; } $arrAnchor = array(); $arrLinks = array(); while ($objTerm->next()) { $link = utf8_substr($objTerm->term, 0, 1); $key = 'gl' . utf8_romanize($link); $arrAnchor[$key] = $link; $arrLinks[$key] = array('link' => $link); if ($this->glossary_menu_filter) { $href .= '&gl=' . $key; $arrLinks[$key]['href'] = $this->addToUrl($href); } else { $arrLinks[$key]['href'] = ampersand($this->Environment->request, true) . '#' . $key; } } $this->Template->request = ampersand($this->Environment->request, true); $this->Template->anchors = $arrAnchor; $this->Template->links = $arrLinks; }
/** * Build up the list with all countries information and cache this information. * * Return all data from the cache. * * @return array|null * * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public static function getCountriesList() { if (empty(self::$arrCountries)) { $countries = array(); $arrTmp = array(); // Load the language files. \System::loadLanguageFile('countries'); \System::loadLanguageFile('continents'); // Include all files with name. require_once TL_ROOT . '/system/config/countries.php'; require_once TL_ROOT . '/system/config/countriesByContinent.php'; /** @var $countriesByContinent array */ foreach ($countriesByContinent as $strConKey => $arrCountries) { // Add the main value. $strParentName = strlen($GLOBALS['TL_LANG']['CONTINENT'][$strConKey]) ? utf8_romanize($GLOBALS['TL_LANG']['CONTINENT'][$strConKey]) : $strConKey; // Add all countries. foreach (array_keys($arrCountries) as $key) { $arrTmp[$key] = array('name' => strlen($GLOBALS['TL_LANG']['CNT'][$key]) ? utf8_romanize($GLOBALS['TL_LANG']['CNT'][$key]) : $countries[$key], 'parent-name' => $strParentName, 'parent-short' => $strConKey); } } self::$arrCountries = $arrTmp; } return self::$arrCountries; }
/** * Verification callback to check that a username is valid * * @param string Username * * @return bool */ protected function _verifyUsername(&$username) { if ($this->isUpdate() && $username === $this->getExisting('username')) { return true; // unchanged, always pass } // standardize white space in names $username = preg_replace('/\\s+/u', ' ', $username); try { // if this matches, then \v isn't known (appears to be PCRE < 7.2) so don't strip if (!preg_match('/\\v/', 'v')) { $newName = preg_replace('/\\v+/u', ' ', $username); if (is_string($newName)) { $username = $newName; } } } catch (Exception $e) { } $username = trim($username); $usernameLength = utf8_strlen($username); $minLength = $this->getOption(self::OPTION_USERNAME_LENGTH_MIN); $maxLength = $this->getOption(self::OPTION_USERNAME_LENGTH_MAX); if (!$this->getOption(self::OPTION_ADMIN_EDIT)) { if ($minLength > 0 && $usernameLength < $minLength) { $this->error(new XenForo_Phrase('please_enter_name_that_is_at_least_x_characters_long', array('count' => $minLength)), 'username'); return false; } if ($maxLength > 0 && $usernameLength > $maxLength) { $this->error(new XenForo_Phrase('please_enter_name_that_is_at_most_x_characters_long', array('count' => $maxLength)), 'username'); return false; } $disallowedNames = $this->getOption(self::OPTION_USERNAME_DISALLOWED_NAMES); if ($disallowedNames) { foreach ($disallowedNames as $name) { $name = trim($name); if ($name === '') { continue; } if (stripos($username, $name) !== false) { $this->error(new XenForo_Phrase('please_enter_another_name_disallowed_words'), 'username'); return false; } } } $matchRegex = $this->getOption(self::OPTION_USERNAME_REGEX); if ($matchRegex) { $matchRegex = str_replace('#', '\\#', $matchRegex); // escape delim only if (!preg_match('#' . $matchRegex . '#i', $username)) { $this->error(new XenForo_Phrase('please_enter_another_name_required_format'), 'username'); return false; } } $censoredUserName = XenForo_Helper_String::censorString($username); if ($censoredUserName !== $username) { $this->error(new XenForo_Phrase('please_enter_name_that_does_not_contain_any_censored_words'), 'username'); return false; } } // ignore check if unicode properties aren't compiled try { if (@preg_match("/\\p{C}/u", $username)) { $this->error(new XenForo_Phrase('please_enter_name_without_using_control_characters'), 'username'); return false; } } catch (Exception $e) { } if (strpos($username, ',') !== false) { $this->error(new XenForo_Phrase('please_enter_name_that_does_not_contain_comma'), 'username'); return false; } if (XenForo_Helper_Email::isEmailValid($username)) { $this->error(new XenForo_Phrase('please_enter_name_that_does_not_resemble_an_email_address'), 'username'); return false; } $existingUser = $this->_getUserModel()->getUserByName($username); if ($existingUser && $existingUser['user_id'] != $this->get('user_id')) { $this->error(new XenForo_Phrase('usernames_must_be_unique'), 'username'); return false; } // compare against romanized name to help reduce confusable issues $romanized = utf8_deaccent(utf8_romanize($username)); if ($romanized != $username) { $existingUser = $this->_getUserModel()->getUserByName($romanized); if ($existingUser && $existingUser['user_id'] != $this->get('user_id')) { $this->error(new XenForo_Phrase('usernames_must_be_unique'), 'username'); return false; } } return true; }
/** * Save the current value * @param mixed * @throws Exception */ protected function save($varValue) { if ($this->Input->post('FORM_SUBMIT') != $this->strTable || !file_exists(TL_ROOT . '/' . $this->strPath . '/' . $this->varValue . $this->strExtension) || !$this->isMounted($this->strPath . '/' . $this->varValue . $this->strExtension) || $this->varValue == $varValue) { return; } $this->import('Files'); $arrData = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]; $varValue = utf8_romanize($varValue); // Call save_callback if (is_array($arrData['save_callback'])) { foreach ($arrData['save_callback'] as $callback) { $this->import($callback[0]); $varValue = $this->{$callback}[0]->{$callback}[1]($varValue, $this); } } $this->Files->rename($this->strPath . '/' . $this->varValue . $this->strExtension, $this->strPath . '/' . $varValue . $this->strExtension); // Add a log entry if (stristr($this->intId, '__new__') == true) { $this->log('Folder "' . $this->strPath . '/' . $varValue . $this->strExtension . '" has been created', 'DC_Folder save()', TL_FILES); } else { $this->log('File or folder "' . $this->strPath . '/' . $this->varValue . $this->strExtension . '" has been renamed to "' . $this->strPath . '/' . $varValue . $this->strExtension . '"', 'DC_Folder save()', TL_FILES); } // Set the new value so the input field can show it if ($this->Input->get('act') == 'editAll') { $session = $this->Session->getData(); if (($index = array_search($this->urlEncode($this->strPath . '/' . $this->varValue) . $this->strExtension, $session['CURRENT']['IDS'])) !== false) { $session['CURRENT']['IDS'][$index] = $this->urlEncode($this->strPath . '/' . $varValue) . $this->strExtension; $this->Session->setData($session); } } $this->varValue = $varValue; }
/** * Test romanization of character that would usually be deaccented in a different * way FS#1117 * * @author Andreas Gohr <*****@*****.**> */ function test_deaccented() { $this->assertEqual("a A a A a o O", utf8_romanize("å Å ä Ä ä ö Ö")); }
/** * Generate the filter panel and return it as HTML string * * @param integer $intFilterPanel * * @return string */ protected function filterMenu($intFilterPanel) { $fields = ''; $this->bid = 'tl_buttons_a'; $sortingFields = array(); $session = $this->Session->getData(); $filter = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 4 ? $this->strTable . '_' . CURRENT_ID : $this->strTable; // Get the sorting fields foreach ($GLOBALS['TL_DCA'][$this->strTable]['fields'] as $k => $v) { if (intval($v['filter']) == $intFilterPanel) { $sortingFields[] = $k; } } // Return if there are no sorting fields if (empty($sortingFields)) { return ''; } // Set filter from user input if (\Input::post('FORM_SUBMIT') == 'tl_filters') { foreach ($sortingFields as $field) { if (\Input::post($field, true) != 'tl_' . $field) { $session['filter'][$filter][$field] = \Input::post($field, true); } else { unset($session['filter'][$filter][$field]); } } $this->Session->setData($session); } else { foreach ($sortingFields as $field) { if (isset($session['filter'][$filter][$field])) { // Sort by day if (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(5, 6))) { if ($session['filter'][$filter][$field] == '') { $this->procedure[] = $field . "=''"; } else { $objDate = new \Date($session['filter'][$filter][$field]); $this->procedure[] = $field . ' BETWEEN ? AND ?'; $this->values[] = $objDate->dayBegin; $this->values[] = $objDate->dayEnd; } } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(7, 8))) { if ($session['filter'][$filter][$field] == '') { $this->procedure[] = $field . "=''"; } else { $objDate = new \Date($session['filter'][$filter][$field]); $this->procedure[] = $field . ' BETWEEN ? AND ?'; $this->values[] = $objDate->monthBegin; $this->values[] = $objDate->monthEnd; } } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(9, 10))) { if ($session['filter'][$filter][$field] == '') { $this->procedure[] = $field . "=''"; } else { $objDate = new \Date($session['filter'][$filter][$field]); $this->procedure[] = $field . ' BETWEEN ? AND ?'; $this->values[] = $objDate->yearBegin; $this->values[] = $objDate->yearEnd; } } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['multiple']) { // CSV lists (see #2890) if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['csv'])) { $this->procedure[] = $this->Database->findInSet('?', $field, true); $this->values[] = $session['filter'][$filter][$field]; } else { $this->procedure[] = $field . ' LIKE ?'; $this->values[] = '%"' . $session['filter'][$filter][$field] . '"%'; } } else { $this->procedure[] = $field . '=?'; $this->values[] = $session['filter'][$filter][$field]; } } } } // Add sorting options foreach ($sortingFields as $cnt => $field) { $arrValues = array(); $arrProcedure = array(); if ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 4) { $arrProcedure[] = 'pid=?'; $arrValues[] = CURRENT_ID; } if (!empty($this->root) && is_array($this->root)) { $arrProcedure[] = "id IN(" . implode(',', array_map('intval', $this->root)) . ")"; } // Check for a static filter (see #4719) if (!empty($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['filter']) && is_array($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['filter'])) { foreach ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['filter'] as $fltr) { $arrProcedure[] = $fltr[0]; $arrValues[] = $fltr[1]; } } // Support empty ptable fields (backwards compatibility) if ($GLOBALS['TL_DCA'][$this->strTable]['config']['dynamicPtable']) { $arrProcedure[] = $this->ptable == 'tl_article' ? "(ptable=? OR ptable='')" : "ptable=?"; $arrValues[] = $this->ptable; } $objFields = $this->Database->prepare("SELECT DISTINCT " . $field . " FROM " . $this->strTable . (is_array($arrProcedure) && strlen($arrProcedure[0]) ? ' WHERE ' . implode(' AND ', $arrProcedure) : ''))->execute($arrValues); // Begin select menu $fields .= ' <select name="' . $field . '" id="' . $field . '" class="tl_select' . (isset($session['filter'][$filter][$field]) ? ' active' : '') . '"> <option value="tl_' . $field . '">' . (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['label']) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['label'][0] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['label']) . '</option> <option value="tl_' . $field . '">---</option>'; if ($objFields->numRows) { $options = $objFields->fetchEach($field); // Sort by day if (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(5, 6))) { $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'] == 6 ? rsort($options) : sort($options); foreach ($options as $k => $v) { if ($v == '') { $options[$v] = '-'; } else { $options[$v] = \Date::parse(\Config::get('dateFormat'), $v); } unset($options[$k]); } } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(7, 8))) { $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'] == 8 ? rsort($options) : sort($options); foreach ($options as $k => $v) { if ($v == '') { $options[$v] = '-'; } else { $options[$v] = date('Y-m', $v); $intMonth = date('m', $v) - 1; if (isset($GLOBALS['TL_LANG']['MONTHS'][$intMonth])) { $options[$v] = $GLOBALS['TL_LANG']['MONTHS'][$intMonth] . ' ' . date('Y', $v); } } unset($options[$k]); } } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(9, 10))) { $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'] == 10 ? rsort($options) : sort($options); foreach ($options as $k => $v) { if ($v == '') { $options[$v] = '-'; } else { $options[$v] = date('Y', $v); } unset($options[$k]); } } // Manual filter if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['multiple']) { $moptions = array(); // TODO: find a more effective solution foreach ($options as $option) { // CSV lists (see #2890) if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['csv'])) { $doptions = trimsplit($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['csv'], $option); } else { $doptions = deserialize($option); } if (is_array($doptions)) { $moptions = array_merge($moptions, $doptions); } } $options = $moptions; } $options = array_unique($options); $options_callback = array(); // Call the options_callback if ((is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options_callback']) || is_callable($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options_callback'])) && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference']) { if (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options_callback'])) { $strClass = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options_callback'][0]; $strMethod = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options_callback'][1]; $this->import($strClass); $options_callback = $this->{$strClass}->{$strMethod}($this); } elseif (is_callable($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options_callback'])) { $options_callback = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options_callback']($this); } // Sort options according to the keys of the callback array $options = array_intersect(array_keys($options_callback), $options); } $options_sorter = array(); $blnDate = in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(5, 6, 7, 8, 9, 10)); // Options foreach ($options as $kk => $vv) { $value = $blnDate ? $kk : $vv; // Options callback if (!empty($options_callback) && is_array($options_callback)) { $vv = $options_callback[$vv]; } elseif (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['foreignKey'])) { $key = explode('.', $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['foreignKey'], 2); $objParent = $this->Database->prepare("SELECT " . $key[1] . " AS value FROM " . $key[0] . " WHERE id=?")->limit(1)->execute($vv); if ($objParent->numRows) { $vv = $objParent->value; } } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['isBoolean'] || $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['multiple']) { $vv = $vv != '' ? $GLOBALS['TL_LANG']['MSC']['yes'] : $GLOBALS['TL_LANG']['MSC']['no']; } elseif ($field == 'pid') { $this->loadDataContainer($this->ptable); $showFields = $GLOBALS['TL_DCA'][$this->ptable]['list']['label']['fields']; if (!$showFields[0]) { $showFields[0] = 'id'; } $objShowFields = $this->Database->prepare("SELECT " . $showFields[0] . " FROM " . $this->ptable . " WHERE id=?")->limit(1)->execute($vv); if ($objShowFields->numRows) { $vv = $objShowFields->{$showFields[0]}; } } $option_label = ''; // Use reference array if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference'])) { $option_label = is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference'][$vv]) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference'][$vv][0] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference'][$vv]; } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options'])) { $option_label = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options'][$vv]; } // No empty options allowed if (!strlen($option_label)) { $option_label = $vv ?: '-'; } $options_sorter[' <option value="' . specialchars($value) . '"' . (isset($session['filter'][$filter][$field]) && $value == $session['filter'][$filter][$field] ? ' selected="selected"' : '') . '>' . $option_label . '</option>'] = utf8_romanize($option_label); } // Sort by option values if (!$blnDate) { natcasesort($options_sorter); if (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(2, 4, 12))) { $options_sorter = array_reverse($options_sorter, true); } } $fields .= "\n" . implode("\n", array_keys($options_sorter)); } // End select menu $fields .= ' </select> '; // Force a line-break after six elements (see #3777) if (($cnt + 1) % 6 == 0) { $fields .= '<br>'; } } return ' <div class="tl_filter tl_subpanel"> <strong>' . $GLOBALS['TL_LANG']['MSC']['filter'] . ':</strong> ' . $fields . ' </div>'; }
/** * Clean a name of a key for use as a file name. * * Romanizes non-latin characters, then strips away anything that's * not a letter, number, or underscore. * * @author Tom N Harris <*****@*****.**> */ function idx_cleanName($name) { $name = utf8_romanize(trim((string) $name)); $name = preg_replace('#[ \\./\\:-]+#', '_', $name); $name = preg_replace('/[^A-Za-z0-9_]/', '', $name); return strtolower($name); }
/** * Return the available languages as array * * @param boolean $blnInstalledOnly If true, return only installed languages * * @return array An array of languages */ public static function getLanguages($blnInstalledOnly = false) { $return = array(); $languages = array(); $arrAux = array(); $langsNative = array(); static::loadLanguageFile('languages'); include TL_ROOT . '/system/config/languages.php'; foreach ($languages as $strKey => $strName) { $arrAux[$strKey] = isset($GLOBALS['TL_LANG']['LNG'][$strKey]) ? utf8_romanize($GLOBALS['TL_LANG']['LNG'][$strKey]) : $strName; } asort($arrAux); $arrBackendLanguages = scan(TL_ROOT . '/system/modules/core/languages'); foreach (array_keys($arrAux) as $strKey) { if ($blnInstalledOnly && !in_array($strKey, $arrBackendLanguages)) { continue; } $return[$strKey] = isset($GLOBALS['TL_LANG']['LNG'][$strKey]) ? $GLOBALS['TL_LANG']['LNG'][$strKey] : $languages[$strKey]; if (isset($langsNative[$strKey]) && $langsNative[$strKey] != $return[$strKey]) { $return[$strKey] .= ' - ' . $langsNative[$strKey]; } } return $return; }
/** * Remove unwanted chars from ID * * Cleans a given ID to only use allowed characters. Accented characters are * converted to unaccented ones * * @author Andreas Gohr <*****@*****.**> * @param string $raw_id The pageid to clean * @param boolean $ascii Force ASCII * @return string cleaned id */ function cleanID($raw_id, $ascii = false) { global $conf; static $sepcharpat = null; global $cache_cleanid; $cache =& $cache_cleanid; if ($conf['syslog']) { syslog(LOG_WARNING, '[pageutils.php] cleanID: raw_id: ' . $raw_id); } // check if it's already in the memory cache if (isset($cache[(string) $raw_id])) { return $cache[(string) $raw_id]; } $sepchar = $conf['sepchar']; if ($sepcharpat == null) { // build string only once to save clock cycles $sepcharpat = '#\\' . $sepchar . '+#'; } $id = trim((string) $raw_id); if ($conf['mixedcase'] == 0) { $id = utf8_strtolower($id); } //alternative namespace seperator if ($conf['useslash']) { $id = strtr($id, ';/', '::'); } else { $id = strtr($id, ';/', ':' . $sepchar); } if ($conf['deaccent'] == 2 || $ascii) { $id = utf8_romanize($id); } if ($conf['deaccent'] || $ascii) { $id = utf8_deaccent($id, -1); } //remove specials if specialcharacters is set to 0 if ($conf['specialcharacters'] == 0) { $id = utf8_stripspecials($id, $sepchar, '\\*'); } if ($ascii) { $id = utf8_strip($id); } //clean up $id = preg_replace($sepcharpat, $sepchar, $id); $id = preg_replace('#:+#', ':', $id); $id = trim($id, ':._-'); $id = preg_replace('#:[:\\._\\-]+#', ':', $id); $id = preg_replace('#[:\\._\\-]+:#', ':', $id); $cache[(string) $raw_id] = $id; if ($conf['syslog']) { syslog(LOG_WARNING, '[pageutils.php] cleanID: id to be returned: ' . $id); } return $id; }
/** * Check a file name and romanize it * * @param mixed $varValue * * @return mixed * * @throws Exception */ public function checkFilename($varValue) { $varValue = utf8_romanize($varValue); $varValue = str_replace('"', '', $varValue); if (strpos($varValue, '/') !== false || preg_match('/\\.$/', $varValue)) { throw new Exception($GLOBALS['TL_LANG']['ERR']['invalidName']); } return $varValue; }
/** * Remove unwanted chars from ID * * Cleans a given ID to only use allowed characters. Accented characters are * converted to unaccented ones * * @author Andreas Gohr <*****@*****.**> * @param string $raw_id The pageid to clean * @param boolean $ascii Force ASCII * @param boolean $media Allow leading or trailing _ for media files */ function cleanID($raw_id, $ascii = false, $media = false) { global $conf; static $sepcharpat = null; global $cache_cleanid; $cache =& $cache_cleanid; // check if it's already in the memory cache if (isset($cache[(string) $raw_id])) { return $cache[(string) $raw_id]; } $sepchar = $conf['sepchar']; if ($sepcharpat == null) { // build string only once to save clock cycles $sepcharpat = '#\\' . $sepchar . '+#'; } $id = trim((string) $raw_id); $id = utf8_strtolower($id); //alternative namespace seperator $id = strtr($id, ';', ':'); if ($conf['useslash']) { $id = strtr($id, '/', ':'); } else { $id = strtr($id, '/', $sepchar); } if ($conf['deaccent'] == 2 || $ascii) { $id = utf8_romanize($id); } if ($conf['deaccent'] || $ascii) { $id = utf8_deaccent($id, -1); } //remove specials $id = utf8_stripspecials($id, $sepchar, '\\*'); if ($ascii) { $id = utf8_strip($id); } //clean up $id = preg_replace($sepcharpat, $sepchar, $id); $id = preg_replace('#:+#', ':', $id); $id = $media ? trim($id, ':.-') : trim($id, ':._-'); $id = preg_replace('#:[:\\._\\-]+#', ':', $id); $cache[(string) $raw_id] = $id; return $id; }
/** * Validate input and set value * @return void */ public function validate() { $this->varValue = $this->getPost($this->strName); // No file specified if (!isset($_FILES[$this->strName]) || empty($_FILES[$this->strName]['name'])) { if ($this->mandatory) { if (is_array($this->varValue)) { foreach ($this->varValue as $file) { if (is_file(TL_ROOT . '/isotope/' . substr($file['src'], 0, 1) . '/' . $file['src'])) { return; } } } $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel)); } return; } $file = $_FILES[$this->strName]; $maxlength_kb = number_format($GLOBALS['TL_CONFIG']['maxFileSize'] / 1024, 1, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']); // Romanize the filename $file['name'] = utf8_romanize($file['name']); // File was not uploaded if (!is_uploaded_file($file['tmp_name'])) { if (in_array($file['error'], array(1, 2))) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb . ' kB', __METHOD__, TL_ERROR); } if ($file['error'] == 3) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name'])); $this->log('File "' . $file['name'] . '" was only partially uploaded', __METHOD__, TL_ERROR); } unset($_FILES[$this->strName]); return; } // File is too big if ($GLOBALS['TL_CONFIG']['maxFileSize'] > 0 && $file['size'] > $GLOBALS['TL_CONFIG']['maxFileSize']) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb . ' kB', __METHOD__, TL_ERROR); unset($_FILES[$this->strName]); return; } $pathinfo = pathinfo($file['name']); $uploadTypes = trimsplit(',', $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['eval']['extensions']); // File type is not allowed if (!in_array(strtolower($pathinfo['extension']), $uploadTypes)) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $pathinfo['extension'])); $this->log('File type "' . $pathinfo['extension'] . '" is not allowed to be uploaded (' . $file['name'] . ')', __METHOD__, TL_ERROR); unset($_FILES[$this->strName]); return; } if (($arrImageSize = @getimagesize($file['tmp_name'])) != false) { // Image exceeds maximum image width if ($arrImageSize[0] > $GLOBALS['TL_CONFIG']['imageWidth'] || $arrImageSize[0] > $GLOBALS['TL_CONFIG']['gdMaxImgWidth']) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], $file['name'], $GLOBALS['TL_CONFIG']['imageWidth'])); $this->log('File "' . $file['name'] . '" exceeds the maximum image width of ' . $GLOBALS['TL_CONFIG']['imageWidth'] . ' pixels', __METHOD__, TL_ERROR); unset($_FILES[$this->strName]); return; } // Image exceeds maximum image height if ($arrImageSize[1] > $GLOBALS['TL_CONFIG']['imageHeight'] || $arrImageSize[1] > $GLOBALS['TL_CONFIG']['gdMaxImgHeight']) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], $file['name'], $GLOBALS['TL_CONFIG']['imageHeight'])); $this->log('File "' . $file['name'] . '" exceeds the maximum image height of ' . $GLOBALS['TL_CONFIG']['imageHeight'] . ' pixels', __METHOD__, TL_ERROR); unset($_FILES[$this->strName]); return; } } // Save file in the isotope folder if (!$this->hasErrors()) { $this->import('Files'); $this->import('Database'); $pathinfo = pathinfo($file['name']); $strCacheName = standardize($pathinfo['filename'], true) . '.' . $pathinfo['extension']; $uploadFolder = 'isotope/' . substr($strCacheName, 0, 1); if (is_file(TL_ROOT . '/' . $uploadFolder . '/' . $strCacheName) && md5_file($file['tmp_name']) != md5_file(TL_ROOT . '/' . $uploadFolder . '/' . $strCacheName)) { $strCacheName = standardize($pathinfo['filename'], true) . '-' . substr(md5_file($file['tmp_name']), 0, 8) . '.' . $pathinfo['extension']; $uploadFolder = 'isotope/' . substr($strCacheName, 0, 1); } // Make sure directory exists $this->Files->mkdir($uploadFolder); $this->Files->move_uploaded_file($file['tmp_name'], $uploadFolder . '/' . $strCacheName); if (!is_array($this->varValue)) { $this->varValue = array(); } $this->varValue[] = array('src' => $strCacheName, 'translate' => !$_SESSION['BE_DATA']['language'][$this->strTable][$this->currentRecord] ? '' : 'all'); } unset($_FILES[$this->strName]); }
/** * Add the relation filters * @param \DataContainer $dc in BE * @return string */ public function addRelationFilters($dc) { if (empty(static::$arrFilterableFields)) { return ''; } $filter = $GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['mode'] == 4 ? $dc->table . '_' . CURRENT_ID : $dc->table; $session = \Session::getInstance()->getData(); // Set filter from user input if (\Input::post('FORM_SUBMIT') == 'tl_filters') { foreach (array_keys(static::$arrFilterableFields) as $field) { if (\Input::post($field, true) != 'tl_' . $field) { $session['filter'][$filter][$field] = \Input::post($field, true); } else { unset($session['filter'][$filter][$field]); } } \Session::getInstance()->setData($session); } $count = 0; $return = '<div class="tl_filter tl_subpanel"> <strong>' . $GLOBALS['TL_LANG']['HST']['advanced_filter'] . '</strong> '; foreach (static::$arrFilterableFields as $field => $arrRelation) { $return .= '<select name="' . $field . '" class="tl_select' . (isset($session['filter'][$filter][$field]) ? ' active' : '') . '"> <option value="tl_' . $field . '">' . $GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['label'][0] . '</option> <option value="tl_' . $field . '">---</option>'; $arrIds = Model::getRelatedValues($arrRelation['reference_table'], $field); if (empty($arrIds)) { $return .= '</select> '; // Add the line-break after 5 elements if (++$count % 5 == 0) { $return .= '<br>'; } continue; } $options = array_unique($arrIds); $options_callback = array(); // Store the field name to be used e.g. in the options_callback $this->field = $field; // Call the options_callback if ((is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options_callback']) || is_callable($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options_callback'])) && !$GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['reference']) { if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options_callback'])) { $strClass = $GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options_callback'][0]; $strMethod = $GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options_callback'][1]; $objClass = \System::importStatic($strClass); $options_callback = $objClass->{$strMethod}($this); } elseif (is_callable($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options_callback'])) { $options_callback = $GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options_callback']($this); } // Sort options according to the keys of the callback array $options = array_intersect(array_keys($options_callback), $options); } $options_sorter = array(); // Options foreach ($options as $kk => $vv) { $value = $vv; // Options callback if (!empty($options_callback) && is_array($options_callback)) { $vv = $options_callback[$vv]; } elseif (isset($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['foreignKey'])) { // Replace the ID with the foreign key $key = explode('.', $GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['foreignKey'], 2); $objParent = \Database::getInstance()->prepare("SELECT " . $key[1] . " AS value FROM " . $key[0] . " WHERE id=?")->limit(1)->execute($vv); if ($objParent->numRows) { $vv = $objParent->value; } } $option_label = ''; // Use reference array if (isset($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['reference'])) { $option_label = is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['reference'][$vv]) ? $GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['reference'][$vv][0] : $GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['reference'][$vv]; } elseif ($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options'])) { // Associative array $option_label = $GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['options'][$vv]; } // No empty options allowed if (!strlen($option_label)) { $option_label = $vv ?: '-'; } $options_sorter[' <option value="' . specialchars($value) . '"' . (isset($session['filter'][$filter][$field]) && $value == $session['filter'][$filter][$field] ? ' selected="selected"' : '') . '>' . $option_label . '</option>'] = utf8_romanize($option_label); } $return .= "\n" . implode("\n", array_keys($options_sorter)); $return .= '</select> '; // Add the line-break after 5 elements if (++$count % 5 == 0) { $return .= '<br>'; } } return $return . '</div>'; }
/** * Save the current value * * @param mixed $varValue * * @throws \Exception */ protected function save($varValue) { if (\Input::post('FORM_SUBMIT') != $this->strTable) { return; } $arrData = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]; // File names if ($this->strField == 'name') { if (!file_exists(TL_ROOT . '/' . $this->strPath . '/' . $this->varValue . $this->strExtension) || !$this->isMounted($this->strPath . '/' . $this->varValue . $this->strExtension) || $this->varValue === $varValue) { return; } $this->import('Files'); $varValue = utf8_romanize($varValue); // Trigger the save_callback if (is_array($arrData['save_callback'])) { foreach ($arrData['save_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $this); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $this); } } } // The target exists if (strcasecmp($this->strPath . '/' . $this->varValue . $this->strExtension, $this->strPath . '/' . $varValue . $this->strExtension) !== 0 && file_exists(TL_ROOT . '/' . $this->strPath . '/' . $varValue . $this->strExtension)) { throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['fileExists'], $varValue)); } $arrImageTypes = trimsplit(',', strtolower(\Config::get('validImageTypes'))); // Remove potentially existing thumbnails (see #6641) if (in_array(substr($this->strExtension, 1), $arrImageTypes)) { foreach (glob(TL_ROOT . '/assets/images/*/' . $this->varValue . '-*' . $this->strExtension) as $strThumbnail) { $this->Files->delete(str_replace(TL_ROOT . '/', '', $strThumbnail)); } } // Rename the file $this->Files->rename($this->strPath . '/' . $this->varValue . $this->strExtension, $this->strPath . '/' . $varValue . $this->strExtension); // New folders if (stristr($this->intId, '__new__') !== false) { // Update the database if ($this->blnIsDbAssisted && \Dbafs::shouldBeSynchronized($this->strPath . '/' . $varValue . $this->strExtension)) { $this->objActiveRecord = \Dbafs::addResource($this->strPath . '/' . $varValue . $this->strExtension); } $this->log('Folder "' . $this->strPath . '/' . $varValue . $this->strExtension . '" has been created', __METHOD__, TL_FILES); } else { // Update the database if ($this->blnIsDbAssisted) { $syncSource = \Dbafs::shouldBeSynchronized($this->strPath . '/' . $this->varValue . $this->strExtension); $syncTarget = \Dbafs::shouldBeSynchronized($this->strPath . '/' . $varValue . $this->strExtension); if ($syncSource && $syncTarget) { \Dbafs::moveResource($this->strPath . '/' . $this->varValue . $this->strExtension, $this->strPath . '/' . $varValue . $this->strExtension); } elseif ($syncSource) { \Dbafs::deleteResource($this->strPath . '/' . $this->varValue . $this->strExtension); } elseif ($syncTarget) { \Dbafs::addResource($this->strPath . '/' . $varValue . $this->strExtension); } } $this->log('File or folder "' . $this->strPath . '/' . $this->varValue . $this->strExtension . '" has been renamed to "' . $this->strPath . '/' . $varValue . $this->strExtension . '"', __METHOD__, TL_FILES); } // Set the new value so the input field can show it if (\Input::get('act') == 'editAll') { $session = $this->Session->getData(); if (($index = array_search($this->strPath . '/' . $this->varValue . $this->strExtension, $session['CURRENT']['IDS'])) !== false) { $session['CURRENT']['IDS'][$index] = $this->strPath . '/' . $varValue . $this->strExtension; $this->Session->setData($session); } } $this->varValue = $varValue; } elseif ($this->blnIsDbAssisted && $this->objActiveRecord !== null) { // Convert date formats into timestamps if ($varValue != '' && in_array($arrData['eval']['rgxp'], array('date', 'time', 'datim'))) { $objDate = new \Date($varValue, \Date::getFormatFromRgxp($arrData['eval']['rgxp'])); $varValue = $objDate->tstamp; } // Make sure unique fields are unique if ($arrData['eval']['unique'] && $varValue != '' && !$this->Database->isUniqueValue($this->strTable, $this->strField, $varValue, $this->objActiveRecord->id)) { throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $arrData['label'][0] ?: $this->strField)); } // Handle multi-select fields in "override all" mode if (\Input::get('act') == 'overrideAll' && ($arrData['inputType'] == 'checkbox' || $arrData['inputType'] == 'checkboxWizard') && $arrData['eval']['multiple']) { if ($this->objActiveRecord !== null) { $new = deserialize($varValue, true); $old = deserialize($this->objActiveRecord->{$this->strField}, true); switch (\Input::post($this->strInputName . '_update')) { case 'add': $varValue = array_values(array_unique(array_merge($old, $new))); break; case 'remove': $varValue = array_values(array_diff($old, $new)); break; case 'replace': $varValue = $new; break; } if (!is_array($varValue) || empty($varValue)) { $varValue = ''; } elseif (isset($arrData['eval']['csv'])) { $varValue = implode($arrData['eval']['csv'], $varValue); // see #2890 } else { $varValue = serialize($varValue); } } } // Convert arrays (see #2890) if ($arrData['eval']['multiple'] && isset($arrData['eval']['csv'])) { $varValue = implode($arrData['eval']['csv'], deserialize($varValue, true)); } // Trigger the save_callback if (is_array($arrData['save_callback'])) { foreach ($arrData['save_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $this); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $this); } } } // Save the value if there was no error if (($varValue != '' || !$arrData['eval']['doNotSaveEmpty']) && ($this->varValue != $varValue || $arrData['eval']['alwaysSave'])) { // If the field is a fallback field, empty all other columns if ($arrData['eval']['fallback'] && $varValue != '') { $this->Database->execute("UPDATE " . $this->strTable . " SET " . $this->strField . "=''"); } // Set the correct empty value (see #6284, #6373) if ($varValue === '') { $varValue = \Widget::getEmptyValueByFieldType($GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['sql']); } $this->objActiveRecord->{$this->strField} = $varValue; $this->objActiveRecord->save(); $this->blnCreateNewVersion = true; $this->varValue = deserialize($varValue); } } }
protected function _getUrlVersionOfTag($tag) { $db = $this->_getDb(); $urlVersion = preg_replace('/[^a-zA-Z0-9_ -]/', '', utf8_romanize(utf8_deaccent($tag))); $urlVersion = preg_replace('/[ -]+/', '-', $urlVersion); if (!strlen($urlVersion)) { $urlVersion = 1 + intval($db->fetchOne("\r\n\t\t\t\tSELECT MAX(tag_id)\r\n\t\t\t\tFROM xf_tag\r\n\t\t\t")); } else { $existing = $db->fetchRow("\r\n\t\t\t\tSELECT *\r\n\t\t\t\tFROM xf_tag\r\n\t\t\t\tWHERE tag_url = ?\r\n\t\t\t\t\tOR (tag_url LIKE ? AND tag_url REGEXP ?)\r\n\t\t\t\tORDER BY tag_id DESC\r\n\t\t\t\tLIMIT 1\r\n\t\t\t", array($urlVersion, "{$urlVersion}-%", "^{$urlVersion}-[0-9]+\$")); if ($existing) { $counter = 1; if ($existing['tag_url'] != $urlVersion && preg_match('/-(\\d+)$/', $existing['tag_url'], $match)) { $counter = $match[1]; } $testExists = true; while ($testExists) { $counter++; $testExists = $db->fetchOne("\r\n\t\t\t\t\t\tSELECT tag_id\r\n\t\t\t\t\t\tFROM xf_tag\r\n\t\t\t\t\t\tWHERE tag_url = ?\r\n\t\t\t\t\t", "{$urlVersion}-{$counter}"); } $urlVersion .= "-{$counter}"; } } return $urlVersion; }
/** * Validate the input and set the value */ public function validate() { // No file specified if (!isset($_FILES[$this->strName]) || empty($_FILES[$this->strName]['name'])) { if ($this->mandatory) { if ($this->strLabel == '') { $this->addError($GLOBALS['TL_LANG']['ERR']['mdtryNoLabel']); } else { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel)); } } return; } $file = $_FILES[$this->strName]; $maxlength_kb = $this->getReadableSize($this->maxlength); // Romanize the filename $file['name'] = utf8_romanize($file['name']); // File was not uploaded if (!is_uploaded_file($file['tmp_name'])) { if (in_array($file['error'], array(1, 2))) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, 'FormFileUpload validate()', TL_ERROR); } if ($file['error'] == 3) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name'])); $this->log('File "' . $file['name'] . '" was only partially uploaded', 'FormFileUpload validate()', TL_ERROR); } unset($_FILES[$this->strName]); return; } // File is too big if ($this->maxlength > 0 && $file['size'] > $this->maxlength) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb)); $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } $strExtension = pathinfo($file['name'], PATHINFO_EXTENSION); $uploadTypes = trimsplit(',', $this->extensions); // File type is not allowed if (!in_array(strtolower($strExtension), $uploadTypes)) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $strExtension)); $this->log('File type "' . $strExtension . '" is not allowed to be uploaded (' . $file['name'] . ')', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } if (($arrImageSize = @getimagesize($file['tmp_name'])) != false) { // Image exceeds maximum image width if ($arrImageSize[0] > $GLOBALS['TL_CONFIG']['imageWidth']) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], $file['name'], $GLOBALS['TL_CONFIG']['imageWidth'])); $this->log('File "' . $file['name'] . '" exceeds the maximum image width of ' . $GLOBALS['TL_CONFIG']['imageWidth'] . ' pixels', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } // Image exceeds maximum image height if ($arrImageSize[1] > $GLOBALS['TL_CONFIG']['imageHeight']) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], $file['name'], $GLOBALS['TL_CONFIG']['imageHeight'])); $this->log('File "' . $file['name'] . '" exceeds the maximum image height of ' . $GLOBALS['TL_CONFIG']['imageHeight'] . ' pixels', 'FormFileUpload validate()', TL_ERROR); unset($_FILES[$this->strName]); return; } } // Store file in the session and optionally on the server if (!$this->hasErrors()) { $_SESSION['FILES'][$this->strName] = $_FILES[$this->strName]; $this->log('File "' . $file['name'] . '" uploaded successfully', 'FormFileUpload validate()', TL_FILES); if ($this->storeFile) { $strUploadFolder = $this->uploadFolder; // Overwrite upload folder with user home directory if ($this->useHomeDir && FE_USER_LOGGED_IN) { $this->import('FrontendUser', 'User'); if ($this->User->assignDir && $this->User->homeDir && is_dir(TL_ROOT . '/' . $this->User->homeDir)) { $strUploadFolder = $this->User->homeDir; } } // Store the file if the upload folder exists if (strlen($strUploadFolder) && is_dir(TL_ROOT . '/' . $strUploadFolder)) { $this->import('Files'); // Do not overwrite existing files if ($this->doNotOverwrite && file_exists(TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'])) { $offset = 1; $pathinfo = pathinfo($file['name']); $name = $pathinfo['filename']; $arrAll = scan(TL_ROOT . '/' . $strUploadFolder); $arrFiles = preg_grep('/^' . preg_quote($name, '/') . '.*\\.' . preg_quote($pathinfo['extension'], '/') . '/', $arrAll); foreach ($arrFiles as $strFile) { if (preg_match('/__[0-9]+\\.' . preg_quote($pathinfo['extension'], '/') . '$/', $strFile)) { $strFile = str_replace('.' . $pathinfo['extension'], '', $strFile); $intValue = intval(substr($strFile, strrpos($strFile, '_') + 1)); $offset = max($offset, $intValue); } } $file['name'] = str_replace($name, $name . '__' . ++$offset, $file['name']); } $this->Files->move_uploaded_file($file['tmp_name'], $strUploadFolder . '/' . $file['name']); $this->Files->chmod($strUploadFolder . '/' . $file['name'], $GLOBALS['TL_CONFIG']['defaultFileChmod']); $_SESSION['FILES'][$this->strName] = array('name' => $file['name'], 'type' => $file['type'], 'tmp_name' => TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'], 'error' => $file['error'], 'size' => $file['size'], 'uploaded' => true); $this->log('File "' . $file['name'] . '" has been moved to "' . $strUploadFolder . '"', 'FormFileUpload validate()', TL_FILES); } } } unset($_FILES[$this->strName]); }
/** * Export a theme * * @param \DataContainer $dc */ public function exportTheme($dc) { // Get the theme meta data $objTheme = $this->Database->prepare("SELECT * FROM tl_theme WHERE id=?")->limit(1)->execute($dc->id); if ($objTheme->numRows < 1) { return; } // Romanize the name $strName = utf8_romanize($objTheme->name); $strName = strtolower(str_replace(' ', '_', $strName)); $strName = preg_replace('/[^A-Za-z0-9._-]/', '', $strName); $strName = basename($strName); // Create a new XML document $xml = new \DOMDocument('1.0', 'UTF-8'); $xml->formatOutput = true; // Root element $tables = $xml->createElement('tables'); $tables = $xml->appendChild($tables); // Add the tables $this->addTableTlTheme($xml, $tables, $objTheme); $this->addTableTlStyleSheet($xml, $tables, $objTheme); $this->addTableTlModule($xml, $tables, $objTheme); $this->addTableTlLayout($xml, $tables, $objTheme); $this->addTableTlImageSize($xml, $tables, $objTheme); // Generate the archive $strTmp = md5(uniqid(mt_rand(), true)); $objArchive = new \ZipWriter('system/tmp/' . $strTmp); // Add the files $this->addTableTlFiles($xml, $tables, $objTheme, $objArchive); // Add the template files $this->addTemplatesToArchive($objArchive, $objTheme->templates); // HOOK: add custom logic if (isset($GLOBALS['TL_HOOKS']['exportTheme']) && is_array($GLOBALS['TL_HOOKS']['exportTheme'])) { foreach ($GLOBALS['TL_HOOKS']['exportTheme'] as $callback) { \System::importStatic($callback[0])->{$callback}[1]($xml, $objArchive, $objTheme->id); } } // Add the XML document $objArchive->addString($xml->saveXML(), 'theme.xml'); // Close the archive $objArchive->close(); // Open the "save as …" dialogue $objFile = new \File('system/tmp/' . $strTmp, true); $objFile->sendToBrowser($strName . '.cto'); }
public function verifyUsername($username, $userId = null) { // standardize white space in names $username = preg_replace('/\\s+/u', ' ', $username); try { $newName = preg_replace('/\\v+/u', ' ', $username); if (is_string($newName)) { $username = $newName; } } catch (Exception $e) { } $username = trim($username); $usernameLength = utf8_strlen($username); $minLength = $this->getOption('usernameLength', 'min'); $maxLength = $this->getOption('usernameLength', 'max'); if ($minLength > 0 && $usernameLength < $minLength) { return new XenForo_Phrase('please_enter_name_that_is_at_least_x_characters_long', array('count' => $minLength)); } if ($maxLength > 0 && $usernameLength > $maxLength) { return new XenForo_Phrase('please_enter_name_that_is_at_most_x_characters_long', array('count' => $maxLength)); } $disallowedNames = preg_split('/\\r?\\n/', $this->getOption('usernameValidation', 'disallowedNames')); if ($disallowedNames) { foreach ($disallowedNames as $name) { $name = trim($name); if ($name === '') { continue; } if (stripos($username, $name) !== false) { return new XenForo_Phrase('please_enter_another_name_disallowed_words'); } } } $matchRegex = $this->getOption('usernameValidation', 'matchRegex'); if ($matchRegex) { $matchRegex = str_replace('#', '\\#', $matchRegex); // escape delim only if (!preg_match('#' . $matchRegex . '#i', $username)) { return new XenForo_Phrase('please_enter_another_name_required_format'); } } $censoredUserName = XenForo_Helper_String::censorString($username); if ($censoredUserName !== $username) { return new XenForo_Phrase('please_enter_name_that_does_not_contain_any_censored_words'); } // ignore check if unicode properties aren't compiled try { if (@preg_match("/\\p{C}/u", $username)) { return new XenForo_Phrase('please_enter_name_without_using_control_characters'); } } catch (Exception $e) { } if (strpos($username, ',') !== false) { return new XenForo_Phrase('please_enter_name_that_does_not_contain_comma'); } if (Zend_Validate::is($username, 'EmailAddress')) { return new XenForo_Phrase('please_enter_name_that_does_not_resemble_an_email_address'); } $existingUser = XenForo_Model::create('XenForo_Model_User')->getUserByName($username); if ($existingUser && (!$userId || $userId && $userId != $existingUser['user_id'])) { return new XenForo_Phrase('usernames_must_be_unique'); } // compare against romanized name to help reduce confusable issues $romanized = utf8_deaccent(utf8_romanize($username)); if ($romanized != $username) { $existingUser = XenForo_Model::create('XenForo_Model_User')->getUserByName($romanized); if ($existingUser && (!$userId || $userId && $userId != $existingUser['user_id'])) { return new XenForo_Phrase('usernames_must_be_unique'); } } return true; }
/** * Gets version of a title that is valid in a URL. Invalid elements are stripped * or replaced with '-'. It may not be possible to reverse a URL'd title to the * original title. * * @param string $title * @param boolean $romanize If true, non-latin strings are romanized * * @return string */ public static function getTitleForUrl($title, $romanize = false) { if ($romanize) { $title = utf8_romanize(utf8_deaccent($title)); } $title = strtr($title, '`!"$%^&*()-+={}[]<>;:@#~,./?|' . "\r\n\t\\", ' ' . ' '); $title = strtr($title, array('"' => '', "'" => '')); $title = preg_replace('/[ ]+/', '-', trim($title)); return strtr($title, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); }