Instantiate the Database object (Factory)
public static getInstance ( array $arrCustomConfig = null ) : |
||
$arrCustomConfig | array | A configuration array |
Résultat | The Database object |
/** * @param $arrStructure * @return array */ protected function getUsedTranslationFieldIds($arrStructure) { $database = Database::getInstance(); $arrFids = array(); // Get used field ids if (is_array($arrStructure)) { foreach ($arrStructure as $strTable => $arrFields) { if (is_array($arrFields) && !empty($arrFields)) { switch ($GLOBALS['TL_DCA'][$strTable]['config']['dataContainer']) { case 'Table': $objData = $database->prepare(sprintf("SELECT %s FROM %s", implode(', ', $arrFields), $strTable))->execute(); if ($objData !== null) { foreach ($arrFields as $strField) { $arrFids = array_merge($arrFids, $objData->fetchEach($strField)); } } break; case 'File': foreach ($arrFields as $strField) { $arrFids[] = $GLOBALS['TL_CONFIG'][$strField]; } break; } } } $arrFids = array_diff($arrFids, array(0)); $arrFids = array_unique($arrFids); } return $arrFids; }
/** * @param $table * @param $field */ public static function convertTranslationField($table, $field) { $backup = $field . '_backup'; $objDatabase = Database::getInstance(); /* @var $objLanguages Languages */ $objLanguages = \System::getContainer()->get('craffft.translation_fields.service.languages'); // Backup the original column and then change the column type if (!$objDatabase->fieldExists($backup, $table, true)) { $objDatabase->query("ALTER TABLE `{$table}` ADD `{$backup}` text NULL"); $objDatabase->query("UPDATE `{$table}` SET `{$backup}`=`{$field}`"); $objDatabase->query("ALTER TABLE `{$table}` CHANGE `{$field}` `{$field}` int(10) unsigned NOT NULL default '0'"); $objDatabase->query("UPDATE `{$table}` SET `{$field}`='0'"); } $objRow = $objDatabase->query("SELECT id, {$backup} FROM {$table} WHERE {$backup}!=''"); while ($objRow->next()) { if (is_numeric($objRow->{$backup})) { $intFid = $objRow->{$backup}; } else { if (strlen($objRow->{$backup}) > 0) { $intFid = TranslationFieldsModel::saveValuesAndReturnFid($objLanguages->getLanguagesWithValue($objRow->{$backup})); } else { $intFid = 0; } } $objDatabase->prepare("UPDATE {$table} SET {$field}=? WHERE id=?")->execute($intFid, $objRow->id); } }
public function setDefaultCategories($table, $id) { $catDefault = $this->User->maeEventCatDefault; if ($table == "tl_calendar_events" && is_array($catDefault) && count($catDefault) > 0) { Database::getInstance()->prepare("UPDATE tl_calendar_events SET categories=? WHERE id=?")->execute(serialize($catDefault), $id); } }
public function onMasterOptions(DataContainer $dc) { if (($jumpTo = PageModel::findByPk($dc->activeRecord->jumpTo)) === null) { return []; } $associated = []; $pageFinder = new PageFinder(); foreach ($pageFinder->findAssociatedForPage($jumpTo, true) as $page) { $associated[] = $page->id; } if (0 === count($associated)) { return []; } $options = []; $result = Database::getInstance()->prepare(' SELECT id, title FROM ' . $this->table . ' WHERE jumpTo IN (' . implode(',', $associated) . ') AND master=0 ORDER BY title ')->execute($dc->activeRecord->language); while ($result->next()) { $options[$result->id] = sprintf($GLOBALS['TL_LANG'][$this->table]['isSlave'], $result->title); } return $options; }
public function export(\Contao\DC_Table $dc) { $database = \Contao\Database::getInstance(); $stage_id = $database->query("SELECT s.id FROM tl_beachcup_stage AS s WHERE s.start_date >= UNIX_TIMESTAMP() ORDER BY s.start_date ASC LIMIT 1")->fetchAssoc()["id"]; $data = $database->query("select tl_beachcup_registration.id as ANMELDUNG_ID, tl_beachcup_tournament.name_de AS TURNIER, DATE_FORMAT(from_unixtime(tl_beachcup_registration.tstamp), '%d.%m.%Y') as DATUM_ANMELDUNG,\n p1.surname as NACHNAME_1, p1.name as VORNAME_1, p1.tax_number as STEUER_NR_1, DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL p1.birth_date SECOND), '%d.%m.%Y') as GEB_DATUM_1, p1.birth_place as GEB_ORT_1, p1.gender as GESCHLECHT_1, p1.address as ADRESSE_1, p1.zip_code as PLZ_1, p1.city as ORT_1, p1.country as LAND_1, p1.email as EMAIL_1, p1.phone_number as TEL_1, p1.shirt_size as SHIRT_1, p1.has_shirt as SHIRT_ERHALTEN_1, p1.is_fipav as FIPAV_1, p1level.description_de as SPIELER_LEVEL_1, p1.has_medical_certificate as AERZTL_ZEUGNIS_1, p1.is_confirmed as EIGENERKLAERUNG_1,\n p2.surname as NACHNAME_2, p2.name as VORNAME_2, p2.tax_number as STEUER_NR_2, DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL p2.birth_date SECOND), '%d.%m.%Y') as GEB_DATUM_2, p2.birth_place as GEB_ORT_2, p2.gender as GESCHLECHT_2, p2.address as ADRESSE_2, p2.zip_code as PLZ_2, p2.city as ORT_2, p2.country as LAND_2, p2.email as EMAIL_2, p2.phone_number as TEL_2, p2.shirt_size as SHIRT_2, p2.has_shirt as SHIRT_ERHALTEN_2, p2.is_fipav as FIPAV_2, p2level.description_de as SPIELER_LEVEL_2, p2.has_medical_certificate as AERZTL_ZEUGNIS_2, p2.is_confirmed as EIGENERKLAERUNG_2,\n tl_beachcup_registration_state.code as STATUS_ANMELDUNG\n from tl_beachcup_registration\n join tl_beachcup_team on tl_beachcup_team.id = tl_beachcup_registration.team_id\n join tl_beachcup_player p1 on p1.id = tl_beachcup_team.player_1\n join tl_beachcup_player_level p1level on p1level.id = p1.player_level\n join tl_beachcup_player p2 on p2.id = tl_beachcup_team.player_2\n join tl_beachcup_player_level p2level on p2level.id = p2.player_level\n join tl_beachcup_tournament on tl_beachcup_tournament.id = tl_beachcup_registration.tournament_id\n join tl_beachcup_registration_state on tl_beachcup_registration_state.id = tl_beachcup_registration.state_id\n join tl_beachcup_stage on tl_beachcup_stage.id = tl_beachcup_tournament.stage_id\n where tl_beachcup_stage.id = {$stage_id} and tl_beachcup_registration_state.code != 'REJECTED'\n order by tl_beachcup_tournament.date, tl_beachcup_tournament.name_de, tl_beachcup_registration.tstamp;")->fetchAllAssoc(); if (count($data) > 0) { $headers = array(); foreach ($data[0] as $key => $value) { $headers[] = $key; } $file = fopen("php://memory", "w"); fputcsv($file, $headers, ";"); foreach ($data as $record) { fputcsv($file, $record, ";"); } fseek($file, 0); header('Content-Encoding: iso-8859-1'); header('Content-Type: application/csv; charset=iso-8859-1'); header('Content-Disposition: attachement; filename="Anmeldungen.csv";'); echo ""; fpassthru($file); exit; } \Contao\Controller::redirect('contao/main.php?do=registration'); }
/** * Generate the module */ protected function compile() { $dc = \Contao\Database::getInstance(); $row = $dc->prepare('SELECT * FROM tl_rs_settings WHERE id = ?')->limit(1)->execute($this->rs_setting)->fetchAssoc(); $href = ''; if ($row) { $customerid = '6857'; $lang = $row['language_demo']; $speed = $row['speed']; $readid = $this->rs_readid ? $this->rs_readid : $this->strColumn; $stattype = \Contao\Environment::get('host'); $url = \Contao\Environment::get('base'); $url2 = \Contao\Environment::get('requestUri'); if ($url2 != '/') { $url .= substr($url2, 1); } if ($row['have_license']) { $customerid = $row['customer_id']; $lang = $row['language']; } $protocol = \Contao\Environment::get('https'); $ssl = false; if (isset($protocol)) { if ('on' == strtolower($protocol)) { $ssl = true; } if ('1' == $protocol) { $ssl = true; } } if (!$GLOBALS['RS_IN_HEAD']) { $GLOBALS['RS_IN_HEAD'] = true; if ($ssl) { $GLOBALS['TL_HEAD'][] = '<script src="system/modules/readspeaker/assets/rs_ssl/ReadSpeaker.js?pids=embhl" type="text/javascript"></script>'; } else { $GLOBALS['TL_HEAD'][] = '<script src="http://f1.eu.readspeaker.com/script/' . $customerid . '/ReadSpeaker.js?pids=embhl" type="text/javascript"></script>'; } } $GLOBALS['TL_HEAD'][] = '<script src="system/modules/readspeaker/assets/readspeaker.js"></script>'; $GLOBALS['TL_HEAD'][] = '<script type="text/javascript"> <!-- window.rsConf = {general: {usePost: true}}; //--> </script>'; $href = ''; if ($ssl) { $href .= "https://app.readspeaker.com/cgi-bin/rsent?"; } else { $href .= "http://app.eu.readspeaker.com/cgi-bin/rsent?"; } $href .= "customerid=" . $customerid; $href .= "&lang=" . $lang; $href .= "&readid=" . $readid; $href .= "&url=" . urlencode($url); $href .= "&stattype=" . $stattype; } $this->Template->href = $href; $this->Template->button_title = $this->rs_player_title; }
public function getAllEvents($arrEvents, $arrCalendars, $intStart, $intEnd, \Contao\Module $objModule) { // FIXME it's possible to filter a list for categories, it doesn't allow by its configuration $result = array(); $modCats = deserialize($objModule->event_categories, true); $hasCatCfg = is_array($modCats) && count($modCats) > 0; $filterParam_ar = array('category'); $objFilterMod = Database::getInstance()->prepare("SELECT mae_event_catname FROM tl_module WHERE mae_event_catname != '' AND type='mae_event_filter' AND mae_event_list=?")->execute($objModule->id); while ($objFilterMod->fetchAssoc()) { $filterParam_ar[] = $objFilterMod->mae_event_catname; } foreach ($filterParam_ar as $paramName) { $filterCat = Input::get($paramName); if (!empty($filterCat) && $filterCat != "all") { if (!is_numeric($filterCat)) { $objCat = Database::getInstance()->prepare("SELECT id FROM tl_mae_event_cat WHERE alias=?")->execute($filterCat); if ($objCat->numRows == 1) { $filterCat = $objCat->id; } } if ($hasCatCfg) { $modCats = array($filterCat); $hasCatCfg = false; } else { $modCats[] = $filterCat; } } // have filter value } // each possible category url parameter if (is_array($arrEvents) && count($arrEvents) > 0 && count($modCats) > 0) { foreach ($arrEvents as $day => $times) { foreach ($times as $time => $events) { foreach ($events as $event) { $evtCats = unserialize($event['categories']); if (!is_array($evtCats)) { $evtCats = array(); } foreach ($modCats as $modCat) { if (in_array($modCat, $evtCats)) { $result[$day][$time][] = $event; break; } } // compare categories module <=> event } // event } // times } // days } else { $result = $arrEvents; } // if no category filter set return $result; }
/** * Generate this sub module code. * * @return string */ public function generateRewrites(\Bit3\Contao\Htaccess\Event\GenerateRewritesEvent $event) { $objPages = \Contao\Database::getInstance()->prepare("SELECT alias, dns FROM tl_page WHERE createRobotsTxt = 1 AND useDomainSpecificRobotsTxt = 1 AND published = 1 AND fallback = 1")->execute(); while ($objPages->next()) { $strRewriteRule = sprintf($GLOBALS['TL_CONFIG']['RobotsTxtEditorRewriteCond'], $this->prepareUrl($objPages->dns)) . "\n" . sprintf($GLOBALS['TL_CONFIG']['RobotsTxtEditorRewriteRule'], $this->prepareUrl(FILE_ROBOTS_TXT), $this->prepareUrl(RobotsTxtEditor::getDomainSpecificFilePath($objPages->alias))); $pre = $event->getPre(); $pre->append(PHP_EOL . $strRewriteRule); } }
/** * @param $tablename * @param $alias * @param null $lang * @param array $item * @param array $wrapper * @return string */ public static function getHrefAttributes($tablename, $alias, $lang = null, $item = array(), $wrapper = array()) { $tableWrapper = $tablename; $tableData = $tableWrapper . '_data'; $Database = Database::getInstance(); $currentItemDB = array(); $strHrefLang = ''; if (empty($item) || empty($wrapper)) { $currentItemDB = $Database->prepare('SELECT ' . $tableData . '.*, ' . $tableWrapper . '.fallback, ' . $tableWrapper . '.language FROM ' . $tableData . ' LEFT OUTER JOIN ' . $tableWrapper . ' ON ' . $tableData . '.pid = ' . $tableWrapper . '.id WHERE ' . $tableData . '.alias = ? OR ' . $tableData . '.id = ?')->limit(1)->execute($alias, (int) $alias); $currentItemDB = $currentItemDB->row(); } if (!empty($item) && !empty($wrapper) && empty($currentItemDB)) { $currentItemDB['id'] = $item['id']; $currentItemDB['alias'] = $item['alias']; $currentItemDB['mainLanguage'] = $item['mainLanguage']; $currentItemDB['fallback'] = $wrapper['fallback']; $currentItemDB['language'] = $wrapper['language']; } if (!empty($currentItemDB)) { // get all items with the same fallback item $fallback = !$currentItemDB['fallback'] ? $currentItemDB['mainLanguage'] : $currentItemDB['id']; // select alias $translationDB = $Database->prepare('SELECT ' . $tableData . '.*, ' . $tableData . '.mainLanguage, ' . $tableWrapper . '.language, ' . $tableWrapper . '.fallback, ' . $tableWrapper . '.rootPage, ' . $tableWrapper . '.addDetailPage FROM ' . $tableData . ' LEFT OUTER JOIN ' . $tableWrapper . ' ON ' . $tableData . '.pid = ' . $tableWrapper . '.id WHERE ' . $tableData . '.id = ? OR ' . $tableData . '.mainLanguage = ?')->execute($fallback, (int) $fallback); while ($translationDB->next()) { $url = '/'; if (!$translationDB->addDetailPage) { continue; } // default if ($translationDB->source == 'default') { $objParent = PageModel::findWithDetails($translationDB->rootPage); if (!static::pageIsEnable($objParent)) { continue; } $domain = ($objParent->rootUseSSL ? 'https://' : 'http://') . ($objParent->domain ?: \Environment::get('host')) . TL_PATH . '/'; $strUrl = $domain . \Controller::generateFrontendUrl($objParent->row(), \Config::get('useAutoItem') && !\Config::get('disableAlias') ? '/%s' : '/items/%s', $objParent->language); $url = static::getLink($translationDB, $strUrl); } // external if ($translationDB->source == 'external') { $url = $translationDB->url; } // internal if ($translationDB->source == 'internal') { $objParent = PageModel::findWithDetails($translationDB->jumpTo); if (!static::pageIsEnable($objParent)) { continue; } $domain = ($objParent->rootUseSSL ? 'https://' : 'http://') . ($objParent->domain ?: \Environment::get('host')) . TL_PATH . '/'; $url = $domain . \Controller::generateFrontendUrl($objParent->row()); } $strHrefLang .= '<link rel="alternate" hreflang="' . $translationDB->language . '" href="' . $url . '">'; } } return $strHrefLang; }
/** * @param $strType * @return array */ public static function findStyleDesignationByNotDisabledType($strType) { if (!in_array($strType, self::getAvailableTypes())) { return array(); } $t = self::$strTable; $objDatabase = Database::getInstance(); $objCssStyleSelector = $objDatabase->prepare("SELECT id, styleDesignation FROM {$t} WHERE disableIn" . ucfirst($strType) . "=? ORDER BY styleDesignation ASC")->execute(0); return $objCssStyleSelector->fetchEach('styleDesignation'); }
/** * Find target article for a root page and current article. * * @param ArticleModel $currentArticle * @param int $targetRootId * @param bool $currentIsFallback * @param bool $targetIsFallback * * @return \ArticleModel|null */ private function findTargetArticle(ArticleModel $currentArticle, $targetRootId, $currentIsFallback, $targetIsFallback) { // If the target root is fallback, the article ID will match our current "languageMain" if ($targetIsFallback) { return $this->findPublishedArticle(array('tl_article.id = ' . $currentArticle->languageMain)); } $subpages = Database::getInstance()->getChildRecords($targetRootId, 'tl_page'); if (0 === count($subpages)) { return null; } return $this->findPublishedArticle(array('tl_article.languageMain = ?', 'tl_article.pid IN (' . implode(',', $subpages) . ')'), array($currentIsFallback ? $currentArticle->id : $currentArticle->languageMain)); }
/** * Mograte from string to array. * * @param $column */ protected function migrateFromStringToArray($column) { $database = Database::getInstance(); $result = $database->prepare("SELECT * FROM orm_avisota_message_content WHERE {$column}>0")->execute(); if ($result->count() < 1) { return; } while ($result->next()) { if (is_array(unserialize($result->{$column}))) { continue; } $database->prepare("UPDATE orm_avisota_message_content %s WHERE id=?")->set(array($column => serialize((array) $result->{$column})))->execute($result->id); } }
public function writeMessage(DataContainer $dc) { Message::reset(); if (TL_MODE == 'BE' && Input::get('act') && Input::get('act') == 'edit') { $banner = new ReadSpeaker\RS_Messages(); $db = \Contao\Database::getInstance(); $module = $db->prepare("SELECT * FROM tl_content WHERE id = ?")->execute($dc->id)->row(); if ($module) { $rs_banner = false; $rs_doc_banner = false; $rs_ce_end_banner = false; switch ($module['type']) { case 'rs_content_ce': $rs_banner = true; $rs_ce_end_banner = true; break; case 'rs_content_end': $rs_banner = true; break; case 'rs_content_doc': $rs_banner = true; $rs_doc_banner = true; break; case 'rs_content_skip': $rs_banner = true; break; case 'rs_content_read': $rs_banner = true; break; default: break; } if ($rs_banner) { $banner->addBannerReadSpeakerTop($GLOBALS['TL_LANG']['CTE'][$module['type']][0], $GLOBALS['TL_LANG']['CTE'][$module['type']][1]); if ($rs_ce_end_banner) { $banner->addBannerNotForgetEndContentElement(); } if ($rs_doc_banner) { $banner->addBannerPossibleDocReaderFileTypes(); } } } } }
/** * Hook for searchable pages * * @param array $arrPages * @param number $intRoot * @param string $blnIsSitemap * @return string */ public function getSearchablePages($arrPages, $intRoot = 0, $blnIsSitemap = false) { $db = Database::getInstance(); $arrRoot = array(); if ($intRoot > 0) { $arrRoot = $db->getChildRecords($intRoot, 'tl_page', true); } // Read jump to page details $objResult = $db->prepare("SELECT jumpTo, company_archiv FROM tl_module WHERE type=?")->execute('company_list'); $arrModules = $objResult->fetchAllAssoc(); if (count($arrModules) > 0) { $arrPids = array(); foreach ($arrModules as $arrModule) { if (is_array($arrRoot) && count($arrRoot) > 0 && !in_array($arrModule['jumpTo'], $arrRoot)) { continue; } $objParent = \PageModel::findWithDetails($arrModule['jumpTo']); // The target page does not exist if ($objParent === null) { continue; } // The target page has not been published (see #5520) if (!$objParent->published) { continue; } // The target page is exempt from the sitemap (see #6418) if ($blnIsSitemap && $objParent->sitemap == 'map_never') { continue; } // Set the domain (see #6421) $domain = ($objParent->rootUseSSL ? 'https://' : 'http://') . ($objParent->domain ?: \Environment::get('host')) . TL_PATH . '/'; $arrPids[] = $arrModule['company_archiv']; $objCompanies = CompanyModel::findByPids($arrPids, 0, 0, array('order' => 'id ASC')); while ($objCompanies->next()) { $arrCompany = $objCompanies->row(); $arrPages[] = $domain . $this->generateFrontendUrl($objParent->row(), '/companyID/' . $arrCompany['id'], $objParent->language); } } } return $arrPages; }
public function onLanguageMainOptions(DataContainer $dc) { $pageFinder = new PageFinder(); $current = ArticleModel::findByPk($dc->id); $page = PageModel::findByPk($current->pid); if (null === $page || ($master = $pageFinder->findAssociatedInMaster($page)) === null) { return []; } $options = []; $result = Database::getInstance()->prepare(' SELECT id, title FROM tl_article WHERE pid=? AND id NOT IN ( SELECT languageMain FROM tl_article WHERE id!=? AND pid=? AND languageMain > 0 ) ')->execute($master->id, $current->id, $page->id); while ($result->next()) { $options[$result->id] = sprintf('%s [ID %s]', $result->title, $result->id); } return $options; }
/** * Get the status * * @return bool */ public function getStatus() { foreach ($this->tables as $table) { $db = Database::getInstance(); if (!$db->tableExists($table)) { continue; } switch ($table) { case 'tl_news': $records = $db->execute("SELECT * FROM tl_news WHERE pid IN (SELECT id FROM tl_news_archive WHERE seo_serp_ignore='')"); break; case 'tl_calendar_events': $records = $db->execute("SELECT * FROM tl_calendar_events WHERE pid IN (SELECT id FROM tl_calendar WHERE seo_serp_ignore='')"); break; case 'tl_page': $rootIds = $db->execute("SELECT id FROM tl_page WHERE type='root' AND seo_serp_ignore=''"); $pageIds = $db->getChildRecords($rootIds->fetchEach('id'), 'tl_page'); if (count($pageIds) < 1) { return true; } $records = $db->execute("SELECT * FROM tl_page WHERE id IN (" . implode(',', $pageIds) . ")"); break; default: $records = $db->execute("SELECT * FROM " . $table); break; } while ($records->next()) { try { $this->runTests($table, $records->row()); } catch (ErrorException $e) { return false; } catch (WarningException $e) { // do nothing } } } return true; }
/** * @param bool $isOnlyIDs * @return array */ public function filterFields($isOnlyIDs = false) { $arrClosedEntries = array(); // Get all secure accessdata results $objSecureAccessdata = Database::getInstance()->prepare("SELECT * FROM tl_secure_accessdata")->execute(); if ($objSecureAccessdata !== null) { while ($objSecureAccessdata->next()) { $id = $objSecureAccessdata->id; $author = $objSecureAccessdata->author; $protect = Encryption::decrypt($objSecureAccessdata->protect); $protect_users = Encryption::decrypt(deserialize($objSecureAccessdata->protect_users)); $protect_groups = Encryption::decrypt(deserialize($objSecureAccessdata->protect_groups)); // If protected if ($protect == 1) { // If not admin if ($this->User->admin != 1) { // If not author if ($this->User->id != $author) { // If not in user array if (!(is_array($protect_users) && in_array($this->User->id, $protect_users))) { // If not in group array if (!(is_array($this->User->groups) && is_array($protect_groups) && count(array_intersect($this->User->groups, $protect_groups)) > 0)) { if ($isOnlyIDs == true) { $arrClosedEntries[] = $id; } else { $arrClosedEntries[] = array('id!=?', $id); } } } } } } } } return $arrClosedEntries; }
public function writeMessage($dc) { $banner = new ReadSpeaker\RS_Messages(); Message::reset(); $db = \Contao\Database::getInstance(); $module = $db->prepare("SELECT * FROM tl_module WHERE id = ?")->execute($dc->id)->row(); $rs_banner = false; switch ($module['type']) { case 'mod_rs': $rs_banner = true; break; case 'mod_rs_skip_from_here': $rs_banner = true; break; case 'mod_rs_read_from_here': $rs_banner = true; break; default: break; } if ($rs_banner) { $banner->addBannerReadSpeakerTop($GLOBALS['TL_LANG']['FMD'][$module['type']][0], $GLOBALS['TL_LANG']['FMD'][$module['type']][1]); } }
public function removeTags($tag) { if (!is_string($tag)) { $this->sendRes(); } $tagname = $tag ? $tag : ''; $db = Database::getInstance(); $existInSearchDB = $db->prepare("SELECT * FROM tl_prosearch_data WHERE tags LIKE ? ORDER BY tstamp DESC LIMIT 10")->execute("%{$tagname}%"); if ($existInSearchDB->count() > 1) { $this->sendRes(); } $db->prepare('DELETE FROM tl_prosearch_tags WHERE tagname = ?')->execute($tagname); $this->sendRes(); }
/** * Extract the Widget attributes from a Data Container array * * @param array $arrData The field configuration array * @param string $strName The field name in the form * @param mixed $varValue The field value * @param string $strField The field name in the database * @param string $strTable The table name in the database * @param DataContainer|null $objDca An optional DataContainer object * * @return array An attributes array that can be passed to a widget */ public static function getAttributesFromDca($arrData, $strName, $varValue = null, $strField = '', $strTable = '', $objDca = null) { $arrAttributes = $arrData['eval']; $arrAttributes['id'] = $strName; $arrAttributes['name'] = $strName; $arrAttributes['strField'] = $strField; $arrAttributes['strTable'] = $strTable; $arrAttributes['label'] = ($label = is_array($arrData['label']) ? $arrData['label'][0] : $arrData['label']) != false ? $label : $strField; $arrAttributes['description'] = $arrData['label'][1]; $arrAttributes['type'] = $arrData['inputType']; $arrAttributes['dataContainer'] = $objDca; // Internet Explorer does not support onchange for checkboxes and radio buttons if ($arrData['eval']['submitOnChange']) { if ($arrData['inputType'] == 'checkbox' || $arrData['inputType'] == 'checkboxWizard' || $arrData['inputType'] == 'radio' || $arrData['inputType'] == 'radioTable') { $arrAttributes['onclick'] = trim($arrAttributes['onclick'] . " Backend.autoSubmit('" . $strTable . "')"); } else { $arrAttributes['onchange'] = trim($arrAttributes['onchange'] . " Backend.autoSubmit('" . $strTable . "')"); } } $arrAttributes['allowHtml'] = $arrData['eval']['allowHtml'] || strlen($arrData['eval']['rte']) || $arrData['eval']['preserveTags'] ? true : false; // Decode entities if HTML is allowed if ($arrAttributes['allowHtml'] || $arrData['inputType'] == 'fileTree') { $arrAttributes['decodeEntities'] = true; } // Add Ajax event if ($arrData['inputType'] == 'checkbox' && is_array($GLOBALS['TL_DCA'][$strTable]['subpalettes']) && in_array($strField, array_keys($GLOBALS['TL_DCA'][$strTable]['subpalettes'])) && $arrData['eval']['submitOnChange']) { $arrAttributes['onclick'] = "AjaxRequest.toggleSubpalette(this, 'sub_" . $strName . "', '" . $strField . "')"; } // Options callback if (is_array($arrData['options_callback'])) { $arrCallback = $arrData['options_callback']; $arrData['options'] = static::importStatic($arrCallback[0])->{$arrCallback[1]}($objDca); } elseif (is_callable($arrData['options_callback'])) { $arrData['options'] = $arrData['options_callback']($objDca); } elseif (isset($arrData['foreignKey'])) { $arrKey = explode('.', $arrData['foreignKey'], 2); $objOptions = \Database::getInstance()->query("SELECT id, " . $arrKey[1] . " AS value FROM " . $arrKey[0] . " WHERE tstamp>0 ORDER BY value"); $arrData['options'] = array(); while ($objOptions->next()) { $arrData['options'][$objOptions->id] = $objOptions->value; } } // Add default option to single checkbox if ($arrData['inputType'] == 'checkbox' && !isset($arrData['options']) && !isset($arrData['options_callback']) && !isset($arrData['foreignKey'])) { if (TL_MODE == 'FE' && isset($arrAttributes['description'])) { $arrAttributes['options'][] = array('value' => 1, 'label' => $arrAttributes['description']); } else { $arrAttributes['options'][] = array('value' => 1, 'label' => $arrAttributes['label']); } } // Add options if (is_array($arrData['options'])) { $blnIsAssociative = $arrData['eval']['isAssociative'] || array_is_assoc($arrData['options']); $blnUseReference = isset($arrData['reference']); if ($arrData['eval']['includeBlankOption'] && !$arrData['eval']['multiple']) { $strLabel = isset($arrData['eval']['blankOptionLabel']) ? $arrData['eval']['blankOptionLabel'] : '-'; $arrAttributes['options'][] = array('value' => '', 'label' => $strLabel); } foreach ($arrData['options'] as $k => $v) { if (!is_array($v)) { $arrAttributes['options'][] = array('value' => $blnIsAssociative ? $k : $v, 'label' => $blnUseReference ? ($ref = is_array($arrData['reference'][$v]) ? $arrData['reference'][$v][0] : $arrData['reference'][$v]) != false ? $ref : $v : $v); continue; } $key = $blnUseReference ? ($ref = is_array($arrData['reference'][$k]) ? $arrData['reference'][$k][0] : $arrData['reference'][$k]) != false ? $ref : $k : $k; $blnIsAssoc = array_is_assoc($v); foreach ($v as $kk => $vv) { $arrAttributes['options'][$key][] = array('value' => $blnIsAssoc ? $kk : $vv, 'label' => $blnUseReference ? ($ref = is_array($arrData['reference'][$vv]) ? $arrData['reference'][$vv][0] : $arrData['reference'][$vv]) != false ? $ref : $vv : $vv); } } } $arrAttributes['value'] = \StringUtil::deserialize($varValue); // Convert timestamps if ($varValue != '' && in_array($arrData['eval']['rgxp'], array('date', 'time', 'datim'))) { $objDate = new \Date($varValue, \Date::getFormatFromRgxp($arrData['eval']['rgxp'])); $arrAttributes['value'] = $objDate->{$arrData['eval']['rgxp']}; } // Add the "rootNodes" array as attribute (see #3563) if (isset($arrData['rootNodes']) && !isset($arrData['eval']['rootNodes'])) { $arrAttributes['rootNodes'] = $arrData['rootNodes']; } // HOOK: add custom logic if (isset($GLOBALS['TL_HOOKS']['getAttributesFromDca']) && is_array($GLOBALS['TL_HOOKS']['getAttributesFromDca'])) { foreach ($GLOBALS['TL_HOOKS']['getAttributesFromDca'] as $callback) { $arrAttributes = static::importStatic($callback[0])->{$callback[1]}($arrAttributes, $objDca); } } return $arrAttributes; }
/** * Limits the available pages in page picker to the fallback page tree. * * @param int $pageId */ private function setRootNodesForPage($pageId) { $page = PageModel::findWithDetails($pageId); $root = PageModel::findByPk($page->rootId); if ($root->fallback && (!$root->languageRoot || ($languageRoot = PageModel::findByPk($root->languageRoot)) === null)) { return; } $pageFinder = new PageFinder(); $masterRoot = $pageFinder->findMasterRootForPage($page); if (null !== $masterRoot) { $GLOBALS['TL_DCA']['tl_page']['fields']['languageMain']['eval']['rootNodes'] = Database::getInstance()->prepare('SELECT id FROM tl_page WHERE pid=?')->execute($masterRoot->id)->fetchEach('id'); } }
/** * Generate the Google XML sitemaps * * @param integer $intId The root page ID */ public function generateSitemap($intId = 0) { $time = \Date::floorToMinute(); $objDatabase = \Database::getInstance(); $this->purgeXmlFiles(); // Only root pages should have sitemap names $objDatabase->execute("UPDATE tl_page SET createSitemap='', sitemapName='' WHERE type!='root'"); // Get a particular root page if ($intId > 0) { do { $objRoot = $objDatabase->prepare("SELECT * FROM tl_page WHERE id=?")->limit(1)->execute($intId); if ($objRoot->numRows < 1) { break; } $intId = $objRoot->pid; } while ($objRoot->type != 'root' && $intId > 0); // Make sure the page is published if (!$objRoot->published || $objRoot->start != '' && $objRoot->start > $time || $objRoot->stop != '' && $objRoot->stop <= $time + 60) { return; } // Check the sitemap name if (!$objRoot->createSitemap || !$objRoot->sitemapName) { return; } $objRoot->reset(); } else { $objRoot = $objDatabase->execute("SELECT id, language, sitemapName FROM tl_page WHERE type='root' AND createSitemap='1' AND sitemapName!='' AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'"); } // Return if there are no pages if ($objRoot->numRows < 1) { return; } // Create the XML file while ($objRoot->next()) { $objFile = new \File('web/share/' . $objRoot->sitemapName . '.xml'); $objFile->truncate(); $objFile->append('<?xml version="1.0" encoding="UTF-8"?>'); $objFile->append('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">'); // Find the searchable pages $arrPages = \Backend::findSearchablePages($objRoot->id, '', true); // HOOK: take additional pages if (isset($GLOBALS['TL_HOOKS']['getSearchablePages']) && is_array($GLOBALS['TL_HOOKS']['getSearchablePages'])) { foreach ($GLOBALS['TL_HOOKS']['getSearchablePages'] as $callback) { $this->import($callback[0]); $arrPages = $this->{$callback[0]}->{$callback[1]}($arrPages, $objRoot->id, true, $objRoot->language); } } // Add pages foreach ($arrPages as $strUrl) { $strUrl = rawurlencode($strUrl); $strUrl = str_replace(array('%2F', '%3F', '%3D', '%26', '%3A//'), array('/', '?', '=', '&', '://'), $strUrl); $strUrl = ampersand($strUrl, true); $objFile->append(' <url><loc>' . $strUrl . '</loc></url>'); } $objFile->append('</urlset>'); $objFile->close(); // Add a log entry $this->log('Generated sitemap "' . $objRoot->sitemapName . '.xml"', __METHOD__, TL_CRON); } }
/** * Find the first active page by its member groups * * @param string $arrIds An array of member group IDs * * @return PageModel|null The model or null if there is no matching member group */ public static function findFirstActiveByMemberGroups($arrIds) { if (!is_array($arrIds) || empty($arrIds)) { return null; } $time = \Date::floorToMinute(); $objDatabase = \Database::getInstance(); $arrIds = array_map('intval', $arrIds); $objResult = $objDatabase->prepare("SELECT p.* FROM tl_member_group g LEFT JOIN tl_page p ON g.jumpTo=p.id WHERE g.id IN(" . implode(',', $arrIds) . ") AND g.jumpTo>0 AND g.redirect='1' AND g.disable!='1' AND (g.start='' OR g.start<='{$time}') AND (g.stop='' OR g.stop>'" . ($time + 60) . "') AND p.published='1' AND (p.start='' OR p.start<='{$time}') AND (p.stop='' OR p.stop>'" . ($time + 60) . "') ORDER BY " . $objDatabase->findInSet('g.id', $arrIds))->limit(1)->execute(); if ($objResult->numRows < 1) { return null; } return new static($objResult); }
/** * @param null $dc */ public function sendPasswordEmail($dc = null) { // Front end call if (!$dc instanceof DataContainer) { return; } if ($this->isDisabledAccountmail($dc)) { return; } // Return if there is no active record if (!$dc->activeRecord) { return; } // Send login data if ($dc->activeRecord->sendLoginData == 1) { // Set different passwords on overrideAll mode, when no password was given if (Input::get('act') == 'overrideAll' && $GLOBALS['ACCOUNTMAIL']['AUTO_PASSWORD'] === true) { $this->setPostPassword('', $dc->id); } if ($this->getPostPassword($dc->id) == '' || $this->getPostPassword($dc->id) == '*****') { // Set empty password $this->setPostPassword('', $dc->id); // Generate new password $this->setAutoPassword($dc); } if ($this->getPostPassword($dc->id) != '' && $this->getPostPassword($dc->id) != '*****') { $strType = $this->getType($dc); $arrParameters = $this->getParameters($dc); $strLanguage = $this->getAccountLanguage($dc); if (!strlen($strType)) { return; } if ($this->sendEmail($dc->activeRecord->email, $strType, $arrParameters, $strLanguage)) { // Disable sendLoginData field $dc->activeRecord->sendLoginData = ''; // Disable sendLoginData field in the database Database::getInstance()->prepare("UPDATE " . $dc->table . " SET sendLoginData='', loginDataAlreadySent='1' WHERE id=?")->execute($dc->activeRecord->id); // Show success message Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['login_data_send']); } else { // Show error message Message::addError($GLOBALS['TL_LANG']['MSC']['login_data_not_send']); } } } }
/** * Get the applicable record IDs * * @return array */ protected function getRecordIds() { return Database::getInstance()->prepare("SELECT id FROM tl_news WHERE pid=?")->execute(CURRENT_ID)->fetchEach('id'); }
<?php /** * Contao Open Source CMS * * Copyright (c) 2005-2016 Leo Feyer * * @package F Modul * @author Alexander Naumov http://www.alexandernaumov.de * @license commercial * @copyright 2016 Alexander Naumov */ // $modules = array(); $database = \Contao\Database::getInstance(); if ($database->tableExists('tl_fmodules') && empty($modules)) { $moduleDB = $database->prepare('SELECT * FROM tl_fmodules')->execute(); if ($moduleDB->count()) { while ($moduleDB->next()) { if ($moduleDB->tablename) { $modules[] = substr($moduleDB->tablename, 3, strlen($moduleDB->tablename)); } } } } // $GLOBALS['TL_DCA']['tl_content']['fields']['fview'] = array('label' => array("View", ""), 'sql' => "varchar(50) NOT NULL default ''"); // $view = \Contao\Input::get('view'); // foreach ($modules as $tablename) {
/** * Add a breadcrumb menu to the page tree * * @param string $strKey * * @throws AccessDeniedException * @throws \RuntimeException */ public static function addPagesBreadcrumb($strKey = 'tl_page_node') { /** @var AttributeBagInterface $objSession */ $objSession = \System::getContainer()->get('session')->getBag('contao_backend'); // Set a new node if (isset($_GET['pn'])) { // Check the path (thanks to Arnaud Buchoux) if (\Validator::isInsecurePath(\Input::get('pn', true))) { throw new \RuntimeException('Insecure path ' . \Input::get('pn', true)); } $objSession->set($strKey, \Input::get('pn', true)); \Controller::redirect(preg_replace('/&pn=[^&]*/', '', \Environment::get('request'))); } $intNode = $objSession->get($strKey); if ($intNode < 1) { return; } // Check the path (thanks to Arnaud Buchoux) if (\Validator::isInsecurePath($intNode)) { throw new \RuntimeException('Insecure path ' . $intNode); } $arrIds = array(); $arrLinks = array(); $objUser = \BackendUser::getInstance(); // Generate breadcrumb trail if ($intNode) { $intId = $intNode; $objDatabase = \Database::getInstance(); do { $objPage = $objDatabase->prepare("SELECT * FROM tl_page WHERE id=?")->limit(1)->execute($intId); if ($objPage->numRows < 1) { // Currently selected page does not exist if ($intId == $intNode) { $objSession->set($strKey, 0); return; } break; } $arrIds[] = $intId; // No link for the active page if ($objPage->id == $intNode) { $arrLinks[] = \Backend::addPageIcon($objPage->row(), '', null, '', true) . ' ' . $objPage->title; } else { $arrLinks[] = \Backend::addPageIcon($objPage->row(), '', null, '', true) . ' <a href="' . \Backend::addToUrl('pn=' . $objPage->id) . '" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['selectNode']) . '">' . $objPage->title . '</a>'; } // Do not show the mounted pages if (!$objUser->isAdmin && $objUser->hasAccess($objPage->id, 'pagemounts')) { break; } $intId = $objPage->pid; } while ($intId > 0 && $objPage->type != 'root'); } // Check whether the node is mounted if (!$objUser->hasAccess($arrIds, 'pagemounts')) { $objSession->set($strKey, 0); throw new AccessDeniedException('Page ID ' . $intNode . ' is not mounted.'); } // Limit tree $GLOBALS['TL_DCA']['tl_page']['list']['sorting']['root'] = array($intNode); // Add root link $arrLinks[] = \Image::getHtml('pagemounts.svg') . ' <a href="' . \Backend::addToUrl('pn=0') . '" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['selectAllNodes']) . '">' . $GLOBALS['TL_LANG']['MSC']['filterAll'] . '</a>'; $arrLinks = array_reverse($arrLinks); // Insert breadcrumb menu $GLOBALS['TL_DCA']['tl_page']['list']['sorting']['breadcrumb'] .= ' <ul id="tl_breadcrumb"> <li>' . implode(' > </li><li>', $arrLinks) . '</li> </ul>'; }
/** * NewsListDataFactory constructor. */ public function __construct() { $this->setDatabase(Database::getInstance()); }
/** * @param array $arrClasses * @param DataContainer $dc */ protected function saveClassesToCssClass(array $arrClasses, DataContainer $dc) { $strCssClassName = $this->getCssClassName($dc->id); $strClasses = implode(' ', $arrClasses); $strClasses = str_replace(' ', ' ', $strClasses); $strClasses = trim($strClasses); $dc->activeRecord->cssClass = $strClasses; Input::setPost($strCssClassName, $strClasses); $objDatabase = Database::getInstance(); $objDatabase->prepare("UPDATE {$dc->table} SET cssClass=? WHERE id=?")->execute($strClasses, $dc->id); }
/** * Add a list of versions to a template * * @param BackendTemplate|object $objTemplate */ public static function addToTemplate(BackendTemplate $objTemplate) { $arrVersions = array(); $objUser = \BackendUser::getInstance(); $objDatabase = \Database::getInstance(); // Get the total number of versions $objTotal = $objDatabase->prepare("SELECT COUNT(*) AS count FROM tl_version WHERE version>1" . (!$objUser->isAdmin ? " AND userid=?" : ""))->execute($objUser->id); $intLast = ceil($objTotal->count / 30); $intPage = \Input::get('vp') !== null ? \Input::get('vp') : 1; $intOffset = ($intPage - 1) * 30; // Validate the page number if ($intPage < 1 || $intLast > 0 && $intPage > $intLast) { header('HTTP/1.1 404 Not Found'); } // Create the pagination menu $objPagination = new \Pagination($objTotal->count, 30, 7, 'vp', new \BackendTemplate('be_pagination')); $objTemplate->pagination = $objPagination->generate(); // Get the versions $objVersions = $objDatabase->prepare("SELECT pid, tstamp, version, fromTable, username, userid, description, editUrl, active FROM tl_version" . (!$objUser->isAdmin ? " WHERE userid=?" : "") . " ORDER BY tstamp DESC, pid, version DESC")->limit(30, $intOffset)->execute($objUser->id); while ($objVersions->next()) { $arrRow = $objVersions->row(); // Add some parameters $arrRow['from'] = max($objVersions->version - 1, 1); // see #4828 $arrRow['to'] = $objVersions->version; $arrRow['date'] = date(\Config::get('datimFormat'), $objVersions->tstamp); $arrRow['description'] = \StringUtil::substr($arrRow['description'], 32); $arrRow['shortTable'] = \StringUtil::substr($arrRow['fromTable'], 18); // see #5769 if ($arrRow['editUrl'] != '') { $arrRow['editUrl'] = preg_replace('/&(amp;)?rt=[^&]+/', '&rt=' . REQUEST_TOKEN, ampersand($arrRow['editUrl'])); } $arrVersions[] = $arrRow; } $intCount = -1; $arrVersions = array_values($arrVersions); // Add the "even" and "odd" classes foreach ($arrVersions as $k => $v) { $arrVersions[$k]['class'] = ++$intCount % 2 == 0 ? 'even' : 'odd'; try { // Mark deleted versions (see #4336) $objDeleted = $objDatabase->prepare("SELECT COUNT(*) AS count FROM " . $v['fromTable'] . " WHERE id=?")->execute($v['pid']); $arrVersions[$k]['deleted'] = $objDeleted->count < 1; } catch (\Exception $e) { // Probably a disabled module --$intCount; unset($arrVersions[$k]); } } $objTemplate->versions = $arrVersions; }