Exemple #1
0
 function testRollback()
 {
     $f = Group::getList();
     $iNumGroups = count($f);
     DBUtil::startTransaction();
     $g = Group::createFromArray(array('name' => 'rollback'));
     if (!$this->assertGroup($g)) {
         return;
     }
     $f = Group::getList();
     $iNowNumGroups = count($f);
     $this->assertEqual($iNumGroups + 1, $iNowNumGroups, 'New group not in list');
     DBUtil::rollback();
     $f = Group::getList();
     $iRollbackNumGroups = count($f);
     $this->assertEqual($iNumGroups, $iRollbackNumGroups, 'New group still in list (should be rolled back)');
 }
Exemple #2
0
<?php

require_once "../../config/dmsDefaults.php";
require_once KT_LIB_DIR . '/documentmanagement/documentutil.inc.php';
require_once KT_LIB_DIR . '/filelike/fsfilelike.inc.php';
error_reporting(E_ALL);
$oFolder =& Folder::get(1);
$oUser =& User::get(1);
$sLocalname = KT_DIR . "/tests/document/dataset1/critique-of-pure-reason.txt";
$sFilename = tempnam("/tmp", "kt_tests_document_add");
copy($sLocalname, $sFilename);
DBUtil::startTransaction();
$oDocument =& KTDocumentUtil::add($oFolder, "testfullupload2.txt", $oUser, array('contents' => new KTFSFileLike($sFilename), 'metadata' => array()));
if (PEAR::isError($oDocument)) {
    print "FAILURE\n";
    var_dump($oDocument);
    exit(0);
}
DBUtil::commit();
print "SUCCESS\n";
 function createFolderDetailsPermission()
 {
     $sPermissionsTable = KTUtil::getTableName('permissions');
     $bExists = DBUtil::getOneResultKey("SELECT COUNT(id) AS cnt FROM {$sPermissionsTable} WHERE name = 'ktcore.permissions.folder_details'", 'cnt');
     if ($bExists) {
         return;
     }
     DBUtil::startTransaction();
     $aPermissionInfo = array('human_name' => 'Core: Folder Details', 'name' => 'ktcore.permissions.folder_details', 'built_in' => true);
     $res = DBUtil::autoInsert($sPermissionsTable, $aPermissionInfo);
     if (PEAR::isError($res)) {
         return $res;
     }
     $iFolderDetailsPermissionId = $res;
     $sQuery = "SELECT id FROM {$sPermissionsTable} WHERE name = ?";
     $aParams = array("ktcore.permissions.read");
     $iReadPermissionId = DBUtil::getOneResultKey(array($sQuery, $aParams), "id");
     $sPermissionAssignmentsTable = KTUtil::getTableName('permission_assignments');
     $sQuery = "SELECT permission_object_id, permission_descriptor_id FROM {$sPermissionAssignmentsTable} WHERE permission_id = ?";
     $aParams = array($iReadPermissionId);
     $aRows = DBUtil::getResultArray(array($sQuery, $aParams));
     foreach ($aRows as $aRow) {
         $aRow['permission_id'] = $iFolderDetailsPermissionId;
         DBUtil::autoInsert($sPermissionAssignmentsTable, $aRow);
     }
     $sDocumentTable = KTUtil::getTableName('documents');
     $sFolderTable = KTUtil::getTableName('folders');
     DBUtil::runQuery("UPDATE {$sDocumentTable} SET permission_lookup_id = NULL");
     DBUtil::runQuery("UPDATE {$sFolderTable} SET permission_lookup_id = NULL");
     DBUtil::commit();
 }
Exemple #4
0
 function do_trytype()
 {
     $oForm = $this->form_changetype();
     $res = $oForm->validate();
     $data = $res['results'];
     $errors = $res['errors'];
     if (!empty($errors)) {
         $oForm->handleError();
     }
     $document_type = $data['type'];
     $doctypeid = $document_type->getId();
     // Get the current document type, fieldsets and metadata
     $iOldDocTypeID = $this->oDocument->getDocumentTypeID();
     $fieldsets = KTMetadataUtil::fieldsetsForDocument($this->oDocument, $iOldDocTypeID);
     $mdlist = DocumentFieldLink::getByDocument($this->oDocument);
     $field_values = array();
     foreach ($mdlist as $oFieldLink) {
         $field_values[$oFieldLink->getDocumentFieldID()] = $oFieldLink->getValue();
     }
     DBUtil::startTransaction();
     // Update the document with the new document type id
     $this->oDocument->startNewMetadataVersion($this->oUser);
     $this->oDocument->setDocumentTypeId($doctypeid);
     $res = $this->oDocument->update();
     if (PEAR::isError($res)) {
         DBUtil::rollback();
         return $res;
     }
     // Ensure all values for fieldsets common to both document types are retained
     $fs_ids = array();
     $doctype_fieldsets = KTFieldSet::getForDocumentType($doctypeid);
     foreach ($doctype_fieldsets as $fieldset) {
         $fs_ids[] = $fieldset->getId();
     }
     $MDPack = array();
     foreach ($fieldsets as $oFieldset) {
         if ($oFieldset->getIsGeneric() || in_array($oFieldset->getId(), $fs_ids)) {
             $fields = $oFieldset->getFields();
             foreach ($fields as $oField) {
                 $val = isset($field_values[$oField->getId()]) ? $field_values[$oField->getId()] : '';
                 if (!empty($val)) {
                     $MDPack[] = array($oField, $val);
                 }
             }
         }
     }
     $core_res = KTDocumentUtil::saveMetadata($this->oDocument, $MDPack, array('novalidate' => true));
     if (PEAR::isError($core_res)) {
         DBUtil::rollback();
         return $core_res;
     }
     DBUtil::commit();
     $oKTTriggerRegistry = KTTriggerRegistry::getSingleton();
     $aTriggers = $oKTTriggerRegistry->getTriggers('edit', 'postValidate');
     foreach ($aTriggers as $aTrigger) {
         $sTrigger = $aTrigger[0];
         $oTrigger = new $sTrigger();
         $aInfo = array("document" => $this->oDocument, "aOptions" => $MDPack);
         $oTrigger->setInfo($aInfo);
         $ret = $oTrigger->postValidate();
     }
     // Check if there are any dynamic conditions / permissions that need to be updated on the document
     // If there are dynamic conditions then update the permissions on the document
     // The dynamic condition test fails unless the changes exists in the DB therefore update permissions after committing the transaction.
     $iPermissionObjectId = $this->oDocument->getPermissionObjectID();
     $dynamicCondition = KTPermissionDynamicCondition::getByPermissionObjectId($iPermissionObjectId);
     if (!PEAR::isError($dynamicCondition) && !empty($dynamicCondition)) {
         $res = KTPermissionUtil::updatePermissionLookup($this->oDocument);
     }
     $this->successRedirectToMain(sprintf(_kt("You have selected a new document type: %s. "), $data['type']->getName()));
 }
 /**
  * Loop through the queue and archive the items.
  *
  * @return unknown
  */
 public function processQueue()
 {
     global $default;
     // get items from queue
     $queue = $this->getQueue();
     if (PEAR::isError($queue)) {
         $default->log->debug('Download Queue: error on fetching queue - ' . $queue->getMessage());
         return false;
     }
     // Set queue as locked
     touch($this->lockFile);
     // Loop through items and create downloads
     foreach ($queue as $code => $download) {
         // reset the error messages
         $this->errors = null;
         // if the user_id is not set then skip
         if (!isset($download[0]['user_id']) || empty($download[0]['user_id'])) {
             $default->log->debug('Download Queue: no user id set for download code ' . $code);
             $error = array(_kt('No user id has been set, the archive cannot be created.'));
             $result = $this->setItemStatus($code, 3, $error);
             continue;
         }
         // Force a session for the user
         $_SESSION['userID'] = $download[0]['user_id'];
         $baseFolderId = $download[0]['folder_id'];
         // Create a new instance of the archival class
         $zip = new ZipFolder('', $code);
         $res = $zip->checkConvertEncoding();
         if (PEAR::isError($res)) {
             $default->log->error('Download Queue: Archive class check convert encoding error - ' . $res->getMessage());
             $error = array(_kt('The archive cannot be created. An error occurred in the encoding.'));
             $result = $this->setItemStatus($code, 3, $error);
             continue;
         }
         $result = $this->setItemStatus($code, 1);
         if (PEAR::isError($result)) {
             $default->log->error('Download Queue: item status could not be set for user: '******'userID'] . ', code: ' . $code . ', error: ' . $result->getMessage());
         }
         $default->log->debug('Download Queue: Creating download for user: '******'userID'] . ', code: ' . $code);
         DBUtil::startTransaction();
         // Add the individual files and folders into the archive
         foreach ($download as $item) {
             if ($item['object_type'] == 'document') {
                 $docId = $item['object_id'];
                 $this->addDocument($zip, $docId);
             }
             if ($item['object_type'] == 'folder') {
                 $folderId = $item['object_id'];
                 $this->addFolder($zip, $folderId);
             }
         }
         $res = $zip->createZipFile();
         if (PEAR::isError($res)) {
             $default->log->debug('Download Queue: Archive could not be created. Exiting transaction. ' . $res->getMessage());
             DBUtil::rollback();
             $error = array(_kt('The archive could not be created.'));
             $result = $this->setItemStatus($code, 3, $error);
             continue;
         }
         $default->log->debug('Download Queue: Archival successful');
         $oTransaction = KTFolderTransaction::createFromArray(array('folderid' => $baseFolderId, 'comment' => "Bulk export", 'transactionNS' => 'ktstandard.transactions.bulk_export', 'userid' => $_SESSION['userID'], 'ip' => Session::getClientIP()));
         if (PEAR::isError($oTransaction)) {
             $default->log->debug('Download Queue: transaction could not be logged. ' . $oTransaction->getMessage());
         }
         DBUtil::commit();
         // Set status for the download
         $this->errors['archive'] = $_SESSION['zipcompression'];
         $result = $this->setItemStatus($code, 2, $this->errors);
         if (PEAR::isError($result)) {
             $default->log->error('Download Queue: item status could not be set for user: '******'userID'] . ', code: ' . $code . ', error: ' . $result->getMessage());
         }
         // reset the error messages
         $this->errors = null;
         $_SESSION['zipcompression'] = null;
     }
     // Remove lock file
     @unlink($this->lockFile);
 }
 /**
  * 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();
 }
 /**
  * Bulk archives a list of folders and/or documents
  *
  * <code>
  * $ktapi = new KTAPI();
  * $session = $ktapi->start_system_session();
  * $document = $ktapi->get_document_by_id($documentid);
  * $folder = $ktapi->get_folder_by_name('New test folder');
  *
  * $aItems = array($document, $folder);
  * $bulk = new KTAPI_BulkActions($ktapi)
  * $res = $bulk->archive($aItems, 'Bulk archive');
  *
  * // if documents / folders failed
  * if(!empty($res)) {
  *     // display reason for documents failure
  *     foreach($res['docs'] as $failedDoc){
  *         echo '<br>' . $failedDoc['object']->get_title() . ' - reason: '.$failedDoc['reason'];
  *     }
  *     // display reason for folders failure
  *     foreach($res['folders'] as $failedDoc){
  *         echo '<br>' . $failedFolder['object']->get_folder_name() . ' - reason: '.$failedFolder['reason'];
  *     }
  * }
  * </code>
  *
  * @author KnowledgeTree Team
  * @access public
  * @param array $items The folders and/or documents
  * @param string $reason The reason for performing the archival
  * @return void|PEAR_Error Nothing on success | PEAR_Error on failure
  */
 function archive($items, $reason)
 {
     if (empty($items)) {
         return;
     }
     if (!is_array($items)) {
         $items = array($items);
     }
     // Archive the document or folder
     // Items that fail are returned in an array with the reason for failure.
     $failed = array();
     foreach ($items as $item) {
         // Documents
         if ($item instanceof KTAPI_Document) {
             $res = $item->archive($reason);
             if (PEAR::isError($res)) {
                 $failed['docs'][] = array('object' => $item, 'reason' => $res->getMessage());
                 continue;
             }
         } else {
             if ($item instanceof KTAPI_Folder) {
                 // Folders - need to recurse in
                 DBUtil::startTransaction();
                 $res = $this->recurseFolder($item, $reason, 'archive');
                 if (PEAR::isError($res)) {
                     DBUtil::rollback();
                     $failed['folders'][] = array('object' => $item, 'reason' => $res->getMessage());
                     continue;
                 }
                 DBUtil::commit();
             }
         }
     }
     return $failed;
 }
 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;
 }
 function startTransaction()
 {
     DBUtil::startTransaction();
     $this->bTransactionStarted = true;
 }
 /**
  * applies queries to the database
  * @return
  * @param $filename Object
  */
 function applySQL($filename)
 {
     global $default;
     DBUtil::setupAdminDatabase();
     $db = $default->_admindb;
     $content = file_get_contents($filename);
     $aQueries = SQLFile::splitSQL($content);
     DBUtil::startTransaction();
     foreach ($aQueries as $sQuery) {
         $res = DBUtil::runQuery($sQuery, $db);
         if (PEAR::isError($res)) {
             continue;
         }
     }
     DBUtil::commit();
 }
 /**
  * Load the plugins for the current page
  *
  * @param unknown_type $sType
  */
 static function loadPlugins($sType)
 {
     // Check the current page - can be extended.
     // Currently we only distinguish between the dashboard and everything else.
     if ($sType != 'dashboard') {
         $sType = 'general';
     }
     $aPlugins = array();
     $aPluginHelpers = array();
     $aDisabled = array();
     // Get the list of enabled plugins
     $query = "SELECT h.classname, h.pathname, h.plugin FROM plugin_helper h\n            INNER JOIN plugins p ON (p.namespace = h.plugin)\n           WHERE p.disabled = 0 AND h.classtype='plugin' ORDER BY p.orderby";
     $aPluginHelpers = DBUtil::getResultArray($query);
     if (PEAR::isError($aPluginHelpers)) {
         global $default;
         $default->log->debug('Error in pluginutil: ' . $aPluginHelpers->getMessage());
         return false;
     }
     // Check that there are plugins and if not, register them
     if (empty($aPluginHelpers) || isset($_POST['_force_plugin_truncate'])) {
         DBUtil::startTransaction();
         KTPluginUtil::registerPlugins();
         DBUtil::commit();
         $query = "SELECT h.classname, h.pathname, h.plugin FROM plugin_helper h\n        \t   INNER JOIN plugins p ON (p.namespace = h.plugin)\n        \t   WHERE p.disabled = 0 AND h.classtype='plugin' ORDER BY p.orderby";
         $aPluginHelpers = DBUtil::getResultArray($query);
     }
     // Create plugin objects
     foreach ($aPluginHelpers as $aItem) {
         $classname = $aItem['classname'];
         $path = $aItem['pathname'];
         if (!empty($path)) {
             $path = KT_DIR . '/' . $path;
             require_once $path;
             $oPlugin = new $classname($path);
             if ($oPlugin->load()) {
                 $aPlugins[] = $oPlugin;
             } else {
                 $aDisabled[] = "'{$aItem['plugin']}'";
             }
         }
     }
     $sDisabled = implode(',', $aDisabled);
     // load plugin helpers into global space
     $query = 'SELECT h.* FROM plugin_helper h
         INNER JOIN plugins p ON (p.namespace = h.plugin)
     	WHERE p.disabled = 0 ';
     //WHERE viewtype='{$sType}'";
     if (!empty($sDisabled)) {
         $query .= " AND h.plugin NOT IN ({$sDisabled}) ";
     }
     $query .= ' ORDER BY p.orderby';
     $aPluginList = DBUtil::getResultArray($query);
     KTPluginUtil::load($aPluginList);
     // Load the template locations - ignore disabled plugins
     // Allow for templates that don't correctly link to the plugin
     $query = "SELECT * FROM plugin_helper h\n            LEFT JOIN plugins p ON (p.namespace = h.plugin)\n            WHERE h.classtype='locations' AND (disabled = 0 OR disabled IS NULL) AND unavailable = 0";
     $aLocations = DBUtil::getResultArray($query);
     if (!empty($aLocations)) {
         $oTemplating =& KTTemplating::getSingleton();
         foreach ($aLocations as $location) {
             $aParams = explode('|', $location['object']);
             call_user_func_array(array(&$oTemplating, 'addLocation2'), $aParams);
         }
     }
     return true;
 }
 /**
  * This tells the manager to manage a file that has been uploaded.
  *
  * @param string $filename
  * @param string $tempfile
  * @param string $action
  */
 function uploaded($filename, $tempfile, $action, $relatedid = null)
 {
     $filename = basename($filename);
     $now = date('Y-m-d H:i:s');
     $now_str = date('YmdHis');
     // Ensure the temp directory exists otherwise an error is thrown.
     if (realpath($this->temp_dir) == FALSE) {
         mkdir($this->temp_dir, 0777, true);
     }
     $newtempfile = realpath($this->temp_dir) . '/' . $_SESSION['userID'] . '-' . $now_str;
     if (OS_WINDOWS) {
         $tempfile = str_replace('/', '\\', $tempfile);
         $newtempfile = str_replace('\\', '/', $newtempfile);
     }
     DBUtil::startTransaction();
     $id = DBUtil::autoInsert('uploaded_files', array('tempfilename' => $newtempfile, 'filename' => $filename, 'userid' => $_SESSION['userID'], 'uploaddate' => $now, 'action' => $action), array('noid' => true));
     if (PEAR::isError($id)) {
         DBUtil::rollback();
         return $id;
     }
     global $php_errormsg;
     if (is_uploaded_file($tempfile)) {
         $result = @move_uploaded_file($tempfile, $newtempfile);
     } else {
         $result = @rename($tempfile, $newtempfile);
     }
     $tmp = $php_errormsg;
     if ($result == false) {
         DBUtil::rollback();
         return new PEAR_Error($tmp);
     }
     DBUtil::commit();
     return $newtempfile;
 }
 /**
  * This copies a folder to another location.
  *
  * <code>
  * $root = $this->ktapi->get_root_folder();
  * $folder = $root->add_folder("Test folder");
  * $new_folder = $root->add_folder("New test folder");
  * $res = $folder->copy($new_folder, "Test copy");
  * </code>
  *
  * @author KnowledgeTree Team
  * @access public
  * @param KTAPI_Folder $ktapi_target_folder
  * @param string $reason
  */
 function copy($ktapi_target_folder, $reason = '')
 {
     assert(!is_null($ktapi_target_folder));
     assert(is_a($ktapi_target_folder, 'KTAPI_Folder'));
     $user = $this->ktapi->get_user();
     $target_folder = $ktapi_target_folder->get_folder();
     $result = $this->can_user_access_object_requiring_permission($target_folder, KTAPI_PERMISSION_WRITE);
     if (PEAR::isError($result)) {
         return $result;
     }
     DBUtil::startTransaction();
     $result = KTFolderUtil::copy($this->folder, $target_folder, $user, $reason);
     if (PEAR::isError($result)) {
         DBUtil::rollback();
         return new KTAPI_Error(KTAPI_ERROR_INTERNAL_ERROR, $result);
     }
     DBUtil::commit();
 }
 /**
  * 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();
 }
Exemple #15
0
 function do_import()
 {
     set_time_limit(0);
     $aErrorOptions = array('redirect_to' => array('main', sprintf('fFolderId=%d', $this->oFolder->getId())));
     $aErrorOptions['message'] = _kt('Invalid document type provided');
     $oDocumentType = $this->oValidator->validateDocumentType($_REQUEST['fDocumentTypeId'], $aErrorOptions);
     $aErrorOptions['message'] = _kt('Invalid path provided');
     $sPath = $this->oValidator->validateString($_REQUEST['path'], $aErrorOptions);
     $matches = array();
     $aFields = array();
     foreach ($_REQUEST as $k => $v) {
         if (preg_match('/^metadata_(\\d+)$/', $k, $matches)) {
             $aFields[] = array(DocumentField::get($matches[1]), $v);
         }
     }
     $aOptions = array('documenttype' => $oDocumentType, 'metadata' => $aFields, 'copy_upload' => 'true');
     $po =& new JavascriptObserver($this);
     $po->start();
     $oUploadChannel =& KTUploadChannel::getSingleton();
     $oUploadChannel->addObserver($po);
     $fs =& new KTFSImportStorage($sPath);
     $bm =& new KTBulkImportManager($this->oFolder, $fs, $this->oUser, $aOptions);
     DBUtil::startTransaction();
     $res = $bm->import();
     if (PEAR::isError($res)) {
         DBUtil::rollback();
         $_SESSION["KTErrorMessage"][] = _kt("Bulk import failed") . ": " . $res->getMessage();
     } else {
         DBUtil::commit();
         $this->addInfoMessage(_kt("Bulk import succeeded"));
     }
     $po->redirectToFolder($this->oFolder->getId());
     exit(0);
 }
Exemple #16
0
 /**
  * Performs actual import action. | iNET Process
  * @Return.
  * @param.
  */
 function do_import()
 {
     set_time_limit(0);
     $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);
     $aErrorOptions['message'] = _kt('Invalid path provided');
     $tmpPath = $_REQUEST['path'];
     //Backwards compatibility
     if ($tmpPath == '') {
         $tmpPath = $_REQUEST['data'];
         $tmpPath = $tmpPath['path'];
     }
     $sPath = $this->oValidator->validateString($tmpPath, $aErrorOptions);
     /*
             $matches = array();
             $aFields = array();
             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
                 }
             }
     
             $aOptions = array(
                 'documenttype' => $oDocumentType,
                 'metadata' => $aFields,
                 'copy_upload' => 'true',
             );
     */
     // Newer metadata form field catcher that works with ktcore form array type fields named like
     // name='metadata[fieldset][metadata_9]'
     $aData = $_REQUEST['data'];
     $data = $aData;
     /*
     		$oForm = $this->getBulkImportForm();
     $res = $oForm->validate();
     if (!empty($res['errors'])) {
         return $oForm->handleError();
     }
     $data = $res['results'];
     */
     $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());
         foreach ($fields as $oField) {
             $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, 'copy_upload' => 'true');
     $po =& new JavascriptObserver($this);
     $po->start();
     $oUploadChannel =& KTUploadChannel::getSingleton();
     $oUploadChannel->addObserver($po);
     $fs =& new KTFSImportStorage($sPath);
     $bm =& new KTBulkImportManager($this->oFolder, $fs, $this->oUser, $aOptions);
     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);
     }
     DBUtil::startTransaction();
     $res = $bm->import();
     if (PEAR::isError($res)) {
         DBUtil::rollback();
         $_SESSION["KTErrorMessage"][] = _kt("Bulk import failed") . ": " . $res->getMessage();
     } else {
         DBUtil::commit();
         $this->addInfoMessage(_kt("Bulk import succeeded"));
     }
     $po->redirectToFolder($this->oFolder->getId());
     exit(0);
 }