/** * @see parent::delete() */ function delete() { // Suppression du fichier correspondant if ($this->file_id) { $this->loadFile(); if ($this->_ref_file->file_id) { $this->_ref_file->delete(); } } //suppression de la doc return parent::delete(); }
/** * Deletes unnecessary files, which don't relate to version or object. * * @param int $portion Count of files which we want to delete. Default value is 10. * @return string */ public static function deleteUnnecessaryFiles($portion = 10) { $query = new Query(FileTable::getEntity()); $query->addSelect('ID')->addFilter('=EXTERNAL_ID', 'unnecessary')->addFilter('=MODULE_ID', Driver::INTERNAL_MODULE_ID)->setLimit($portion); $workLoad = false; $dbResult = $query->exec(); while ($row = $dbResult->fetch()) { $workLoad = true; \CFile::delete($row['ID']); } if (!$workLoad) { return ''; } return static::className() . '::deleteUnnecessaryFiles();'; }
public function delete() { $result = false; if ($this->_perms->checkModuleItem($this->_tbl_module, 'delete', $this->{$this->_tbl_key})) { $q = $this->_getQuery(); $q->addTable('tasks'); $q->addQuery('task_id'); $q->addWhere('task_project = ' . (int) $this->project_id); $tasks_to_delete = $q->loadColumn(); $q->clear(); $task = new CTask(); $task->overrideDatabase($this->_query); foreach ($tasks_to_delete as $task_id) { $task->task_id = $task_id; $task->delete(); } $q->clear(); $q->addTable('files'); $q->addQuery('file_id'); $q->addWhere('file_project = ' . (int) $this->project_id); $files_to_delete = $q->loadColumn(); $q->clear(); $file = new CFile(); $file->overrideDatabase($this->_query); foreach ($files_to_delete as $file_id) { $file->file_id = $file_id; $file->delete(); } $q->clear(); $q->addTable('events'); $q->addQuery('event_id'); $q->addWhere('event_project = ' . (int) $this->project_id); $events_to_delete = $q->loadColumn(); $q->clear(); $event = new CEvent(); $event->overrideDatabase($this->_query); foreach ($events_to_delete as $event_id) { $event->event_id = $event_id; $event->delete(); } $q->clear(); // remove the project-contacts and project-departments map $q->setDelete('project_contacts'); $q->addWhere('project_id =' . (int) $this->project_id); $q->exec(); $q->clear(); $q->setDelete('project_departments'); $q->addWhere('project_id =' . (int) $this->project_id); $q->exec(); $q->clear(); $q->setDelete('tasks'); $q->addWhere('task_represents_project =' . (int) $this->project_id); $q->clear(); if ($msg = parent::delete()) { return $msg; } return true; } return $result; }
public function delete(CAppUI $AppUI = null) { global $AppUI; $perms = $AppUI->acl(); $result = false; $this->_error = array(); /* * TODO: This should probably use the canDelete method from above too to * not only check permissions but to check dependencies... luckily the * previous version didn't check it either, so we're no worse off. */ if ($perms->checkModuleItem('projects', 'delete', $this->project_id)) { $q = $this->_query; $q->addTable('tasks'); $q->addQuery('task_id'); $q->addWhere('task_project = ' . (int) $this->project_id); $tasks_to_delete = $q->loadColumn(); $q->clear(); foreach ($tasks_to_delete as $task_id) { $q->setDelete('user_tasks'); $q->addWhere('task_id =' . $task_id); $q->exec(); $q->clear(); $q->setDelete('task_dependencies'); $q->addWhere('dependencies_req_task_id =' . (int) $task_id); $q->exec(); $q->clear(); } $q->setDelete('tasks'); $q->addWhere('task_project =' . (int) $this->project_id); $q->exec(); $q->clear(); $q->addTable('files'); $q->addQuery('file_id'); $q->addWhere('file_project = ' . (int) $this->project_id); $files_to_delete = $q->loadColumn(); $q->clear(); foreach ($files_to_delete as $file_id) { $file = new CFile(); $file->load($file_id); $file->delete($AppUI); } $q->setDelete('events'); $q->addWhere('event_project =' . (int) $this->project_id); $q->exec(); $q->clear(); // remove the project-contacts and project-departments map $q->setDelete('project_contacts'); $q->addWhere('project_id =' . (int) $this->project_id); $q->exec(); $q->clear(); $q->setDelete('project_departments'); $q->addWhere('project_id =' . (int) $this->project_id); $q->exec(); $q->clear(); $q->setDelete('tasks'); $q->addWhere('task_represents_project =' . (int) $this->project_id); $q->clear(); if ($msg = parent::delete()) { return $msg; } return true; } return $result; }
protected function processActionCommit() { $this->checkRequiredPostParams(array('editSessionId')); if ($this->errorCollection->hasErrors()) { $this->sendJsonErrorResponse(); } $this->checkUpdatePermissions(); $currentSession = $this->getEditSessionByCurrentUser((int) $this->request->getPost('editSessionId')); if (!$currentSession) { $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_FIND_EDIT_SESSION'), self::ERROR_COULD_NOT_FIND_EDIT_SESSION))); $this->sendJsonErrorResponse(); } $tmpFile = \CTempFile::getFileName(uniqid('_wd')); checkDirPath($tmpFile); $fileData = new FileData(); $fileData->setId($currentSession->getServiceFileId()); $fileData->setSrc($tmpFile); $newNameFileAfterConvert = null; if ($this->documentHandler->isNeedConvertExtension($this->file->getExtension())) { $newNameFileAfterConvert = getFileNameWithoutExtension($this->file->getName()) . '.' . $this->documentHandler->getConvertExtension($this->file->getExtension()); $fileData->setMimeType(TypeFile::getMimeTypeByFilename($newNameFileAfterConvert)); } else { $fileData->setMimeType(TypeFile::getMimeTypeByFilename($this->file->getName())); } $fileData = $this->documentHandler->downloadFile($fileData); if (!$fileData) { if ($this->documentHandler->isRequiredAuthorization()) { $this->sendNeedAuth(); } $this->errorCollection->add($this->documentHandler->getErrors()); $this->sendJsonErrorResponse(); } $this->deleteEditSession($currentSession); $oldName = $this->file->getName(); //rename in cloud service $renameInCloud = $fileData->getName() && $fileData->getName() != $this->file->getName(); if ($newNameFileAfterConvert || $renameInCloud) { if ($newNameFileAfterConvert && $renameInCloud) { $newNameFileAfterConvert = getFileNameWithoutExtension($fileData->getName()) . '.' . getFileExtension($newNameFileAfterConvert); } $this->file->rename($newNameFileAfterConvert); } $fileArray = \CFile::makeFileArray($tmpFile); $fileArray['name'] = $this->file->getName(); $fileArray['type'] = $fileData->getMimeType(); $fileArray['MODULE_ID'] = Driver::INTERNAL_MODULE_ID; /** @noinspection PhpDynamicAsStaticMethodCallInspection */ $fileId = \CFile::saveFile($fileArray, Driver::INTERNAL_MODULE_ID); if (!$fileId) { \CFile::delete($fileId); $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_SAVE_FILE'), self::ERROR_COULD_NOT_SAVE_FILE))); $this->sendJsonErrorResponse(); } $versionModel = $this->file->addVersion(array('ID' => $fileId, 'FILE_SIZE' => $fileArray['size']), $this->getUser()->getId(), true); if (!$versionModel) { \CFile::delete($fileId); $this->errorCollection->add(array(new Error(Loc::getMessage('DISK_DOC_CONTROLLER_ERROR_COULD_NOT_ADD_VERSION'), self::ERROR_COULD_NOT_ADD_VERSION))); $this->errorCollection->add($this->file->getErrors()); $this->sendJsonErrorResponse(); } if ($this->isLastEditSessionForFile()) { $this->deleteFile($currentSession, $fileData); } $this->sendJsonSuccessResponse(array('objectId' => $this->file->getId(), 'newName' => $this->file->getName(), 'oldName' => $oldName)); }
/** * @ignore */ public static function maybeUpdateThirdParty() { if (!self::isInCliMode()) { // This method can be run in CLI mode only. assert('false', vs(isset($this), get_defined_vars())); return false; } $updates = CConfiguration::option("updates"); $updatesAreEnabled = $updates["enable"]; if ($updatesAreEnabled) { $minTimeBetweenDoUpdatesDays = $updates["minTimeBetweenDoUpdatesDays"]; $components = $updates["components"]; assert('is_int($minTimeBetweenDoUpdatesDays)', vs(isset($this), get_defined_vars())); // Logging. $logging = $updates["logging"]; $loggingIsEnabled = $logging["enable"]; $logFp = $logging["logFilePath"]; if ($loggingIsEnabled) { assert('!CString::isEmpty($logFp)', vs(isset($this), get_defined_vars())); $logFp = CFilePath::frameworkPath($logFp); CShell::setLogging($logFp); } // Mailing. $mailing = $updates["mailing"]; $mailingIsEnabled = $mailing["enable"]; if ($mailingIsEnabled) { $adminMail = CConfiguration::option("admin.mail"); $to = $adminMail["to"]; $from = $adminMail["from"]; $transport = $adminMail["transport"]; assert('!CString::isEmpty($to) && !CString::isEmpty($from) && !CString::isEmpty($transport)', vs(isset($this), get_defined_vars())); $mail; if (CString::equalsCi($transport, "smtp")) { $smtpOutgoingServer = $adminMail["smtpOutgoingServer"]; $smtpUsername = $adminMail["smtpUsername"]; $smtpPassword = $adminMail["smtpPassword"]; assert('!CString::isEmpty($smtpOutgoingServer) && !CString::isEmpty($smtpUsername) && ' . '!CString::isEmpty($smtpPassword)', vs(isset($this), get_defined_vars())); $mail = CMail::makeSmtp($smtpOutgoingServer, $smtpUsername, $smtpPassword, $from, $to); } else { if (CString::equalsCi($transport, "system")) { $mail = CMail::makeSystem($from, $to); } else { assert('false', vs(isset($this), get_defined_vars())); } } CShell::setMailing($mail); } $thirdPartyDp = $GLOBALS["PHRED_PATH_TO_THIRD_PARTY"]; $lastUpdateTimeFp = CFilePath::add($thirdPartyDp, self::$ms_thirdPartyLastUpdateTimeFn); // Read the file containing the Unix seconds of the last update time stamp (if exists) and compare that // time with the current time. $numDaysSinceLastUpdate; if (CFile::exists($lastUpdateTimeFp)) { $lastUpdateTime = new CTime(CString::toInt(CFile::read($lastUpdateTimeFp))); $currTime = CTime::now(); if ($lastUpdateTime->isBefore($currTime)) { $numDaysSinceLastUpdate = $currTime->diffInDays($lastUpdateTime); if ($numDaysSinceLastUpdate < $minTimeBetweenDoUpdatesDays) { // It is too early for updates yet. return false; } } else { assert('false', vs(isset($this), get_defined_vars())); } } $date = CShell::currentDate(); CShell::say("Started on {$date}."); if (isset($numDaysSinceLastUpdate)) { CShell::say("It has been {$numDaysSinceLastUpdate} day(s) since last successful update."); } $concurrLockFp = CFilePath::add($thirdPartyDp, self::$ms_thirdPartyConcurrLockFn); // Try locking the operation. if (!self::setLock($concurrLockFp, false)) { assert('false', vs(isset($this), get_defined_vars())); CShell::onError(false, "Could not obtain a lock on the operation."); CShell::writeToLog("\n"); return false; } $phpConfigNeedsReload = false; $totalNumComponents = CMap::length($components); $numComponentsUpdated = 0; // The Browser Capabilities Project (BrowsCap). if (CMap::hasKey($components, "browsCap")) { $browsCap = $components["browsCap"]; $skip = $browsCap["skip"]; if (!$skip) { CShell::say("Updating the Browser Capabilities Project (BrowsCap) ..."); $lookupFileUrl = $browsCap["lookupFileUrl"]; assert('!CString::isEmpty($lookupFileUrl)', vs(isset($this), get_defined_vars())); // Component-related constants. static $s_configOptName = "browscap"; static $s_lookupFileDownloadTimeoutSeconds = 120; if (self::hasConfigOption($s_configOptName)) { $browsCapLookupFp = CString::trim(self::configOption($s_configOptName)); if (!CString::isEmpty($browsCapLookupFp)) { $browsCapDp = CFilePath::directory($browsCapLookupFp); CShell::say("Downloading a BrowsCap lookup file from '{$lookupFileUrl}' ..."); $temporaryFp = CFile::createTemporary($browsCapDp); $downloadRes = CInetRequest::downloadFile($lookupFileUrl, $temporaryFp, $s_lookupFileDownloadTimeoutSeconds); if ($downloadRes) { // After the file is downloaded into a temporary one, move it to the destination, // safely replacing the existing file, if any. CFile::move($temporaryFp, $browsCapLookupFp); $numComponentsUpdated++; $phpConfigNeedsReload = true; $downloadedFileSizeKB = CUUnit::convertStoragef((double) CFile::size($browsCapLookupFp), CUUnit::BYTE, CUUnit::KILOBYTE); $downloadedFileSizeKB = CMathf::round($downloadedFileSizeKB, 2); CShell::say("Done. The downloaded file is {$downloadedFileSizeKB} KB in size."); } else { CShell::onError(false, "Could not download a BrowsCap lookup file from '{$lookupFileUrl}'."); } // Just in case, check for any temporary files that could have been left by any previous // operations in the directory. $leftoverFiles = CFile::findFiles(CFilePath::add($browsCapDp, CFile::DEFAULT_TEMPORARY_FILE_PREFIX . "*")); if (!CArray::isEmpty($leftoverFiles)) { // Cleanup the directory from the temporary files. $len = CArray::length($leftoverFiles); for ($i = 0; $i < $len; $i++) { CFile::delete($leftoverFiles[$i]); } } } else { CShell::onError(false, "Could not read the value of '{$s_configOptName}' option " . "in the PHP CLI configuration file."); } } else { CShell::onError(false, "Could not find '{$s_configOptName}' option in the PHP CLI configuration file."); } } else { CShell::say("Skipping the Browser Capabilities Project (BrowsCap)."); } } // All the components have been processed. Unlock the operation. self::unsetLock($concurrLockFp); $date = CShell::currentDate(); if ($numComponentsUpdated != 0) { // One or more third-party components have been updated. Put a time stamp on the directory where the // components are located. CFile::write($lastUpdateTimeFp, CString::fromInt(CTime::currentUTime())); if ($numComponentsUpdated == $totalNumComponents) { CShell::speak("Success. All {$totalNumComponents} third-party component(s)"); } else { CShell::speak("Partial success. {$numComponentsUpdated} out of {$totalNumComponents} third-party component(s)"); } CShell::say("have been updated. Completed on {$date}."); } else { CShell::say("No third-party components have been updated. Completed on {$date}."); } return $phpConfigNeedsReload; } else { return false; } }
protected function hook_postDelete() { $q = $this->_getQuery(); $q->addTable('tasks'); $q->addQuery('task_id'); $q->addWhere('task_project = ' . $this->_old_key); $tasks_to_delete = $q->loadColumn(); $q->clear(); $task = new w2p_Actions_BulkTasks(); $task->overrideDatabase($this->_query); foreach ($tasks_to_delete as $task_id) { $task->task_id = $task_id; $task->delete(); } $q->clear(); $q->addTable('files'); $q->addQuery('file_id'); $q->addWhere('file_project = ' . $this->_old_key); $files_to_delete = $q->loadColumn(); $q->clear(); $file = new CFile(); $file->overrideDatabase($this->_query); foreach ($files_to_delete as $file_id) { $file->file_id = $file_id; $file->delete(); } $q->clear(); $q->addTable('events'); $q->addQuery('event_id'); $q->addWhere('event_project = ' . $this->_old_key); $events_to_delete = $q->loadColumn(); $q->clear(); $event = new CEvent(); $event->overrideDatabase($this->_query); foreach ($events_to_delete as $event_id) { $event->event_id = $event_id; $event->delete(); } $q->clear(); // remove the project-contacts and project-departments map $q->setDelete('project_contacts'); $q->addWhere('project_id =' . $this->_old_key); $q->exec(); $q->clear(); $q->setDelete('project_departments'); $q->addWhere('project_id =' . $this->_old_key); $q->exec(); $q->clear(); $q->setDelete('tasks'); $q->addWhere('task_represents_project =' . $this->_old_key); parent::hook_preDelete(); }
public static function delete($primary) { // get old data $oldData = static::getByPrimary($primary)->fetch(); // remove row $result = parent::delete($primary); // remove files $entityName = static::getEntity()->getName(); $hlblock = HighloadBlockTable::getList(array('select' => array('ID'), 'filter' => array('=NAME' => $entityName)))->fetch(); // add other fields $fields = $GLOBALS['USER_FIELD_MANAGER']->getUserFields('HLBLOCK_' . $hlblock['ID']); foreach ($oldData as $k => $v) { $arUserField = $fields[$k]; if ($arUserField["USER_TYPE"]["BASE_TYPE"] == "file") { if (is_array($oldData[$k])) { foreach ($oldData[$k] as $value) { \CFile::delete($value); } } else { \CFile::delete($oldData[$k]); } } } return $result; }
protected function finalize() { if ($this->m_done) { return; } if (is_resource($this->m_curl)) { curl_close($this->m_curl); } if (isset($this->m_downloadFile)) { $this->m_downloadFile->done(); } if (isset($this->m_uploadFile)) { $this->m_uploadFile->done(); } if (isset($this->m_fileUploadTempFp) && CFile::exists($this->m_fileUploadTempFp)) { CFile::delete($this->m_fileUploadTempFp); } $this->m_done = true; }
/** * Изменение документа * * @param integer $id ID документа * @param array $data Данные документа */ function updateDocument($id, $data) { global $DB; if (!$data['letters_doc_frm_user_3_db_id'] || $data['letters_doc_frm_user_3_db_id'] == 'null') { $data['letters_doc_frm_user_3_db_id'] = null; $data['letters_doc_frm_user3_status_data'] = null; $data['letters_doc_frm_user3_status_date_data'] = null; } if (!$data['letters_doc_frm_user3_status_date_data']) { $data['letters_doc_frm_user3_status_date_data'] = null; } if (!$data['letters_doc_frm_user2_status_date_data']) { $data['letters_doc_frm_user2_status_date_data'] = null; } if (!$data['letters_doc_frm_user1_status_date_data']) { $data['letters_doc_frm_user1_status_date_data'] = null; } if (!$data['letters_doc_frm_user3_status_data']) { $data['letters_doc_frm_user3_status_data'] = null; } if (!$data['letters_doc_frm_user2_status_data']) { $data['letters_doc_frm_user2_status_data'] = null; } if (!$data['letters_doc_frm_user1_status_data']) { $data['letters_doc_frm_user1_status_data'] = null; } if (!$data['letters_doc_frm_parent_db_id'] || $data['letters_doc_frm_parent_db_id'] == 'null') { $data['letters_doc_frm_parent_db_id'] = null; } if (!$data['letters_doc_frm_group'] || $data['letters_doc_frm_group'] == 'null') { $data['letters_doc_frm_group'] = null; } if (!$data['letters_doc_frm_group_db_id'] || $data['letters_doc_frm_group_db_id'] == 'null') { $data['letters_doc_frm_group_db_id'] = null; } if (!$data['letters_doc_frm_group_db_id'] && !empty($data['letters_doc_frm_group'])) { $data['letters_doc_frm_group_db_id'] = letters::checkCreateGroup($data['letters_doc_frm_group']); } if ($data['letters_doc_frm_user_1_section'] == '1') { $data['letters_doc_frm_user_1_section'] = true; } else { $data['letters_doc_frm_user_1_section'] = false; } if ($data['letters_doc_frm_user_2_section'] == '1') { $data['letters_doc_frm_user_2_section'] = true; } else { $data['letters_doc_frm_user_2_section'] = false; } if ($data['letters_doc_frm_user_3_section'] == '1') { $data['letters_doc_frm_user_3_section'] = true; } else { $data['letters_doc_frm_user_3_section'] = false; } if ($data['letters_doc_frm_withoutourdoc'] == '1') { $data['letters_doc_frm_withoutourdoc'] = true; } else { $data['letters_doc_frm_withoutourdoc'] = false; } $doc = self::getDocument($id); $doc_data['title'] = $data['letters_doc_frm_title']; $doc_data['user_1'] = $data['letters_doc_frm_user_1_db_id']; $doc_data['user_2'] = $data['letters_doc_frm_user_2_db_id']; $doc_data['user_3'] = $data['letters_doc_frm_user_3_db_id']; $doc_data['group_id'] = $data['letters_doc_frm_group_db_id']; $doc_data['parent'] = $data['letters_doc_frm_parent_db_id']; $doc_data['user_status_1'] = $data['letters_doc_frm_user1_status_data']; $doc_data['user_status_2'] = $data['letters_doc_frm_user2_status_data']; $doc_data['user_status_3'] = $data['letters_doc_frm_user3_status_data']; $doc_data['user_status_date_1'] = $data['letters_doc_frm_user1_status_date_data']; $doc_data['user_status_date_2'] = $data['letters_doc_frm_user2_status_date_data']; $doc_data['user_status_date_3'] = $data['letters_doc_frm_user3_status_date_data']; $doc_data['is_user_1_company'] = $data['letters_doc_frm_user_1_section'] ? 't' : 'f'; $doc_data['is_user_2_company'] = $data['letters_doc_frm_user_2_section'] ? 't' : 'f'; $doc_data['is_user_3_company'] = $data['letters_doc_frm_user_3_section'] ? 't' : 'f'; $doc_data['withoutourdoc'] = $data['withoutourdoc'] ? 't' : 'f'; if (isset($data['letters_doc_frm_comment']) && $data['letters_doc_frm_comment']) { $doc_data['comment'] = $data['letters_doc_frm_comment']; } else { $data['letters_doc_frm_comment'] = $doc['comment']; } if ($doc_data['user_status_1'] != $doc['user_status_1'] || $doc_data['user_status_2'] != $doc['user_status_2'] || $doc_data['user_status_3'] != $doc['user_status_3']) { letters::updateDateStatusChange($id); } letters::saveHistory($id, $doc_data); $sql = "UPDATE letters SET\n date_add = " . ($data['letters_doc_frm_dateadd_eng_format'] ? "'{$data['letters_doc_frm_dateadd_eng_format']}'" : "NOW()") . ",\n title = ?,\n user_1 = ?,\n user_2 = ?,\n user_3 = ?,\n group_id = ?,\n parent = ?,\n user_status_1 = ?, \n user_status_2 = ?, \n user_status_3 = ?, \n user_status_date_1 = ?, \n user_status_date_2 = ?, \n user_status_date_3 = ?,\n is_user_1_company = ?, \n is_user_2_company = ?, \n is_user_3_company = ?, \n withoutourdoc = ?,\n comment = ?\n WHERE id = ?i;"; $DB->query($sql, $data['letters_doc_frm_title'], $data['letters_doc_frm_user_1_db_id'], $data['letters_doc_frm_user_2_db_id'], $data['letters_doc_frm_user_3_db_id'], $data['letters_doc_frm_group_db_id'], $data['letters_doc_frm_parent_db_id'], $data['letters_doc_frm_user1_status_data'], $data['letters_doc_frm_user2_status_data'], $data['letters_doc_frm_user3_status_data'], $data['letters_doc_frm_user1_status_date_data'], $data['letters_doc_frm_user2_status_date_data'], $data['letters_doc_frm_user3_status_date_data'], $data['letters_doc_frm_user_1_section'], $data['letters_doc_frm_user_2_section'], $data['letters_doc_frm_user_3_section'], $data['letters_doc_frm_withoutourdoc'], $data['letters_doc_frm_comment'], $id); $sql = "UPDATE letters SET is_out=false WHERE (user_status_1 IS DISTINCT FROM 1 AND user_status_2 IS DISTINCT FROM 1 AND user_status_3 IS DISTINCT FROM 1) AND id=?i"; $DB->query($sql, $id); require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/attachedfiles.php"; require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/CFile.php"; $attachedfiles = new attachedfiles($data['attachedfiles_session']); $attachedfiles_files = $attachedfiles->getFiles(); if ($attachedfiles_files) { foreach ($attachedfiles_files as $attachedfiles_file) { $cFile = new CFile(); $cFile->table = 'file'; $cFile->GetInfoById($attachedfiles_file['id']); if ($cFile->id != $doc['file_id']) { $ext = $cFile->getext(); $tmp_dir = "letters/"; $tmp_name = $cFile->secure_tmpname($tmp_dir, '.' . $ext); $tmp_name = substr_replace($tmp_name, "", 0, strlen($tmp_dir)); $cFile->_remoteCopy($tmp_dir . $tmp_name, true); $sql = "UPDATE letters SET file_id = ?i WHERE id = ?i"; $DB->query($sql, $cFile->id, intval($id)); $cFile->delete($doc['file_id']); } } } $attachedfiles->clear(); return $id; }
/** * @deprecated В настоящий момент не используется на сайте * * При создании и изменении текста поста в сообществе проверяет, на все ли загруженые при наборе текста в визивиге * изображения есть ссылки в тексте комментария, если не на все, удаляет лишние. * При создании комментария обновляет cid (ID Сообщения сообщества) записи в commune_attaches * @param int $messageId - номер записи в commune_messages * @param string $text - текст комментария * @param bool $edit - true когда редактируется * */ function checkWysiwygInlineImages($messageId, $text, $edit = false) { session_start(); $filesIds = $_SESSION['wysiwyg_inline_files']; //получить id вставленных при наборе текста файлов global $DB; //получаем все теги img из соообщения if ($text == '') { return; } $text = str_replace("<cut>", "", $text); // Не любит cut сволочь $dom = new DOMDocument(); $dom->validateOnParse = false; libxml_use_internal_errors(true); $dom->loadHTML($text); libxml_use_internal_errors(false); $images = $dom->getElementsByTagName('img'); $w_files = array(); //файлы, ссылки на которые есть в wisywyg for ($i = 0; $i < $images->length; $i++) { $filePath = $images->item($i)->getAttribute('src'); $filePath = str_replace(WDCPREFIX . "/", "", $filePath); $file = new CFile($filePath, "file_commune"); if ($file->id) { $w_files[$file->id] = $file->id; } } if ($cid) { //если комментарий редактируется, добавим к идентификаторам вновь вставленных в визивиг файлов идентификаторв ранее вставленных $rows = $DB->rows("SELECT fid FROM commune_attach\n \t \t\t\tWHERE cid = {$cid} AND inline = TRUE"); foreach ($rows as $row) { $filesIds[$row['fid']] = $row['fid']; } } //удалить из $filesIds те, ссылок на которые нет в тексте визивига foreach ($filesIds as $id) { if (!$w_files[$id]) { $cfile = new CFile($id, "file_commune"); if ($cfile->id) { $cfile->delete($id); } unset($filesIds[$id]); } } $ids = join(',', $filesIds); if (count($filesIds)) { $cmd = "UPDATE commune_attach \n\t \t SET cid = {$messageId},\n\t \t temp = FALSE\n\t WHERE fid IN ( {$ids} )"; $DB->query($cmd); } $_SESSION['wysiwyg_inline_files'] = array(); }
/** * При создании и изменении текста комментария проверяет, на все ли загруженые при наборе текста в визивиге * изображения есть ссылки в тексте комментария, если не на все, удаляет лишние. * При создании комментария обновляет cid (ID Сообщения сообщества) записи в commune_attaches * @param $messageId - номер записи в commune_messages * @param $text - текст комментария * @param $cid - идентификатор комментария в commune_messages * */ function checkWysiwygInlineImages($messageId, $text, $cid) { session_start(); $filesIds = $_SESSION['wysiwyg_inline_files']; //получить id вставленных при наборе текста файлов global $DB; $model = $this->model(); //если в таблице есть поля для хранения флага временного файла и флага файла в визивиге if ($model['attaches']['fields']['temp'] && $model['attaches']['fields']['inline']) { //получаем все теги img из соообщения $text = str_replace("<cut>", "", $text); // DOM не любит этот тег $dom = new DOMDocument(); $dom->validateOnParse = false; $dom->loadHTML($text); $images = $dom->getElementsByTagName('img'); $w_files = array(); //файлы, ссылки на которые есть в wisywyg for ($i = 0; $i < $images->length; $i++) { $filePath = $images->item($i)->getAttribute('src'); $filePath = str_replace(WDCPREFIX . "/", "", $filePath); $file = new CFile($filePath, $model['attaches']['file_table']); if ($file->id) { $w_files[$file->id] = $file->id; } } if ($cid) { //если комментарий редактируется, добавим к идентификаторам вновь вставленных в визивиг файлов идентификаторв ранее вставленных $cmd = "SELECT {$model['attaches']['fields']['file']} FROM {$model['attaches']['table']}\n \t \t\t\tWHERE {$model['attaches']['fields']['comment']} = {$cid} AND {$model['attaches']['fields']['inline']} = TRUE"; $rows = $DB->rows($cmd); foreach ($rows as $row) { $filesIds[$row[$model['attaches']['fields']['file']]] = $row[$model['attaches']['fields']['file']]; } } if (!$filesIds) { return; } //удалить из $filesIds те, ссылок на которые нет в тексте визивига foreach ($filesIds as $id) { if (!$w_files[$id]) { $cfile = new CFile($id, $model['attaches']['file_table']); if ($cfile->id) { $cfile->delete($id); } unset($filesIds[$id]); } } $ids = join(',', $filesIds); if (count($filesIds)) { $cmd = "UPDATE {$model['attaches']['table']} \n\t \t SET {$model['attaches']['fields']['comment']} = {$messageId},\n\t \t temp = FALSE\n\t WHERE {$model['attaches']['fields']['file']} IN ( {$ids} )"; $DB->query($cmd); } } $_SESSION['wysiwyg_inline_files'] = array(); }
function Delete($id) { global $DB; $id = IntVal($id); $res = $DB->query('SELECT FILE_ID FROM b_mail_msg_attachment WHERE MESSAGE_ID = ' . $id); while ($file = $res->fetch()) { if ($file['FILE_ID']) { CFile::delete($file['FILE_ID']); } } $strSql = "DELETE FROM b_mail_msg_attachment WHERE ID=" . $id; $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__); }
/** * Очищает текущую сессию от загруженных в нее файлов * * @global object $DB * @param string $resource Сессия загрзчика * @return boolean */ static function sclear($resource) { global $DB; $sql = "SELECT file_id FROM attachedfiles WHERE session = ? AND status IN (?l)"; $files = $DB->rows($sql, $resource, array(uploader::STATUS_CREATE, uploader::STATUS_REMOVE)); if ($files) { foreach ($files as $file) { $cFile = new CFile($file['file_id']); if ($cFile->id) { $cFile->delete($file['file_id']); } } } return $DB->query("DELETE FROM attachedfiles WHERE session = ?", $resource); }
/** * Deletes file and all connected data and entities (@see Sharing, @see Rights, etc). * @param int $deletedBy Id of user. * @return bool * @throws \Bitrix\Main\ArgumentNullException */ public function delete($deletedBy) { $this->errorCollection->clear(); $success = EditSessionTable::deleteByFilter(array('OBJECT_ID' => $this->id)); if (!$success) { return false; } $success = ExternalLinkTable::deleteByFilter(array('OBJECT_ID' => $this->id)); if (!$success) { return false; } foreach ($this->getSharingsAsReal() as $sharing) { $sharing->delete($deletedBy); } //with status unreplied, declined (not approved) $success = SharingTable::deleteByFilter(array('REAL_OBJECT_ID' => $this->id)); if (!$success) { return false; } foreach ($this->getAttachedObjects() as $attached) { $attached->delete(); } unset($attached); BizProcDocument::deleteWorkflowsFile($this->id); SimpleRightTable::deleteBatch(array('OBJECT_ID' => $this->id)); $success = RightTable::deleteByFilter(array('OBJECT_ID' => $this->id)); if (!$success) { return false; } $success = VersionTable::deleteByFilter(array('OBJECT_ID' => $this->id)); if (!$success) { return false; } DeletedLog::addFile($this, $deletedBy, $this->errorCollection); \CFile::delete($this->fileId); $deleteResult = FileTable::delete($this->id); if (!$deleteResult->isSuccess()) { return false; } Driver::getInstance()->getIndexManager()->dropIndex($this); if (!$this->isLink()) { //todo potential - very hard operation. foreach (File::getModelList(array('filter' => array('REAL_OBJECT_ID' => $this->id, '!=REAL_OBJECT_ID' => $this->id))) as $link) { $link->delete($deletedBy); } unset($link); } $event = new Event(Driver::INTERNAL_MODULE_ID, "onAfterDeleteFile", array($this->getId(), $deletedBy)); $event->send(); return true; }
protected function finalize() { if (is_resource($this->m_multiCurl)) { curl_multi_close($this->m_multiCurl); } if (isset($this->m_cookiesFp) && CFile::exists($this->m_cookiesFp)) { CFile::delete($this->m_cookiesFp); } $this->m_done = true; }
public static function OnBeforeUserTypeDelete($field) { global $APPLICATION, $USER_FIELD_MANAGER; if (preg_match('/^HLBLOCK_(\\d+)$/', $field['ENTITY_ID'], $matches)) { // get entity info $hlblock_id = $matches[1]; $hlblock = HighloadBlockTable::getById($hlblock_id)->fetch(); if (empty($hlblock)) { $APPLICATION->throwException(sprintf('Entity "HLBLOCK_%s" wasn\'t found.', $hlblock_id)); return false; } $fieldType = $USER_FIELD_MANAGER->getUserType($field["USER_TYPE_ID"]); if ($fieldType['BASE_TYPE'] == 'file') { // if it was file field, then delete all files $entity = static::compileEntity($hlblock); /** @var DataManager $dataClass */ $dataClass = $entity->getDataClass(); $rows = $dataClass::getList(array('select' => array($field['FIELD_NAME']))); while ($oldData = $rows->fetch()) { if (empty($oldData[$field['FIELD_NAME']])) { continue; } if (is_array($oldData[$field['FIELD_NAME']])) { foreach ($oldData[$field['FIELD_NAME']] as $value) { \CFile::delete($value); } } else { \CFile::delete($oldData[$field['FIELD_NAME']]); } } } // drop db column $connection = Application::getConnection(); $connection->dropColumn($hlblock['TABLE_NAME'], $field['FIELD_NAME']); // if multiple - drop utm table if ($field['MULTIPLE'] == 'Y') { $utmTableName = static::getMultipleValueTableName($hlblock, $field); $connection->dropTable($utmTableName); } return array('PROVIDE_STORAGE' => false); } return true; }
public function testIsPosPastEnd() { $filePath = CFile::createTemporary(); CFile::write($filePath, "Hello"); $file = new CFile($filePath, CFile::READ); $file->readBytes(5); $this->assertFalse($file->isPosPastEnd()); $file->done(); // only needed in these tests CFile::write($filePath, "Hello"); $file = new CFile($filePath, CFile::READ); $file->setPosToEnd(); $this->assertFalse($file->isPosPastEnd()); $file->done(); // only needed in these tests CFile::write($filePath, "Hello"); $file = new CFile($filePath, CFile::READ); $file->readBytes(5); $data = $file->readAvailableBytes(5); $this->assertTrue($file->isPosPastEnd() && $data->equals("")); $file->done(); // only needed in these tests CFile::delete($filePath); }
public function delete() { $success = parent::deleteInternal(); if (!$success) { return false; } \CFile::delete($this->fileId); return true; }
$AppUI->setMsg('Could not duplicate file, check file permissions', UI_MSG_ERROR); $AppUI->redirect($redirect); } else { $new_file->file_real_filename = $dup_realname; $result = $new_file->store(); if (count($new_file->getError())) { $AppUI->setMsg($new_file->getError(), UI_MSG_ERROR); } else { $AppUI->setMsg('duplicated', UI_MSG_OK, true); } $AppUI->redirect($redirect); } } // delete the file if ($del) { $result = $obj->delete(); if (count($obj->getError())) { $AppUI->setMsg($obj->getError(), UI_MSG_ERROR); $AppUI->redirect($redirect); } if ($result) { $obj->notify($notify); $obj->notifyContacts($notifyContacts); $AppUI->setMsg($action, UI_MSG_OK, true); $AppUI->redirect($redirect); } } // cancel the file checkout if ($cancel) { $obj->cancelCheckout($file_id); $AppUI->setMsg('checkout canceled', UI_MSG_OK, true);
$file_id = CValue::post("file_id"); $content = CValue::post("svg_content"); $del = CValue::post("del", 0); $export = CValue::post("export", 0); $remove_draft = CValue::post("remove_draft", 0); $file = new CFile(); $file->load($file_id); $file->bind($_POST); if ($export) { $file->_id = null; } $file->fillFields(); $file->loadTargetObject(); $file->updateFormFields(); if ($del) { if ($msg = $file->delete()) { CAppUI::stepAjax($msg, UI_MSG_ERROR); } else { CAppUI::stepAjax("CFile-msg-delete", UI_MSG_OK); } } else { $file->file_type = "image/fabricjs"; if ($export) { $svg = new CFile(); $svg->file_name = $file->file_name; $svg->file_type = "image/svg+xml"; $svg->author_id = $file->author_id; $svg->loadMatchingObject(); $svg->fillFields(); $svg->setObject($file->_ref_object); $svg->updateFormFields();
$version = dPgetParam($_POST, 'file_version', 0); $revision_type = dPgetParam($_POST, 'revision_type', 0); if (strcasecmp('major', $revision_type) == 0) { $major_num = strtok($version, ".") + 1; $_POST['file_version'] = $major_num; } if (!$obj->bind($_POST)) { $AppUI->setMsg($obj->getError(), UI_MSG_ERROR); $AppUI->redirect(); } // prepare (and translate) the module name ready for the suffix $AppUI->setMsg('File'); // delete the file if ($del) { $obj->load($file_id); if ($msg = $obj->delete()) { $AppUI->setMsg($msg, UI_MSG_ERROR); $AppUI->redirect(); } else { if ($not == '1') { $obj->notify(); } $AppUI->setMsg("deleted", UI_MSG_ALERT, true); $AppUI->redirect("m=files"); } } set_time_limit(600); ignore_user_abort(1); //echo "<pre>";print_r($_POST);echo "</pre>";die; $upload = null; if (isset($_FILES['formfile'])) {
/** * @param $name * @param $targetElementId * @param TmpFile $tmpFile * @param array $data * @return array|bool * @throws AccessDeniedException */ public function updateFile($name, $targetElementId, TmpFile $tmpFile, array $data = array()) { /** @var File $file */ $file = File::loadById($targetElementId); if (!$file) { $this->errorCollection->add(array(new Error("Could not " . __METHOD__ . " by id {$targetElementId}", 11154))); $tmpFile->delete(); return false; } if (!$file->canUpdate($this->storage->getCurrentUserSecurityContext())) { $tmpFile->delete(); throw new AccessDeniedException(); } /** @var array $fileArray */ if ($tmpFile->isCloud() && $tmpFile->getContentType()) { /** @noinspection PhpDynamicAsStaticMethodCallInspection */ $fileId = \CFile::saveFile(array('name' => $tmpFile->getFilename(), 'tmp_name' => $tmpFile->getAbsolutePath(), 'type' => $tmpFile->getContentType()), Driver::INTERNAL_MODULE_ID, true, true); /** @noinspection PhpDynamicAsStaticMethodCallInspection */ $fileArray = \CFile::getFileArray($fileId); if (!$fileArray) { $this->errorCollection->add(array(new Error("Could not " . __METHOD__ . " getFileArray", 1115541))); $tmpFile->delete(); return false; } if (!empty($data['originalTimestamp'])) { $fileArray['UPDATE_TIME'] = DateTime::createFromTimestamp($this->convertFromExternalVersion($data['originalTimestamp'])); } if ($file->addVersion($fileArray, $this->getUser()->getId())) { $tmpFile->delete(); $this->loadFormattedFolderTreeAndBreadcrumbs(); return $this->formatFileToResponse($file); } else { \CFile::delete($fileId); } } else { $fileArray = \CFile::makeFileArray($tmpFile->getAbsolutePath()); if (!$fileArray) { $this->errorCollection->add(array(new Error("Could not " . __METHOD__ . " MakeFileArray", 11155))); $tmpFile->delete(); return false; } if (!empty($data['originalTimestamp'])) { $fileArray['UPDATE_TIME'] = DateTime::createFromTimestamp($this->convertFromExternalVersion($data['originalTimestamp'])); } if ($file->uploadVersion($fileArray, $this->getUser()->getId())) { $tmpFile->delete(); $this->loadFormattedFolderTreeAndBreadcrumbs(); return $this->formatFileToResponse($file); } } $this->errorCollection->add(array(new Error("Could not " . __METHOD__ . ", uploadVersion", 11156))); $this->errorCollection->add($file->getErrors()); $tmpFile->delete(); return false; }
public function testClone() { $filePath0 = CFile::createTemporary(); $filePath1 = CFile::createTemporary(); $filePath2 = CFile::createTemporary(); $filePath3 = CFile::createTemporary(); CFile::write($filePath0, "The quick"); CFile::write($filePath1, " brown fox"); CFile::write($filePath2, " jumps over"); CFile::write($filePath3, " the lazy dog."); $hash0 = new CHash(CHash::SHA256); $hash0->computeMoreFromFile($filePath0); $hash0->computeMoreFromFile($filePath1); $hash0->computeMoreFromFile($filePath2); $hash0->computeMoreFromFile($filePath3); $hash1 = clone $hash0; $hash1->computeMoreFromFile($filePath0); $this->assertTrue($hash0->finalize()->equals("ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c")); $this->assertTrue($hash1->finalize()->equals("14dc40e99be202c4e59a0c6d1a8854bb50253624080435ed8c65bd6e5e880c95")); CFile::delete($filePath0); CFile::delete($filePath1); CFile::delete($filePath2); CFile::delete($filePath3); }
/** * @param mixed $primary * * @return Entity\DeleteResult */ public static function delete($primary) { global $USER_FIELD_MANAGER; // check primary static::normalizePrimary($primary); static::validatePrimary($primary); // get old data $oldData = static::getByPrimary($primary)->fetch(); $hlblock = static::getHighloadBlock(); $entity = static::getEntity(); $result = new Entity\DeleteResult(); //event before delete $event = new Entity\Event($entity, self::EVENT_ON_BEFORE_DELETE, array("id" => $primary)); $event->send(); $event->getErrors($result); //event before delete (modern with namespace) $event = new Entity\Event($entity, self::EVENT_ON_BEFORE_DELETE, array("id" => $primary, "primary" => $primary, "oldFields" => $oldData), true); $event->send(); $event->getErrors($result); // return if any error if (!$result->isSuccess(true)) { return $result; } //event on delete $event = new Entity\Event($entity, self::EVENT_ON_DELETE, array("id" => $primary)); $event->send(); //event on delete (modern with namespace) $event = new Entity\Event($entity, self::EVENT_ON_DELETE, array("id" => $primary, "primary" => $primary, "oldFields" => $oldData), true); $event->send(); // remove row $connection = Main\Application::getConnection(); $helper = $connection->getSqlHelper(); $tableName = $entity->getDBTableName(); $id = array(); foreach ($primary as $k => $v) { $id[] = $k . " = '" . $helper->forSql($v) . "'"; } $where = implode(' AND ', $id); $sql = "DELETE FROM " . $tableName . " WHERE " . $where; $connection->queryExecute($sql); $fields = $USER_FIELD_MANAGER->getUserFields('HLBLOCK_' . $hlblock['ID']); foreach ($oldData as $k => $v) { $userfield = $fields[$k]; // remove multi values if ($userfield['MULTIPLE'] == 'Y') { $utmTableName = HighloadBlockTable::getMultipleValueTableName($hlblock, $userfield); $connection->query(sprintf('DELETE FROM %s WHERE %s = %d', $helper->quote($utmTableName), $helper->quote('ID'), $primary['ID'])); } // remove files if ($userfield["USER_TYPE"]["BASE_TYPE"] == "file") { if (is_array($oldData[$k])) { foreach ($oldData[$k] as $value) { \CFile::delete($value); } } else { \CFile::delete($oldData[$k]); } } } //event after delete $event = new Entity\Event($entity, self::EVENT_ON_AFTER_DELETE, array("id" => $primary)); $event->send(); //event after delete (modern with namespace) $event = new Entity\Event($entity, self::EVENT_ON_AFTER_DELETE, array("id" => $primary, "primary" => $primary, "oldFields" => $oldData), true); $event->send(); return $result; }
function checkPayment($sbr_id, $delay = null) { require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/pskb.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/onlinedengi.php'; $objResponse = new xajaxResponse(); $sbr_id = __paramValue('int', $sbr_id); if (!$sbr_id) { $objResponse->call('finance_raise_err', 'Запрос не может быть обработан.'); return $objResponse; } $uid = get_uid(0); if (!$uid) { $objResponse->redirect('/'); return $objResponse; } $sbr = sbr_meta::getInstance(); if (!$sbr->initFromId($sbr_id)) { $objResponse->call('finance_raise_err', 'Запрос не может быть обработан.'); return $objResponse; } if ($sbr->status == sbr::STATUS_REFUSED) { $objResponse->call('finance_raise_err', 'Запрос не может быть обработан. Исполнитель отказался от сделки.'); return $objResponse; } if ($sbr->data['scheme_type'] != sbr::SCHEME_LC) { $objResponse->call('finance_raise_err', 'Указанная схема не поддерживается.'); return $objResponse; } $pskb = new pskb($sbr); $state = $pskb->checkNew(); if ($state == 'err') { $objResponse->call('finance_raise_err', $pskb->getError()); return $objResponse; } if ($state == 'form') { $objResponse->script("setTimeout(function() { xajax_checkPayment({$sbr_id});}, 2000);"); return $objResponse; } if ($state == 'new') { $lc = $pskb->getLC(); if ($lc['ps_emp'] == onlinedengi::BANK_YL) { $sbr->getDocs(); if ($sbr->docs) { foreach ($sbr->docs as $doc) { if ($doc['type'] == sbr::DOCS_TYPE_STATEMENT) { $doc_file = new CFile($doc['file_id']); //$doc_file->original_name = $doc['name']; $doc_file->delete($doc['file_id']); $sbr->removeEvent(24); } } } $stage = current($sbr->stages); if ($lc['ps_emp'] == onlinedengi::BANK_YL) { if ($doc_file = $stage->generateStatement($doc_err, $lc)) { // формируем заявление на аккредитив $doc = array('file_id' => $doc_file->id, 'status' => sbr::DOCS_STATUS_SIGN, 'access_role' => sbr::DOCS_ACCESS_EMP, 'owner_role' => 0, 'type' => sbr::DOCS_TYPE_STATEMENT, 'subtype' => 1); $sbr->addDocR($doc); $doc_file->original_name = $sbr->post_doc['name']; } } $objResponse->script('document.location.reload();'); return $objResponse; } if ($lc['ps_emp'] == onlinedengi::CARD) { $objResponse->call('pskb_frame', $lc['lc_id'], pskb::getNonceSign($lc['lc_id'])); } else { $objResponse->call('finance_send_frm'); } return $objResponse; } if ($state == 'cover') { $objResponse->script('document.location.reload();'); return $objResponse; } // $objResponse->call('finance_raise_err', 'Указанная схема не поддерживается.'); return $objResponse; }
} else { $new_file->file_real_filename = $dup_realname; $new_file->file_date = str_replace("'", '', $db->DBTimeStamp(time())); if ($msg = $new_file->store($AppUI)) { $AppUI->setMsg($msg, UI_MSG_ERROR); $AppUI->redirect($redirect); } else { $AppUI->setMsg('duplicated', UI_MSG_OK, true); $AppUI->redirect($redirect); } } } // delete the file if ($del) { $obj->load($file_id); if ($msg = $obj->delete($AppUI)) { $AppUI->setMsg($msg, UI_MSG_ERROR); $AppUI->redirect(); } else { $obj->notify($notify); $obj->notifyContacts($notifyContacts); $AppUI->setMsg($action, UI_MSG_OK, true); $AppUI->redirect($redirect); } } // cancel the file checkout if ($cancel) { $obj->cancelCheckout($file_id); $AppUI->setMsg('checkout canceled', UI_MSG_OK, true); $AppUI->redirect($redirect); }
/** * Очистка файлов сессии. */ public function clear($skey = false) { global $DB; $sql = 'SELECT file_id FROM attachedfiles WHERE session ' . ($skey ? ' = ?u' : 'IN (?l)') . ' AND status IN (1,2)'; $files = $DB->rows($sql, $skey ? $this->session[$skey] : $this->session); if ($files) { foreach ($files as $file) { $cFile = new CFile($file['file_id']); if ($cFile->id) { $cFile->delete($file['file_id']); } } } $sql = 'DELETE FROM attachedfiles WHERE session ' . ($skey ? ' = ?u' : 'IN (?l)') . ''; $DB->query($sql, $skey ? $this->session[$skey] : $this->session); }
/** * Очистка файлов сессии * */ public function clear($skey = false) { global $DB; $sql = "SELECT file_id FROM attachedfiles WHERE session " . ($skey ? " = ?u" : "IN (?l)") . " AND status IN (1,2)"; $files = $DB->rows($sql, $skey ? $this->session[$skey] : $this->session); if ($files) { foreach ($files as $file) { $cFile = new CFile($file['file_id']); if ($cFile->id) { $cFile->delete($file['file_id']); } } } $sql = "DELETE FROM attachedfiles WHERE session " . ($skey ? " = ?u" : "IN (?l)") . ""; $DB->query($sql, $skey ? $this->session[$skey] : $this->session); }