Esempio n. 1
0
 function loadFromDB($pid = -1)
 {
     $andWhere = '';
     if ($pid + 1) {
         $andWhere = ' AND pid=' . $pid;
     }
     $res = $this->databaseHandle->exec_SELECTquery('*', $this->getTableName(), 'uid=' . $this->getUid() . ' AND deleted=0 ' . $andWhere);
     if ($this->databaseHandle->sql_num_rows($res) == 0) {
         $this->data = null;
         $this->origData = array();
     } else {
         $this->data = $this->origData = $this->databaseHandle->sql_fetch_assoc($res);
     }
     $this->loaded = true;
 }
Esempio n. 2
0
 /**
  * Determines if the current user may write in a certain topic.
  * @param  mixed   $topic The topic identifier. This may either be a topic UID pointing to
  *                        a record in the tx_mmforum_topics table or an associative array
  *                        already containing this record.
  * @return boolean        TRUE, if the user that is currently logged in may write in the
  *                        specified topic, otherwise FALSE.
  * @author Martin Helmich <*****@*****.**>
  */
 function getMayWrite_topic($topic)
 {
     $userId = $this->getUserID();
     // If the $topic parameter is not an array, treat this parameter as a topic UID.
     if (!is_array($topic)) {
         $topic = intval($topic);
         // Look in the cache. In case of a hit, just return the result
         $cacheRes = $this->cache->restore('getMayWrite_topic_' . $topic . '_' . $userId);
         if ($cacheRes !== null) {
             return $cacheRes;
         }
         // Load the topic's forum UID
         $res = $this->databaseHandle->exec_SELECTquery('f.*', 'tx_mmforum_forums f, tx_mmforum_topics t', 't.uid="' . $topic . '" AND f.uid = t.forum_id');
         $arr = $this->databaseHandle->sql_fetch_assoc($res);
         $result = $this->getMayWrite_forum($arr);
         // Save the result to cache and return
         $this->cache->save('getMayWrite_topic_' . $topic . '_' . $userId, $result);
         return $result;
     } else {
         /* If the topic's forum UID is already known, just delegate to the
          * getMayWrite_forum function. Since the result of that function is
          * already being cached, there is no need to cache the result at this
          * place again. */
         return $this->getMayWrite_forum($topic['forum_id']);
     }
 }
 /**
  * Migrate dam references to fal references
  *
  * @param \mysqli_result $result
  * @param string $table
  * @param string $type
  * @param array $fieldnameMapping Re-map fieldnames e.g.
  *    tx_damnews_dam_images => tx_falttnews_fal_images
  *
  * @return void
  */
 protected function migrateDamReferencesToFalReferences($result, $table, $type, $fieldnameMapping = array())
 {
     $counter = 0;
     $total = $this->database->sql_num_rows($result);
     $this->controller->infoMessage('Found ' . $total . ' ' . $table . ' records with a dam ' . $type);
     while ($record = $this->database->sql_fetch_assoc($result)) {
         $identifier = $this->getFullFileName($record);
         try {
             $fileObject = $this->storageObject->getFile($identifier);
         } catch (\Exception $e) {
             // If file is not found
             // getFile will throw an invalidArgumentException if the file
             // does not exist. Create an empty file to avoid this. This is
             // usefull in a development environment that has the production
             // database but not all the physical files.
             try {
                 GeneralUtility::mkdir_deep(PATH_site . $this->storageBasePath . dirname($identifier));
             } catch (\Exception $e) {
                 $this->controller->errorMessage('Unable to create directory: ' . PATH_site . $this->storageBasePath . $identifier);
                 continue;
             }
             $config = $this->controller->getConfiguration();
             if (isset($config['createMissingFiles']) && (int) $config['createMissingFiles']) {
                 $this->controller->infoMessage('Creating empty missing file: ' . PATH_site . $this->storageBasePath . $identifier);
                 try {
                     GeneralUtility::writeFile(PATH_site . $this->storageBasePath . $identifier, '');
                 } catch (\Exception $e) {
                     $this->controller->errorMessage('Unable to create file: ' . PATH_site . $this->storageBasePath . $identifier);
                     continue;
                 }
             } else {
                 $this->controller->errorMessage('File not found: ' . PATH_site . $this->storageBasePath . $identifier);
                 continue;
             }
             $fileObject = $this->storageObject->getFile($identifier);
         }
         if ($fileObject instanceof \TYPO3\CMS\Core\Resource\File) {
             if ($fileObject->isMissing()) {
                 $this->controller->warningMessage('FAL did not find any file resource for DAM record. DAM uid: ' . $record['uid'] . ': "' . $identifier . '"');
                 continue;
             }
             $record['uid_local'] = $fileObject->getUid();
             foreach ($fieldnameMapping as $old => $new) {
                 if ($record['ident'] === $old) {
                     $record['ident'] = $new;
                 }
             }
             $progress = number_format(100 * ($counter++ / $total), 1) . '% of ' . $total;
             if (!$this->doesFileReferenceExist($record)) {
                 $insertData = array('tstamp' => time(), 'crdate' => time(), 'cruser_id' => $GLOBALS['BE_USER']->user['uid'], 'uid_local' => $record['uid_local'], 'uid_foreign' => (int) $record['uid_foreign'], 'sorting' => (int) $record['sorting'], 'sorting_foreign' => (int) $record['sorting_foreign'], 'tablenames' => (string) $record['tablenames'], 'fieldname' => (string) $record['ident'], 'table_local' => 'sys_file', 'pid' => $record['item_pid'], 'l10n_diffsource' => (string) $record['l18n_diffsource']);
                 $this->database->exec_INSERTquery('sys_file_reference', $insertData);
                 $this->amountOfMigratedRecords++;
                 $this->controller->message($progress . ' Migrating relation for ' . (string) $record['tablenames'] . ' uid: ' . $record['item_uid'] . ' dam uid: ' . $record['dam_uid'] . ' to fal uid: ' . $record['uid_local']);
             } else {
                 $this->controller->message($progress . ' Reference already exists for uid: ' . (int) $record['item_uid']);
             }
         }
     }
     $this->database->sql_free_result($result);
 }
 /**
  * Get a user from DB by social identifier
  *
  * @param string $identifier social identifier
  * @param string $extraWhere Additional WHERE clause: " AND ...
  * @param array $dbUserSetup User db table definition: $this->db_user
  * @return mixed User array or FALSE
  */
 public function fetchUserRecordByIdentifier($identifier, $extraWhere = '', $dbUserSetup = '')
 {
     $result = FALSE;
     $identityClassName = 'Portrino\\PxHybridAuth\\Domain\\Model\\Identity\\' . ucfirst($this->getServiceProvider()) . 'Identity';
     if (class_exists($identityClassName) && defined($identityClassName . '::EXTBASE_TYPE')) {
         $extbaseType = constant($identityClassName . '::EXTBASE_TYPE');
         $identityClause = 'deleted=0 AND hidden=0 AND identifier=' . $this->db->fullQuoteStr($identifier, 'tx_pxhybridauth_domain_model_identity') . ' AND ' . 'tx_extbase_type=' . $this->db->fullQuoteStr($extbaseType, 'tx_pxhybridauth_domain_model_identity');
         $socialIdentities = $this->db->exec_SELECTgetRows('*', 'tx_pxhybridauth_domain_model_identity', $identityClause);
         foreach ($socialIdentities as $socialIdentity) {
             if (isset($socialIdentity['fe_user'])) {
                 $dbUser = is_array($dbUserSetup) ? $dbUserSetup : $this->db_user;
                 // Look up the user by the username and/or extraWhere:
                 $dbres = $this->db->exec_SELECTquery('*', $dbUser['table'], 'uid' . '=' . $this->db->fullQuoteStr($socialIdentity['fe_user'], $dbUser['table']) . $this->db->fullQuoteStr($dbUser['check_pid_clause'], $dbUser['table']) . $dbUser['enable_clause'] . $extraWhere);
                 if ($dbres) {
                     $result = $this->db->sql_fetch_assoc($dbres);
                     $this->db->sql_free_result($dbres);
                     if ($result) {
                         break;
                     }
                 }
             }
         }
     }
     return $result;
 }
    /**
     * Displays a statistic grouped by the time of day.
     *
     * @return  string The statistic table
     * @author  Martin Helmich <*****@*****.**>
     * @version 2007-05-31
     */
    function stat_timeOfDay()
    {
        $tstamp_Start = $this->param['start'];
        $tstamp_Stop = $this->param['stop'];
        $table = $this->param['table'];
        $timeField = $this->timeFields[$table];
        $tstamp_Span = $tstamp_Stop - $tstamp_Start;
        $hours = $tstamp_Span / 60 / 60;
        $results = array();
        if ($this->param['mode'] == 'total') {
            $tTstamp_Stop = $tstamp_Start;
            if ($this->param['month'] == 'all') {
                return '<br /><br />' . $this->getLL('error.noMonth') . '<br /><br />';
            }
            if ($this->param['day'] == 'all') {
                return '<br /><br />' . $this->getLL('error.noDay') . '<br /><br />';
            }
            if ($this->param['year'] == 'all') {
                return '<br /><br />' . $this->getLL('error.noYear') . '<br /><br />';
            }
            $maxValue = 0;
            for ($i = 0; $i < 24; $i++) {
                $tTstamp_Stop += 3600 * $i;
                if ($tTstamp_Stop > $GLOBALS['EXEC_TIME']) {
                    $results[$i] = 0;
                    continue;
                }
                $res = $this->databaseHandle->exec_SELECTquery('COUNT(*)', $table, "{$timeField} <= {$tTstamp_Stop} AND deleted=0");
                list($num) = $this->databaseHandle->sql_fetch_row($res);
                $results[$i] = $num;
                if ($num > $maxValue) {
                    $maxValue = $num;
                }
            }
        } else {
            $res = $this->databaseHandle->exec_SELECTquery('*', $table, "{$timeField} >= {$tstamp_Start} AND {$timeField} <= {$tstamp_Stop} AND deleted=0");
            $maxValue = 0;
            while ($arr = $this->databaseHandle->sql_fetch_assoc($res)) {
                $hour = intval(date("H", $arr[$timeField]));
                $results[$hour]++;
                if ($results[$hour] > $maxValue) {
                    $maxValue = $results[$hour];
                }
            }
        }
        $content = $this->getDateTitleLink($tstamp_Start, $tstamp_Stop, 4, 0);
        for ($i = 0; $i < 24; $i++) {
            $result = intval($results[$i]);
            $avg = round($result / $hours, 2);
            $width = $maxValue ? round($result / $maxValue * 100, 2) : 0;
            $color = $i % 2 ? '#e00000' : '#ff0000';
            $content .= '<tr class="mm_forum-listrow' . ($i % 2 ? '2' : '') . '">
	<td style="width:1px; white-space:nowrap; text-align:right; padding:2px;">' . $i . ':00</td><td style="width:1px; white-space:nowrap;">&mdash; ' . $i . ':59</td>
	<td style="width:1px; padding:2px;">' . $result . '</td>
	<td><div style="background-color: ' . $color . '; width:' . $width . '%; height:14px; border-right: 1px solid #660000; border-bottom: 1px solid #660000; border-top: 1px solid #ff6666;">&nbsp;</div></td>
</tr>';
        }
        $content .= '</table>';
        return $content;
    }
 /**
  * Determines the user's rank by his/her post count.
  *
  * @author  Martin Helmich <*****@*****.**>
  * @version 2007-06-06
  * @param   int   $post_count The user's post count.
  * @return  array             The regarding user rank as associative array.
  */
 function getRankByPostCount($post_count)
 {
     $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_ranks', 'minPosts <= ' . $post_count . ' AND deleted=0 AND hidden=0 AND special=0', '', 'minPosts DESC');
     if ($this->databaseHandle->sql_num_rows($res) == 0) {
         return 'error';
     } else {
         return $this->databaseHandle->sql_fetch_assoc($res);
     }
 }
Esempio n. 7
0
 /**
  *
  * Reads all user groups into an array.
  * @return array An array containing information on all feuser groups. The
  *               array follows the pattern [Group UID]=>[Group name]
  *
  */
 function feGroups2Array()
 {
     $ug = array();
     $res = $this->databaseHandle->exec_SELECTquery('uid,title', 'fe_groups', 'hidden=0 and deleted=0', '', 'uid asc');
     while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
         $ug[$row['uid']] = $row['title'];
     }
     return $ug;
 }
 /**
  * Fetches the UIDs of all maximal versions for all extensions.
  * This is done by doing a LEFT JOIN to itself ("a" and "b") and comparing
  * both integer_version fields.
  *
  * @param int $repositoryUid
  * @return array
  */
 protected function fetchMaximalVersionsForAllExtensions($repositoryUid)
 {
     $queryResult = $this->databaseConnection->sql_query('SELECT a.uid AS uid ' . 'FROM ' . self::TABLE_NAME . ' a ' . 'LEFT JOIN ' . self::TABLE_NAME . ' b ON a.repository = b.repository AND a.extension_key = b.extension_key AND a.integer_version < b.integer_version ' . 'WHERE a.repository = ' . (int) $repositoryUid . ' AND b.extension_key IS NULL ' . 'ORDER BY a.uid');
     $extensionUids = array();
     while ($row = $this->databaseConnection->sql_fetch_assoc($queryResult)) {
         $extensionUids[] = $row['uid'];
     }
     $this->databaseConnection->sql_free_result($queryResult);
     return $extensionUids;
 }
 /**
  *
  * Generates an HTML <OPTION>-List that contains all toplevel boards.
  *
  * @param  Integer $selectedUid The UID of the forum that is to be marked as
  *                              preselected
  * @return String               HTML content
  */
 function getForumSelectOptionList($selectedUid = NULL)
 {
     $content = '';
     $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_forums', 'deleted=0 AND parentID=0 ' . $this->p->getStoragePIDQuery(), '', 'sorting ASC');
     while ($arr = $this->databaseHandle->sql_fetch_assoc($res)) {
         $selected = $arr['uid'] == $selectedUid;
         $content .= '<option value="' . $arr['uid'] . '" ' . ($selected ? 'selected="selected"' : '') . '>' . $this->validator->specialChars($arr['forum_name']) . '</option>';
     }
     return $content;
 }
Esempio n. 10
0
 /**
  * Check if there are still resources left for the process with the given id
  * Used to determine timeouts and to ensure a proper cleanup if there's a timeout
  *
  * @param  string  identification string for the process
  * @return boolean determines if the process is still active / has resources
  */
 function CLI_checkIfProcessIsActive($pid)
 {
     $ret = false;
     $this->db->sql_query('BEGIN');
     $res = $this->db->exec_SELECTquery('process_id,active,ttl', 'tx_crawler_process', 'process_id = \'' . $pid . '\'  AND deleted=0', '', 'ttl', '0,1');
     if ($row = $this->db->sql_fetch_assoc($res)) {
         $ret = intVal($row['active']) == 1;
     }
     $this->db->sql_query('COMMIT');
     return $ret;
 }
 /**
  * @test
  *
  * @return void
  */
 public function sqlFetchAssocReturnsAssocArray()
 {
     $this->prepareTableForFetchTests();
     $res = $this->subject->admin_query("SELECT * FROM {$this->testTable} ORDER BY id");
     $expectedResult = [['id' => '1', $this->testField => null, $this->anotherTestField => null, 'name' => 'Mr. Smith', 'deleted' => '0', 'street' => 'Oakland Road', 'city' => 'Los Angeles', 'country' => 'USA'], ['id' => '2', $this->testField => null, $this->anotherTestField => null, 'name' => 'Ms. Smith', 'deleted' => '0', 'street' => 'Oakland Road', 'city' => 'Los Angeles', 'country' => 'USA'], ['id' => '3', $this->testField => null, $this->anotherTestField => null, 'name' => 'Alice im Wunderland', 'deleted' => '0', 'street' => 'Große Straße', 'city' => 'Königreich der Herzen', 'country' => 'Wunderland'], ['id' => '4', $this->testField => null, $this->anotherTestField => null, 'name' => 'Agent Smith', 'deleted' => '1', 'street' => 'Unbekannt', 'city' => 'Unbekannt', 'country' => 'Matrix']];
     $i = 0;
     while ($row = $this->subject->sql_fetch_assoc($res)) {
         $this->assertSame($expectedResult[$i], $row);
         $i++;
     }
 }
 /**
  * Find the affected page ids by going through all the flexforms of all
  * active fal gallery content elements and checking if the current folder
  * is contained in the settings folder.
  *
  * @param Folder $folder The folder to check
  *
  * @return array
  */
 protected function getAffectedPageIds(Folder $folder)
 {
     $pids = array();
     if ($folder->getStorage()->getDriverType() === 'Local') {
         $res = $this->databaseConnection->sql_query("\n\t\t\t\tSELECT\n\t\t\t\t\tpid,\n\t\t\t\t\tExtractValue(pi_flexform, '/T3FlexForms/data/sheet[@index=''list'']/language/field[@index=''settings.default.folder'']/value') as folder\n\t\t\t\tFROM\n\t\t\t\t\ttt_content\n\t\t\t\tWHERE\n\t\t\t\t\tlist_type = 'falgallery_pi1'\n\t\t\t\t\tAND deleted = 0\n\t\t\t\t\tAND hidden = 0\n\t\t\t\t\tAND ExtractValue(pi_flexform, '/T3FlexForms/data/sheet[@index=''list'']/language/field[@index=''settings.default.folder'']/value') LIKE 'file:" . $folder->getCombinedIdentifier() . "%'");
         while ($row = $this->databaseConnection->sql_fetch_assoc($res)) {
             $pids[] = $row['pid'];
         }
         $this->databaseConnection->sql_free_result($res);
     }
     return $pids;
 }
Esempio n. 13
0
 /**
  * Retrieves the default character set of the database.
  *
  * @return string
  */
 protected function getDefaultDatabaseCharset()
 {
     $result = $this->databaseConnection->admin_query('SHOW VARIABLES LIKE "character_set_database"');
     $row = $this->databaseConnection->sql_fetch_assoc($result);
     $key = $row['Variable_name'];
     $value = $row['Value'];
     $databaseCharset = '';
     if ($key == 'character_set_database') {
         $databaseCharset = $value;
     }
     return $databaseCharset;
 }
Esempio n. 14
0
 /**
  * Update categories in flexforms
  *
  * @param string $pluginName
  * @param array $oldNewCategoryUidMapping
  * @param string $flexformField name of the flexform's field to look for
  * @return void
  */
 protected function updateFlexformCategories($pluginName, $oldNewCategoryUidMapping, $flexformField)
 {
     $count = 0;
     $title = 'Update flexforms categories (' . $pluginName . ':' . $flexformField . ')';
     $res = $this->databaseConnection->exec_SELECTquery('uid, pi_flexform', 'tt_content', 'CType=\'list\' AND list_type=\'' . $pluginName . '\' AND deleted=0');
     /** @var \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools $flexformTools */
     $flexformTools = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\FlexForm\\FlexFormTools');
     while ($row = $this->databaseConnection->sql_fetch_assoc($res)) {
         $status = null;
         $xmlArray = GeneralUtility::xml2array($row['pi_flexform']);
         if (!is_array($xmlArray) || !isset($xmlArray['data'])) {
             $status = FlashMessage::ERROR;
             $message = 'Flexform data of plugin "' . $pluginName . '" not found.';
         } elseif (!isset($xmlArray['data']['sDEF']['lDEF'])) {
             $status = FlashMessage::WARNING;
             $message = 'Flexform data of record tt_content:' . $row['uid'] . ' did not contain sheet: sDEF';
         } elseif (isset($xmlArray[$flexformField . '_updated'])) {
             $status = FlashMessage::NOTICE;
             $message = 'Flexform data of record tt_content:' . $row['uid'] . ' is already updated for ' . $flexformField . '. No update needed...';
         } else {
             // Some flexforms may have displayCond
             if (isset($xmlArray['data']['sDEF']['lDEF'][$flexformField]['vDEF'])) {
                 $updated = false;
                 $oldCategories = GeneralUtility::trimExplode(',', $xmlArray['data']['sDEF']['lDEF'][$flexformField]['vDEF'], true);
                 if (!empty($oldCategories)) {
                     $newCategories = array();
                     foreach ($oldCategories as $uid) {
                         if (isset($oldNewCategoryUidMapping[$uid])) {
                             $newCategories[] = $oldNewCategoryUidMapping[$uid];
                             $updated = true;
                         } else {
                             $status = FlashMessage::WARNING;
                             $message = 'The category ' . $uid . ' of record tt_content:' . $row['uid'] . ' was not found in sys_category records. Maybe the category was deleted before the migration? Please check manually...';
                         }
                     }
                     if ($updated) {
                         $count++;
                         $xmlArray[$flexformField . '_updated'] = 1;
                         $xmlArray['data']['sDEF']['lDEF'][$flexformField]['vDEF'] = implode(',', $newCategories);
                         $this->databaseConnection->exec_UPDATEquery('tt_content', 'uid=' . $row['uid'], array('pi_flexform' => $flexformTools->flexArray2Xml($xmlArray)));
                     }
                 }
             }
         }
         if ($status !== null) {
             $this->messageArray[] = array($status, $title, $message);
         }
     }
     $status = FlashMessage::INFO;
     $message = 'Updated ' . $count . ' tt_content flexforms for  "' . $pluginName . ':' . $flexformField . '"';
     $this->messageArray[] = array($status, $title, $message);
 }
Esempio n. 15
0
 /**
  * Transforms a Resource from a database query to an array of rows.
  *
  * @param resource $result The result
  * @return array The result as an array of rows (tuples)
  */
 protected function getRowsFromResult($result)
 {
     $rows = array();
     while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
         if (is_array($row)) {
             // Get language uid from querySettings.
             // Ensure the backend handling is not broken (fallback to Get parameter 'L' if needed)
             $overlaidRow = $this->doLanguageAndWorkspaceOverlay($this->query->getSource(), $row, $this->query->getQuerySettings());
             $contentObject = GeneralUtility::makeInstance($this->objectType, $this->query->getType(), $overlaidRow);
             $rows[] = $contentObject;
         }
     }
     return $rows;
 }
Esempio n. 16
0
    /**
     * Migrate locations with relations
     *
     * @return void
     */
    protected function migrateLocations()
    {
        $locations = $this->fetchLocations();
        while ($row = $this->database->sql_fetch_assoc($locations)) {
            $location = $this->mapFieldsPreImport($row, 'locations');
            $table = 'tx_storefinder_domain_model_location';
            if ($record = $this->isAlreadyImported($location, $table)) {
                unset($location['import_id']);
                $this->database->exec_UPDATEquery($table, 'uid = ' . $record['uid'], $location);
                $this->records['locations'][$row['uid']] = $location['uid'] = $record['uid'];
            } else {
                $this->database->exec_INSERTquery($table, $location);
                $this->records['locations'][$row['uid']] = $location['uid'] = $this->database->sql_insert_id();
            }
            $this->mapFieldsPostImport($row, $location, 'locations');
            $this->migrateFilesToFal($row, $location, $this->fileMapping['locations']['media']);
            $this->migrateFilesToFal($row, $location, $this->fileMapping['locations']['imageurl']);
            $this->migrateFilesToFal($row, $location, $this->fileMapping['locations']['icon']);
        }
        $this->database->sql_query('
			update tx_storefinder_domain_model_location AS l
				LEFT JOIN (
					SELECT uid_foreign, COUNT(*) AS count
					FROM sys_category_record_mm
					WHERE tablenames = \'tx_storefinder_domain_model_location\' AND fieldname = \'categories\'
					GROUP BY uid_foreign
				) AS c ON l.uid = c.uid_foreign
			set l.categories = COALESCE(c.count, 0);
		');
        $this->database->sql_query('
			update tx_storefinder_domain_model_location AS l
				LEFT JOIN (
					SELECT uid_local, COUNT(*) AS count
					FROM tx_storefinder_location_attribute_mm
					GROUP BY uid_local
				) AS a ON l.uid = a.uid_local
			set l.attributes = COALESCE(a.count, 0);
		');
        $this->database->sql_query('
			update tx_storefinder_domain_model_location AS l
				LEFT JOIN (
					SELECT uid_local, COUNT(*) AS count
					FROM tx_storefinder_location_location_mm
					GROUP BY uid_local
				) AS a ON l.uid = a.uid_local
			set l.related = COALESCE(a.count, 0);
		');
        $this->messageArray[] = array('message' => count($this->records['locations']) . ' locations migrated');
    }
 /**
  * Check whether field name is valid.
  * -> prevent sql injection
  *
  * @param string $field field name
  * @return boolean true, if column name is valid
  */
 protected function validateName($field)
 {
     if ($field === 'username') {
         return true;
     }
     $res = $this->databaseHandle->admin_get_fields('fe_users');
     if ($res) {
         while ($row = $this->databaseHandle->sql_fetch_assoc($res)) {
             if ($row['Field'] === $field) {
                 return true;
             }
         }
     }
     return false;
 }
Esempio n. 18
0
    /**
     * Gets the latest posts from all public forums.
     *
     * @author  Martin Helmich <*****@*****.**>
     * @return  array             An array containing all matching posts
     */
    function getPosts_all()
    {
        $res = $this->databaseHandle->exec_SELECTquery($this->selectFields, 'tx_mmforum_posts p
			 LEFT JOIN tx_mmforum_posts_text x ON x.post_id = p.uid
			 LEFT JOIN fe_users u ON u.uid = p.poster_id
			 LEFT JOIN tx_mmforum_topics t ON t.uid = p.topic_id
			 LEFT JOIN tx_mmforum_forums f ON t.forum_id = f.uid
			 LEFT JOIN tx_mmforum_forums c ON f.parentID = c.uid', 'p.deleted=0 AND
			 t.deleted=0 AND
			 f.deleted=0 ' . $this->pObj->getMayRead_forum_query('f') . $this->pObj->getMayRead_forum_query('c'), '', 'p.post_time DESC', $this->getPostNum());
        $results = array();
        while ($arr = $this->databaseHandle->sql_fetch_assoc($res)) {
            array_push($results, $arr);
        }
        return $results;
    }
Esempio n. 19
0
 /**
  * Get array with markers from a complete form
  *
  * @return array
  */
 protected function getFieldMarkersFromForm()
 {
     $result = array();
     $select = 'f.marker, f.uid';
     $from = 'tx_powermail_domain_model_forms fo ' . 'LEFT JOIN tx_powermail_domain_model_pages p ON p.forms = fo.uid ' . 'LEFT JOIN tx_powermail_domain_model_fields f ON f.pages = p.uid';
     $where = 'fo.uid = ' . (int) $this->formUid . ' and f.deleted = 0';
     $groupBy = '';
     $orderBy = '';
     $limit = 1000;
     $res = $this->databaseConnection->exec_SELECTquery($select, $from, $where, $groupBy, $orderBy, $limit);
     if ($res) {
         while ($row = $this->databaseConnection->sql_fetch_assoc($res)) {
             $result['_' . $row['uid']] = $row['marker'];
         }
     }
     return $result;
 }
 /**
  * Update existing record
  *
  * @return int uid of updated record
  */
 protected function update()
 {
     // find existing record in database
     $searchterm = $this->databaseConnection->fullQuoteStr($this->getProperty($this->getUniqueField()), $this->getTable());
     $res = $this->databaseConnection->exec_SELECTquery('uid', $this->getTable(), $this->getUniqueField() . ' = ' . $searchterm . ' and deleted = 0 ' . $this->getAdditionalWhereClause(), '', '', 1);
     if ($res) {
         $row = $this->databaseConnection->sql_fetch_assoc($res);
     }
     // if there is no existing entry, insert new one
     if (empty($row['uid'])) {
         return $this->insert();
     }
     // update existing entry (only if mode is not "none")
     if ($this->getMode() !== 'none') {
         $this->databaseConnection->exec_UPDATEquery($this->getTable(), 'uid = ' . (int) $row['uid'], $this->getProperties());
     }
     return $row['uid'];
 }
 function get($data)
 {
     if (is_int($data)) {
         /* Load record from database */
         $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_userfields', 'uid=' . intval($data));
         if ($this->databaseHandle->sql_num_rows($res) == 0) {
             return null;
         }
         $arr = $this->databaseHandle->sql_fetch_assoc($res);
     } else {
         $arr = $data;
     }
     /* Unserialize array with meta information */
     $arr['meta'] = unserialize($arr['meta']);
     /* Parse configuration TypoScript */
     $parser =& $this->userLib->getTSParser();
     $parser->setup = array();
     $parser->parse($arr['config']);
     $arr['config_parsed'] = $parser->setup;
     /* Do some corrections for backwards compatibility */
     if (!$arr['meta']['label']['default']) {
         $arr['meta']['label']['default'] = $arr['label'];
     }
     if (!$arr['meta']['type']) {
         $arr['meta']['type'] = 'custom';
     }
     if (!$arr['meta']['link'] && $arr['config_parsed']['datasource']) {
         $arr['meta']['link'] = $arr['config_parsed']['datasource'];
     }
     if (!isset($arr['meta']['required']) && isset($arr['config_parsed']['required'])) {
         $arr['meta']['required'] = $arr['config_parsed']['required'] ? true : false;
     }
     if (!$arr['meta']['text']['validate']) {
         $arr['meta']['text']['validate'] = 'none';
     }
     if (!$arr['meta']['text']['length']) {
         $arr['meta']['text']['length'] = '-1';
     }
     $this->data = $arr;
     $this->meta =& $arr['meta'];
     $this->conf =& $arr['config_parsed'];
 }
 /**
  * Get array with related fields to a form
  *
  * @param int $uid
  * @return array
  */
 protected function getFieldsFromForm($uid)
 {
     if (ConfigurationUtility::isReplaceIrreWithElementBrowserActive()) {
         return $this->getFieldsFromFormAlternative($uid);
     }
     $result = array();
     $select = 'f.title';
     $from = 'tx_powermail_domain_model_forms fo ' . 'LEFT JOIN tx_powermail_domain_model_pages p ON p.forms = fo.uid ' . 'LEFT JOIN tx_powermail_domain_model_fields f ON f.pages = p.uid';
     $where = 'fo.uid = ' . (int) $uid . ' and p.deleted = 0 and f.deleted = 0';
     $groupBy = '';
     $orderBy = '';
     $limit = 1000;
     $res = $this->databaseConnection->exec_SELECTquery($select, $from, $where, $groupBy, $orderBy, $limit);
     if ($res) {
         while ($row = $this->databaseConnection->sql_fetch_assoc($res)) {
             $result[] = $row['title'];
         }
     }
     return $result;
 }
Esempio n. 23
0
 /**
  * Encrypt old bounce account passwords and preserve old default config
  *
  * @return string[]
  */
 private function getQueriesToEncryptOldBounceAccountPasswords()
 {
     // Fetch the old records - they will have a default port and an empty config.
     $rs = $this->databaseConnection->exec_SELECTquery('uid, password', 'tx_newsletter_domain_model_bounceaccount', 'port = 0 AND config = \'\'');
     $records = [];
     while ($record = $this->databaseConnection->sql_fetch_assoc($rs)) {
         $records[] = $record;
     }
     $this->databaseConnection->sql_free_result($rs);
     if (empty($records)) {
         return [];
     }
     // Keep the old config to not break old installations
     $config = Tools::encrypt("poll ###SERVER###\nproto ###PROTOCOL### \nusername \"###USERNAME###\"\npassword \"###PASSWORD###\"\n");
     $queries = [];
     foreach ($records as $record) {
         $queries[] = $this->databaseConnection->UPDATEquery('tx_newsletter_domain_model_bounceaccount', 'uid=' . intval($record['uid']), ['password' => Tools::encrypt($record['password']), 'config' => $config]);
     }
     return ['Encrypt bounce account passwords' => $queries];
 }
Esempio n. 24
0
 /**
  * DB select object by id
  *
  * @param int $uid Uid
  * @param Tx_Commerce_Dao_BasicDaoObject $object Object
  *
  * @return void
  */
 protected function dbSelectById($uid, Tx_Commerce_Dao_BasicDaoObject &$object)
 {
     $dbFields = '*';
     $dbTable = $this->dbTable;
     $dbWhere = 'uid = ' . (int) $uid;
     $dbWhere .= 'AND deleted = 0';
     // execute query
     $res = $this->database->exec_SELECTquery($dbFields, $dbTable, $dbWhere);
     // insert into object
     $model = $this->database->sql_fetch_assoc($res);
     if ($model) {
         // parse into object
         $this->parser->parseModelToObject($model, $object);
     } else {
         // no object found, empty obj and id
         $object->clear();
     }
     // free results
     $this->database->sql_free_result($res);
 }
Esempio n. 25
0
 /**
  * Clear the TYPO3 page cache for the given record.
  * If the record lies on a page, then we clear the cache of this page.
  * If the record has no PID column, we clear the cache of the current page as best-effort.
  *
  * Much of this functionality is taken from DataHandler::clear_cache() which unfortunately only works with logged-in BE user.
  *
  * @param string $tableName Table name of the record
  * @param int $uid UID of the record
  * @return void
  */
 protected function clearPageCache($tableName, $uid)
 {
     $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
     if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
     } else {
         // if disabled, return
         return;
     }
     $pageIdsToClear = array();
     $storagePage = NULL;
     $columns = $this->databaseHandle->admin_get_fields($tableName);
     if (array_key_exists('pid', $columns)) {
         $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid=' . (int) $uid);
         if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
             $storagePage = $row['pid'];
             $pageIdsToClear[] = $storagePage;
         }
     } elseif (isset($GLOBALS['TSFE'])) {
         // No PID column - we can do a best-effort to clear the cache of the current page if in FE
         $storagePage = $GLOBALS['TSFE']->id;
         $pageIdsToClear[] = $storagePage;
     }
     if ($storagePage === NULL) {
         return;
     }
     if (!isset($this->pageTSConfigCache[$storagePage])) {
         $this->pageTSConfigCache[$storagePage] = BackendUtility::getPagesTSconfig($storagePage);
     }
     if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
         $clearCacheCommands = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']), TRUE);
         $clearCacheCommands = array_unique($clearCacheCommands);
         foreach ($clearCacheCommands as $clearCacheCommand) {
             if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($clearCacheCommand)) {
                 $pageIdsToClear[] = $clearCacheCommand;
             }
         }
     }
     foreach ($pageIdsToClear as $pageIdToClear) {
         $this->cacheService->getPageIdStack()->push($pageIdToClear);
     }
 }
 /**
  * Get AUTO_INCREMENT fields from $table
  *
  * @since 1.0.0
  *
  * @param string $table
  * @return array
  */
 protected function getAutoIncrementFields($table)
 {
     $table = preg_replace('/[^a-z0-9_]/', '', $table);
     if (isset($this->autoIncrementFieldCache[$table])) {
         return $this->autoIncrementFieldCache[$table];
     } else {
         $fields = array();
         if (!$table) {
             return $fields;
         }
         $result = $this->databaseConnection->sql_query("SHOW COLUMNS FROM `" . $table . "`;");
         while ($row = $this->databaseConnection->sql_fetch_assoc($result)) {
             if ($row['Extra'] == 'auto_increment') {
                 $fields[] = $row['Field'];
             }
         }
         $this->databaseConnection->sql_free_result($result);
         $this->autoIncrementFieldCache[$table] = $fields;
         return $fields;
     }
 }
 /**
  * Get Forms from Database
  *
  * @param int $startPid
  * @param int $language
  * @return array
  */
 protected function getAllForms($startPid, $language)
 {
     $this->initialize();
     $select = 'fo.uid, fo.title';
     $from = 'tx_powermail_domain_model_forms fo';
     $where = 'fo.deleted = 0 and fo.hidden = 0 and ' . '(fo.sys_language_uid IN (-1,0) or ' . '(fo.l10n_parent = 0 and fo.sys_language_uid = ' . (int) $language . '))';
     if (!empty($startPid)) {
         $where .= ' and fo.pid in (' . $this->getPidListFromStartingPoint($startPid) . ')';
     }
     $groupBy = '';
     $orderBy = 'fo.title ASC';
     $limit = 10000;
     $res = $this->databaseConnection->exec_SELECTquery($select, $from, $where, $groupBy, $orderBy, $limit);
     $array = [];
     if ($res) {
         while ($row = $this->databaseConnection->sql_fetch_assoc($res)) {
             $array[] = $row;
         }
     }
     return $array;
 }
 /**
  * Removes all processed files and also deletes the associated physical files
  *
  * @param int|NULL $storageUid If not NULL, only the processed files of the given storage are removed
  * @return int Number of failed deletions
  */
 public function removeAll($storageUid = null)
 {
     $res = $this->databaseConnection->exec_SELECTquery('*', $this->table, 'identifier <> \'\'');
     $logger = $this->getLogger();
     $errorCount = 0;
     while ($row = $this->databaseConnection->sql_fetch_assoc($res)) {
         if ($storageUid && (int) $storageUid !== (int) $row['storage']) {
             continue;
         }
         try {
             $file = $this->createDomainObject($row);
             $file->getStorage()->setEvaluatePermissions(false);
             $file->delete(true);
         } catch (\Exception $e) {
             $logger->error('Failed to delete file "' . $row['identifier'] . '" in storage uid ' . $row['storage'] . '.', array('exception' => $e));
             ++$errorCount;
         }
     }
     $this->databaseConnection->exec_TRUNCATEquery($this->table);
     return $errorCount;
 }
 /**
  * Loads the record of an user field.
  * This function load the entire record of a custom user field. The
  * field's typoscript configuration is automatically parsed and the
  * array of metadata that is stored in the database is automatically
  * unserialized.
  *
  * @param  mixed $value Some data the record is to be initialized with.
  *                     This may be either the record's UID or the entire
  *                     record itself as array.
  * @return array       The record of the user field.
  *
  * @author  Martin Helmich <*****@*****.**>
  * @version 2009-02-16
  */
 function getUserFieldData($value)
 {
     if (is_array($value)) {
         $data = $value;
     } else {
         if (MathUtility::canBeInterpretedAsInteger($value) || intval($value) != 0) {
             $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_userfields', 'uid=' . intval($value));
             if ($this->databaseHandle->sql_num_rows($res) == 0) {
                 return null;
             }
             $data = $this->databaseHandle->sql_fetch_assoc($res);
         }
     }
     /* Parse configuration TypoScript */
     $parser = $this->getTSParser();
     $parser->parse($data['config']);
     $data['config_parsed'] = $parser->setup;
     $parser->setup = array();
     $this->initializeOldMetaArray($data);
     return $data;
 }
 /**
  *
  * Deletes a single posts.
  * This method deletes a single post and all associated objects (alerts, ratings,
  * search index entries etc.).
  *
  * @author  Martin Helmich <*****@*****.**>
  * @version 2009-12-20
  * @param   int     $postId   The UID of the post that is to be deleted.
  * @param   boolean $noUpdate Set to TRUE, in order to suspend updating of
  *                            internal counters.
  * @return  void
  */
 function delete_post($postId, $noUpdate = false)
 {
     $arr = $this->databaseHandle->sql_fetch_assoc($this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_posts', 'uid=' . intval($postId)));
     $uA = array('deleted' => 1, 'tstamp' => $GLOBALS['EXEC_TIME']);
     $this->databaseHandle->exec_UPDATEquery('tx_mmforum_posts', $uA, 'uid=' . intval($postId));
     $this->databaseHandle->exec_UPDATEquery('tx_mmforum_posts_text', $uA, 'post_id=' . intval($postId));
     $this->databaseHandle->exec_UPDATEquery('tx_mmforum_post_alert', $uA, 'post_id=' . intval($postId));
     $this->databaseHandle->exec_UPDATEquery('tx_mmforum_attachments', $uA, 'post_id=' . intval($postId));
     $this->databaseHandle->exec_DELETEquery('tx_mmforum_wordmatch', 'post_id=' . intval($postId) . '');
     if (ExtensionManagementUtility::isLoaded('ratings')) {
         $this->databaseHandle->exec_DELETEquery('tx_ratings_data', $uA, 'reference="tx_mmforum_posts_' . intval($postId) . '"');
     }
     if (!$noUpdate) {
         $this->updateTopicPostCount($arr['topic_id']);
         $this->updateForumPostCount($arr['forum_id']);
         $this->updateUserPostCount($arr['poster_id']);
     } else {
         $this->updateQueue_addTopic($arr['topic_id']);
         $this->updateQueue_addForum($arr['forum_id']);
         $this->updateQueue_addUser($arr['poster_id']);
     }
 }