function userHasPermissionOnItem($oUser, $oPermission, $oItem, $aOptions = null)
 {
     require_once KT_LIB_DIR . '/permissions/permissionutil.inc.php';
     if (KTPermissionUtil::userHasPermissionOnItem($oUser, $oPermission, $oItem)) {
         return;
     }
     $this->oDispatcher->errorPage(_kt("Insufficient permissions to perform action"));
 }
 function allowTransition($oDocument, $oUser)
 {
     if (!$this->isLoaded()) {
         return true;
     }
     // the actual permissions are stored in the array.
     if (!is_null($this->aConfig['perms'])) {
         foreach ($this->aConfig['perms'] as $sPermName) {
             $oPerm = KTPermission::getByName($sPermName);
             if (PEAR::isError($oPerm)) {
                 continue;
                 // possible loss of referential integrity, just ignore it for now.
             }
             $res = KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDocument);
             if (!$res) {
                 return false;
             }
         }
     }
     return true;
 }
 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 _performUpgrade()
 {
     $this->_deleteSmartyFiles();
     $this->_deleteProxyFiles();
     require_once KT_LIB_DIR . '/cache/cache.inc.php';
     $oCache =& KTCache::getSingleton();
     $oCache->deleteAllCaches();
     require_once KT_LIB_DIR . '/permissions/permissionutil.inc.php';
     $po =& new KTRebuildPermissionObserver($this);
     $po->start();
     $oChannel =& KTPermissionChannel::getSingleton();
     $oChannel->addObserver($po);
     set_time_limit(0);
     ignore_user_abort(true);
     KTPermissionUtil::rebuildPermissionLookups(true);
     $po->end();
     $versionFile = KT_DIR . '/docs/VERSION-NAME.txt';
     $fp = fopen($versionFile, 'rt');
     $systemVersion = fread($fp, filesize($versionFile));
     fclose($fp);
     $query = "UPDATE system_settings SET value = ? WHERE name = ?";
     $aParams = array($systemVersion, "knowledgetreeVersion");
     DBUtil::runQuery(array($query, $aParams));
     $query = "UPDATE system_settings SET value = ? WHERE name = ?";
     $aParams = array($this->version, "databaseVersion");
     return DBUtil::runQuery(array($query, $aParams));
 }
Example #5
0
 /**
  * Generates the necessary joins and where clause and parameters to
  * ensure that all the documents returns are accessible to the user
  * given for the permission listed.
  *
  * Returns a list of the following elements:
  *      - String representing the where clause
  *      - Array of parameters that go with the where clause
  *      - String with the SQL necessary to join with the tables in the
  *        where clause
  */
 function permissionToSQL($oUser, $sPermissionName, $sItemTableName = "D")
 {
     if (is_null($oUser)) {
         return array("", array(), "");
     }
     if (is_null($sPermissionName)) {
         $sPermissionName = 'ktcore.permissions.read';
     }
     $oPermission =& KTPermission::getByName($sPermissionName);
     $sPermissionLookupsTable = KTUtil::getTableName('permission_lookups');
     $sPermissionLookupAssignmentsTable = KTUtil::getTableName('permission_lookup_assignments');
     $sPermissionDescriptorsTable = KTUtil::getTableName('permission_descriptors');
     $sJoinSQL = "\n            INNER JOIN {$sPermissionLookupsTable} AS PL ON {$sItemTableName}.permission_lookup_id = PL.id\n            INNER JOIN {$sPermissionLookupAssignmentsTable} AS PLA ON PL.id = PLA.permission_lookup_id AND PLA.permission_id = ?\n            ";
     $aPermissionDescriptors = KTPermissionUtil::getPermissionDescriptorsForUser($oUser);
     if (count($aPermissionDescriptors) === 0) {
         return PEAR::raiseError(_kt('You have no permissions'));
     }
     $sPermissionDescriptors = DBUtil::paramArray($aPermissionDescriptors);
     $sSQLString = "PLA.permission_descriptor_id IN ({$sPermissionDescriptors})";
     $aParams = array($oPermission->getId());
     $aParams = kt_array_merge($aParams, $aPermissionDescriptors);
     return array($sSQLString, $aParams, $sJoinSQL);
 }
Example #6
0
 function do_removeDynamicCondition()
 {
     $aOptions = array('redirect_to' => array('main', 'fFolderId=' . $this->oFolder->getId()));
     if (!KTBrowseUtil::inAdminMode($this->oUser, $this->oFolder)) {
         $this->oValidator->userHasPermissionOnItem($this->oUser, $this->_sEditShowPermission, $this->oFolder, $aOptions);
     }
     $aOptions = array('redirect_to' => array('edit', 'fFolderId=' . $this->oFolder->getId()));
     $oDynamicCondition =& $this->oValidator->validateDynamicCondition($_REQUEST['fDynamicConditionId'], $aOptions);
     $res = $oDynamicCondition->delete();
     $this->oValidator->notError($res, $aOptions);
     $oTransaction = KTFolderTransaction::createFromArray(array('folderid' => $this->oFolder->getId(), 'comment' => _kt('Removed dynamic permissions'), 'transactionNS' => 'ktcore.transactions.permissions_change', 'userid' => $_SESSION['userID'], 'ip' => Session::getClientIP()));
     $aOptions = array('defaultmessage' => _kt('Error updating permissions'), 'redirect_to' => array('edit', sprintf('fFolderId=%d', $this->oFolder->getId())));
     $this->oValidator->notErrorFalse($oTransaction, $aOptions);
     $oPO = KTPermissionObject::get($this->oFolder->getPermissionObjectId());
     KTPermissionUtil::updatePermissionLookupForPO($oPO);
     $this->successRedirectTo('edit', _kt('Dynamic permission removed'), 'fFolderId=' . $this->oFolder->getId());
 }
 /**
  * COPY method helper for Folders
  *
  * @param  array   parameter passing array
  * @param  int     Parent Folder ID
  * @return string  HTTP status code or false
  */
 function _COPYFolder($options, $iFolderID)
 {
     /* ** Ensure that the destination path exists ** */
     if ($options['dest'] == '') {
         $options["dest"] = substr($options["dest_url"], strlen($_SERVER["SCRIPT_NAME"]));
     }
     $this->ktwebdavLog("Entering _COPYFolder. options are " . print_r($options, true), 'info', true);
     /* ** RFC 2518 Section 8.8.3. DAV compliant servers must support depth headers of '0' and 'infinity'.
        Check the requested depth. If depth is set to '0', set copyall to false. A depth of 0 indicates
        that the folder is copied without any children. If depth is set to '1', return a 400 error. ** */
     $copyAll = true;
     if ($options["depth"] != "infinity") {
         if ($options['depth'] == '0') {
             $copyAll = false;
             $this->ktwebdavLog("Depth is 0. Copy only the base folder.", 'info', true);
         } else {
             $this->ktwebdavLog("400 Bad request. Depth must be infinity or 0.", 'info', true);
             return "400 Bad request - Depth must be 'infinity' or '0'.";
         }
     }
     global $default;
     $new = true;
     /* ** Get the relevant paths. Get the basename of the destination path as the destination path name.
        Check whether the destination path refers to a folder / document. ** */
     $source_path = $options["path"];
     $dest_path = urldecode($options["dest"]);
     $sDestPathName = basename($dest_path);
     list($iDestFolder, $iDestDoc) = $this->_folderOrDocument($dest_path);
     /* ** Get the source and destination folder objects.
        If the destination document is null, then the destination is an existing folder. Check overwrite.
        If overwrite is true, then check permissions and delete the folder, continue.
        If the destination document returns an id, then the destination is a document, return 409 error.
        If the destination document is false, then continue. ** */
     $oSrcFolder = Folder::get($iFolderID);
     $oDestFolder = Folder::get($iDestFolder);
     include_once KT_LIB_DIR . '/foldermanagement/folderutil.inc.php';
     if (is_null($iDestDoc)) {
         // Destination is a folder and exists
         //$sDestPathName = '';
         $this->ktwebdavLog("Destination Folder exists.", 'info', true);
         $oReplaceFolder = $oDestFolder;
         if ($options['overwrite'] != 'T') {
             $this->ktwebdavLog("Overwrite needs to be TRUE.", 'info', true);
             return "412 Precondition Failed - Destination Folder exists. Overwrite needs to be TRUE.";
         }
         $this->ktwebdavLog("Overwrite is TRUE, deleting Destination Folder.", 'info', true);
         // Check if the user has permissions to delete this folder
         $oPerm =& KTPermission::getByName('ktcore.permissions.delete');
         $oUser =& User::get($this->userID);
         if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oReplaceFolder)) {
             return "403 Forbidden - User does not have sufficient permissions";
         }
         KTFolderUtil::delete($oReplaceFolder, $oUser, 'KTWebDAV move overwrites target.');
         // Destination folder has been deleted - get new object of destination parent folder
         list($iDestFolder, $iDestDoc) = $this->_folderOrDocument($dest_path);
         $oDestFolder = Folder::get($iDestFolder);
         $new = false;
     } else {
         if ($iDestDoc !== false) {
             // Destination is a document
             return "409 Conflict - Can't write a collection to a document";
         }
     }
     /* ** Get the destination folder object and the source document object.
        Check if user has permission to write to the folder.
        Copy the document. Pass parameters for the destination folder name and the depth of copy. ** */
     $oUser =& User::get($this->userID);
     $this->ktwebdavLog("Got an oSrcFolder of " . print_r($oSrcFolder, true), 'info', true);
     $this->ktwebdavLog("Got an oDestFolder of " . print_r($oDestFolder, true), 'info', true);
     $this->ktwebdavLog("Got an oUser of " . print_r($oUser, true), 'info', true);
     // Check if the user has permissions to write in this folder
     $oPerm =& KTPermission::getByName('ktcore.permissions.write');
     $oUser =& User::get($this->userID);
     if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDestFolder)) {
         return "403 Forbidden - User does not have sufficient permissions";
     }
     $reason = isset($_SERVER['HTTP_REASON']) && !empty($_SERVER['HTTP_REASON']) ? $_SERVER['HTTP_REASON'] : "KTWebDAV Copy.";
     $res = KTFolderUtil::copy($oSrcFolder, $oDestFolder, $oUser, $reason, $sDestPathName, $copyAll);
     if (PEAR::isError($res)) {
         $this->ktwebdavLog("Copy on folder failed: " . $res->getMessage(), 'info', true);
         return "500 Internal Server Error - Copy on folder failed.";
     }
     if ($new) {
         $this->ktwebdavLog("201 Created", 'info', true);
         return "201 Created";
     } else {
         $this->ktwebdavLog("204 No Content", 'info', true);
         return "204 No Content";
     }
 }
 function renegeratePermissionsForRole($iRoleId, $iFolderId)
 {
     $iStartFolderId = $iFolderId;
     /*
      * 1. find all folders & documents "below" this one which use the role
      *    definition _active_ (not necessarily present) at this point.
      * 2. tell permissionutil to regen their permissions.
      *
      * The find algorithm is:
      *
      *  folder_queue <- (iStartFolderId)
      *  while folder_queue is not empty:
      *     active_folder =
      *     for each folder in the active_folder:
      *         find folders in _this_ folder without a role-allocation on the iRoleId
      *            add them to the folder_queue
      *         update the folder's permissions.
      *         find documents in this folder:
      *            update their permissions.
      */
     $sRoleAllocTable = KTUtil::getTableName('role_allocations');
     $sFolderTable = KTUtil::getTableName('folders');
     $sQuery = sprintf('SELECT f.id as id FROM %s AS f LEFT JOIN %s AS ra ON (f.id = ra.folder_id) WHERE ra.id IS NULL AND f.parent_id = ?', $sFolderTable, $sRoleAllocTable);
     $folder_queue = array($iStartFolderId);
     while (!empty($folder_queue)) {
         $active_folder = array_pop($folder_queue);
         $aParams = array($active_folder);
         $aNewFolders = DBUtil::getResultArrayKey(array($sQuery, $aParams), 'id');
         if (PEAR::isError($aNewFolders)) {
             //$this->errorRedirectToMain(_kt('Failure to generate folderlisting.'));
             echo _kt('Failure to generate folderlisting.');
         }
         $folder_queue = kt_array_merge($folder_queue, (array) $aNewFolders);
         // push.
         // update the folder.
         $oFolder =& Folder::get($active_folder);
         if (PEAR::isError($oFolder) || $oFolder == false) {
             //$this->errorRedirectToMain(_kt('Unable to locate folder: ') . $active_folder);
             echo _kt('Unable to locate folder: ') . $active_folder;
         }
         KTPermissionUtil::updatePermissionLookup($oFolder);
         $aDocList =& Document::getList(array('folder_id = ?', $active_folder));
         if (PEAR::isError($aDocList) || $aDocList === false) {
             //$this->errorRedirectToMain(sprintf(_kt('Unable to get documents in folder %s: %s'), $active_folder, $aDocList->getMessage()));
             echo _kt('Unable to get documents in folder ') . $active_folder;
         }
         foreach ($aDocList as $oDoc) {
             if (!PEAR::isError($oDoc)) {
                 KTPermissionUtil::updatePermissionLookup($oDoc);
             }
         }
     }
 }
Example #9
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()));
 }
 /**
  * Gets which users/groups/roles are to be informed when a state is
  * arrived at.
  */
 function getInformedForState($oState)
 {
     $iDescriptorId = $oState->getInformDescriptorId();
     if (empty($iDescriptorId)) {
         return array();
     }
     return KTPermissionUtil::getAllowedForDescriptor($iDescriptorId);
 }
 function rebuildPermissionLookups($bEmptyOnly = true)
 {
     if ($bEmptyOnly) {
         $sTable = KTUtil::getTableName('folders');
         $sQuery = sprintf("SELECT id FROM %s WHERE permission_lookup_id IS NULL AND permission_object_id IS NOT NULL", $sTable);
     } else {
         $sTable = KTUtil::getTableName('folders');
         $sQuery = sprintf("SELECT id FROM %s WHERE permission_object_id IS NOT NULL", $sTable);
     }
     $aIds = DBUtil::getResultArrayKey($sQuery, 'id');
     foreach ($aIds as $iId) {
         $oFolder =& Folder::get($iId);
         KTPermissionUtil::updatePermissionLookup($oFolder);
     }
     if ($bEmptyOnly) {
         $sTable = KTUtil::getTableName('documents');
         $sQuery = sprintf("SELECT id FROM %s WHERE permission_lookup_id IS NULL", $sTable);
     } else {
         $sTable = KTUtil::getTableName('documents');
         $sQuery = sprintf("SELECT id FROM %s", $sTable);
     }
     $aIds = DBUtil::getResultArrayKey($sQuery, 'id');
     foreach ($aIds as $iId) {
         $oDocument =& Document::get($iId);
         KTPermissionUtil::updatePermissionLookup($oDocument);
     }
 }
<?php

require_once "../../config/dmsDefaults.php";
require_once KT_LIB_DIR . '/foldermanagement/Folder.inc';
require_once KT_LIB_DIR . '/documentmanagement/Document.inc';
require_once KT_LIB_DIR . '/permissions/permissionutil.inc.php';
error_reporting(E_ALL);
/*
$aFolders =& Folder::getList();
foreach ($aFolders as $oFolder) {
    KTPermissionUtil::updatePermissionLookup($oFolder);
}
$aDocuments =& Document::getList('permission_object_id IS NOT NULL');
foreach ($aDocuments as $oDocument) {
    KTPermissionUtil::updatePermissionLookup($oDocument);
}
*/
$oDocument = Document::get(447);
KTPermissionUtil::updatePermissionLookup($oDocument);
Example #13
0
 /**
  * Finds folders that aren't reachable by the user but to which the
  * user has read permissions.
  *
  * Returns an array of Folder objects.
  */
 function getBrowseableFolders($oUser)
 {
     $aPermissionDescriptors = KTPermissionUtil::getPermissionDescriptorsForUser($oUser);
     if (empty($aPermissionDescriptors)) {
         return array();
     }
     $sPermissionDescriptors = DBUtil::paramArray($aPermissionDescriptors);
     $oPermission = KTPermission::getByName('ktcore.permissions.read');
     $oPermission2 = KTPermission::getByName('ktcore.permissions.folder_details');
     $aPermissionIds = array($oPermission->getId(), $oPermission->getId(), $oPermission2->getId(), $oPermission2->getId());
     $sFoldersTable = KTUtil::getTableName('folders');
     $sPLTable = KTUtil::getTableName('permission_lookups');
     $sPLATable = KTUtil::getTableName('permission_lookup_assignments');
     $sQuery = "SELECT DISTINCT F.id AS id FROM\n            {$sFoldersTable} AS F\n                LEFT JOIN {$sPLTable} AS PL ON F.permission_lookup_id = PL.id\n                LEFT JOIN {$sPLATable} AS PLA ON PLA.permission_lookup_id = PL.id AND (PLA.permission_id = ? || PLA.permission_id = ?)\n\n            LEFT JOIN {$sFoldersTable} AS F2 ON F.parent_id = F2.id\n                LEFT JOIN {$sPLTable} AS PL2 ON F2.permission_lookup_id = PL2.id\n                LEFT JOIN {$sPLATable} AS PLA2 ON PLA2.permission_lookup_id = PL2.id AND (PLA2.permission_id = ? || PLA.permission_id = ?)\n            WHERE\n                PLA.permission_descriptor_id IN ({$sPermissionDescriptors})\n                AND F2.id <> 1\n                AND NOT (PLA2.permission_descriptor_id IN ({$sPermissionDescriptors}))";
     $aParams = kt_array_merge($aPermissionIds, $aPermissionDescriptors, $aPermissionDescriptors);
     $res = DBUtil::getResultArrayKey(array($sQuery, $aParams), 'id');
     if (PEAR::isError($res)) {
         return $res;
     }
     $aFolders = array();
     foreach ($res as $iFolderId) {
         $aFolders[] = Folder::get($iFolderId);
     }
     return $aFolders;
 }
Example #14
0
function resolveSearchShortcuts($result)
{
    $oPermission =& KTPermission::getByName('ktcore.permissions.read');
    $permId = $oPermission->getID();
    $oUser = User::get($_SESSION['userID']);
    $aPermissionDescriptors = KTPermissionUtil::getPermissionDescriptorsForUser($oUser);
    $sPermissionDescriptors = empty($aPermissionDescriptors) ? -1 : implode(',', $aPermissionDescriptors);
    $documentIds = implode(',', array_keys($result['docs']));
    $linkedDocuments = array();
    if (!empty($documentIds)) {
        $sql = "SELECT d.id, d.linked_document_id from documents d ";
        $sql .= 'INNER JOIN permission_lookups AS PL ON d.permission_lookup_id = PL.id ' . "\n";
        $sql .= 'INNER JOIN permission_lookup_assignments AS PLA ON PL.id = PLA.permission_lookup_id AND PLA.permission_id = ' . $permId . " \n";
        $sql .= " WHERE d.linked_document_id in ({$documentIds}) AND PLA.permission_descriptor_id IN ({$sPermissionDescriptors})";
        $rs = DBUtil::getResultArray($sql);
        foreach ($rs as $row) {
            $id = $row['id'];
            $linked_id = $row['linked_document_id'];
            $result['shortdocs'][$id] = new DocumentShortcutResultItem($id, $result['docs'][$linked_id]);
        }
    }
    $folderIds = implode(',', array_keys($result['folders']));
    $linkedFolders = array();
    if (!empty($folderIds)) {
        $sql = "SELECT f.id, f.linked_folder_id from folders f ";
        $sql .= 'INNER JOIN permission_lookups AS PL ON f.permission_lookup_id = PL.id ' . "\n";
        $sql .= 'INNER JOIN permission_lookup_assignments AS PLA ON PL.id = PLA.permission_lookup_id AND PLA.permission_id = ' . $permId . " \n";
        $sql .= " WHERE f.linked_folder_id in ({$folderIds}) AND PLA.permission_descriptor_id IN ({$sPermissionDescriptors})";
        $rs = DBUtil::getResultArray($sql);
        foreach ($rs as $row) {
            $id = $row['id'];
            $linked_id = $row['linked_folder_id'];
            $result['shortfolders'][$id] = new FolderShortcutResultItem($id, $result['folders'][$linked_id]);
        }
    }
    return $result;
}
Example #15
0
 function check_entity($oEntity)
 {
     if (is_a($oEntity, 'Document')) {
         if ($oEntity->getImmutable()) {
             return PEAR::raiseError(_kt('Document cannot be checked out as it is immutable'));
         }
         // Check that the document isn't already checked out
         if ($oEntity->getIsCheckedOut()) {
             $checkedOutUser = $oEntity->getCheckedOutUserID();
             $sUserId = $_SESSION['userID'];
             if ($checkedOutUser != $sUserId) {
                 $oCheckedOutUser = User::get($checkedOutUser);
                 return PEAR::raiseError($oEntity->getName() . ': ' . _kt('Document has already been checked out by ') . $oCheckedOutUser->getName());
             }
         }
         // Check that the checkout action isn't restricted for the document
         if (!KTWorkflowUtil::actionEnabledForDocument($oEntity, 'ktcore.actions.document.checkout')) {
             return PEAR::raiseError($oEntity->getName() . ': ' . _kt('Checkout is restricted by the workflow state.'));
         }
     } else {
         if (!is_a($oEntity, 'Folder')) {
             return PEAR::raiseError(_kt('Document cannot be checked out'));
         }
     }
     //we need to do an extra folder permission check in case of a shortcut
     if (is_a($oEntity, 'Folder') && $oEntity->isSymbolicLink()) {
         if (!KTPermissionUtil::userHasPermissionOnItem($this->oUser, $this->_sPermission, $oEntity->getLinkedFolder())) {
             return PEAR::raiseError(_kt('You do not have the required permissions'));
         }
     }
     return parent::check_entity($oEntity);
 }
Example #16
0
 function do_setpermissionallocations()
 {
     $aPermissionAllowed = (array) KTUtil::arrayGet($_REQUEST, 'foo');
     // thanks BD.
     $this->startTransaction();
     $aStatePermAssigns = KTWorkflowStatePermissionAssignment::getByState($this->oState);
     // we now walk the alloc'd perms, and go.
     foreach ($aStatePermAssigns as $oPermAssign) {
         $aAllowed = (array) $aPermissionAllowed[$oPermAssign->getPermissionId()];
         // is already role, group, etc.
         $oDescriptor = KTPermissionUtil::getOrCreateDescriptor($aAllowed);
         if (PEAR::isError($oDescriptor)) {
             $this->errorRedirectTo('allocatepermissions', _kt('Failed to allocate as specified.'));
         }
         $oPermAssign->setDescriptorId($oDescriptor->getId());
         $res = $oPermAssign->update();
         if (PEAR::isError($res)) {
             $this->errorRedirectTo('allocatepermissions', _kt('Failed to allocate as specified.'));
         }
     }
     KTPermissionUtil::updatePermissionLookupForState($this->oState);
     $this->successRedirectTo('managepermissions', _kt('Permissions Allocated.'));
 }
 function _show()
 {
     if (is_null($this->_sShowPermission)) {
         return true;
     }
     $oFolder = Folder::get($this->oDocument->getFolderId());
     if ($this->_bMutator && $this->oDocument->getImmutable()) {
         if ($this->_bMutationAllowedByAdmin === true) {
             if (!KTBrowseUtil::inAdminMode($this->oUser, $oFolder)) {
                 return false;
             }
         } else {
             return false;
         }
     }
     if ($this->_bAdminAlwaysAvailable) {
         if (Permission::userIsSystemAdministrator($this->oUser->getId())) {
             return true;
         }
         if (Permission::isUnitAdministratorForFolder($this->oUser, $this->oDocument->getFolderId())) {
             return true;
         }
     }
     $oPermission =& KTPermission::getByName($this->_sShowPermission);
     if (PEAR::isError($oPermission)) {
         return true;
     }
     if (!KTWorkflowUtil::actionEnabledForDocument($this->oDocument, $this->sName)) {
         return false;
     }
     // be nasty in archive/delete status.
     $status = $this->oDocument->getStatusID();
     if ($status == DELETED || $status == ARCHIVED) {
         return false;
     }
     if ($this->bAllowInAdminMode) {
         // check if this user is in admin mode
         if (KTBrowseUtil::inAdminMode($this->oUser, $oFolder)) {
             return true;
         }
     }
     return KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPermission, $this->oDocument);
 }
Example #18
0
 /**
  * Deletes a symbolic link folder
  *
  * @param Folder $folder tthe symbolic link folder to delete
  * @param User $user the current user
  * @return unknown
  */
 static function deleteSymbolicLink($folder, $user = null)
 {
     //validate input
     if (is_numeric($folder)) {
         $folder = Folder::get($folder);
     }
     if (!$folder instanceof Folder) {
         return PEAR::raiseError(_kt('Folder not specified'));
     }
     if (!$folder->isSymbolicLink()) {
         return PEAR::raiseError(_kt('Folder must be a symbolic link entity'));
     }
     if (is_null($user)) {
         $user = $_SESSION['userID'];
     }
     if (is_numeric($user)) {
         $user = User::get($user);
     }
     //check if the user has sufficient permissions
     $oPerm = KTPermission::getByName('ktcore.permissions.delete');
     if (!KTBrowseUtil::inAdminMode($user, $folder)) {
         if (!KTPermissionUtil::userHasPermissionOnItem($user, $oPerm, $folder)) {
             return PEAR::raiseError(_kt('You\'re not authorized to delete shortcuts'));
         }
     }
     // we only need to delete the folder entry for the link
     $sql = "DELETE FROM folders WHERE id=?";
     DBUtil::runQuery(array($sql, array($folder->getId())));
 }
 function setAllowed($aAllowed)
 {
     $oDescriptor = KTPermissionUtil::getOrCreateDescriptor($aAllowed);
     // fully done, etc.
     $this->iPermissionDescriptorId = $oDescriptor->getId();
 }
Example #20
0
 function update($bPathMove = false)
 {
     //var_dump($this); exit(0);
     $res = parent::update();
     if ($res === true && $bPathMove === true) {
         KTPermissionUtil::updatePermissionLookup($this);
     }
     return $res;
 }
Example #21
0
 function do_delete()
 {
     $this->oPage->setBreadcrumbDetails(_kt("link"));
     // check security
     $oPermission =& KTPermission::getByName('ktcore.permissions.write');
     if (PEAR::isError($oPermission) || !KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPermission, $this->oDocument)) {
         $this->errorRedirectToMain(_kt('You do not have sufficient permissions to delete a link'), sprintf("fDocumentId=%d", $this->oDocument->getId()));
         exit(0);
     }
     // check validity of things
     $oDocumentLink = DocumentLink::get(KTUtil::arrayGet($_REQUEST, 'fDocumentLinkId'));
     if (PEAR::isError($oDocumentLink)) {
         $this->errorRedirectToMain(_kt('Invalid document link selected.'));
         exit(0);
     }
     $oParentDocument = Document::get(KTUtil::arrayGet($_REQUEST, 'fDocumentId'));
     if (PEAR::isError($oParentDocument)) {
         $this->errorRedirectToMain(_kt('Invalid document selected.'));
         exit(0);
     }
     // do deletion
     $this->startTransaction();
     // Cannot call delete directly if no link exists.
     if ($oDocumentLink) {
         $res = $oDocumentLink->delete();
         if (PEAR::isError($res)) {
             $this->errorRedirectToMain(_kt('Could not delete document link'), sprintf('fDocumentId=%d', $oParentDocument->getId()));
             exit(0);
         }
     } else {
         $this->successRedirectToMain(_kt('Document link not deleted. Document link does not exists, or previously deleted.'), sprintf('fDocumentId=%d', $oParentDocument->getId()));
     }
     $this->commitTransaction();
     $this->successRedirectToMain(_kt('Document link deleted'), sprintf('fDocumentId=%d', $oParentDocument->getId()));
     exit(0);
 }
Example #22
0
 function check()
 {
     $this->browse_mode = KTUtil::arrayGet($_REQUEST, 'fBrowseMode', 'folder');
     $action = KTUtil::arrayGet($_REQUEST, $this->event_var, 'main');
     $this->editable = false;
     // catch the alternative actions.
     if ($action != 'main') {
         return true;
     }
     // if we're going to main ...
     // folder browse mode
     if ($this->browse_mode == 'folder') {
         $in_folder_id = KTUtil::arrayGet($_REQUEST, 'fFolderId');
         if (empty($in_folder_id)) {
             $oConfig = KTConfig::getSingleton();
             if ($oConfig->get('tweaks/browseToUnitFolder')) {
                 $iHomeFolderId = $this->oUser->getHomeFolderId();
                 if ($iHomeFolderId) {
                     $in_folder_id = $iHomeFolderId;
                 }
             }
         }
         $folder_id = (int) $in_folder_id;
         // conveniently, will be 0 if not possible.
         if ($folder_id == 0) {
             $folder_id = 1;
         }
         $_REQUEST['fBrowseMode'] = 'folder';
         // here we need the folder object to do the breadcrumbs.
         $oFolder =& Folder::get($folder_id);
         if (PEAR::isError($oFolder)) {
             return false;
             // just fail.
         }
         // check whether the user can edit this folder
         $oPerm = KTPermission::getByName('ktcore.permissions.write');
         if (KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPerm, $oFolder)) {
             $this->editable = true;
         } else {
             $this->editable = false;
         }
         // set the title and breadcrumbs...
         $this->oPage->setTitle(_kt('Browse'));
         if (KTPermissionUtil::userHasPermissionOnItem($this->oUser, 'ktcore.permissions.folder_details', $oFolder)) {
             $this->oPage->setSecondaryTitle($oFolder->getName());
         } else {
             if (KTBrowseUtil::inAdminMode($this->oUser, $oFolder)) {
                 $this->oPage->setSecondaryTitle(sprintf('(%s)', $oFolder->getName()));
             } else {
                 $this->oPage->setSecondaryTitle('...');
             }
         }
         //Figure out if we came here by navigating trough a shortcut.
         //If we came here from a shortcut, the breadcrumbspath should be relative
         //to the shortcut folder.
         $iSymLinkFolderId = KTUtil::arrayGet($_REQUEST, 'fShortcutFolder', null);
         if (is_numeric($iSymLinkFolderId)) {
             $oBreadcrumbsFolder = Folder::get($iSymLinkFolderId);
             $this->aBreadcrumbs = kt_array_merge($this->aBreadcrumbs, KTBrowseUtil::breadcrumbsForFolder($oBreadcrumbsFolder, array('final' => false)));
             $this->aBreadcrumbs[] = array('name' => $oFolder->getName());
         } else {
             $this->aBreadcrumbs = kt_array_merge($this->aBreadcrumbs, KTBrowseUtil::breadcrumbsForFolder($oFolder));
         }
         $this->oFolder =& $oFolder;
         // we now have a folder, and need to create the query.
         $aOptions = array('ignorepermissions' => KTBrowseUtil::inAdminMode($this->oUser, $oFolder));
         $this->oQuery = new BrowseQuery($oFolder->getId(), $this->oUser, $aOptions);
         $this->resultURL = KTUtil::addQueryString($_SERVER['PHP_SELF'], sprintf('fFolderId=%d', $oFolder->getId()));
         // and the portlets
         $portlet = new KTActionPortlet(sprintf(_kt('About this folder')));
         $aActions = KTFolderActionUtil::getFolderInfoActionsForFolder($this->oFolder, $this->oUser);
         $portlet->setActions($aActions, $this->sName);
         $this->oPage->addPortlet($portlet);
         $portlet = new KTActionPortlet(sprintf(_kt('Actions on this folder')));
         $aActions = KTFolderActionUtil::getFolderActionsForFolder($oFolder, $this->oUser);
         $portlet->setActions($aActions, null);
         $this->oPage->addPortlet($portlet);
     } else {
         if ($this->browse_mode == 'lookup_value') {
             // browsing by a lookup value
             $this->editable = false;
             // check the inputs
             $field = KTUtil::arrayGet($_REQUEST, 'fField', null);
             $oField = DocumentField::get($field);
             if (PEAR::isError($oField) || $oField == false) {
                 $this->errorRedirectToMain('No Field selected.');
                 exit(0);
             }
             $value = KTUtil::arrayGet($_REQUEST, 'fValue', null);
             $oValue = MetaData::get($value);
             if (PEAR::isError($oValue) || $oValue == false) {
                 $this->errorRedirectToMain('No Value selected.');
                 exit(0);
             }
             $this->oQuery = new ValueBrowseQuery($oField, $oValue);
             $this->resultURL = KTUtil::addQueryString($_SERVER['PHP_SELF'], sprintf('fBrowseMode=lookup_value&fField=%d&fValue=%d', $field, $value));
             // setup breadcrumbs
             $this->aBreadcrumbs = array(array('name' => _kt('Lookup Values'), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], 'action=selectField')), array('name' => $oField->getName(), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], 'action=selectLookup&fField=' . $oField->getId())), array('name' => $oValue->getName(), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], sprintf('fBrowseMode=lookup_value&fField=%d&fValue=%d', $field, $value))));
         } else {
             if ($this->browse_mode == 'document_type') {
                 // browsing by document type
                 $this->editable = false;
                 $doctype = KTUtil::arrayGet($_REQUEST, 'fType', null);
                 $oDocType = DocumentType::get($doctype);
                 if (PEAR::isError($oDocType) || $oDocType == false) {
                     $this->errorRedirectToMain('No Document Type selected.');
                     exit(0);
                 }
                 $this->oQuery = new TypeBrowseQuery($oDocType);
                 // FIXME probably want to redirect to self + action=selectType
                 $this->aBreadcrumbs[] = array('name' => _kt('Document Types'), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], 'action=selectType'));
                 $this->aBreadcrumbs[] = array('name' => $oDocType->getName(), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], 'fBrowseMode=document_type&fType=' . $oDocType->getId()));
                 $this->resultURL = KTUtil::addQueryString($_SERVER['PHP_SELF'], sprintf('fType=%s&fBrowseMode=document_type', $doctype));
             } else {
                 // FIXME what should we do if we can't initiate the browse?  we "pretend" to have no perms.
                 return false;
             }
         }
     }
     return true;
 }
Example #23
0
 /**
  * Builds the main SQL query
  *
  * @return string $sql
  */
 private function buildCoreSQL()
 {
     if (count($this->metadata) + count($this->db) == 0) {
         // return empty result set
         return '';
     }
     $sql = 'SELECT ' . "\n";
     if ($this->context == ExprContext::DOCUMENT) {
         // we are doing this because content table is dependant on metadata table
         if ($this->used_tables['document_content_version'] > 0) {
             $this->used_tables['document_metadata_version']++;
         }
         $sql .= ' DISTINCT d.id, dmv.name as title';
     } else {
         $sql .= ' DISTINCT f.id, f.name as title';
     }
     /*
      * This section of code builds the part of the query which is used to
      * determine ranking for db fields
      *
      * 0 = "does not match"
      */
     $offset = 0;
     foreach ($this->db as $expr) {
         $offset++;
         $sql .= ", ifnull(" . $this->getSQLEvalExpr($expr) . ",0) as expr{$offset} ";
     }
     /*
      * This section of code builds the part of the query which is used to
      * determine ranking for metadata fields
      *
      * 0 = "does not match"
      */
     foreach ($this->metadata as $expr) {
         $offset++;
         $sql .= ", ifnull(" . $this->getSQLEvalExpr($expr) . ",0) as expr{$offset} ";
     }
     $sql .= "\n" . 'FROM ' . "\n";
     if ($this->context == ExprContext::DOCUMENT) {
         $primaryAlias = 'd';
         $sql .= ' documents d ' . "\n";
         if ($this->used_tables['document_metadata_version'] > 0) {
             $sql .= ' INNER JOIN document_metadata_version dmv ON d.metadata_version_id=dmv.id' . "\n";
         }
         if ($this->used_tables['document_content_version'] > 0) {
             $sql .= ' INNER JOIN document_content_version dcv ON dmv.content_version_id=dcv.id ' . "\n";
         }
         // NOTE this was the old method of dealing with joining on the document_fields_link table;
         // the new method incorporates previously set up joining code which was not completely understood
         // at the time I modified this code; it allows everything to be more encapsulated within the classes and
         // done in a more generic way which does not require a special case code snippet such as the one commented
         // out below.
         //            if ($this->used_tables['document_fields_link'] > 0)
         //            {
         //                for ($i = 0; $i < $this->used_tables['document_fields_link']; ++$i)
         //                {
         //                    if ($i > 0) $counter = $i;
         //                    else $counter = '';
         //
         //                    $sql .= ' LEFT JOIN document_fields_link pdfl' . $counter . ' '
         //                         .  'ON dmv.id=pdfl' . $counter . '.metadata_version_id ' . "\n";
         //                }
         //            }
         if ($this->used_tables['tag_words'] > 0) {
             $sql .= ' LEFT OUTER JOIN document_tags dt  ON dt.document_id=d.id ' . "\n" . ' LEFT OUTER JOIN tag_words tw  ON dt.tag_id = tw.id ' . "\n";
         }
     } else {
         $primaryAlias = 'f';
         $sql .= ' folders f ' . "\n";
     }
     /*
      * This builds the JOINs required to correctly select on multiple tables.
      * 
      * NOTE This is explicitly required for multi-selecting from the same table using multiple
      * joins with different offset naming.
      * This multi-selecting is necessary to avoid issues with complex queries
      * requiring different results from a single column within a database table.
      *
      * For an example of how the field classes need to be set up to take advantage of this code
      * look at the constructors for the AnyMetadataField class or the MimeTypeField class.
      */
     $offset = 0;
     foreach ($this->db as $expr) {
         $field = $expr->left();
         $jointable = $field->getJoinTable();
         if (!is_null($jointable)) {
             $fieldname = $this->resolveTableToAlias($field->getTable()) . '.' . $field->getField();
             $joinalias = "{$jointable}{$offset}";
             $joinfield = $field->getJoinField();
             $sql .= " LEFT OUTER JOIN {$jointable} {$joinalias} ON {$fieldname}={$joinalias}.{$joinfield}\n";
         }
         $offset++;
     }
     if ($this->context == ExprContext::DOCUMENT) {
         $offset = 0;
         foreach ($this->metadata as $expr) {
             $offset++;
             $field = $expr->left();
             $fieldid = $field->getFieldId();
             $sql .= " LEFT JOIN document_fields_link dfl{$offset} ON dfl{$offset}.metadata_version_id=d.metadata_version_id AND dfl{$offset}.document_field_id={$fieldid}" . "\n";
             $sql .= " LEFT JOIN document_fields df{$offset} ON df{$offset}.id=dfl{$offset}.document_field_id" . "\n";
         }
     }
     // Add permissions sql for read access
     $oPermission =& KTPermission::getByName('ktcore.permissions.read');
     $permId = $oPermission->getID();
     $oUser = User::get($_SESSION['userID']);
     $aPermissionDescriptors = KTPermissionUtil::getPermissionDescriptorsForUser($oUser);
     $sPermissionDescriptors = empty($aPermissionDescriptors) ? -1 : implode(',', $aPermissionDescriptors);
     $sql .= "INNER JOIN permission_lookups AS PL ON {$primaryAlias}.permission_lookup_id = PL.id\n";
     $sql .= 'INNER JOIN permission_lookup_assignments AS PLA ON PL.id = PLA.permission_lookup_id AND PLA.permission_id = ' . $permId . " \n";
     $sql .= "WHERE PLA.permission_descriptor_id IN ({$sPermissionDescriptors}) AND ";
     if ($this->context == ExprContext::DOCUMENT) {
         $sql .= "d.linked_document_id is null";
         if ($this->incl_status) {
             $sql .= " AND dmv.status_id=1 AND d.status_id=1";
         }
     } else {
         $sql .= "f.linked_folder_id is null";
     }
     $sql .= ' AND ';
     return $sql;
 }
Example #24
0
 function do_changestate()
 {
     $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())));
     $oPermission =& KTPermission::getByName('ktcore.permissions.workflow');
     $sRedirectTo = implode('&', $aErrorOptions['redirect_to']);
     if (PEAR::isError($oPermission)) {
         $this->errorRedirectTo($sRedirectTo, _kt("Error getting permission"));
         exit(0);
     }
     if (!KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPermission, $this->oDocument)) {
         $this->errorRedirectTo($sRedirectTo, _kt("You do not have permission to close this thread"));
         exit(0);
     }
     $iStateId = KTUtil::arrayGet($_REQUEST, 'state');
     if (!in_array($iStateId, $this->aTransitions[$oThread->getState()])) {
         $this->errorRedirectTo($sRedirectTo, _kt("Invalid transition"));
         exit(0);
     }
     $aErrorOptions['message'] = _kt("No reason provided");
     $sReason = $this->oValidator->validateString(KTUtil::arrayGet($_REQUEST, 'reason'), $aErrorOptions);
     if ($iStateId > $oThread->getState()) {
         $sTransactionNamespace = 'ktcore.transactions.collaboration_step_approve';
     } else {
         $sTransactionNamespace = 'ktcore.transactions.collaboration_step_rollback';
     }
     // Start the transaction comment creation
     $this->startTransaction();
     $oThread->setState($iStateId);
     if ($iStateId == DISCUSSION_CLOSED) {
         $oThread->setCloseMetadataVersion($this->oDocument->getMetadataVersion());
     } else {
         if ($iStateId == DISCUSSION_CONCLUSION) {
             $oThread->setCloseReason($sReason);
         }
     }
     $oDocumentTransaction = new DocumentTransaction($this->oDocument, $sReason, $sTransactionNamespace);
     $oDocumentTransaction->create();
     $res = $oThread->update();
     $aErrorOptions['message'] = _kt("There was an error updating the thread with the new comment");
     $this->oValidator->notError($res, $aErrorOptions);
     // Thread closed correctly, so commit
     $this->commitTransaction();
     $this->successRedirectTo('viewThread', _kt("Thread state changed"), sprintf('fDocumentId=%d&fThreadId=%d', $this->oDocument->getId(), $oThread->getId()));
     exit(0);
 }
 function rebuildAllPermissions()
 {
     $oRootFolder = Folder::get(1);
     KTPermissionUtil::updatePermissionLookupRecursive($oRootFolder);
 }
Example #26
0
 function do_createUnit()
 {
     $aOptions = array('redirect_to' => array('main'), 'message' => _kt('Invalid folder chosen'));
     $oParentFolder = $this->oValidator->validateFolder($_REQUEST['browse'], $aOptions);
     $aOptions = array('redirect_to' => array('addUnit', sprintf('browse=%d', $oParentFolder->getId())), 'message' => _kt('No name given'));
     $sName = $this->oValidator->validateString($_REQUEST['unit_name'], $aOptions);
     $aOptions['message'] = _kt('A unit with that name already exists.');
     $sName = $this->oValidator->validateDuplicateName('Unit', $sName, $aOptions);
     $oFolder = KTFolderUtil::add($oParentFolder, $sName, $this->oUser);
     $aOptions = array('redirect_to' => array('addUnit2', sprintf('fFolderId=%d&unit_name=%s', $oParentFolder->getId(), $sName)), 'defaultmessage' => 'Error creating folder');
     $this->oValidator->notError($oFolder, $aOptions);
     KTPermissionUtil::copyPermissionObject($oFolder);
     $oUnit = Unit::createFromArray(array('name' => $sName, 'folderid' => $oFolder->getId()));
     return $this->successRedirectToMain(_kt('Unit created'));
 }
 function do_reown()
 {
     $oForm = $this->form_owner();
     $res = $oForm->validate();
     $data = $res['results'];
     $errors = $res['errors'];
     if (!empty($errors)) {
         return $oForm->handleError();
     }
     $oUser = $data['user'];
     $this->startTransaction();
     $this->oDocument->setOwnerID($oUser->getId());
     $res = $this->oDocument->update();
     if (PEAR::isError($res)) {
         $this->errorRedirectToMain(sprintf(_kt('Failed to update document: %s'), $res->getMessage()), sprintf('fDocumentId=%d', $this->oDocument->getId()));
     }
     $res = KTPermissionUtil::updatePermissionLookup($this->oDocument);
     if (PEAR::isError($res)) {
         $this->errorRedirectToMain(sprintf(_kt('Failed to update document: %s'), $res->getMessage()), sprintf('fDocumentId=%d', $this->oDocument->getId()));
     }
     $this->successRedirectToMain(_kt('Ownership changed.'), sprintf('fDocumentId=%d', $this->oDocument->getId()));
 }
Example #28
0
 function _importfolder($oFolder, $sPath)
 {
     $oPermission = KTPermission::getByName('ktcore.permissions.addFolder');
     $aDocPaths = $this->oStorage->listDocuments($sPath);
     if (PEAR::isError($aDocPaths)) {
         return $aDocPaths;
     }
     $oDocObjects = array();
     foreach ($aDocPaths as $sDocumentPath) {
         $res = $this->_importdocument($oFolder, $sDocumentPath);
         if (PEAR::isError($res)) {
             return $res;
         }
         // Store document object
         $this->uploadedDocs[] = $res;
     }
     $aFolderPaths = $this->oStorage->listFolders($sPath);
     if (PEAR::isError($aFolderPaths)) {
         return $aFolderPaths;
     }
     $oFolderObjects = array();
     foreach ($aFolderPaths as $sFolderPath) {
         $sFolderBasePath = basename($sFolderPath);
         $sFolderBasePath = $this->is_utf8($sFolderBasePath) ? $sFolderBasePath : utf8_encode($sFolderBasePath);
         if (Folder::folderExistsName($sFolderPath, KTUtil::getId($oFolder))) {
             $_SESSION['KTErrorMessage'][] = sprintf(_kt("The folder %s is already present in %s.  Adding files into pre-existing folder."), $sFolderBasePath, $oFolder->getName());
             $aOptions = Folder::getList("parent_id = " . KTUtil::getId($oFolder) . ' AND name = "' . DBUtil::escapeSimple($sFolderBasePath) . '"');
             if (PEAR::isError($aOptions)) {
                 return $aOptions;
             }
             if (count($aOptions) != 1) {
                 return PEAR::raiseError(sprintf(_kt("Two folders named %s present in %s. Unable to decide which to use..."), $sFolderName, $oFolder->getName()));
             } else {
                 $oThisFolder = $aOptions[0];
             }
         } else {
             if (KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPermission, $oFolder)) {
                 $oThisFolder = KTFolderUtil::add($oFolder, $sFolderBasePath, $this->oUser, true);
             } else {
                 $oThisFolder = $oFolder;
                 if (!in_array('Your documents have been added to this folder and not the folder structure within the upload file because you do not have permission to add any folders.', $_SESSION['KTErrorMessage'])) {
                     $_SESSION['KTErrorMessage'][] = sprintf(_kt('Your documents have been added to this folder and not the folder structure within the upload file because you do not have permission to add any folders.'));
                 }
             }
         }
         if (PEAR::isError($oThisFolder)) {
             return $oThisFolder;
         }
         $res = $this->_importfolder($oThisFolder, $sFolderPath);
         if (PEAR::isError($res)) {
             return $res;
         }
         // Store folder object
         $this->uploadedFolders[] = $res;
     }
 }
 /**
  * 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();
 }
<?php

require_once "../../config/dmsDefaults.php";
require_once KT_LIB_DIR . '/foldermanagement/Folder.inc';
require_once KT_LIB_DIR . '/permissions/permissionutil.inc.php';
error_reporting(E_ALL);
$oFolder =& Folder::get(2);
$oPO = KTPermissionObject::get($oFolder->getPermissionObjectID());
$res = KTPermissionUtil::findRootObjectForPermissionObject($oPO);
var_dump($res);