/** * Gets the document path and calls the conversion function * * @return boolean */ public function processDocument() { $oStorage = KTStorageManagerUtil::getSingleton(); $path = $oStorage->temporaryFile($this->document); $ext = KTMime::getFileType($this->document->getMimeTypeID()); if (!file_exists($path)) { global $default; $default->log->debug('PDF Converter: Document, id: ' . $this->document->iId . ', does not exist at given storage path: ' . $path); return sprintf(_kt("The document, id: %s, does not exist at the given storage path: %s"), $this->document->iId, $path); } // check for OO $available = $this->checkOO(); // do pdf conversion if (!$available) { global $default; $default->log->error("PDF Converter: Cannot connect to Open Office Server on host {$this->ooHost} : {$this->ooPort}"); return _kt('Cannot connect to Open Office Server.'); } $res = $this->convertFile($path, $ext); if ($res !== true) { global $default; $default->log->debug('PDF Converter: Document, id: ' . $this->document->iId . ', could not be converted to pdf.'); return sprintf(_kt("The document, id: %s, could not be converted to pdf format. The following error occurred: \"%s\"."), $this->document->iId, $res); } return true; }
/** * Constructor * * @param string $sZipFileName The name of the zip file - gets ignored at the moment. * @param string $exportCode The code to use if a zip file has already been created. */ function ZipFolder($sZipFileName = null, $exportCode = null, $extension = 'zip') { $this->oKTConfig =& KTConfig::getSingleton(); $this->oStorage =& KTStorageManagerUtil::getSingleton(); $this->sOutputEncoding = $this->oKTConfig->get('export/encoding', 'UTF-8'); $this->extension = $extension; $this->sPattern = "[\\*|\\%|\\\\|\\/|\\<|\\>|\\+|\\:|\\?|\\||\\'|\"]"; $this->sFolderPattern = "[\\*|\\%|\\<|\\>|\\+|\\:|\\?|\\||\\'|\"]"; if (!empty($exportCode)) { $this->exportCode = $exportCode; } else { $this->exportCode = KTUtil::randomString(); } // Check if the temp directory has been created and stored in session $aData = KTUtil::arrayGet($_SESSION['zipcompression'], $exportCode); if (!empty($aData) && isset($aData['dir'])) { $sTmpPath = $aData['dir']; } else { $sBasedir = $this->oKTConfig->get("urls/tmpDirectory"); $sTmpPath = tempnam($sBasedir, 'kt_compress_zip'); unlink($sTmpPath); mkdir($sTmpPath, 0755); } // Hard coding the zip file name. // It normally uses the folder name but if there are special characters in the name then it doesn't download properly. $sZipFileName = 'kt_zip'; $this->sTmpPath = $sTmpPath; $this->sZipFileName = $sZipFileName; $this->aPaths = array(); $aReplace = array("[" => "[[]", " " => "[ ]", "*" => "[*]", "?" => "[?]"); $this->aReplaceKeys = array_keys($aReplace); $this->aReplaceValues = array_values($aReplace); }
public function processDocument() { $oStorage = KTStorageManagerUtil::getSingleton(); $path = $oStorage->temporaryFile($this->document); if (!file_exists($path)) { global $default; $default->log->debug('Document, id: ' . $this->document->iId . ', does not exist at given storage path: ' . $path); return false; } // do pdf conversion $res = $this->convertFile($path); if ($res === false) { global $default; $default->log->debug('Document, id: ' . $this->document->iId . ', could not be converted to pdf.'); return false; } return true; }
/** * Constructor * * @param string $sZipFileName The name of the zip file. * @param string $exportCode The code to use if a zip file has already been created. */ function KTPclZip($sZipFileName = 'kt_pclzip', $exportCode = null, $extension = 'zip') { //TODO: Cherry pick some of this logic borrowed from lib/foldremanagement/compressionArchiveUtil.inc.php $this->oKTConfig =& KTConfig::getSingleton(); $this->oStorage =& KTStorageManagerUtil::getSingleton(); $this->sOutputEncoding = $this->oKTConfig->get('export/encoding', 'UTF-8'); $this->extension = $extension; $this->sPattern = "[\\*|\\%|\\\\|\\/|\\<|\\>|\\+|\\:|\\?|\\||\\'|\"]"; $this->sFolderPattern = "[\\*|\\%|\\<|\\>|\\+|\\:|\\?|\\||\\'|\"]"; if (!empty($exportCode)) { $this->exportCode = $exportCode; } else { $this->exportCode = KTUtil::randomString(); } // Check if the temp directory has been created and stored in session $aData = KTUtil::arrayGet($_SESSION['zipcompression'], $exportCode); if (!empty($aData) && isset($aData['dir'])) { $sTmpPath = $aData['dir']; } else { $sBasedir = $this->oKTConfig->get("urls/tmpDirectory"); $sTmpPath = tempnam($sBasedir, 'kt_compress_zip'); unlink($sTmpPath); mkdir($sTmpPath, 0755); } $this->sTmpPath = $sTmpPath; $this->sZipFileName = $sZipFileName; $this->aPaths = array(); $this->_pclZip = new PclZip($sZipFileName); /* //TODO: Cherry pick some of this logic borrowed from lib/foldremanagement/compressionArchiveUtil.inc.php $aReplace = array ("[" => "[[]", " " => "[ ]", "*" => "[*]", "?" => "[?]" ); $this->aReplaceKeys = array_keys ( $aReplace ); $this->aReplaceValues = array_values ( $aReplace ); */ }
function download_ext($document_id, $hash, $version = null) { $storage =& KTStorageManagerUtil::getSingleton(); $document = Document::get($document_id); if (PEAR::isError($document)) { return $document; } if (!empty($version)) { $version = KTDocumentContentVersion::get($version); $res = $storage->downloadVersion($document, $version); } else { $res = $storage->download($document); } if (PEAR::isError($res)) { return $res; } $sql = "DELETE FROM download_files WHERE hash='{$hash}' AND session='{$this->session}' AND document_id={$document_id}"; $result = DBUtil::runQuery($sql); return true; }
/** * Returns a reference to a file to be downloaded. * * @author KnowledgeTree Team * @access public * @param int $document_id * @return kt_response. */ public function download_small_document($document_id, $version = null) { $document =& $this->get_document_by_id($document_id); if (PEAR::isError($document)) { $response['status_code'] = 1; $response['message'] = $document->getMessage(); return $response; } $result = $document->download(); if (PEAR::isError($result)) { $response['status_code'] = 1; $response['message'] = $result->getMessage(); return $response; } $content = ''; $document = $document->document; $oStorage =& KTStorageManagerUtil::getSingleton(); $filename = $oStorage->temporaryFile($document); $fp = fopen($filename, 'rb'); if ($fp === false) { $response['status_code'] = 1; $response['message'] = 'The file is not in the storage system. Please contact an administrator!'; return $response; } $content = fread($fp, filesize($filename)); fclose($fp); $content = base64_encode($content); $response['status_code'] = 0; $response['results'] = $content; return $response; }
/** * Restores a deleted document * * @author KnowledgeTree Team * @access public */ function restore() { DBUtil::startTransaction(); $storage =& KTStorageManagerUtil::getSingleton(); $folder = Folder::get($this->document->getRestoreFolderId()); if (PEAR::isError($folder)) { $this->document->setFolderId(1); $folder = Folder::get(1); } else { $this->document->setFolderId($this->document->getRestoreFolderId()); } $storage->restore($this->document); $this->document->setStatusId(LIVE); $this->document->setPermissionObjectId($folder->getPermissionObjectId()); $res = $this->document->update(); $res = KTPermissionUtil::updatePermissionLookup($this->document); $user = $this->ktapi->get_user(); $oTransaction = new DocumentTransaction($this->document, 'Restored from deleted state by ' . $user->getName(), 'ktcore.transactions.update'); $oTransaction->create(); DBUtil::commit(); }
function transform() { $iMimeTypeId = $this->oDocument->getMimeTypeId(); $sMimeType = KTMime::getMimeTypeName($iMimeTypeId); if (!array_key_exists($sMimeType, $this->mimetypes)) { return; } $oStorage = KTStorageManagerUtil::getSingleton(); $sFile = $oStorage->temporaryFile($this->oDocument); $tempstub = 'transform'; if ($this->command != null) { $tempstub = $this->command; } $oKTConfig =& KTConfig::getSingleton(); $sBasedir = $oKTConfig->get("urls/tmpDirectory"); $myfilename = tempnam($sBasedir, 'kt.' . $tempstub); if (OS_WINDOWS) { $intermediate = tempnam($sBasedir, 'kt.' . $tempstub); if (!@copy($sFile, $intermediate)) { return; } } else { $intermediate = $sFile; } $contents = $this->extract_contents($intermediate, $myfilename); @unlink($myfilename); if (OS_WINDOWS) { @unlink($intermediate); } if (empty($contents)) { return; } $aInsertValues = array('document_id' => $this->oDocument->getId(), 'document_text' => $contents); $sTable = KTUtil::getTableName('document_text'); // clean up the document query "stuff". // FIXME this suggests that we should move the _old_ document_searchable_text across to the old-document's id if its a checkin. DBUtil::runQuery(array('DELETE FROM ' . $sTable . ' WHERE document_id = ?', array($this->oDocument->getId()))); DBUtil::autoInsert($sTable, $aInsertValues, array('noid' => true)); }
function copy($oSrcFolder, $oDestFolder, $oUser, $sReason, $sDestFolderName = NULL, $copyAll = true) { $sDestFolderName = empty($sDestFolderName) ? $oSrcFolder->getName() : $sDestFolderName; if (KTFolderUtil::exists($oDestFolder, $sDestFolderName)) { return PEAR::raiseError(_kt("Folder with the same name already exists in the new parent folder")); } // // FIXME the failure cleanup code here needs some serious work. // $oPerm = KTPermission::getByName('ktcore.permissions.read'); $oBaseFolderPerm = KTPermission::getByName('ktcore.permissions.addFolder'); if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oBaseFolderPerm, $oDestFolder)) { return PEAR::raiseError(_kt('You are not allowed to create folders in the destination.')); } // Check if the source folder inherits its permissions // Get source PO id and its parent PO id $iSrcPoId = $oSrcFolder->getPermissionObjectID(); $oSrcParent = Folder::get($oSrcFolder->getParentID()); $iSrcParentPoId = $oSrcParent->getPermissionObjectID(); // If the folder defines its own permissions then we copy the permission object // If the source folder inherits permissions we must change it to inherit from the new parent folder $bInheritPermissions = false; if ($iSrcPoId == $iSrcParentPoId) { $bInheritPermissions = true; } $aFolderIds = array(); // of oFolder $aDocuments = array(); // of oDocument $aFailedDocuments = array(); // of String $aFailedFolders = array(); // of String $aRemainingFolders = array($oSrcFolder->getId()); DBUtil::startTransaction(); while (!empty($aRemainingFolders) && $copyAll) { $iFolderId = array_pop($aRemainingFolders); $oFolder = Folder::get($iFolderId); if (PEAR::isError($oFolder) || $oFolder == false) { DBUtil::rollback(); return PEAR::raiseError(sprintf(_kt('Failure resolving child folder with id = %d.'), $iFolderId)); } // don't just stop ... plough on. if (KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oFolder)) { $aFolderIds[] = $iFolderId; } else { $aFailedFolders[] = $oFolder->getName(); } // child documents $aChildDocs = Document::getList(array('folder_id = ?', array($iFolderId))); foreach ($aChildDocs as $oDoc) { if (KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDoc)) { $aDocuments[] = $oDoc; } else { $aFailedDocuments[] = $oDoc->getName(); } } // child folders. $aCFIds = Folder::getList(array('parent_id = ?', array($iFolderId)), array('ids' => true)); $aRemainingFolders = kt_array_merge($aRemainingFolders, $aCFIds); } if (!empty($aFailedDocuments) || !empty($aFailedFolders)) { $sFD = ''; $sFF = ''; if (!empty($aFailedDocuments)) { $sFD = _kt('Documents: ') . implode(', ', $aFailedDocuments) . '. '; } if (!empty($aFailedFolders)) { $sFF = _kt('Folders: ') . implode(', ', $aFailedFolders) . '.'; } return PEAR::raiseError(_kt('You do not have permission to copy these items. ') . $sFD . $sFF); } // first we walk the tree, creating in the new location as we go. // essentially this is an "ok" pass. $oStorage =& KTStorageManagerUtil::getSingleton(); $aFolderMap = array(); $sTable = 'folders'; $sGetQuery = 'SELECT * FROM ' . $sTable . ' WHERE id = ? '; $aParams = array($oSrcFolder->getId()); $aRow = DBUtil::getOneResult(array($sGetQuery, $aParams)); unset($aRow['id']); $aRow['name'] = $sDestFolderName; $aRow['description'] = $sDestFolderName; $aRow['parent_id'] = $oDestFolder->getId(); $aRow['parent_folder_ids'] = sprintf('%s,%s', $oDestFolder->getParentFolderIDs(), $oDestFolder->getId()); $aRow['full_path'] = $oDestFolder->getFullPath() . '/' . $aRow['name']; $id = DBUtil::autoInsert($sTable, $aRow); if (PEAR::isError($id)) { DBUtil::rollback(); return $id; } $sSrcFolderId = $oSrcFolder->getId(); $aFolderMap[$sSrcFolderId]['parent_id'] = $id; $aFolderMap[$sSrcFolderId]['parent_folder_ids'] = $aRow['parent_folder_ids']; $aFolderMap[$sSrcFolderId]['full_path'] = $aRow['full_path']; $aFolderMap[$sSrcFolderId]['name'] = $aRow['name']; $oNewBaseFolder = Folder::get($id); $res = $oStorage->createFolder($oNewBaseFolder); if (PEAR::isError($res)) { // it doesn't exist, so rollback and raise.. DBUtil::rollback(); return $res; } $aRemainingFolders = Folder::getList(array('parent_id = ?', array($oSrcFolder->getId())), array('ids' => true)); while (!empty($aRemainingFolders) && $copyAll) { $iFolderId = array_pop($aRemainingFolders); $aParams = array($iFolderId); $aRow = DBUtil::getOneResult(array($sGetQuery, $aParams)); unset($aRow['id']); // since we are nested, we will have solved the parent first. $sPrevParentId = $aRow['parent_id']; $aRow['parent_id'] = $aFolderMap[$aRow['parent_id']]['parent_id']; $aRow['parent_folder_ids'] = sprintf('%s,%s', $aFolderMap[$sPrevParentId]['parent_folder_ids'], $aRow['parent_id']); $aRow['full_path'] = sprintf('%s/%s', $aFolderMap[$sPrevParentId]['full_path'], $aRow['name']); $id = DBUtil::autoInsert($sTable, $aRow); if (PEAR::isError($id)) { $oStorage->removeFolder($oNewBaseFolder); DBUtil::rollback(); return $id; } $aFolderMap[$iFolderId]['parent_id'] = $id; $aFolderMap[$iFolderId]['parent_folder_ids'] = $aRow['parent_folder_ids']; $aFolderMap[$iFolderId]['full_path'] = $aRow['full_path']; $aFolderMap[$iFolderId]['name'] = $aRow['name']; $oNewFolder = Folder::get($id); $res = $oStorage->createFolder($oNewFolder); if (PEAR::isError($res)) { // first delete, then rollback, then fail out. $oStorage->removeFolder($oNewBaseFolder); DBUtil::rollback(); return $res; } $aCFIds = Folder::getList(array('parent_id = ?', array($iFolderId)), array('ids' => true)); $aRemainingFolders = kt_array_merge($aRemainingFolders, $aCFIds); } // now we can go ahead. foreach ($aDocuments as $oDocument) { $oChildDestinationFolder = Folder::get($aFolderMap[$oDocument->getFolderID()]['parent_id']); $res = KTDocumentUtil::copy($oDocument, $oChildDestinationFolder); if (PEAR::isError($res) || $res === false) { $oStorage->removeFolder($oNewBaseFolder); DBUtil::rollback(); return PEAR::raiseError(_kt('Delete Aborted. Unexpected failure to copydocument: ') . $oDocument->getName() . $res->getMessage()); } } $sComment = sprintf(_kt("Folder copied from %s to %s"), $oSrcFolder->getFullPath(), $oDestFolder->getFullPath()); if ($sReason !== null) { $sComment .= sprintf(_kt(" (reason: %s)"), $sReason); } $oTransaction = KTFolderTransaction::createFromArray(array('folderid' => $oFolder->getId(), 'comment' => $sComment, 'transactionNS' => 'ktcore.transactions.copy', 'userid' => $oUser->getId(), 'ip' => Session::getClientIP())); // If the folder inherits its permissions then we set it to inherit from the new parent folder and update permissions // If it defines its own then copy the permission object over if ($bInheritPermissions) { $aOptions = array('evenifnotowner' => true); KTPermissionUtil::inheritPermissionObject($oNewBaseFolder, $aOptions); } else { KTPermissionUtil::copyPermissionObject($oNewBaseFolder); } // and store DBUtil::commit(); return true; }
$metadata_version_id = $row['metadata_version_id']; $document = Document::get($document_id, $metadata_version_id); $core =& $document->_oDocumentContentVersion; $filename = $document->getFileName(); $md5 = $core->getStorageHash(); if (empty($md5)) { if ($dots > 0) { print "\n"; } print "Document Id: {$document_id} - Content Id: {$content_id} - No MD5 hash available.\n"; $no_hash++; $current = 0; $dots = 0; // don't exit here, we do so later } $storage = KTStorageManagerUtil::getSingleton(); $storage_path = $storage->temporaryFile($document); if (PEAR::isError($storage_path)) { if ($dots > 0) { print "\n"; } print "Document Id: {$document_id} - Content Id: {$content_id} - Storage engine reported an error: " . $storage_path->getMessage() . "\n"; $no_hash++; $current = 0; $dots = 0; continue; } if (!file_exists($storage_path)) { if ($dots > 0) { print "\n"; }
function sendEmailDocument($aDestEmailAddress, $iDocumentID, $sDocumentName, $sComment, &$aEmailErrors) { global $default; // Get the email list as a string for the logs $sDestEmails = implode(',', $aDestEmailAddress); $oSendingUser = User::get($_SESSION['userID']); $sMessage .= sprintf(_kt("Your colleague, %s, wishes you to view the attached document entitled '%s'."), $oSendingUser->getName(), $sDocumentName); $sMessage .= "\n\n"; if (strlen($sComment) > 0) { $sMessage .= '<br><br>' . _kt('Comments') . ':<br>' . $sComment; } $sTitle = sprintf(_kt("Document (ID %s): %s from %s"), $iDocumentID, $sDocumentName, $oSendingUser->getName()); $sEmail = null; $sEmailFrom = null; $oConfig =& KTConfig::getSingleton(); if (!$oConfig->get('email/sendAsSystem')) { $sEmail = $oSendingUser->getEmail(); $sEmailFrom = $oSendingUser->getName(); } $oEmail = new Email($sEmail, $sEmailFrom); $oDocument = Document::get($iDocumentID); // Request a standard file path so that it can be attached to the // email $oStorage =& KTStorageManagerUtil::getSingleton(); $sDocumentPath = $oStorage->temporaryFile($oDocument); $sDocumentFileName = $oDocument->getFileName(); $res = $oEmail->sendAttachment($aDestEmailAddress, $sTitle, $sMessage, $sDocumentPath, $sDocumentFileName); // Tell the storage we don't need the temporary file anymore. $oStorage->freeTemporaryFile($sDocumentPath); if (PEAR::isError($res)) { $default->log->error($res->getMessage()); $aEmailErrors[] = $res->getMessage(); return $res; } else { if ($res === false) { $default->log->error("Error sending email ({$sTitle}) to {$sDestEmails}"); $aEmailErrors[] = "Error sending email ({$sTitle}) to {$sDestEmails}"; return PEAR::raiseError(sprintf(_kt("Error sending email (%s) to %s"), $sTitle, $sDestEmails)); } else { $default->log->info("Send email ({$sTitle}) to {$sDestEmails}"); } } // emailed link transaction $oDocumentTransaction = new DocumentTransaction($oDocument, sprintf(_kt("Document copy emailed to %s. "), $sDestEmails) . $sComment, 'ktcore.transactions.email_attachment'); if ($oDocumentTransaction->create()) { $default->log->debug("emailBL.php created email link document transaction for document ID={$iDocumentID}"); } else { $default->log->error("emailBL.php couldn't create email link document transaction for document ID={$iDocumentID}"); } }
function do_finish_restore() { $selected_docs = KTUtil::arrayGet($_REQUEST, 'selected_docs', array()); $aDocuments = array(); foreach ($selected_docs as $doc_id) { $oDoc =& Document::get($doc_id); if (PEAR::isError($oDoc) || $oDoc === false) { $this->errorRedirectToMain(_kt('Invalid document id specified. Aborting restore')); } else { if ($oDoc->getStatusId() != DELETED) { $this->errorRedirectToMain(sprintf(_kt('%s is not a deleted document. Aborting restore'), $oDoc->getName())); } } $aDocuments[] = $oDoc; } $this->startTransaction(); $aErrorDocuments = array(); $aSuccessDocuments = array(); $oStorage =& KTStorageManagerUtil::getSingleton(); foreach ($aDocuments as $oDoc) { $oFolder = Folder::get($oDoc->getRestoreFolderId()); // move to root if parent no longer exists. if (PEAR::isError($oFolder)) { $oDoc->setFolderId(1); $oFolder = Folder::get(1); } else { $oDoc->setFolderId($oDoc->getRestoreFolderId()); } if ($oStorage->restore($oDoc)) { $oDoc = Document::get($oDoc->getId()); // storage path has changed for most recent object... $oDoc->setStatusId(LIVE); $oDoc->setPermissionObjectId($oFolder->getPermissionObjectId()); $res = $oDoc->update(); if (PEAR::isError($res) || $res == false) { $aErrorDocuments[] = $oDoc->getName(); continue; // skip transactions, etc. } $res = KTPermissionUtil::updatePermissionLookup($oDoc); if (PEAR::isError($res)) { $aErrorDocuments[] = $oDoc->getName(); continue; // skip transactions, etc. } // create a doc-transaction. // FIXME does this warrant a transaction-type? $oTransaction = new DocumentTransaction($oDoc, sprintf(_kt("Restored from deleted state by %s"), $this->oUser->getName()), 'ktcore.transactions.update'); if (!$oTransaction->create()) { // do nothing? the state of physicaldocumentmanager... } $aSuccessDocuments[] = $oDoc->getName(); } else { $aErrorDocuments[] = $oDoc->getName(); } } $this->commitTransaction(); $msg = sprintf(_kt('%d documents restored.'), count($aSuccessDocuments)); if (count($aErrorDocuments) != 0) { $msg .= _kt('Failed to restore') . ': ' . join(', ', $aErrorDocuments); } $this->successRedirectToMain($msg); }
function do_checkout_final() { $sReason = KTUtil::arrayGet($_REQUEST, 'reason'); $this->oValidator->notEmpty($sReason); $oKTTriggerRegistry = KTTriggerRegistry::getSingleton(); $aTriggers = $oKTTriggerRegistry->getTriggers('checkoutDownload', 'postValidate'); foreach ($aTriggers as $aTrigger) { $sTrigger = $aTrigger[0]; $oTrigger = new $sTrigger(); $aInfo = array('document' => $this->oDocument); $oTrigger->setInfo($aInfo); $ret = $oTrigger->postValidate(); if (PEAR::isError($ret)) { return $ret; } } $oStorage =& KTStorageManagerUtil::getSingleton(); $oStorage->download($this->oDocument, true); exit(0); }
function do_processInitialData() { $oForm = $this->form_initialdata(); $res = $oForm->validate(); if (!empty($res['errors'])) { if (!isset($res['errors']['file'])) { $aError['file'] = array(_kt('Please reselect the file to upload.')); } return $oForm->handleError('', $aError); } $data = $res['results']; $key = KTUtil::randomString(32); // joy joy, we need to store the file first, or PHP will (helpfully) // clean it up for us $oKTConfig =& KTConfig::getSingleton(); $sBasedir = $oKTConfig->get("urls/tmpDirectory"); $sFilename = tempnam($sBasedir, 'kt_storecontents'); //$oContents = new KTFSFileLike($data['file']['tmp_name']); //$oOutputFile = new KTFSFileLike($sFilename); //$res = KTFileLikeUtil::copy_contents($oContents, $oOutputFile); //if (PEAR::isError($res)) { // $oForm->handleError(sprintf(_kt("Failed to store file: %s"), $res->getMessage())); //} $oStorage =& KTStorageManagerUtil::getSingleton(); $oStorage->uploadTmpFile($data['file']['tmp_name'], $sFilename); $data['file']['tmp_name'] = $sFilename; $_SESSION['_add_data'] = array($key => $data); // if we don't need metadata $fieldsets = $this->getFieldsetsForType($data['document_type']); if (empty($fieldsets)) { return $this->successRedirectTo('finalise', _kt("File uploaded successfully. Processing."), sprintf("fFileKey=%s", $key)); } // if we need metadata $this->successRedirectTo('metadata', _kt("File uploaded successfully. Please fill in the metadata below."), sprintf("fFileKey=%s", $key)); }
/** * Returns a reference to a file to be downloaded. * * @param string $session_id * @param int $document_id * @return kt_response. status_code can be KTWS_ERR_INVALID_SESSION, KTWS_ERR_INVALID_DOCUMENT or KTWS_SUCCESS */ function download_small_document($session_id, $document_id, $version = null) { $this->debug("download_small_document('{$session_id}',{$document_id})"); $kt =& $this->get_ktapi($session_id); if (is_array($kt)) { return new SOAP_Value('return', "{urn:{$this->namespace}}kt_response", $kt); } $response = KTWebService::_status(KTWS_ERR_INVALID_DOCUMENT); $document =& $kt->get_document_by_id($document_id); if (PEAR::isError($document)) { $response['message'] = $document->getMessage(); $this->debug("download_small_document - cannot get documentid {$document_id} - " . $document->getMessage(), $session_id); return new SOAP_Value('return', "{urn:{$this->namespace}}kt_response", $response); } $result = $document->download(); if (PEAR::isError($result)) { $response['message'] = $result->getMessage(); $this->debug("download_small_document - cannot download - " . $result->getMessage(), $session_id); return new SOAP_Value('return', "{urn:{$this->namespace}}kt_response", $response); } $content = ''; $document = $document->document; $oStorage =& KTStorageManagerUtil::getSingleton(); $filename = $oStorage->temporaryFile($document); $fp = fopen($filename, 'rb'); if ($fp === false) { $response['message'] = 'The file is not in the storage system. Please contact an administrator!'; $this->debug("download_small_document - cannot write {$filename}", $session_id); return new SOAP_Value('return', "{urn:{$this->namespace}}kt_response", $response); } $content = fread($fp, filesize($filename)); fclose($fp); $content = base64_encode($content); $response['status_code'] = KTWS_SUCCESS; $response['message'] = $content; return new SOAP_Value('return', "{urn:{$this->namespace}}kt_response", $response); }
public function run() { global $argc; if (isset($argc)) { $this->nl = "\n"; $this->tab = "\t"; print "Storage Verification{$this->nl}"; print "===================={$this->nl}"; } else { $this->nl = '<br>'; $this->tab = ' '; print "<b>Storage Verification</b>{$this->nl}"; } $sql = "SELECT\n dmv.id as metadata_version_id, dcv.document_id, dcv.md5hash, dcv.size\n FROM\n document_content_version dcv\n INNER JOIN document_metadata_version dmv ON dcv.id=dmv.content_version_id"; $rows = DBUtil::getResultArray($sql); $this->count = 0; $this->lineCount = 0; $storage =& KTStorageManagerUtil::getSingleton(); foreach ($rows as $row) { $doc = Document::get($row['document_id'], $row['metadata_version_id']); if (PEAR::isError($doc)) { $msg = $doc->getMessage(); $this->error($doc, "Error with document: {$msg}"); continue; } $this->doc = $doc; $tmpPath = $storage->temporaryFile($doc); if (!file_exists($tmpPath)) { $this->error("Temporary file could not be resolved: {$tmpPath}"); continue; } $expectedSize = $row['size']; $currentSize = filesize($tmpPath); if ($expectedSize != $currentSize) { $this->error("Filesize does not match. Expected: {$expectedSize} Current: {$currentSize}"); continue; } $expectedHash = $row['md5hash']; $currentHash = md5_file($tmpPath); if ($expectedHash != $currentHash) { $this->error("Hash does not match. Expected: {$expectedHash} Current: {$currentHash}"); continue; } $this->progress(); } print "{$this->nl}Done.{$this->nl}{$this->nl}"; }
/** * Delete a selected version of the document. */ function deleteVersion($oDocument, $iVersionID, $sReason) { $oDocument =& KTUtil::getObject('Document', $oDocument); $oVersion =& KTDocumentMetadataVersion::get($iVersionID); $oStorageManager =& KTStorageManagerUtil::getSingleton(); global $default; if (empty($sReason)) { return PEAR::raiseError(_kt('Deletion requires a reason')); } if (PEAR::isError($oDocument) || $oDocument == false) { return PEAR::raiseError(_kt('Invalid document object.')); } if (PEAR::isError($oVersion) || $oVersion == false) { return PEAR::raiseError(_kt('Invalid document version object.')); } $iContentId = $oVersion->getContentVersionId(); $oContentVersion = KTDocumentContentVersion::get($iContentId); if (PEAR::isError($oContentVersion) || $oContentVersion == false) { return PEAR::raiseError(_kt('Invalid document content version object.')); } // Check that the document content is not the same as the current content version $sDocStoragePath = $oDocument->getStoragePath(); $sVersionStoragePath = $oContentVersion->getStoragePath(); if ($sDocStoragePath == $sVersionStoragePath) { return PEAR::raiseError(_kt("Can't delete version: content is the same as the current document content.")); } DBUtil::startTransaction(); // now delete the document version $res = $oStorageManager->deleteVersion($oVersion); if (PEAR::isError($res) || $res == false) { //could not delete the document version from the file system $default->log->error('Deletion: Filesystem error deleting the metadata version ' . $oVersion->getMetadataVersion() . ' of the document ' . $oDocument->getFileName() . ' from folder ' . Folder::getFolderPath($oDocument->getFolderID()) . ' id=' . $oDocument->getFolderID()); // we use a _real_ transaction here ... DBUtil::rollback(); return PEAR::raiseError(_kt('There was a problem deleting the document from storage.')); } // change status for the metadata version $oVersion->setStatusId(VERSION_DELETED); $oVersion->update(); // set the storage path to empty // $oContentVersion->setStoragePath(''); DBUtil::commit(); }
function restore($iDocId) { // Get the document object $oDoc = Document::get($iDocId); if (PEAR::isError($oDoc) || $oDoc === false) { return $oDoc; } $this->startTransaction(); $iRestoreFolder = $oDoc->getRestoreFolderId(); $oFolder = Folder::get($iRestoreFolder); // move to root if parent no longer exists. if (PEAR::isError($oFolder)) { $oDoc->setFolderId(1); $oFolder = Folder::get(1); } else { $oDoc->setFolderId($iRestoreFolder); } $oStorage = KTStorageManagerUtil::getSingleton(); if ($oStorage->restore($oDoc)) { $oDoc = Document::get($iDocId); // storage path has changed for most recent object... $oDoc->setStatusId(LIVE); $oDoc->setPermissionObjectId($oFolder->getPermissionObjectId()); $res = $oDoc->update(); if (PEAR::isError($res) || $res == false) { return $res; } $res = KTPermissionUtil::updatePermissionLookup($oDoc); if (PEAR::isError($res)) { return $res; } // create a doc-transaction. $oTransaction = new DocumentTransaction($oDoc, sprintf(_kt("Restored from deleted state by %s"), $this->oUser->getName()), 'ktcore.transactions.update'); $oTransaction->create(); } $this->commitTransaction(); return true; }
/** * Perform diagnostics and pre-indexing setup * Refactored from indexDocuments() */ public function preIndexingSetup() { global $default; // Check mimetypes and load the text extractors $this->checkForRegisteredTypes(); // Check diagnostics on extractors if (!$this->doesDiagnosticsPass()) { //unlink($indexLockFile); if ($this->debug) { $default->log->debug('indexDocuments: stopping - diagnostics problem. The administration section will provide more information.'); } return false; } // Load extractor hooks $this->loadExtractorHooks(); $this->storageManager = KTStorageManagerUtil::getSingleton(); // Config setting - urls/tmpDirectory $this->tempPath = $default->tmpDirectory; }
/** * Method for downloading the document as a pdf. * * @deprecated * @return true on success else false */ function do_pdfdownload_deprecated() { $oDocument = $this->oDocument; $oStorage =& KTStorageManagerUtil::getSingleton(); $oConfig =& KTConfig::getSingleton(); $default = realpath(str_replace('\\', '/', KT_DIR . '/../openoffice/program')); putenv('ooProgramPath=' . $oConfig->get('openoffice/programPath', $default)); $cmdpath = KTUtil::findCommand('externalBinary/python'); // Check if openoffice and python are available if ($cmdpath == false || !file_exists($cmdpath) || empty($cmdpath)) { // Set the error messsage and redirect to view document $this->addErrorMessage(_kt('An error occurred generating the PDF - please contact the system administrator. Python binary not found.')); redirect(generateControllerLink('viewDocument', sprintf('fDocumentId=%d', $oDocument->getId()))); exit(0); } //get the actual path to the document on the server $sPath = sprintf("%s/%s", $oConfig->get('urls/documentRoot'), $oStorage->getPath($oDocument)); if (file_exists($sPath)) { // Get a tmp file $sTempFilename = tempnam('/tmp', 'ktpdf'); // We need to handle Windows differently - as usual ;) if (substr(PHP_OS, 0, 3) == 'WIN') { $cmd = "\"" . $cmdpath . "\" \"" . KT_DIR . "/bin/openoffice/pdfgen.py\" \"" . $sPath . "\" \"" . $sTempFilename . "\""; $cmd = str_replace('/', '\\', $cmd); // TODO: Check for more errors here // SECURTIY: Ensure $sPath and $sTempFilename are safe or they could be used to excecute arbitrary commands! // Excecute the python script. TODO: Check this works with Windows $res = `"{$cmd}" 2>&1`; //print($res); //print($cmd); //exit; } else { // TODO: Check for more errors here // SECURTIY: Ensure $sPath and $sTempFilename are safe or they could be used to excecute arbitrary commands! // Excecute the python script. $cmd = $cmdpath . ' ' . KT_DIR . '/bin/openoffice/pdfgen.py ' . escapeshellcmd($sPath) . ' ' . escapeshellcmd($sTempFilename); $res = shell_exec($cmd . " 2>&1"); //print($res); //print($cmd); //exit; } // Check the tempfile exists and the python script did not return anything (which would indicate an error) if (file_exists($sTempFilename) && $res == '') { $mimetype = 'application/pdf'; $size = filesize($sTempFilename); $name = substr($oDocument->getFileName(), 0, strrpos($oDocument->getFileName(), '.')) . '.pdf'; KTUtil::download($sTempFilename, $mimetype, $size, $name); // Remove the tempfile unlink($sTempFilename); // Create the document transaction $oDocumentTransaction =& new DocumentTransaction($oDocument, 'Document downloaded as PDF', 'ktcore.transactions.download', $aOptions); $oDocumentTransaction->create(); // Just stop here - the content has already been sent. exit(0); } else { // Set the error messsage and redirect to view document $this->addErrorMessage(_kt('An error occurred generating the PDF - please contact the system administrator. ' . $res)); redirect(generateControllerLink('viewDocument', sprintf('fDocumentId=%d', $oDocument->getId()))); exit(0); } } else { // Set the error messsage and redirect to view document $this->addErrorMessage(_kt('An error occurred generating the PDF - please contact the system administrator. The path to the document did not exist.')); redirect(generateControllerLink('viewDocument', sprintf('fDocumentId=%d', $oDocument->getId()))); exit(0); } }
/** * GET method helper * * @param array parameter passing array * @param int Document ID * @return bool true on success */ function _GETDocument(&$options, $iDocumentID) { global $default; $oDocument =& Document::get($iDocumentID); // get a temp file, and read. NOTE: NEVER WRITE TO THIS $oStorage =& KTStorageManagerUtil::getSingleton(); $fspath = $oStorage->temporaryFile($oDocument); $this->ktwebdavLog("Filesystem Path is " . $fspath, 'info', true); // detect resource type $mimetype = KTMime::getMimeTypeName($oDocument->getMimeTypeID()); $options['mimetype'] = KTMime::getFriendlyNameForString($mimetype); // detect modification time // see rfc2518, section 13.7 // some clients seem to treat this as a reverse rule // requiering a Last-Modified header if the getlastmodified header was set $options['mtime'] = $oDocument->getVersionCreated(); // detect resource size $options['size'] = $oDocument->getFileSize(); // no need to check result here, it is handled by the base class $options['stream'] = fopen($fspath, "r"); $this->ktwebdavLog("Method is " . $this->currentMethod, 'info', true); if ($this->currentMethod == "get") { // create the document transaction record include_once KT_LIB_DIR . '/documentmanagement/DocumentTransaction.inc'; $oDocumentTransaction =& new DocumentTransaction($oDocument, "Document viewed via KTWebDAV", 'ktcore.transactions.view'); $oDocumentTransaction->iUserID = $this->userID; $oDocumentTransaction->create(); } return true; }
/** * make uploads * @return * * iNET Process */ function do_upload() { set_time_limit(0); global $default; $aErrorOptions = array('redirect_to' => array('main', sprintf('fFolderId=%d', $this->oFolder->getId()))); $aErrorOptions['message'] = _kt('Invalid document type provided'); $requestDocumentType = $_REQUEST['fDocumentTypeId']; //Backwards compatibility if ($requestDocumentType == '' || $requestDocumentType == NULL) { $requestDocumentType = $_REQUEST['data']; $requestDocumentType = $requestDocumentType['fDocumentTypeId']; //New elements come through as arrays } $oDocumentType = $this->oValidator->validateDocumentType($requestDocumentType, $aErrorOptions); unset($aErrorOptions['message']); $fileData = $_FILES['file']; $fileName = 'file'; if ($fileData == '' || $fileData == NULL) { $fileData = $_FILES['_kt_attempt_unique_file']; //$_FILES['_kt_attempt_unique_file']; $fileName = '_kt_attempt_unique_file'; } $aFile = $this->oValidator->validateFile($fileData, $aErrorOptions); // Lets move the file from the windows temp directory into our own directory $oKTConfig =& KTConfig::getSingleton(); $sBasedir = $oKTConfig->get("urls/tmpDirectory"); $tmpFilename = tempnam($sBasedir, 'kt_storebulk'); $oStorage =& KTStorageManagerUtil::getSingleton(); $res = $oStorage->uploadTmpFile($fileData['tmp_name'], $tmpFilename, array('copy_upload' => 'true')); // Save the new temp filename in the file data array $fileData['tmp_name'] = $tmpFilename; if ($res === false) { $default->log->error('File could not be copied from the system temp directory.'); exit('File could not be copied from the system temp directory.'); } $matches = array(); $aFields = array(); // author: Charl Mert // Older kt3 form field submission used name='metadata_9 etc and the aFields array contained them.' // Should keep open here for backwards compatibility but will close it to "discover" the other // old interfaces. /* foreach ($_REQUEST as $k => $v) { if (preg_match('/^metadata_(\d+)$/', $k, $matches)) { // multiselect change start $oDocField = DocumentField::get($matches[1]); if(KTPluginUtil::pluginIsActive('inet.multiselect.lookupvalue.plugin') && $oDocField->getHasInetLookup() && is_array($v)) { $v = join(", ", $v); } $aFields[] = array($oDocField, $v); // previously it was just one line which is commented, just above line // multiselect change end } } */ //Newer metadata form field catcher that works with ktcore form array type fields named like //name='metadata[fieldset][metadata_9]' $aData = $_REQUEST['data']; /* //This validation breaks with ajax loaded form items e.g. a non generic fieldset that submits * //values doesn't pass the check below. $oForm = $this->getBulkUploadForm(); $res = $oForm->validate(); if (!empty($res['errors'])) { return $oForm->handleError(); } $data = $res['results']; var_dump($data); */ $data = $aData; $doctypeid = $requestDocumentType; $aGenericFieldsetIds = KTFieldset::getGenericFieldsets(array('ids' => false)); $aSpecificFieldsetIds = KTFieldset::getForDocumentType($doctypeid, array('ids' => false)); $fieldsets = kt_array_merge($aGenericFieldsetIds, $aSpecificFieldsetIds); $MDPack = array(); foreach ($fieldsets as $oFieldset) { $fields = $oFieldset->getFields(); $values = (array) KTUtil::arrayGet($data, 'fieldset_' . $oFieldset->getId()); //var_dump($values); foreach ($fields as $oField) { //var_dump($oField->getId()); $val = KTUtil::arrayGet($values, 'metadata_' . $oField->getId()); //Fix for multiselect not submitting data due to the value not being flat. $sVal = ''; if (is_array($val)) { foreach ($val as $v) { $sVal .= $v . ", "; } $sVal = substr($sVal, 0, strlen($sVal) - 2); $val = $sVal; } if ($oFieldset->getIsConditional()) { if ($val == _kt('No selection.')) { $val = null; } } if (!is_null($val)) { $MDPack[] = array($oField, $val); } } } $aOptions = array('documenttype' => $oDocumentType, 'metadata' => $MDPack); $fs =& new KTZipImportStorage($fileName, $fileData); if (!$fs->CheckFormat()) { $sFormats = $fs->getFormats(); $this->addErrorMessage(sprintf(_kt("Bulk Upload failed. Archive is not an accepted format. Accepted formats are: .%s"), $sFormats)); controllerRedirect("browse", 'fFolderId=' . $this->oFolder->getID()); exit; } if (KTPluginUtil::pluginIsActive('inet.foldermetadata.plugin')) { require_once KT_DIR . "/plugins/foldermetadata/import/bulkimport.inc.php"; $bm =& new KTINETBulkImportManager($this->oFolder, $fs, $this->oUser, $aOptions); } else { $bm =& new KTBulkImportManager($this->oFolder, $fs, $this->oUser, $aOptions); } $this->startTransaction(); $res = $bm->import(); $aErrorOptions['message'] = _kt("Bulk Upload failed"); $this->oValidator->notError($res, $aErrorOptions); $this->addInfoMessage(_kt("Bulk Upload successful")); $this->commitTransaction(); controllerRedirect("browse", 'fFolderId=' . $this->oFolder->getID()); exit(0); }