The class is responsible for connecting to the database, listing tables and fields, handling transactions and locking tables. It also creates the related Database\Statement and Database\Result objects. Usage: $db = Database::getInstance(); $stmt = $db->prepare("SELECT * FROM tl_user WHERE id=?"); $res = $stmt->execute(4);
 /**
  * Multiple-fields (e.g. select or checkbox) with numberic keys are stored as CSV to improve filters.
  */
 private function convertSerializedValues()
 {
     $t = Attribute::getTable();
     $fields = array();
     $attributes = Attribute::findBy(array("{$t}.multiple='1' AND {$t}.optionsSource='foreignKey'"), null);
     if (null !== $attributes) {
         /** @var Attribute $attribute */
         foreach ($attributes as $attribute) {
             if ($attribute instanceof IsotopeAttributeWithOptions) {
                 $fields[] = $attribute->field_name;
             }
         }
     }
     if (!empty($fields)) {
         /** @var \Database\Result|object $products */
         $products = $this->db->execute("\n                SELECT id, " . implode(', ', $fields) . "\n                FROM tl_iso_product\n                WHERE " . implode(" IS NOT NULL OR ", $fields) . " IS NOT NULL\n            ");
         while ($products->next()) {
             $set = array();
             foreach ($fields as $field) {
                 $value = deserialize($products->{$field});
                 if (!empty($value) && is_array($value)) {
                     $set[$field] = implode(',', $value);
                 }
             }
             if (!empty($set)) {
                 $this->db->prepare("UPDATE tl_iso_product %s WHERE id=?")->set($set)->execute($products->id);
             }
         }
     }
 }
Exemple #2
0
 /**
  * Check if all MetaModels tables are installed.
  *
  * @param \Contao\Database $database The database.
  *
  * @return bool
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function metaModelsTablesPresent($database)
 {
     $tables = array_flip($database->listTables());
     if (!(isset($tables['tl_metamodel']) && isset($tables['tl_metamodel_dca']) && isset($tables['tl_metamodel_dca_sortgroup']) && isset($tables['tl_metamodel_dcasetting']) && isset($tables['tl_metamodel_dcasetting_condition']) && isset($tables['tl_metamodel_attribute']) && isset($tables['tl_metamodel_filter']) && isset($tables['tl_metamodel_filtersetting']) && isset($tables['tl_metamodel_rendersettings']) && isset($tables['tl_metamodel_rendersetting']) && isset($tables['tl_metamodel_dca_combine']))) {
         return false;
     }
     return true;
 }
 public function run($blnInstalled)
 {
     $this->db = \Database::getInstance();
     if ($blnInstalled) {
         $collections = $this->db->execute("SELECT uniqid, COUNT(id) AS total\n                FROM tl_iso_product_collection\n                WHERE uniqid IS NOT NULL\n                GROUP BY uniqid\n                HAVING total>1");
         while ($collections->next()) {
             $this->db->prepare("UPDATE tl_iso_product_collection SET uniqid=NULL WHERE uniqid=?")->execute($collections->uniqid);
         }
     }
 }
 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);
     }
 }
 /**
  * @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;
 }
 /**
  * Convert iso_filterFields configuration for new cumulative filter
  */
 private function updateCumulativeFilterFields()
 {
     if ($this->createDatabaseField('iso_cumulativeFields', 'tl_module')) {
         $modules = $this->db->query("SELECT id, iso_filterFields FROM tl_module WHERE type='iso_cumulativefilter'");
         while ($modules->next()) {
             $fields = deserialize($modules->iso_filterFields);
             if (!empty($fields) && is_array($fields)) {
                 $config = array();
                 foreach ($fields as $field) {
                     $config[] = array('attribute' => $field, 'queryType' => 'and', 'matchCount' => 'none');
                 }
                 $this->db->prepare("UPDATE tl_module SET iso_cumulativeFields=? WHERE id=?")->execute(serialize($config), $modules->id);
             }
         }
     }
 }
Exemple #7
0
 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');
 }
 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;
 }
 /**
  * @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);
     }
 }
 /**
  * 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 .= "&amp;lang=" . $lang;
         $href .= "&amp;readid=" . $readid;
         $href .= "&amp;url=" . urlencode($url);
         $href .= "&amp;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);
     }
 }
Exemple #13
0
 /**
  * @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');
 }
 /**
  * Guard that the access is allowed.
  *
  * @param array $allowedElements The allowed elements.
  * @param int   $contentId       The content id.
  *
  * @return void
  * @throws AccessDeniedException When an invalid content element type is accessed.
  */
 private function guardAllowedAccess($allowedElements, $contentId)
 {
     $actions = array('show', 'create', 'paste', 'select', 'editAll');
     if (!in_array($this->input->get('act'), $actions) && $this->input->get('mode') == 'create') {
         $result = $this->database->prepare('SELECT type FROM tl_content WHERE id=?')->limit(1)->execute($contentId);
         if ($result->numRows && !in_array($result->type, $allowedElements)) {
             $message = sprintf('Attempt to access restricted content element "%s"', $result->type);
             throw new AccessDeniedException($message);
         }
     }
 }
 /**
  * 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);
     }
 }
Exemple #18
0
 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();
                 }
             }
         }
     }
 }
 /**
  * Perform the action.
  *
  * @param int $startSort The first sort index.
  *
  * @param int $pid       The pid.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 private function perform($startSort, $pid)
 {
     $this->loadLanguageFiles();
     // Loop over all attributes now.
     foreach ($this->metaModel->getAttributes() as $attribute) {
         if (!$this->accepts($attribute)) {
             continue;
         }
         $attrId = $attribute->get('id');
         if ($this->knowsAttribute($attribute) || !$this->input->hasValue('attribute_' . $attrId)) {
             continue;
         }
         $data = array_replace_recursive($this->createEmptyDataFor($attribute), array('pid' => $pid, 'sorting' => $startSort, 'tstamp' => time(), 'attr_id' => $attrId));
         $startSort += 128;
         $query = $this->database->prepare('INSERT INTO ' . static::$table . ' %s')->set($data);
         $query->execute();
         $data['id'] = $query->insertId;
         $this->knownAttributes[$attrId] = $data;
     }
 }
 /**
  * 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;
 }
Exemple #24
0
 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]);
     }
 }
 /**
  * @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);
 }
Exemple #26
0
 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();
 }
Exemple #27
0
 /**
  * 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');
     }
 }
Exemple #29
0
 /**
  * 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);
 }