/** * creates an image record for each image which was selected in the select-box */ private function createRecords() { $url = $this->feedImport['feed_url']; // TODO: import image from media feed //$fileNames = explode(',', ); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); $data = curl_exec($ch); curl_close($ch); $xml = new SimpleXMLElement($data, LIBXML_NOCDATA); $maxImages = 5; foreach ($xml->channel[0]->item as $item) { $mediaProperties = $item->children('http://search.yahoo.com/mrss/'); $mediaContent = $mediaProperties->content[0]; $imageUrl = $mediaContent->attributes()->url; $fileName = $this->getFilenameFromUrl($imageUrl); if (trim($fileName) && !isset($this->images[$fileName])) { $filepath = PATH_site . 'uploads/tx_gorillary/' . $fileName; $this->downloadFile($imageUrl, $filepath); $newRecord = array('pid' => $this->feedImport['pid'], 'feedimport' => $this->feedImport['uid'], 'crdate' => time(), 'cruser_id' => $this->feedImport['cruser_id'], 'image' => $fileName, 'title' => trim($item->title), 'description' => trim($item->description), 'link' => $item->link); $this->db->exec_INSERTquery('tx_gorillary_images', $newRecord); $newRecord['uid'] = $this->db->sql_insert_id(); $this->images[$fileName] = $newRecord; } $maxImages--; if ($maxImages == 0) { break; } } }
/** * @test */ public function storedGzipCompressedDataReturnsSameData() { $testStringWithBinary = @gzcompress('sdfkljer4587'); $this->fixture->exec_INSERTquery($this->testTable, array('fieldblob' => $testStringWithBinary)); $id = $this->fixture->sql_insert_id(); $entry = $this->fixture->exec_SELECTgetRows('fieldblob', $this->testTable, 'id = ' . $id); $this->assertEquals($testStringWithBinary, $entry[0]['fieldblob']); }
/** * creates an image record for each image which was selected in the select-box */ private function createRecords() { $fileNames = explode(',', $this->collection['images']); foreach ($fileNames as $fileName) { if (trim($fileName) && !isset($this->images[$fileName])) { $newRecord = array('pid' => $this->collection['pid'], 'collection' => $this->collection['uid'], 'crdate' => time(), 'cruser_id' => $this->collection['cruser_id'], 'image' => $fileName, 'title' => $this->getTitleFromName($fileName)); $this->db->exec_INSERTquery('tx_gorillary_images', $newRecord); $newRecord['uid'] = $this->db->sql_insert_id(); $this->images[$fileName] = $newRecord; } } }
/** * 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); }
/** * Try to acquire a new process with the given id * also performs some auto-cleanup for orphan processes * @todo preemption might not be the most elegant way to clean up * * @param string $id identification string for the process * @return boolean determines whether the attempt to get resources was successful */ function CLI_checkAndAcquireNewProcess($id) { $ret = true; $systemProcessId = getmypid(); if ($systemProcessId < 1) { return FALSE; } $processCount = 0; $orphanProcesses = array(); $this->db->sql_query('BEGIN'); $res = $this->db->exec_SELECTquery('process_id,ttl', 'tx_crawler_process', 'active=1 AND deleted=0'); $currentTime = $this->getCurrentTime(); while ($row = $this->db->sql_fetch_assoc($res)) { if ($row['ttl'] < $currentTime) { $orphanProcesses[] = $row['process_id']; } else { $processCount++; } } // if there are less than allowed active processes then add a new one if ($processCount < intval($this->extensionSettings['processLimit'])) { $this->CLI_debug("add " . $this->CLI_buildProcessId() . " (" . ($processCount + 1) . "/" . intval($this->extensionSettings['processLimit']) . ")"); // create new process record $this->db->exec_INSERTquery('tx_crawler_process', array('process_id' => $id, 'active' => '1', 'ttl' => $currentTime + intval($this->extensionSettings['processMaxRunTime']), 'system_process_id' => $systemProcessId)); } else { $this->CLI_debug("Processlimit reached (" . $processCount . "/" . intval($this->extensionSettings['processLimit']) . ")"); $ret = false; } $this->CLI_releaseProcesses($orphanProcesses, true); // maybe this should be somehow included into the current lock $this->CLI_deleteProcessesMarkedDeleted(); $this->db->sql_query('COMMIT'); return $ret; }
/** * Migrate news_category.image (CSV) to sys_category.images (sys_file_reference) * * @return void */ protected function migrateCategoryImages() { $oldCategories = $this->databaseConnection->exec_SELECTgetRows('uid, pid, image, migrate_sys_category_uid', 'tx_news_domain_model_category', 'deleted=0 AND image!=""'); // no images to process then skip if (!count($oldCategories)) { return; } $processedImages = 0; foreach ($oldCategories as $oldCategory) { $files = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $oldCategory['image'], true); $i = 0; foreach ($files as $file) { if (file_exists(PATH_site . 'uploads/tx_news/' . $file)) { $fileObject = $this->getCategoryImageFolder()->addFile(PATH_site . 'uploads/tx_news/' . $file); $dataArray = array('uid_local' => $fileObject->getUid(), 'tstamp' => $_SERVER['REQUEST_TIME'], 'crdate' => $_SERVER['REQUEST_TIME'], 'tablenames' => 'sys_category', 'uid_foreign' => $oldCategory['migrate_sys_category_uid'], 'pid' => $oldCategory['pid'], 'fieldname' => 'images', 'table_local' => 'sys_file', 'sorting_foreign' => $i); $this->databaseConnection->exec_INSERTquery('sys_file_reference', $dataArray); $processedImages++; } $i++; } } $message = 'Migrated ' . $processedImages . ' category images'; $status = FlashMessage::INFO; $title = ''; $this->messageArray[] = array($status, $title, $message); }
/** * Stores new association to the database. * * @param string $serverUrl Server URL * @param \Auth_OpenID_Association $association OpenID association * @return void */ protected function storeNewAssociation($serverUrl, $association) { $serializedAssociation = serialize($association); $values = array('assoc_handle' => $association->handle, 'content' => base64_encode($serializedAssociation), 'crdate' => $association->issued, 'tstamp' => time(), 'expires' => $association->issued + $association->lifetime - self::ASSOCIATION_EXPIRATION_SAFETY_INTERVAL, 'server_url' => $serverUrl); // In the next query we can get race conditions. sha1_hash prevents many // asociations from being stored for one server $this->databaseConnection->exec_INSERTquery(self::ASSOCIATION_TABLE_NAME, $values); }
/** * Add new sys_file_reference for the preview image * * @param FileReference $fileObject * @param array $postRecord * * @return void */ protected function createPostSysFileReference(FileReference $fileObject, $postRecord) { if (!$fileObject instanceof FileReference) { return; } $dataArray = array('uid_local' => $fileObject->getOriginalFile()->getUid(), 'tablenames' => 'tx_t3blog_post', 'fieldname' => 'preview_image', 'uid_foreign' => $postRecord['uid'], 'table_local' => 'sys_file', 'cruser_id' => 999, 'pid' => $postRecord['pid']); $this->databaseConnection->exec_INSERTquery('sys_file_reference', $dataArray); $this->logDatabaseExec(); }
/** * Sets the entry to cache. * * @param UrlCacheEntry $cacheEntry * @return void */ public function putUrlToCache(UrlCacheEntry $cacheEntry) { $data = array('original_url' => $cacheEntry->getOriginalUrl(), 'page_id' => $cacheEntry->getPageId(), 'request_variables' => json_encode($cacheEntry->getRequestVariables()), 'rootpage_id' => $cacheEntry->getRootPageId(), 'speaking_url' => $cacheEntry->getSpeakingUrl()); if ($cacheEntry->getCacheId()) { $this->databaseConnection->exec_UPDATEquery('tx_realurl_urlcache', 'uid=' . $this->databaseConnection->fullQuoteStr($cacheEntry->getCacheId(), 'tx_realurl_urlcache'), $data); } else { $this->databaseConnection->exec_INSERTquery('tx_realurl_urlcache', $data); $cacheEntry->setCacheId($this->databaseConnection->sql_insert_id()); } }
/** * Add is_dummy_record record and create dummy record * * @return void */ private function prepareTables() { $sql = 'ALTER TABLE %s ADD is_dummy_record tinyint(1) unsigned DEFAULT \'0\' NOT NULL'; foreach ($this->tables as $table) { $_sql = sprintf($sql, $table); $this->database->sql_query($_sql); } $values = array('title' => $this->getUniqueId('title'), 'l10n_diffsource' => '', 'description' => '', 'is_dummy_record' => 1); $this->database->exec_INSERTquery('sys_category', $values); $this->categoryUid = $this->database->sql_insert_id(); }
/** * Adds a row to the storage * * @param string $tableName The database table name * @param array $fieldValues The row to be inserted * @param bool $isRelation TRUE if we are currently inserting into a relation table, FALSE by default * @return int The uid of the inserted row */ public function addRow($tableName, array $fieldValues, $isRelation = FALSE) { if (isset($fieldValues['uid'])) { unset($fieldValues['uid']); } $this->databaseHandle->exec_INSERTquery($tableName, $fieldValues); $this->checkSqlErrors(); $uid = $this->databaseHandle->sql_insert_id(); if (!$isRelation) { $this->clearPageCache($tableName, $uid); } return (int) $uid; }
/** * Create the initial local storage base e.g. for the fileadmin/ directory. * * @param string $name * @param string $basePath * @param string $pathType * @param string $description * @param bool $default set to default storage * @return int uid of the inserted record */ public function createLocalStorage($name, $basePath, $pathType, $description = '', $default = false) { $caseSensitive = $this->testCaseSensitivity($pathType === 'relative' ? PATH_site . $basePath : $basePath); // create the FlexForm for the driver configuration $flexFormData = array('data' => array('sDEF' => array('lDEF' => array('basePath' => array('vDEF' => rtrim($basePath, '/') . '/'), 'pathType' => array('vDEF' => $pathType), 'caseSensitive' => array('vDEF' => $caseSensitive))))); /** @var $flexObj FlexFormTools */ $flexObj = GeneralUtility::makeInstance(FlexFormTools::class); $flexFormXml = $flexObj->flexArray2Xml($flexFormData, true); // create the record $field_values = array('pid' => 0, 'tstamp' => $GLOBALS['EXEC_TIME'], 'crdate' => $GLOBALS['EXEC_TIME'], 'name' => $name, 'description' => $description, 'driver' => 'Local', 'configuration' => $flexFormXml, 'is_online' => 1, 'is_browsable' => 1, 'is_public' => 1, 'is_writable' => 1, 'is_default' => $default ? 1 : 0); $this->db->exec_INSERTquery('sys_file_storage', $field_values); return (int) $this->db->sql_insert_id(); }
/** * Adds a processedfile object in the database * * @param ProcessedFile $processedFile * @return void */ public function add($processedFile) { if ($processedFile->isPersisted()) { $this->update($processedFile); } else { $insertFields = $processedFile->toArray(); $insertFields['crdate'] = $insertFields['tstamp'] = time(); $insertFields = $this->cleanUnavailableColumns($insertFields); $this->databaseConnection->exec_INSERTquery($this->table, $insertFields); $uid = $this->databaseConnection->sql_insert_id(); $processedFile->updateProperties(array('uid' => $uid)); } }
/** * Log the access of the file * * @param integer|null $intFileSize */ protected function logDownload($intFileSize = null) { if ($this->isLoggingEnabled()) { if (is_null($intFileSize)) { $intFileSize = $this->fileSize; } $data_array = array('tstamp' => time(), 'file_name' => $this->file, 'file_size' => $intFileSize, 'user_id' => intval($this->feUserObj->user['uid'])); if (is_null($this->logRowUid)) { $this->databaseConnection->exec_INSERTquery('tx_nawsecuredl_counter', $data_array); $this->logRowUid = $this->databaseConnection->sql_insert_id(); } else { $this->databaseConnection->exec_UPDATEquery('tx_nawsecuredl_counter', '`uid`=' . (int) $this->logRowUid, $data_array); } } }
/** * Writes changes into database * * @return void */ public function updateDatabase() { if (!is_array($this->data)) { return; } $diff = array_diff_assoc($this->data, $this->origData); foreach ($diff as $key => $value) { if (!isset($this->data[$key])) { unset($diff[$key]); } } if (!empty($diff)) { $this->data['tstamp'] = $diff['tstamp'] = $GLOBALS['EXEC_TIME']; if (intVal($this->data['uid']) > 0) { $this->databaseHandle->exec_UPDATEquery($this->getTableName(), 'uid=' . $this->getUid(), $diff); } else { $this->data['crdate'] = $diff['crdate'] = $GLOBALS['EXEC_TIME']; $this->databaseHandle->exec_INSERTquery($this->getTableName(), $diff); $this->setUid($this->databaseHandle->sql_insert_id()); $this->data['uid'] = $this->getUid(); } $this->origData = $this->data; } }
/** * Sets the entry to cache. * * @param UrlCacheEntry $cacheEntry * @return void */ public function putUrlToCache(UrlCacheEntry $cacheEntry) { $data = array('expire' => $cacheEntry->getExpiration(), 'original_url' => $cacheEntry->getOriginalUrl(), 'page_id' => $cacheEntry->getPageId(), 'request_variables' => json_encode($cacheEntry->getRequestVariables()), 'rootpage_id' => $cacheEntry->getRootPageId(), 'speaking_url' => $cacheEntry->getSpeakingUrl()); if ($cacheEntry->getCacheId()) { $this->databaseConnection->exec_UPDATEquery('tx_realurl_urldata', 'uid=' . $this->databaseConnection->fullQuoteStr($cacheEntry->getCacheId(), 'tx_realurl_urldata'), $data); } else { $this->databaseConnection->sql_query('START TRANSACTION'); if ($this->limitTableRecords('tx_realurl_urldata')) { $this->databaseConnection->sql_query('DELETE FROM tx_realurl_uniqalias_cache_map WHERE url_cache_id NOT IN (SELECT uid FROM tx_realurl_urldata)'); } $this->databaseConnection->exec_INSERTquery('tx_realurl_urldata', $data); $cacheEntry->setCacheId($this->databaseConnection->sql_insert_id()); $this->databaseConnection->sql_query('COMMIT'); } }
/** * Add registrant record (if new) and return corresponding uid * * @param $data * @param integer $uid * * @return integer */ private function addRegistrant($data, $uid = 1) { if ((int) $data['registrant'] > 0 && $this->databaseConnection->exec_SELECTcountRows('*', 'fe_users', 'uid=' . (int) $data['registrant'])) { $registrant = $this->databaseConnection->exec_SELECTgetSingleRow('*', 'fe_users', 'uid=' . (int) $data['registrant']); } else { $registrant = ['name' => $data['registrant_name'], 'company' => $data['registrant_company'], 'email' => $data['registrant_email'], 'telephone' => $data['registrant_phone']]; } $checkForExistingRecord = $this->databaseConnection->exec_SELECTgetSingleRow('*', 'tx_projectregistration_domain_model_person', 'name="' . $registrant['name'] . '" AND email="' . $registrant['email'] . '" AND company="' . $registrant['company'] . '" AND phone="' . $registrant['telephone'] . '"'); if ($checkForExistingRecord) { return (int) $checkForExistingRecord['uid']; } else { $this->databaseConnection->exec_INSERTquery('tx_projectregistration_domain_model_person', ['username' => $registrant['username'] ?: '', 'name' => $registrant['name'] ?: '', 'first_name' => $registrant['first_name'] ?: '', 'middle_name' => $registrant['middle_name'] ?: '', 'last_name' => $registrant['last_name'] ?: '', 'company' => $registrant['company'] ?: '', 'address' => $registrant['address'] ?: '', 'zip' => $registrant['zip'] ?: '', 'city' => $registrant['city'] ?: '', 'country' => abs((int) $registrant['ecom_toolbox_country']), 'state' => abs((int) $registrant['ecom_toolbox_state']), 'email' => $registrant['email'] ?: '', 'phone' => $registrant['telephone'] ?: '', 'fax' => $registrant['fax'] ?: '', 'title' => $registrant['title'] ?: '', 'www' => $registrant['www'] ?: '', 'fe_user' => abs((int) $data['registrant'])]); return $uid; } }
/** * Creates a frontend user based on the data of the social user * * @param array $user * @param string $provider * @param string $identifier * * @return array|FALSE the created identity record or false if it is not possible */ protected function addIdentityToFrontendUser($user, $provider, $identifier) { $result = false; $identityClassName = 'Portrino\\PxHybridAuth\\Domain\\Model\\Identity\\' . $provider . 'Identity'; if (class_exists($identityClassName) && defined($identityClassName . '::EXTBASE_TYPE')) { $extbaseType = constant($identityClassName . '::EXTBASE_TYPE'); $this->database->exec_INSERTquery('tx_pxhybridauth_domain_model_identity', ['pid' => $user['pid'], 'tx_extbase_type' => $extbaseType, 'identifier' => $identifier, 'fe_user' => $user['uid'], 'hidden' => 0, 'deleted' => 0, 'tstamp' => time(), 'crdate' => time()]); $id = $this->database->sql_insert_id(); $where = 'uid=' . intval($id); $result = $this->database->exec_SELECTgetSingleRow('*', 'tx_pxhybridauth_domain_model_identity', $where); if ($result) { $this->database->exec_UPDATEquery('fe_users', 'uid=' . intval($user['uid']), ['tx_pxhybridauth_identities' => 1]); } } return $result; }
/** * Db add object * * @param Tx_Commerce_Dao_BasicDaoObject $object Object * * @return void */ protected function dbInsert(Tx_Commerce_Dao_BasicDaoObject &$object) { $dbTable = $this->dbTable; $dbModel = $this->parser->parseObjectToModel($object); // set pid $this->parser->setPid($dbModel, $this->createPid); // execute query $this->database->exec_INSERTquery($dbTable, $dbModel); // any errors $error = $this->database->sql_error(); if (!empty($error)) { $this->addError(array($error, $this->database->INSERTquery($dbTable, $dbModel), '$dbModel' => $dbModel)); } // set object id $object->setId($this->database->sql_insert_id()); }
/** * Adds a topic to a (logged in) user's list of email subscriptions. * * @param \tx_mmforum_base $forumObj The plugin object * @param string $topicId The topic identifier * @param $feUserId * @return bool Whether it worked or not */ function addSubscription(\tx_mmforum_base $forumObj, $topicId, $feUserId) { $feUserId = intval($feUserId); $topicId = intval($topicId); if ($feUserId && $topicId) { // Executing database operations $res = $this->databaseHandle->exec_SELECTquery('uid', 'tx_mmforum_topicmail', 'user_id = ' . $feUserId . ' AND topic_id = ' . $topicId . $forumObj->getStoragePIDQuery()); if ($this->databaseHandle->sql_num_rows($res) < 1) { $insertData = array('pid' => $forumObj->getStoragePID(), 'tstamp' => $GLOBALS['EXEC_TIME'], 'crdate' => $GLOBALS['EXEC_TIME'], 'topic_id' => $topicId, 'user_id' => $feUserId); return $this->databaseHandle->exec_INSERTquery('tx_mmforum_topicmail', $insertData); } else { // it's already added, so "it worked" return true; } } // invalid parameters return false; }
/** * Creates a new category record and stores it into the database. * * @author Martin Helmich <*****@*****.**> * @version 2008-05-16 * @return void */ function save_newCategory() { $insertArray = array('pid' => $this->pid, 'hidden' => $this->param['ctg']['hidden'], 'tstamp' => $GLOBALS['EXEC_TIME'], 'crdate' => $GLOBALS['EXEC_TIME'], 'cruser_id' => $GLOBALS['BE_USER']->user['uid'], 'forum_name' => trim($this->param['ctg']['title']), 'grouprights_read' => $this->param['ctg']['authRead'], 'grouprights_write' => $this->param['ctg']['authWrite'], 'grouprights_mod' => $this->param['ctg']['authMod'], 'parentID' => 0); if (strlen($insertArray['forum_name']) == 0) { return array('title' => '<div class="mm_forum-fatalerror">' . $this->getLL('error.noTitle') . '</div>'); } if ($this->param['ctg']['order'] == 'first') { $insertArray['sorting'] = 0; if ($this->param['ctg']['sorting'] != 0) { $this->globalIncSorting(0, 1, $this->param['ctg']['parentID']); } } elseif ($this->param['ctg']['order'] == 'last') { $insertArray['sorting'] = $this->getMaxSorting() + 1; } else { $this->globalIncSorting($this->param['ctg']['order'], 2, $this->param['ctg']['parentID']); $insertArray['sorting'] = $this->param['ctg']['order'] + 1; } $this->databaseHandle->exec_INSERTquery('tx_mmforum_forums', $insertArray); }
/** * Processes the actual transformation from CSV to sys_file_references * * @param array $source * @param array $destination * @param array $configuration * * @return void */ protected function migrateFilesToFal(array $source, array $destination, array $configuration) { $path = PATH_site . $configuration['sourcePath']; $files = GeneralUtility::trimExplode(',', $source[$configuration['sourceField']], true); $i = 1; foreach ($files as $file) { if (file_exists($path . $file)) { GeneralUtility::upload_copy_move($path . $file, $this->targetDirectory . $file); /** @var \TYPO3\CMS\Core\Resource\File $fileObject */ $fileObject = $this->storage->getFile(self::FILE_MIGRATION_FOLDER . $file); $this->fileIndexRepository->add($fileObject); $count = $this->database->exec_SELECTcountRows('*', 'sys_file_reference', 'tablenames = ' . $this->database->fullQuoteStr($configuration['destinationTable'], 'sys_file_reference') . ' AND fieldname = ' . $this->database->fullQuoteStr($configuration['destinationField'], 'sys_file_reference') . ' AND uid_local = ' . $fileObject->getUid() . ' AND uid_foreign = ' . $destination['uid']); if (!$count) { $dataArray = array('uid_local' => $fileObject->getUid(), 'tablenames' => $configuration['destinationTable'], 'uid_foreign' => $destination['uid'], 'pid' => $source['pid'], 'fieldname' => $configuration['destinationField'], 'sorting_foreign' => $i, 'table_local' => 'sys_file'); $this->database->exec_INSERTquery('sys_file_reference', $dataArray); } } $i++; } }
/** * Saves a value for a user for this field. * This function stores a value for this field for a specific user. * Depending on the field type, the value is stored either into the * fe_users table directly, or into the tx_mmforum_userfields_contents * table. * * @param int $userId The UID of the user for whom the value is to be * added. * @param string $value The value that is to be stored into this field. * @param int $pid The page UID of the data storage page. Submitting * this value as a parameter is just a dirty workaround. * @return void * * @author Martin Helmich <*****@*****.**> * @version 2009-02-16 */ function setForUser($userId, $value, $pid = 0) { /* If the userfield uses an existing field from the fe_users * table, generate an UPDATE query to edit the fe_user record. */ if ($this->isUsingExistingField()) { $updateArray = array('tstamp' => $GLOBALS['EXEC_TIME'], $this->getLinkedUserField() => trim($value)); $this->databaseHandle->exec_UPDATEquery('fe_users', 'uid=' . intval($userId), $updateArray); /* If the userfield does NOT use a field from the fe_users table * and there is already a value present in the tx_mmforum_userfields_contents * table, overwrite this value now. */ } elseif ($this->isSetForUser($userId)) { $updateArray = array('tstamp' => $GLOBALS['EXEC_TIME'], 'field_value' => $value); $this->databaseHandle->exec_UPDATEquery('tx_mmforum_userfields_contents', 'user_id=' . intval($userId) . ' AND field_id=' . intval($this->getUID()) . ' AND deleted=0', $updateArray); /* If there is no value set for this user, then create a tx_mmforum_userfields_contents * record now. */ } else { $insertArray = array('pid' => $pid, 'tstamp' => $GLOBALS['EXEC_TIME'], 'crdate' => $GLOBALS['EXEC_TIME'], 'user_id' => $userId, 'field_id' => $this->getUID(), 'field_value' => $value); $this->databaseHandle->exec_INSERTquery('tx_mmforum_userfields_contents', $insertArray); } }
/** * * Saves changes made to either an existing or a newly created forum to the * datbase. * * @access private * @return Array An array that contains a status code and validation errors, if * some occured. */ function saveEditAction() { $forum = $this->v['forum']; $forumUid = intval($this->v['editForum']); $validationResult = $this->forumValidator->validateEditObject($forumUid, $forum); if (!$this->checkActionAllowance($forum['parent'] == 0 ? 'category' : 'forum', $forumUid == -1 ? 'create' : 'edit')) { return $this->displayNoAccessError(); } if ($validationResult['error']) { return array('success' => FALSE, 'errors' => $validationResult['errors'], 'overrideValues' => $forum); } $saveArray = array('tstamp' => $GLOBALS['EXEC_TIME'], 'forum_name' => $forum['name'], 'forum_desc' => $forum['description'], 'parentID' => $forum['parent'], 'hidden' => $forum['hidden'] ? 1 : 0); if ($forumUid == -1) { $saveArray['pid'] = $this->p->getStoragePID(); $saveArray['crdate'] = $GLOBALS['EXEC_TIME']; $saveArray['sorting'] = $this->getSortingForNewForum($forum['parent']); $this->databaseHandle->exec_INSERTquery('tx_mmforum_forums', $saveArray); } else { $this->databaseHandle->exec_UPDATEquery('tx_mmforum_forums', 'uid=' . intval($forumUid), $saveArray); } return array('success' => TRUE); }
/** * Create new category MM records * * @param array $oldNewCategoryUidMapping * @return void */ protected function migrateCategoryMmRecords(array $oldNewCategoryUidMapping) { $newMmCount = 0; $oldMmRecords = $this->databaseConnection->exec_SELECTgetRows('uid_local, uid_foreign, sorting', 'tx_sfeventmgt_event_category_mm', ''); foreach ($oldMmRecords as $oldMmRecord) { $oldCategoryUid = $oldMmRecord['uid_foreign']; if (!empty($oldNewCategoryUidMapping[$oldCategoryUid])) { $newMmRecord = ['uid_local' => $oldNewCategoryUidMapping[$oldCategoryUid], 'uid_foreign' => $oldMmRecord['uid_local'], 'tablenames' => $oldMmRecord['tablenames'] ?: 'tx_sfeventmgt_domain_model_event', 'sorting_foreign' => $oldMmRecord['sorting'], 'fieldname' => 'category']; // check if relation already exists $foundRelations = $this->databaseConnection->exec_SELECTcountRows('uid_local', 'sys_category_record_mm', 'uid_local=' . $newMmRecord['uid_local'] . ' AND uid_foreign=' . $newMmRecord['uid_foreign'] . ' AND tablenames="' . $newMmRecord['tablenames'] . '"' . ' AND fieldname="' . $newMmRecord['fieldname'] . '"'); if ($foundRelations === 0) { $this->databaseConnection->exec_INSERTquery('sys_category_record_mm', $newMmRecord); if ($this->databaseConnection->sql_affected_rows()) { $newMmCount++; } } } } $message = 'Created ' . $newMmCount . ' new MM relations'; $status = FlashMessage::INFO; $title = ''; $this->messageArray[] = [$status, $title, $message]; }
/** * * Displays a form for editing syntaxhighlghtinh parser options that are * to be used in the forum. * * @return string The HTML user interface * */ function SyntaxHL() { global $LANG; /** @var $LANG \TYPO3\CMS\Lang\LanguageService */ $content = ''; $mmforum = GeneralUtility::_GP('mmforum'); // Process submitted data if (isset($mmforum['delete'])) { $key = key($mmforum['delete']); $this->databaseHandle->exec_UPDATEquery('tx_mmforum_syntaxhl', 'uid=' . $key, array('deleted' => 1)); } if (isset($mmforum['hide'])) { $key = key($mmforum['hide']); $this->databaseHandle->exec_UPDATEquery('tx_mmforum_syntaxhl', 'uid=' . $key, array('hidden' => 1)); } if (isset($mmforum['unhide'])) { $key = key($mmforum['unhide']); $this->databaseHandle->exec_UPDATEquery('tx_mmforum_syntaxhl', 'uid=' . $key, array('hidden' => 0)); } if (isset($mmforum['save'])) { $key = key($mmforum['save']); if ($key == 0) { $insertArr = array('crdate' => $GLOBALS['EXEC_TIME'], 'tstamp' => $GLOBALS['EXEC_TIME'], 'lang_title' => $mmforum['new']['lang_title'], 'lang_pattern' => $mmforum['new']['lang_pattern'], 'lang_code' => $mmforum['new']['lang_code'], 'fe_inserticon' => $mmforum['new']['fe_inserticon']); $this->databaseHandle->exec_INSERTquery('tx_mmforum_syntaxhl', $insertArr); } else { $UpdateArr = array('lang_title' => $mmforum['lang_title'][$key], 'lang_pattern' => $mmforum['lang_pattern'][$key], 'lang_code' => $mmforum['lang_code'][$key], 'fe_inserticon' => $mmforum['fe_inserticon'][$key]); $this->databaseHandle->exec_UPDATEquery('tx_mmforum_syntaxhl', 'uid=' . $key, $UpdateArr); } } // Display syntaxhl editing form $path = ExtensionManagementUtility::extPath('mm_forum') . '/res/img/default/editor_icons/'; $files = GeneralUtility::getFilesInDir($path, 'gif'); $firstFile = ''; $surlOptions = ''; if (count($files) > 0) { foreach ($files as $k => $f) { if ($firstFile == '') { $firstFile = $f; } $surlOptions .= '<option value="' . $f . '"' . ($mmforum['new']['fe_inserticon'] == $f ? 'selected="selected"' : '') . '>' . $f . '</option>'; } } $i = 0; if (!isset($mmforum['new']['fe_inserticon'])) { $mmforum['new']['fe_inserticon'] = $firstFile; } /*$content .= '<table cellpadding="2" cellspacing="0" class="mm_forum-list" width="100%">'; $content .= '<tr> <td class="mm_forum-listrow_header"> </td> <td class="mm_forum-listrow_header">'.$LANG->getLL('tools.fe_inserticon').'</td> <td class="mm_forum-listrow_header"> </td> <td class="mm_forum-listrow_header">'.$LANG->getLL('tools.lang_title').'</td> <td class="mm_forum-listrow_header">'.$LANG->getLL('tools.lang_pattern').'</td> <td class="mm_forum-listrow_header">'.$LANG->getLL('tools.lang_code').'</td> <td class="mm_forum-listrow_header"> </td></tr>';*/ $content .= '<table cellpadding="2" cellspacing="0" width="100%" class="mm_forum-list">'; $content .= '<tr> <td class="mm_forum-listrow_header" colspan="7"><img src="img/tools-syntax.png" style="vertical-align:middle; margin-right:8px;"> ' . $LANG->getLL('tools.syntaxhighlighter') . '</td> </tr>'; $content .= '<tr> <td class="mm_forum-listrow_label"> </td> <td class="mm_forum-listrow_label">' . $LANG->getLL('tools.fe_inserticon') . '</td> <td class="mm_forum-listrow_label"> </td> <td class="mm_forum-listrow_label">' . $LANG->getLL('tools.lang_title') . '</td> <td class="mm_forum-listrow_label">' . $LANG->getLL('tools.lang_pattern') . '</td> <td class="mm_forum-listrow_label">' . $LANG->getLL('tools.lang_code') . '</td> <td class="mm_forum-listrow_label"> </td> </tr>'; $content .= '<tr> <td class="mm_forum-listrow"><b>[' . $LANG->getLL('tools.new') . ']</b></td> <td class="mm_forum-listrow"><img src="../res/img/default/editor_icons/' . htmlspecialchars($mmforum['new']['fe_inserticon']) . '" id="fe_inserticon_preview" /></td> <td class="mm_forum-listrow"><select name="mmforum[new][fe_inserticon]" onchange="document.getElementById(\'fe_inserticon_preview\').src=\'../res/img/default/editor_icons/\'+this[this.selectedIndex].value">' . $surlOptions . '</select></td> <td class="mm_forum-listrow"><input type="text" name="mmforum[new][lang_title]" value="' . htmlspecialchars($mmforum['new']['lang_title']) . '" /></td> <td class="mm_forum-listrow"><input type="text" name="mmforum[new][lang_pattern]" value="' . htmlspecialchars($mmforum['new']['lang_pattern']) . '" /></td> <td class="mm_forum-listrow"><select name="mmforum[new][lang_code]">' . $this->getFileOptionFields('../res/geshi/geshi/', 'php', '', FALSE) . '</select></td> <td align="right" class="mm_forum-listrow"><input type="image" src="img/save.png" name="mmforum[save][0]" /></td> </tr>'; $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_syntaxhl', 'deleted=0', '', 'uid asc'); while ($row = $this->databaseHandle->sql_fetch_assoc($res)) { $content .= !$row['hidden'] ? '<tr class="mm_forum-listrow">' : '<tr class="mm_forum-listrow" style="background-color: #f0f0f0;">'; $content .= ' <td> </td>'; $content .= ' <td><img src="../res/img/default/editor_icons/' . $row['fe_inserticon'] . '" /></td>'; $content .= ' <td><select name="mmforum[fe_inserticon][' . $row['uid'] . ']">' . $this->getFileOptionFields('../res/img/default/editor_icons/', '', $row['fe_inserticon'], TRUE) . '</select></td>'; $content .= ' <td><input type="text" name="mmforum[lang_title][' . $row['uid'] . ']" value="' . $row['lang_title'] . '" /></td>'; $content .= ' <td><input type="text" name="mmforum[lang_pattern][' . $row['uid'] . ']" value="' . $row['lang_pattern'] . '" /></td>'; $content .= ' <td><select name="mmforum[lang_code][' . $row['uid'] . ']">' . $this->getFileOptionFields('../res/geshi/geshi/', 'php', $row['lang_code'], FALSE) . '</select></td>'; $content .= ' <td align="right">'; $content .= ' <a href="index.php?mmforum[tools]=3&mmforum[delete][' . $row['uid'] . ']=1"><img src="img/edit-delete.png" /></a>'; $content .= $row['hidden'] ? '<a href="index.php?mmforum[tools]=3&mmforum[unhide][' . $row['uid'] . ']=1"><img src="img/edit-hide.png" /></a>' : '<a href="index.php?mmforum[tools]=3&mmforum[hide][' . $row['uid'] . ']=1"><img src="img/edit-hide.png" /></a>'; $content .= '<input style="border:0px;" type="image" src="img/save.png" name="mmforum[save][' . $row['uid'] . ']" />'; $content .= ' </td>'; $content .= '</tr>'; } $content .= '</table>'; return $content; }
/** * Creates a user session record and returns its values. * * @param array $tempuser User data array * * @return array The session data for the newly created session. * @todo Define visibility */ public function createUserSession($tempuser) { if ($this->writeDevLog) { GeneralUtility::devLog('Create session ses_id = ' . $this->id, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication'); } // Delete session entry first $this->db->exec_DELETEquery($this->session_table, 'ses_id = ' . $this->db->fullQuoteStr($this->id, $this->session_table) . ' AND ses_name = ' . $this->db->fullQuoteStr($this->name, $this->session_table)); // Re-create session entry $insertFields = $this->getNewSessionRecord($tempuser); $inserted = (bool) $this->db->exec_INSERTquery($this->session_table, $insertFields); if (!$inserted) { $message = 'Session data could not be written to DB. Error: ' . $this->db->sql_error(); GeneralUtility::sysLog($message, 'Core', GeneralUtility::SYSLOG_SEVERITY_WARNING); if ($this->writeDevLog) { GeneralUtility::devLog($message, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2); } } // Updating lastLogin_column carrying information about last login. if ($this->lastLogin_column && $inserted) { $this->db->exec_UPDATEquery($this->user_table, $this->userid_column . '=' . $this->db->fullQuoteStr($tempuser[$this->userid_column], $this->user_table), array($this->lastLogin_column => $GLOBALS['EXEC_TIME'])); } return $inserted ? $insertFields : array(); }
/** * Migrates a single field. * * @param string $table * @param array $row * @param string $fieldname * @param array $fieldConfiguration * @param string $customMessages * @return array A list of performed database queries * @throws \Exception */ protected function migrateField($table, $row, $fieldname, $fieldConfiguration, &$customMessages) { $titleTextContents = []; $alternativeTextContents = []; $captionContents = []; $linkContents = []; $fieldItems = GeneralUtility::trimExplode(',', $row[$fieldname], true); if (empty($fieldItems) || is_numeric($row[$fieldname])) { return []; } if (isset($fieldConfiguration['titleTexts'])) { $titleTextField = $fieldConfiguration['titleTexts']; $titleTextContents = explode(LF, $row[$titleTextField]); } if (isset($fieldConfiguration['alternativeTexts'])) { $alternativeTextField = $fieldConfiguration['alternativeTexts']; $alternativeTextContents = explode(LF, $row[$alternativeTextField]); } if (isset($fieldConfiguration['captions'])) { $captionField = $fieldConfiguration['captions']; $captionContents = explode(LF, $row[$captionField]); } if (isset($fieldConfiguration['links'])) { $linkField = $fieldConfiguration['links']; $linkContents = explode(LF, $row[$linkField]); } $fileadminDirectory = rtrim($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/') . '/'; $queries = []; $i = 0; if (!PATH_site) { throw new \Exception('PATH_site was undefined.'); } $storageUid = (int) $this->storage->getUid(); foreach ($fieldItems as $item) { $fileUid = null; $sourcePath = PATH_site . $fieldConfiguration['sourcePath'] . $item; $targetDirectory = PATH_site . $fileadminDirectory . $fieldConfiguration['targetPath']; $targetPath = $targetDirectory . basename($item); // maybe the file was already moved, so check if the original file still exists if (file_exists($sourcePath)) { if (!is_dir($targetDirectory)) { GeneralUtility::mkdir_deep($targetDirectory); } // see if the file already exists in the storage $fileSha1 = sha1_file($sourcePath); $existingFileRecord = $this->database->exec_SELECTgetSingleRow('uid', 'sys_file', 'sha1=' . $this->database->fullQuoteStr($fileSha1, 'sys_file') . ' AND storage=' . $storageUid); // the file exists, the file does not have to be moved again if (is_array($existingFileRecord)) { $fileUid = $existingFileRecord['uid']; } else { // just move the file (no duplicate) rename($sourcePath, $targetPath); } } if ($fileUid === null) { // get the File object if it hasn't been fetched before try { // if the source file does not exist, we should just continue, but leave a message in the docs; // ideally, the user would be informed after the update as well. /** @var File $file */ $file = $this->storage->getFile($fieldConfiguration['targetPath'] . $item); $fileUid = $file->getUid(); } catch (\InvalidArgumentException $e) { // no file found, no reference can be set $this->logger->notice('File ' . $fieldConfiguration['sourcePath'] . $item . ' does not exist. Reference was not migrated.', ['table' => $table, 'record' => $row, 'field' => $fieldname]); $format = 'File \'%s\' does not exist. Referencing field: %s.%d.%s. The reference was not migrated.'; $message = sprintf($format, $fieldConfiguration['sourcePath'] . $item, $table, $row['uid'], $fieldname); $customMessages .= PHP_EOL . $message; continue; } } if ($fileUid > 0) { $fields = ['fieldname' => $fieldname, 'table_local' => 'sys_file', 'pid' => $table === 'pages' ? $row['uid'] : $row['pid'], 'uid_foreign' => $row['uid'], 'uid_local' => $fileUid, 'tablenames' => $table, 'crdate' => time(), 'tstamp' => time(), 'sorting' => $i + 256, 'sorting_foreign' => $i]; if (isset($titleTextField)) { $fields['title'] = trim($titleTextContents[$i]); } if (isset($alternativeTextField)) { $fields['alternative'] = trim($alternativeTextContents[$i]); } if (isset($captionField)) { $fields['description'] = trim($captionContents[$i]); } if (isset($linkField)) { $fields['link'] = trim($linkContents[$i]); } $this->database->exec_INSERTquery('sys_file_reference', $fields); $queries[] = str_replace(LF, ' ', $this->database->debug_lastBuiltQuery); ++$i; } } // Update referencing table's original field to now contain the count of references, // but only if all new references could be set if ($i === count($fieldItems)) { $this->database->exec_UPDATEquery($table, 'uid=' . $row['uid'], [$fieldname => $i]); $queries[] = str_replace(LF, ' ', $this->database->debug_lastBuiltQuery); } else { $this->recordOffset[$table]++; } return $queries; }
/** * Insert new record * * @return int uid of inserted record */ protected function insert() { $this->databaseConnection->exec_INSERTquery($this->getTable(), $this->getProperties()); return $this->databaseConnection->sql_insert_id(); }
/** * Setting sys_history record, based on content previously set in $this->historyRecords[$table . ':' . $id] (by compareFieldArrayWithCurrentAndUnset()) * * @param string $table Table name * @param int $id Record ID * @param int $logId Log entry ID, important for linking between log and history views * @return void */ public function setHistory($table, $id, $logId) { if (isset($this->historyRecords[$table . ':' . $id]) && (int) $logId > 0) { $fields_values = array(); $fields_values['history_data'] = serialize($this->historyRecords[$table . ':' . $id]); $fields_values['fieldlist'] = implode(',', array_keys($this->historyRecords[$table . ':' . $id]['newRecord'])); $fields_values['tstamp'] = $GLOBALS['EXEC_TIME']; $fields_values['tablename'] = $table; $fields_values['recuid'] = $id; $fields_values['sys_log_uid'] = $logId; $this->databaseConnection->exec_INSERTquery('sys_history', $fields_values); } }