function saveTransitionSources($oTransition, $aStateIds)
 {
     $sTable = KTUtil::getTableName('workflow_state_transitions');
     $aQuery = array("DELETE FROM {$sTable} WHERE transition_id = ?", array($oTransition->getId()));
     $res = DBUtil::runQuery($aQuery);
     if (PEAR::isError($res)) {
         return $res;
     }
     $aOptions = array('noid' => true);
     if (empty($aStateIds)) {
         return;
         // don't fail if there are no transitions.
     }
     foreach ($aStateIds as $iStateId) {
         $res = DBUtil::autoInsert($sTable, array('state_id' => $iStateId, 'transition_id' => $oTransition->getId()), $aOptions);
         if (PEAR::isError($res)) {
             return $res;
         }
     }
     return;
 }
예제 #2
0
 function createFeed($sFeedTitle, $sFeedUrl, $iUserId)
 {
     $aParams = array('user_id' => $iUserId, 'url' => $sFeedUrl, 'title' => $sFeedTitle);
     $res = DBUtil::autoInsert('plugin_rss', $aParams);
     return $res;
 }
예제 #3
0
 /**
  * Register the plugin in the DB
  *
  * @param unknown_type $sClassName
  * @param unknown_type $path
  * @param unknown_type $object
  * @param unknown_type $type
  */
 function registerPluginHelper($sNamespace, $sClassName, $path, $object, $view, $type)
 {
     $sql = "SELECT id FROM plugin_helper WHERE namespace = '{$sNamespace}' AND classtype = '{$type}'";
     $res = DBUtil::getOneResult($sql);
     $aValues = array();
     $aValues['namespace'] = $sNamespace;
     $aValues['plugin'] = !empty($this->sNamespace) ? $this->sNamespace : $sNamespace;
     $aValues['classname'] = $sClassName;
     $aValues['pathname'] = $path;
     $aValues['object'] = $object;
     $aValues['viewtype'] = $view;
     $aValues['classtype'] = $type;
     // if record exists - update it.
     if (!empty($res)) {
         $id = $res['id'];
         $updateRes = DBUtil::autoUpdate('plugin_helper', $aValues, $id);
         if (PEAR::isError($updateRes)) {
             return $updateRes;
         }
         return true;
     }
     // Insert into DB
     $res = DBUtil::autoInsert('plugin_helper', $aValues);
     if (PEAR::isError($res)) {
         return $res;
     }
     return true;
 }
 function saveAssignment($aPermissions)
 {
     $sTable = KTUtil::getTableName('permission_dynamic_assignments');
     $aQuery = array("DELETE FROM {$sTable} WHERE dynamic_condition_id = ?", array($this->getId()));
     $res = DBUtil::runQuery($aQuery);
     if (PEAR::isError($res)) {
         return $res;
     }
     $aInsertOptions = array('noid' => true);
     foreach ($aPermissions as $oPermission) {
         $iPermissionId = KTUtil::getId($oPermission);
         $aInsert = array('dynamic_condition_id' => $this->getId(), 'permission_id' => $iPermissionId);
         $res = DBUtil::autoInsert($sTable, $aInsert, $aInsertOptions);
         if (PEAR::isError($res)) {
             return $res;
         }
     }
 }
예제 #5
0
 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();
 }
예제 #6
0
 * details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * You can contact KnowledgeTree Inc., PO Box 7775 #87847, San Francisco, 
 * California 94120-7775, or email info@knowledgetree.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * KnowledgeTree" logo and retain the original copyright notice. If the display of the 
 * logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
 * must display the words "Powered by KnowledgeTree" and retain the original 
 * copyright notice.
 * Contributor( s): ______________________________________
 *
 */
$checkup = true;
require_once '../../config/dmsDefaults.php';
$s = array("sql*2.99.5*0*2.99.5/dashlet_disabling.sql", "sql*2.99.5*0*2.99.5/role_allocations.sql", "sql*2.99.5*0*2.99.5/transaction_namespaces.sql", "sql*2.99.5*0*2.99.5/fieldset_field_descriptions.sql", "sql*2.99.5*0*2.99.5/role_changes.sql");
$sTable = KTUtil::getTableName('upgrades');
foreach ($s as $u) {
    var_dump($u);
    $f = array('descriptor' => $u, 'result' => true);
    $res = DBUtil::autoInsert($sTable, $f);
    var_dump($res);
}
예제 #7
0
 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;
 }
예제 #8
0
 function setDisabledActionsForState($oState, $aActions)
 {
     $iStateId = KTUtil::getId($oState);
     $sTable = KTUtil::getTableName('workflow_state_disabled_actions');
     $aQuery = array("DELETE FROM {$sTable} WHERE state_id = ?", array($iStateId));
     $res = DBUtil::runQuery($aQuery);
     if (PEAR::isError($res)) {
         return $res;
     }
     if (!is_array($aActions)) {
         return;
     }
     $aOptions = array('noid' => true);
     foreach ($aActions as $sAction) {
         $res = DBUtil::autoInsert($sTable, array('state_id' => $iStateId, 'action_name' => $sAction), $aOptions);
         if (PEAR::isError($res)) {
             return $res;
         }
     }
     return;
 }
 /**
  * This returns
  *
  * @access public
  * @param KTAPI_Document $document
  * @return string
  */
 function allow_download($document, $content_version = null, $multipart = false)
 {
     assert(!is_null($document));
     $content_version = 0;
     $filesize = 0;
     if ($document instanceof KTAPI_Document) {
         $doc_id = $document->documentid;
         $content_version = $document->document->getContentVersionId();
         $filesize = $document->document->getFileSize();
     } else {
         if ($document instanceof Document || $document instanceof DocumentProxy) {
             $doc_id = $document->getId();
             $content_version = $document->getContentVersionId();
             $filesize = $document->getFileSize();
         } else {
             if (is_numeric($document)) {
                 $doc_id = $document;
             } else {
                 die('gracefully');
             }
         }
     }
     //assert(is_a($document, 'KTAPI_Document'));
     $hash = sha1("{$doc_id} {$this->session} {$this->random}");
     $id = DBUtil::autoInsert('download_files', array('document_id' => $doc_id, 'session' => $this->session, 'download_date' => date('Y-m-d H:i:s'), 'content_version' => $content_version, 'filesize' => $filesize, 'hash' => $hash), array('noid' => true));
     return $multipart ? $this->build_multipart_url($hash, $doc_id) : $this->build_url($hash, $doc_id);
 }
예제 #10
0
 /**
  * This associates all the mime types associated with the extractor class.
  *
  */
 public function registerMimeTypes()
 {
     $types = $this->getSupportedMimeTypes();
     if (empty($types)) {
         return;
     }
     $classname = get_class($this);
     $sql = "select id as extractor_id from mime_extractors WHERE name='{$classname}'";
     $rs = DBUtil::getResultArray($sql);
     if (count($rs) == 0) {
         $extractor_id = DBUtil::autoInsert('mime_extractors', array('name' => $classname, 'active' => 1));
     } else {
         $extractor_id = $rs[0]['extractor_id'];
     }
     foreach ($types as $type) {
         $sql = "update mime_types set extractor_id={$extractor_id} where mimetypes='{$type}' and extractor_id is null";
         $rs = DBUtil::runQuery($sql);
     }
 }
 function do_storeRelationship()
 {
     // handle the store, and DON'T give a 500 ;)  does not act on the information.
     global $default;
     $default->log->error(http_build_query($_REQUEST));
     $iFieldsetId = KTUtil::arrayGet($_REQUEST, 'fieldset_id');
     $parent_field = KTUtil::arrayGet($_REQUEST, 'parent_field');
     $parent_lookup = KTUtil::arrayGet($_REQUEST, 'parent_lookup');
     $child_lookups = KTUtil::arrayGet($_REQUEST, 'child_lookups');
     // child lookups is a nested array. in python it would be:
     // child_lookups =
     //  {
     //     field_id:[lookup_id, lookup_id],
     //     field_id:[lookup_id, lookup_id],
     //  }
     $oFieldset =& KTFieldset::get($iFieldsetId);
     $oFieldset->setIsComplete(false);
     $oFieldset->update();
     $oParentInstance = KTMetadataUtil::getOrCreateValueInstanceForLookup($parent_lookup);
     $iBehaviourId = $oParentInstance->getBehaviourId();
     $oParentMetadata =& MetaData::get($oParentInstance->getFieldValueId());
     if (is_null($iBehaviourId)) {
         $oBehaviour =& KTFieldBehaviour::createFromArray(array('name' => 'autoinstance' . $oParentInstance->getId(), 'humanname' => 'Auto instance' . $oParentMetadata->getName(), 'fieldid' => $oParentInstance->getFieldId()));
     } else {
         $oBehaviour =& KTFieldBehaviour::get($iBehaviourId);
     }
     if (PEAR::isError($oBehaviour)) {
         var_dump($oBehaviour);
         return $oBehaviour;
     }
     $iBehaviourId = $oBehaviour->getId();
     $oParentInstance->setBehaviourId($iBehaviourId);
     $oParentInstance->update();
     $sTable = KTUtil::getTableName('field_behaviour_options');
     $aOptions = array('noid' => true);
     $aQuery = array("DELETE FROM {$sTable} WHERE behaviour_id = ?", array($iBehaviourId));
     $res = DBUtil::runQuery($aQuery);
     foreach ($child_lookups as $iFieldId => $aLookups) {
         foreach ($aLookups as $iLookupId) {
             $oValueInstance =& KTMetadataUtil::getOrCreateValueInstanceForLookup($iLookupId);
             if (PEAR::isError($oValueInstance)) {
                 var_dump($oValueInstance);
                 return $oValueInstance;
             }
             $res = DBUtil::autoInsert($sTable, array('behaviour_id' => $iBehaviourId, 'field_id' => $iFieldId, 'instance_id' => $oValueInstance->getId()), $aOptions);
             if (PEAR::isError($res)) {
                 var_dump($res);
                 return $res;
             }
         }
     }
 }
예제 #12
0
 function do_allocate()
 {
     $fWorkflowId = KTUtil::arrayGet($_REQUEST, 'fWorkflowId', null);
     $this->startTransaction();
     $sQuery = 'DELETE FROM ' . KTUtil::getTableName('folder_workflow_map') . ' WHERE folder_id = ?';
     $aParams = array($this->oFolder->getId());
     DBUtil::runQuery(array($sQuery, $aParams));
     if (is_null($fWorkflowId)) {
         $this->successRedirectToMain(_kt('Workflow assignment removed.'), 'fFolderId=' . $this->oFolder->getId());
     }
     $aOptions = array('noid' => true);
     $sTable = KTUtil::getTableName('folder_workflow_map');
     if ($fWorkflowId == null) {
         $fWorkflowId = null;
     }
     $res = DBUtil::autoInsert($sTable, array('folder_id' => $this->oFolder->getId(), 'workflow_id' => $fWorkflowId), $aOptions);
     if (PEAR::isError($res)) {
         $this->errorRedirectToMain(_kt('Error assigning workflow.'), 'fFolderId=' . $this->oFolder->getId());
     }
     $this->successRedirectToMain(_kt('Workflow assignment updated.'), 'fFolderId=' . $this->oFolder->getId());
 }
예제 #13
0
 function copy($oDocument, $oDestinationFolder, $sReason = null, $sDestinationDocName = null)
 {
     // 1. generate a new triad of content, metadata and core objects.
     // 2. update the storage path.
     //print '--------------------------------- BEFORE';
     //print_r($oDocument);
     // TODO: this is not optimal. we have get() functions that will do SELECT when we already have the data in arrays
     // get the core record to be copied
     $sDocumentTable = KTUtil::getTableName('documents');
     $sQuery = 'SELECT * FROM ' . $sDocumentTable . ' WHERE id = ?';
     $aParams = array($oDocument->getId());
     $aCoreRow = DBUtil::getOneResult(array($sQuery, $aParams));
     // we unset the id as a new one will be created on insert
     unset($aCoreRow['id']);
     // get a copy of the latest metadata version for the copied document
     $iOldMetadataId = $aCoreRow['metadata_version_id'];
     $sMetadataTable = KTUtil::getTableName('document_metadata_version');
     $sQuery = 'SELECT * FROM ' . $sMetadataTable . ' WHERE id = ?';
     $aParams = array($iOldMetadataId);
     $aMDRow = DBUtil::getOneResult(array($sQuery, $aParams));
     // we unset the id as a new one will be created on insert
     unset($aMDRow['id']);
     // set the name for the document, possibly using name collission
     if (empty($sDestinationDocName)) {
         $aMDRow['name'] = KTDocumentUtil::getUniqueDocumentName($oDestinationFolder, $aMDRow['name']);
     } else {
         $aMDRow['name'] = $sDestinationDocName;
     }
     // get a copy of the latest content version for the copied document
     $iOldContentId = $aMDRow['content_version_id'];
     $sContentTable = KTUtil::getTableName('document_content_version');
     $sQuery = 'SELECT * FROM ' . $sContentTable . ' WHERE id = ?';
     $aParams = array($iOldContentId);
     $aContentRow = DBUtil::getOneResult(array($sQuery, $aParams));
     // we unset the id as a new one will be created on insert
     unset($aContentRow['id']);
     // set the filename for the document, possibly using name collission
     if (empty($sDestinationDocName)) {
         $aContentRow['filename'] = KTDocumentUtil::getUniqueFilename($oDestinationFolder, $aContentRow['filename']);
     } else {
         $aContentRow['filename'] = $sDestinationDocName;
     }
     // create the new document record
     $aCoreRow['modified'] = date('Y-m-d H:i:s');
     $aCoreRow['folder_id'] = $oDestinationFolder->getId();
     // new location.
     $id = DBUtil::autoInsert($sDocumentTable, $aCoreRow);
     if (PEAR::isError($id)) {
         return $id;
     }
     $iNewDocumentId = $id;
     // create the new metadata record
     $aMDRow['document_id'] = $iNewDocumentId;
     $aMDRow['description'] = $aMDRow['name'];
     $id = DBUtil::autoInsert($sMetadataTable, $aMDRow);
     if (PEAR::isError($id)) {
         return $id;
     }
     $iNewMetadataId = $id;
     // the document metadata version is still pointing to the original
     $aCoreUpdate = array();
     $aCoreUpdate['metadata_version_id'] = $iNewMetadataId;
     $aCoreUpdate['metadata_version'] = 0;
     // create the new content version
     $aContentRow['document_id'] = $iNewDocumentId;
     $id = DBUtil::autoInsert($sContentTable, $aContentRow);
     if (PEAR::isError($id)) {
         return $id;
     }
     $iNewContentId = $id;
     // the metadata content version is still pointing to the original
     $aMetadataUpdate = array();
     $aMetadataUpdate['content_version_id'] = $iNewContentId;
     $aMetadataUpdate['metadata_version'] = 0;
     // apply the updates to the document and metadata records
     $res = DBUtil::autoUpdate($sDocumentTable, $aCoreUpdate, $iNewDocumentId);
     if (PEAR::isError($res)) {
         return $res;
     }
     $res = DBUtil::autoUpdate($sMetadataTable, $aMetadataUpdate, $iNewMetadataId);
     if (PEAR::isError($res)) {
         return $res;
     }
     // now, we have a semi-sane document object. get it.
     $oNewDocument = Document::get($iNewDocumentId);
     //print '--------------------------------- AFTER';
     //print_r($oDocument);
     //print '======';
     //print_r($oNewDocument);
     // copy the metadata from old to new.
     $res = KTDocumentUtil::copyMetadata($oNewDocument, $iOldMetadataId);
     if (PEAR::isError($res)) {
         return $res;
     }
     // Ensure the copied document is not checked out
     $oNewDocument->setIsCheckedOut(false);
     $oNewDocument->setCheckedOutUserID(-1);
     // finally, copy the actual file.
     $oStorage =& KTStorageManagerUtil::getSingleton();
     $res = $oStorage->copy($oDocument, $oNewDocument);
     $oOriginalFolder = Folder::get($oDocument->getFolderId());
     $iOriginalFolderPermissionObjectId = $oOriginalFolder->getPermissionObjectId();
     $iDocumentPermissionObjectId = $oDocument->getPermissionObjectId();
     if ($iDocumentPermissionObjectId === $iOriginalFolderPermissionObjectId) {
         $oNewDocument->setPermissionObjectId($oDestinationFolder->getPermissionObjectId());
     }
     $res = $oNewDocument->update();
     if (PEAR::isError($res)) {
         return $res;
     }
     KTPermissionUtil::updatePermissionLookup($oNewDocument);
     if (is_null($sReason)) {
         $sReason = '';
     }
     $oDocumentTransaction = new DocumentTransaction($oDocument, sprintf(_kt("Copied to folder \"%s\". %s"), $oDestinationFolder->getName(), $sReason), 'ktcore.transactions.copy');
     $oDocumentTransaction->create();
     $oSrcFolder = Folder::get($oDocument->getFolderID());
     $oDocumentTransaction = new DocumentTransaction($oNewDocument, sprintf(_kt("Copied from original in folder \"%s\". %s"), $oSrcFolder->getName(), $sReason), 'ktcore.transactions.copy');
     $oDocumentTransaction->create();
     $oKTTriggerRegistry = KTTriggerRegistry::getSingleton();
     $aTriggers = $oKTTriggerRegistry->getTriggers('copyDocument', 'postValidate');
     foreach ($aTriggers as $aTrigger) {
         $sTrigger = $aTrigger[0];
         $oTrigger = new $sTrigger();
         $aInfo = array('document' => $oNewDocument, 'old_folder' => $oSrcFolder, 'new_folder' => $oDestinationFolder);
         $oTrigger->setInfo($aInfo);
         $ret = $oTrigger->postValidate();
         if (PEAR::isError($ret)) {
             return $ret;
         }
     }
     // fire subscription alerts for the copied document
     $oSubscriptionEvent = new SubscriptionEvent();
     $oFolder = Folder::get($oDocument->getFolderID());
     $oSubscriptionEvent->MoveDocument($oDocument, $oDestinationFolder, $oSrcFolder, 'CopiedDocument');
     return $oNewDocument;
 }
 function do_useBehaviourAndAssign()
 {
     $parent_behaviour = KTUtil::arrayGet($_REQUEST, 'parent_behaviour');
     $fieldset_id = KTUtil::arrayGet($_REQUEST, 'fieldset_id');
     $field_id = KTUtil::arrayGet($_REQUEST, 'field_id');
     $behaviour_id = KTUtil::arrayGet($_REQUEST, 'behaviour_id');
     $lookups_to_assign = KTUtil::arrayGet($_REQUEST, 'lookups_to_assign');
     // array
     $oBehaviour =& $this->oValidator->validateBehaviour($behaviour_id);
     $aValueInstanceIds = array();
     foreach ($lookups_to_assign as $iLookupId) {
         $res = $oValueInstance =& KTValueInstance::createFromArray(array('fieldid' => $field_id, 'behaviourid' => $oBehaviour->getId(), 'fieldvalueid' => abs($iLookupId)));
         $aValueInstanceIds[] = $res->getId();
     }
     if ($parent_behaviour) {
         $oParentBehaviour =& $this->oValidator->validateBehaviour($parent_behaviour);
         $sTable = KTUtil::getTableName('field_behaviour_options');
         $aOptions = array('noid' => true);
         foreach ($aValueInstanceIds as $iId) {
             $res = DBUtil::autoInsert($sTable, array('behaviour_id' => $oParentBehaviour->getId(), 'field_id' => $field_id, 'instance_id' => $iId), $aOptions);
         }
     }
     header('Content-type: application/xml');
     $oTemplating =& KTTemplating::getSingleton();
     $oTemplate =& $oTemplating->loadTemplate('ktcore/metadata/conditional/ajax_complex_use_behaviour_and_assign');
     return $oTemplate->render();
 }
예제 #15
0
 /**
  * Checks whether a session exists for the given user and creates a new one or updates the existing one.
  *
  * @author KnowledgeTree Team
  * @access protected
  * @static
  * @param User $user The User object
  * @param int $ip The users IP address
  * @param string $app The originating application type - ws => webservices | webapp => web application | webdav
  * @return array|PEAR_Error Returns the session string and session id (DB) | a PEAR_Error on failure
  */
 function _check_session(&$user, $ip, $app)
 {
     $user_id = $user->getId();
     Session::removeStaleSessions($user_id);
     $config =& KTConfig::getSingleton();
     $validateSession = $config->get('webservice/validateSessionCount', false);
     if ($validateSession) {
         $sql = "SELECT count(*) >= u.max_sessions as over_limit FROM active_sessions ass INNER JOIN users u ON ass.user_id=u.id WHERE ass.user_id = {$user_id} AND ass.apptype != 'ws'";
         $row = DBUtil::getOneResult($sql);
         if (PEAR::isError($row)) {
             return $row;
         }
         if (is_null($row)) {
             return new PEAR_Error('No record found for user?');
         }
         if ($row['over_limit'] + 0 == 1) {
             return new PEAR_Error('Session limit exceeded. Logout of any active sessions.');
         }
     }
     $session = session_id();
     $newSessionRequired = false;
     if ($app == 'ws') {
         $sql = "select id from active_sessions where user_id={$user_id} AND apptype='ws' and ip='{$ip}'";
         $row = DBUtil::getOneResult($sql);
         if (empty($row)) {
             $newSessionRequired = true;
         } else {
             $sessionid = $row['id'];
             $sql = "update active_sessions set session_id='{$session}' where id={$sessionid}";
             DBUtil::runQuery($sql);
         }
     } else {
         $newSessionRequired = true;
     }
     if ($newSessionRequired) {
         $sessionid = DBUtil::autoInsert('active_sessions', array('user_id' => $user_id, 'session_id' => session_id(), 'lastused' => date('Y-m-d H:i:s'), 'ip' => $ip, 'apptype' => $app));
         if (PEAR::isError($sessionid)) {
             return $sessionid;
         }
     }
     return array($session, $sessionid);
 }
예제 #16
0
 /**
  * postValidate method for trigger
  *
  * @return unknown
  */
 function postValidate()
 {
     global $default;
     $oDocument =& $this->aInfo['document'];
     $aMeta =& $this->aInfo['aOptions'];
     // get document id
     $iDocId = $oDocument->getID();
     // get all tags that are linked to the document
     $sQuery = 'SELECT tw.id FROM tag_words AS tw, document_tags AS dt, documents AS d ' . 'WHERE dt.tag_id = tw.id ' . 'AND dt.document_id = d.id ' . 'AND d.id = ?';
     $aParams = array($iDocId);
     $aTagId = DBUtil::getResultArray(array($sQuery, $aParams));
     if (PEAR::isError($aTagId)) {
         // XXX: log error
         return false;
     }
     // if there are any related tags proceed
     if ($aTagId) {
         // delete all entries from document_tags table for the document
         $sQuery = 'DELETE FROM document_tags ' . 'WHERE document_id = ?';
         $aParams = array($iDocId);
         $removed = DBUtil::runQuery(array($sQuery, $aParams));
         if (PEAR::isError($removed)) {
             // XXX: log error
             return false;
         }
     }
     // proceed to add the tags as per normal
     $sQuery = 'SELECT df.id AS id FROM document_fields AS df ' . 'WHERE df.name = \'Tag\'';
     $sTags = DBUtil::getOneResultKey(array($sQuery), 'id');
     if (PEAR::isError($sTags)) {
         // XXX: log error
         return false;
     }
     $tagString = '';
     if ($sTags) {
         // it is actually correct using $aMeta. It is different to the add trigger above...
         if (count($aMeta) > 0) {
             foreach ($aMeta as $aMetaData) {
                 $oProxy = $aMetaData[0];
                 if ($oProxy->iId == $sTags) {
                     $tagString = $aMetaData[1];
                     break;
                 }
             }
         }
         if ($tagString != '') {
             $words_table = KTUtil::getTableName('tag_words');
             $tagString = str_replace('  ', ' ', $tagString);
             $tags = explode(',', $tagString);
             $aTagIds = array();
             foreach ($tags as $sTag) {
                 $sTag = trim($sTag);
                 if (mb_detect_encoding($sTag) == 'ASCII') {
                     $sTag = strtolower($sTag);
                 }
                 $res = DBUtil::getOneResult(array("SELECT id FROM {$words_table} WHERE tag = ?", array($sTag)));
                 if (PEAR::isError($res)) {
                     return $res;
                 }
                 if (is_null($res)) {
                     $id =& DBUtil::autoInsert($words_table, array('tag' => $sTag));
                     $aTagIds[$sTag] = $id;
                 } else {
                     $aTagIds[$sTag] = $res['id'];
                 }
             }
             $doc_tags = KTUtil::getTableName('document_tags');
             foreach ($aTagIds as $sTag => $tagid) {
                 DBUtil::autoInsert($doc_tags, array('document_id' => $iDocId, 'tag_id' => $tagid), array('noid' => true));
             }
         }
     }
 }
예제 #17
0
 function _recordUpgrade($result)
 {
     if (is_null($this->date)) {
         $this->date = getCurrentDateTime();
     }
     if ($this->parent) {
         $parentid = $this->parent->getDescriptor();
     } else {
         $parentid = null;
     }
     return DBUtil::autoInsert("upgrades", array("descriptor" => $this->getDescriptor(), "description" => $this->description, "date_performed" => $this->date, "result" => $result, "parent" => $parentid));
 }
예제 #18
0
 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));
 }
예제 #19
0
 function do_postreply()
 {
     $aErrorOptions = array('redirect_to' => array('main', sprintf('fDocumentId=%d', $this->oDocument->getId())));
     $iThreadId = KTUtil::arrayGet($_REQUEST, 'fThreadId');
     $oThread = DiscussionThread::get($iThreadId);
     $this->oValidator->notError($oThread, $aErrorOptions);
     $aErrorOptions = array('redirect_to' => array('viewthread', sprintf('fDocumentId=%d&fThreadId=%d', $this->oDocument->getId(), $oThread->getId())));
     $aErrorOptions['message'] = _kt("No subject provided");
     $sSubject = KTUtil::arrayGet($_REQUEST, 'subject');
     $sSubject = $this->oValidator->validateString($sSubject, $aErrorOptions);
     $aErrorOptions['message'] = _kt("No body provided");
     $sBody = KTUtil::arrayGet($_REQUEST, 'body');
     $sBody = $this->oValidator->validateString($sBody, $aErrorOptions);
     // Start the transaction comment creation
     $this->startTransaction();
     // Create comment
     $oComment = DiscussionComment::createFromArray(array('threadid' => $oThread->getId(), 'userid' => $this->oUser->getId(), 'subject' => $sSubject, 'body' => KTUtil::formatPlainText($sBody)));
     $aErrorOptions['message'] = _kt("There was an error adding the comment to the thread");
     $this->oValidator->notError($oComment, $aErrorOptions);
     // Update thread
     $oThread->setLastCommentId($oComment->getId());
     $oThread->incrementNumberOfReplies();
     $res = $oThread->update();
     // add to searchable_text.
     $sTable = KTUtil::getTableName('comment_searchable_text');
     $aSearch = array('comment_id' => $oComment->getId(), 'document_id' => $this->oDocument->getId(), 'body' => sprintf("%s %s", KTUtil::formatPlainText($sBody), $sSubject));
     DBUtil::autoInsert($sTable, $aSearch, array('noid' => true));
     $aErrorOptions['message'] = _kt("There was an error updating the thread with the new comment");
     $this->oValidator->notError($res, $aErrorOptions);
     $oKTTriggerRegistry = KTTriggerRegistry::getSingleton();
     $aTriggers = $oKTTriggerRegistry->getTriggers('discussion', 'postValidate');
     foreach ($aTriggers as $aTrigger) {
         $sTrigger = $aTrigger[0];
         $oTrigger = new $sTrigger();
         $aInfo = array("document" => $this->oDocument, "comment" => $oComment);
         $oTrigger->setInfo($aInfo);
         $ret = $oTrigger->postValidate();
         if (PEAR::isError($ret)) {
             $this->oValidator->notError($res, $aErrorOptions);
         }
     }
     // Thread and comment created correctly, commit to database
     $this->commitTransaction();
     $this->successRedirectTo('viewThread', _kt("Reply posted"), sprintf('fDocumentId=%d&fThreadId=%d', $this->oDocument->getId(), $oThread->getId()));
     exit(0);
 }
 /**
  * Add an item to the download queue
  *
  * @param string $code The identification string for the download
  * @param string $id The object id
  * @param string $type The type of object Folder | Document
  */
 public static function addItem($code, $folderId, $id, $type)
 {
     $fields = array();
     $fields['code'] = $code;
     $fields['folder_id'] = $folderId;
     $fields['object_id'] = $id;
     $fields['object_type'] = $type;
     $fields['user_id'] = $_SESSION['userID'];
     $fields['date_added'] = date('Y-m-d H:i:s');
     $res = DBUtil::autoInsert('download_queue', $fields);
 }
예제 #21
0
 /**
  * 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;
 }
예제 #22
0
 /**
  * Informs the system that the parent field's values in affects the
  * child field's values in a conditional fieldset.
  */
 function addFieldOrder($oParentField, $oChildField, $oFieldset)
 {
     $iParentFieldId = KTUtil::getId($oParentField);
     $iChildFieldId = KTUtil::getId($oChildField);
     $iFieldsetId = KTUtil::getId($oFieldset);
     $aOptions = array('noid' => true);
     $sTable = KTUtil::getTableName('field_orders');
     $aValues = array('parent_field_id' => $iParentFieldId, 'child_field_id' => $iChildFieldId, 'fieldset_id' => $iFieldsetId);
     return DBUtil::autoInsert($sTable, $aValues, $aOptions);
 }
예제 #23
0
 /**
  * This method saves the search query to the database
  *
  * @author KnowledgeTree Tean
  * @access public
  * @static
  * @param string $name The name of the saved search query
  * @param string $query The query string
  * @param string $userID The id of the user saving the query
  * @return string|object $result SUCCESS - The id of the record inserted | FAILURE - a pear error object
  */
 public static function saveSavedSearch($name, $query, $userID)
 {
     // autoInsert does escaping...
     $values = array('name' => $name, 'expression' => $query, 'type' => 'S', 'shared' => 0, 'user_id' => $userID);
     $result = DBUtil::autoInsert('search_saved', $values);
     return $result;
 }
예제 #24
0
} else {
    ?>
<p>Database connectivity successful.</p>

<h3>Privileges</h3>
<?php 
    $selectPriv = DBUtil::runQuery('SELECT COUNT(id) FROM ' . $default->documents_table);
    if (PEAR::isError($selectPriv)) {
        print '<p><font color="red">Unable to do a basic database query.
    Error is: ' . htmlentities($selectPriv->toString()) . '</font></p>';
    } else {
        print '<p>Basic database query successful.</p>';
    }
    $sTable = KTUtil::getTableName('system_settings');
    DBUtil::startTransaction();
    $res = DBUtil::autoInsert($sTable, array('name' => 'transactionTest', 'value' => 1));
    DBUtil::rollback();
    $res = DBUtil::getOneResultKey("SELECT id FROM {$sTable} WHERE name = 'transactionTest'", 'id');
    if (!empty($res)) {
        print '<p><font color="red">Transaction support not available in database</font></p>';
    } else {
        print '<p>Database has transaction support.</p>';
    }
    DBUtil::whereDelete($sTable, array('name' => 'transactionTest'));
    ?>

<?php 
}
?>

  </body>
예제 #25
0
 function do_update()
 {
     $types_mapping = (array) KTUtil::arrayGet($_REQUEST, 'fDocumentTypeAssignment');
     $aWorkflows = KTWorkflow::getList();
     $aTypes = DocumentType::getList();
     $sQuery = 'DELETE FROM ' . KTUtil::getTableName('type_workflow_map');
     $aParams = array();
     DBUtil::runQuery(array($sQuery, $aParams));
     $aOptions = array('noid' => true);
     $sTable = KTUtil::getTableName('type_workflow_map');
     foreach ($aTypes as $oType) {
         $t = $types_mapping[$oType->getId()];
         if ($t == null) {
             $t = null;
         }
         $res = DBUtil::autoInsert($sTable, array('document_type_id' => $oType->getId(), 'workflow_id' => $t), $aOptions);
     }
     $this->successRedirectToMain(_kt('Type mapping updated.'));
 }