function _importfolder($oFolder, $sPath)
 {
     $oPermission = KTPermission::getByName('ktcore.permissions.addFolder');
     $aDocPaths = $this->oStorage->listDocuments($sPath);
     if (PEAR::isError($aDocPaths)) {
         return $aDocPaths;
     }
     foreach ($aDocPaths as $sDocumentPath) {
         $res = $this->_importdocument($oFolder, $sDocumentPath);
         if (PEAR::isError($res)) {
             return $res;
         }
     }
     $aFolderPaths = $this->oStorage->listFolders($sPath);
     if (PEAR::isError($aFolderPaths)) {
         return $aFolderPaths;
     }
     foreach ($aFolderPaths as $sFolderPath) {
         if (Folder::folderExistsName(utf8_encode(basename($sFolderPath)), KTUtil::getId($oFolder))) {
             $_SESSION['KTErrorMessage'][] = sprintf(_kt("The folder %s is already present in %s.  Adding files into pre-existing folder."), utf8_encode(basename($sFolderPath)), $oFolder->getName());
             $aOptions = Folder::getList("parent_id = " . KTUtil::getId($oFolder) . ' AND name = "' . DBUtil::escapeSimple(utf8_encode(basename($sFolderPath))) . '"');
             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, utf8_encode(basename($sFolderPath)), $this->oUser);
             } 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;
         }
     }
 }
 function _show()
 {
     if (is_null($this->_sShowPermission)) {
         return true;
     }
     $oPermission =& KTPermission::getByName($this->_sShowPermission);
     if (PEAR::isError($oPermission)) {
         return true;
     }
     if ($this->_bAdminAlwaysAvailable) {
         if (KTBrowseUtil::inAdminMode($this->oUser, $this->oFolder)) {
             return true;
         }
     }
     return KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPermission, $this->oFolder);
 }
Example #3
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 #4
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;
 }
 function setPersonalFolderPermissions($oPO)
 {
     $aWorkSpaceOwnerRoleID = $this->getRoleIdByName('WorkSpaceOwner');
     $aAdminGroupID = $this->getGroupIdByName('System Administrators');
     //arrays used to make integers for $aAllowed array variable
     $iWorkSpaceOwnerRoleID = $aWorkSpaceOwnerRoleID[0]['id'];
     $iAdminGroupID = $aAdminGroupID[0]['id'];
     //set permissions for the role and the admin group
     $aAllowed = array('role' => array($iWorkSpaceOwnerRoleID), 'group' => array($iAdminGroupID));
     //Get the List of all the permissions
     $aPersonalFolderPermissions = KTPermission::getList();
     //Iterate through and apply all permissions to the current user and the admin group
     foreach ($aPersonalFolderPermissions as $oPersonalFolderPermission) {
         KTPermissionUtil::setPermissionForId($oPersonalFolderPermission, $oPO, $aAllowed);
     }
     //Update permission lookup
     KTPermissionUtil::updatePermissionLookupForPO($oPO);
 }
Example #6
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);
 }
 function getConfigDescription()
 {
     if (!$this->isLoaded()) {
         return _kt('This trigger has no configuration.');
     }
     // the actual permissions are stored in the array.
     $perms = array();
     if (empty($this->aConfig) || is_null($this->aConfig['perms'])) {
         return _kt('No permissions are required to perform this transition');
     }
     foreach ($this->aConfig['perms'] as $sPermName) {
         $oPerm = KTPermission::getByName($sPermName);
         if (!PEAR::isError($oPerm)) {
             $perms[] = $oPerm->getHumanName();
         }
     }
     if (empty($perms)) {
         return _kt('No permissions are required to perform this transition');
     }
     $perm_string = implode(', ', $perms);
     return sprintf(_kt('The following permissions are required: %s'), $perm_string);
 }
 /**
  * Check whether a given user has the given permission on the given
  * object, by virtue of a direct or indirect assignment due to the
  * user, its groups, its roles, or the roles assigned to its groups,
  * and so forth.
  */
 function userHasPermissionOnItem($oUser, $oPermission, $oFolderOrDocument)
 {
     if (is_string($oPermission)) {
         $oPermission =& KTPermission::getByName($oPermission);
     }
     if (PEAR::isError($oPermission)) {
         return false;
     }
     if (PEAR::isError($oFolderOrDocument) || $oFolderOrDocument == null) {
         return false;
     }
     // Quick fix for multiple permissions look ups.
     // For the current lookup, if the permissions have been checked then return their value
     $iPermId = $oPermission->getID();
     $iDocId = $oFolderOrDocument->getID();
     $lookup = 'folders';
     if (is_a($oFolderOrDocument, 'Document') || is_a($oFolderOrDocument, 'DocumentProxy')) {
         $lookup = 'docs';
     }
     // check if permission has been set
     // $permArr[permId] = array('folders' => array('id' => bool), 'docs' => array('id' => bool));
     if (isset(KTPermissionUtil::$permArr[$iPermId][$lookup][$iDocId])) {
         //return KTPermissionUtil::$permArr[$iPermId][$lookup][$iDocId];
     }
     $oPL = KTPermissionLookup::get($oFolderOrDocument->getPermissionLookupID());
     $oPLA = KTPermissionLookupAssignment::getByPermissionAndLookup($oPermission, $oPL);
     if (PEAR::isError($oPLA)) {
         //print $oPL->getID();
         KTPermissionUtil::$permArr[$iPermId][$lookup][$iDocId] = false;
         return false;
     }
     $oPD = KTPermissionDescriptor::get($oPLA->getPermissionDescriptorID());
     // set permission array to true
     KTPermissionUtil::$permArr[$iPermId][$lookup][$iDocId] = true;
     // check for permissions
     $aGroups = GroupUtil::listGroupsForUserExpand($oUser);
     if ($oPD->hasRoles(array(-3))) {
         return true;
     } else {
         if ($oPD->hasUsers(array($oUser))) {
             return true;
         } else {
             if ($oPD->hasGroups($aGroups)) {
                 return true;
             } else {
                 if ($oPD->hasRoles(array(-4)) && !$oUser->isAnonymous()) {
                     return true;
                 }
             }
         }
     }
     // permission isn't true, set to false
     KTPermissionUtil::$permArr[$iPermId][$lookup][$iDocId] = false;
     return false;
 }
Example #9
0
 function check_entity($oEntity)
 {
     $oPermission =& KTPermission::getByName($this->_sPermission);
     if (PEAR::isError($oPermission)) {
         return true;
     }
     // basic document checks
     // TODO: check if this is appropriate
     //       should probably store the 'equivalent' action (ie. document.delete)
     //       and check that, rather than add a new list of actions to the workflow
     //       section
     if (is_a($oEntity, 'Document')) {
         if (!KTWorkflowUtil::actionEnabledForDocument($oEntity, $this->sName)) {
             return PEAR::raiseError(_kt('Action is disabled by workflow'));
         }
         $status = $oEntity->getStatusID();
         if ($status == DELETED || $status == ARCHIVED) {
             return PEAR::raiseError(_kt('Document is archived or deleted'));
         }
     }
     // admin check
     if ($this->bAllowInAdminMode) {
         if (KTBrowseUtil::inAdminMode($this->oUser, null)) {
             return true;
         }
     }
     if (!KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPermission, $oEntity)) {
         return PEAR::raiseError(_kt('You do not have the required permissions'));
     }
     return true;
 }
 /**
  * Deletes a document symbolic link
  *
  * @param Document $document the symbolic link document
  * @param User $user the user deleting the link
  * @return unknown
  */
 static function deleteSymbolicLink($document, $user = null)
 {
     //validate input
     if (is_numeric($document)) {
         $document = Document::get($document);
     }
     if (!$document instanceof Document) {
         return PEAR::raiseError(_kt('Document not specified'));
     }
     if (!$document->isSymbolicLink()) {
         return PEAR::raiseError(_kt('Document must be a symbolic link entity'));
     }
     if (is_null($user)) {
         $user = $_SESSION['userID'];
     }
     if (is_numeric($user)) {
         $user = User::get($user);
     }
     //check permissions
     $oPerm = KTPermission::getByName('ktcore.permissions.delete');
     if (!KTBrowseUtil::inAdminMode($user, $document->getParentID())) {
         if (!KTPermissionUtil::userHasPermissionOnItem($user, $oPerm, $document)) {
             return PEAR::raiseError(_kt('You\'re not authorized to delete this shortcut'));
         }
     }
     // we only need to delete the document entry for the link
     $sql = "DELETE FROM documents WHERE id=?";
     DBUtil::runQuery(array($sql, array($document->getId())));
 }
<?php

require_once "../../config/dmsDefaults.php";
require_once KT_LIB_DIR . "/permissions/permissionobject.inc.php";
require_once KT_LIB_DIR . "/permissions/permissionassignment.inc.php";
require_once KT_LIB_DIR . "/permissions/permission.inc.php";
require_once KT_LIB_DIR . "/permissions/permissionutil.inc.php";
error_reporting(E_ALL);
$oPermissionObject = KTPermissionObject::get(22);
$oPermission = KTPermission::getByName('ktcore.permissions.read');
/*$oPermissionAssignment = KTPermissionAssignment::createFromArray(array(
    'permissionid' => $oPermission->getId(),
    'permissionobjectid' => $oPermissionObject->getId(),
));*/
// $oPermissionAssignment = KTPermissionAssignment::getByPermissionAndObject($oPermission, $oPermissionObject);
$aAllowed = array("group" => array(1, 2, 3, 4));
KTPermissionUtil::setPermissionForID($oPermission, $oPermissionObject, $aAllowed);
Example #12
0
 function do_resolved_users()
 {
     $this->oPage->setBreadcrumbDetails(_kt("Permissions"));
     $oTemplate = $this->oValidator->validateTemplate("ktcore/document/resolved_permissions_user");
     $oPL = KTPermissionLookup::get($this->oDocument->getPermissionLookupID());
     $aPermissions = KTPermission::getList();
     $aMapPermissionGroup = array();
     $aMapPermissionRole = array();
     $aMapPermissionUser = array();
     $aUsers = User::getList();
     foreach ($aPermissions as $oPermission) {
         $oPLA = KTPermissionLookupAssignment::getByPermissionAndLookup($oPermission, $oPL);
         if (PEAR::isError($oPLA)) {
             continue;
         }
         $oDescriptor = KTPermissionDescriptor::get($oPLA->getPermissionDescriptorID());
         $iPermissionID = $oPermission->getID();
         $aMapPermissionGroup[$iPermissionID] = array();
         foreach ($aUsers as $oUser) {
             if (KTPermissionUtil::userHasPermissionOnItem($oUser, $oPermission, $this->oDocument)) {
                 $aMapPermissionUser[$iPermissionID][$oUser->getId()] = true;
                 $aActiveUsers[$oUser->getId()] = true;
             }
         }
     }
     // now we constitute the actual sets.
     $users = array();
     $groups = array();
     $roles = array();
     // should _always_ be empty, barring a bug in permissions::updatePermissionLookup
     // this should be quite limited - direct role -> user assignment is typically rare.
     foreach ($aActiveUsers as $id => $marker) {
         $oUser = User::get($id);
         $users[$oUser->getName()] = $oUser;
     }
     asort($users);
     // ascending, per convention.
     $bEdit = false;
     $sInherited = '';
     $aDynamicControls = array();
     $aWorkflowControls = array();
     // handle conditions
     $iPermissionObjectId = $this->oDocument->getPermissionObjectID();
     if (!empty($iPermissionObjectId)) {
         $oPO = KTPermissionObject::get($iPermissionObjectId);
         $aDynamicConditions = KTPermissionDynamicCondition::getByPermissionObject($oPO);
         if (!PEAR::isError($aDynamicConditions)) {
             foreach ($aDynamicConditions as $oDynamicCondition) {
                 $iConditionId = $oDynamicCondition->getConditionId();
                 if (KTSearchUtil::testConditionOnDocument($iConditionId, $this->oDocument)) {
                     $aPermissionIds = $oDynamicCondition->getAssignment();
                     foreach ($aPermissionIds as $iPermissionId) {
                         $aDynamicControls[$iPermissionId] = true;
                     }
                 }
             }
         }
     }
     // indicate that workflow controls a given permission
     $oState = KTWorkflowUtil::getWorkflowStateForDocument($this->oDocument);
     if (!(PEAR::isError($oState) || is_null($oState) || $oState == false)) {
         $aWorkflowStatePermissionAssignments = KTWorkflowStatePermissionAssignment::getByState($oState);
         foreach ($aWorkflowStatePermissionAssignments as $oAssignment) {
             $aWorkflowControls[$oAssignment->getPermissionId()] = true;
             unset($aDynamicControls[$oAssignment->getPermissionId()]);
         }
     }
     $aTemplateData = array("context" => $this, "permissions" => $aPermissions, "groups" => $groups, "users" => $users, "roles" => $roles, "oDocument" => $this->oDocument, "aMapPermissionGroup" => $aMapPermissionGroup, "aMapPermissionRole" => $aMapPermissionRole, "aMapPermissionUser" => $aMapPermissionUser, "edit" => $bEdit, "inherited" => $sInherited, 'workflow_controls' => $aWorkflowControls, 'conditions_control' => $aDynamicControls);
     return $oTemplate->render($aTemplateData);
 }
Example #13
0
 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';
     }
     $offset = 0;
     foreach ($this->db as $expr) {
         $offset++;
         $sql .= ", ifnull(" . $this->getSQLEvalExpr($expr) . ",0) as expr{$offset} ";
     }
     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";
         }
         if ($this->used_tables['document_fields_link'] > 0) {
             $sql .= ' LEFT JOIN document_fields_link pdfl ON dmv.id=pdfl.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";
     }
     $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 #14
0
 /**
  * This returns a permission object or an error object.
  *
  * @author KnowledgeTree Team
  * @access protected
  * @param string $permission The permissions string
  * @return object $permissions SUCCESS - The KTPermission object | FAILURE - an error object
  */
 public function &get_permission($permission)
 {
     $permissions =& KTPermission::getByName($permission);
     if (is_null($permissions) || PEAR::isError($permissions)) {
         $error = new PEAR_Error(KTAPI_ERROR_PERMISSION_INVALID);
         return $error;
     }
     return $permissions;
 }
Example #15
0
 /**
  * Saves changes made by add() and remove().
  *
  * @author KnowledgeTree Team
  * @access public
  */
 public function save()
 {
     if (!$this->changed) {
         // we don't have to do anything if nothing has changed.
         return;
     }
     // if the current setup is inherited, then we must create a new copy to store the new associations.
     if ($this->getIsInherited()) {
         $this->overrideAllocation();
     }
     $permissions = KTPermission::getList();
     $folderItemObject = $this->_logTransaction(_kt('Updated permissions'), 'ktcore.transactions.permissions_change');
     $permissionObject = KTPermissionObject::get($folderItemObject->getPermissionObjectId());
     // transform the map into the structure expected
     foreach ($permissions as $permission) {
         $permissionId = $permission->getId();
         // not the association is singular here
         $allowed = array('group' => array(), 'role' => array(), 'user' => array());
         // fill the group allocations
         foreach ($this->map['groups']['map'] as $groupId => $allocations) {
             if ($allocations[$permissionId]) {
                 $allowed['group'][] = $groupId;
             }
         }
         // fill the user allocations
         foreach ($this->map['users']['map'] as $userId => $allocations) {
             if ($allocations[$permissionId]) {
                 $allowed['user'][] = $userId;
             }
         }
         // fill the role allocations
         foreach ($this->map['roles']['map'] as $roleId => $allocations) {
             if ($allocations[$permissionId]) {
                 $allowed['role'][] = $roleId;
             }
         }
         KTPermissionUtil::setPermissionForId($permission, $permissionObject, $allowed);
     }
     KTPermissionUtil::updatePermissionLookupForPO($permissionObject);
     // set the copy to be that of the modified version.
     $this->mapCopy = $this->map;
     $this->changed = false;
 }
Example #16
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 #17
0
 /**
  * Get's a folder listing, recursing to the maximum depth.
  * Derived from the get_listing function.
  *
  * <code>
  * $root = $this->ktapi->get_root_folder();
  * $listing = $root->get_full_listing();
  * foreach($listing as $val) {
  * 	if($val['item_type'] == 'F') {
  *   // It's a folder
  *   echo $val['title'];
  *  }
  * }
  * </code>
  *
  * @author KnowledgeTree Team
  * @access public
  * @param string $what
  * @return array
  */
 function get_full_listing($what = 'DFS')
 {
     $what = strtoupper($what);
     $read_permission =& KTPermission::getByName(KTAPI_PERMISSION_READ);
     $folder_permission =& KTPermission::getByName(KTAPI_PERMISSION_VIEW_FOLDER);
     $config = KTConfig::getSingleton();
     $wsversion = $config->get('webservice/version', LATEST_WEBSERVICE_VERSION);
     $user = $this->ktapi->get_user();
     $contents = array();
     if (strpos($what, 'F') !== false) {
         $folder_children = Folder::getList(array('parent_id = ?', $this->folderid));
         foreach ($folder_children as $folder) {
             if (KTPermissionUtil::userHasPermissionOnItem($user, $folder_permission, $folder) || KTPermissionUtil::userHasPermissionOnItem($user, $read_permission, $folder)) {
                 $sub_folder =& $this->ktapi->get_folder_by_id($folder->getId());
                 if (!PEAR::isError($sub_folder)) {
                     $items = $sub_folder->get_full_listing($what);
                 } else {
                     $items = array();
                 }
                 $creator = $this->_resolve_user($folder->getCreatorID());
                 if ($wsversion >= 2) {
                     $array = array('id' => (int) $folder->getId(), 'item_type' => 'F', 'custom_document_no' => 'n/a', 'oem_document_no' => 'n/a', 'title' => $folder->getName(), 'document_type' => 'n/a', 'filename' => $folder->getName(), 'filesize' => 'n/a', 'created_by' => is_null($creator) ? 'n/a' : $creator->getName(), 'created_date' => 'n/a', 'checked_out_by' => 'n/a', 'checked_out_date' => 'n/a', 'modified_by' => 'n/a', 'modified_date' => 'n/a', 'owned_by' => 'n/a', 'version' => 'n/a', 'is_immutable' => 'n/a', 'permissions' => KTAPI_Folder::get_permission_string($folder), 'workflow' => 'n/a', 'workflow_state' => 'n/a', 'mime_type' => 'folder', 'mime_icon_path' => 'folder', 'mime_display' => 'Folder', 'storage_path' => 'n/a');
                     if ($wsversion >= 3) {
                         $array['linked_folder_id'] = $folder->getLinkedFolderId();
                         if ($folder->isSymbolicLink()) {
                             $array['item_type'] = "S";
                         }
                     }
                     $array['items'] = $items;
                     if ($wsversion < 3 || strpos($what, 'F') !== false && !$folder->isSymbolicLink() || $folder->isSymbolicLink() && strpos($what, 'S') !== false) {
                         $contents[] = $array;
                     }
                 } else {
                     $contents[] = array('id' => (int) $folder->getId(), 'item_type' => 'F', 'title' => $folder->getName(), 'creator' => is_null($creator) ? 'n/a' : $creator->getName(), 'checkedoutby' => 'n/a', 'modifiedby' => 'n/a', 'filename' => $folder->getName(), 'size' => 'n/a', 'major_version' => 'n/a', 'minor_version' => 'n/a', 'storage_path' => 'n/a', 'mime_type' => 'folder', 'mime_icon_path' => 'folder', 'mime_display' => 'Folder', 'items' => $items, 'workflow' => 'n/a', 'workflow_state' => 'n/a');
                 }
             }
         }
     }
     if (strpos($what, 'D') !== false) {
         $document_children = Document::getList(array('folder_id = ? AND status_id = 1', $this->folderid));
         // I hate that KT doesn't cache things nicely...
         $mime_cache = array();
         foreach ($document_children as $document) {
             if (KTPermissionUtil::userHasPermissionOnItem($user, $read_permission, $document)) {
                 $created_by = $this->_resolve_user($document->getCreatorID());
                 $created_date = $document->getCreatedDateTime();
                 if (empty($created_date)) {
                     $created_date = 'n/a';
                 }
                 $checked_out_by = $this->_resolve_user($document->getCheckedOutUserID());
                 $checked_out_date = $document->getCheckedOutDate();
                 if (empty($checked_out_date)) {
                     $checked_out_date = 'n/a';
                 }
                 $modified_by = $this->_resolve_user($document->getCreatorID());
                 $modified_date = $document->getLastModifiedDate();
                 if (empty($modified_date)) {
                     $modified_date = 'n/a';
                 }
                 $owned_by = $this->_resolve_user($document->getOwnerID());
                 $mimetypeid = $document->getMimeTypeID();
                 if (!array_key_exists($mimetypeid, $mime_cache)) {
                     $type = KTMime::getMimeTypeName($mimetypeid);
                     $icon = KTMime::getIconPath($mimetypeid);
                     $display = KTMime::getFriendlyNameForString($type);
                     $mime_cache[$mimetypeid] = array('type' => $type, 'icon' => $icon, 'display' => $display);
                 }
                 $mimeinfo = $mime_cache[$mimetypeid];
                 $workflow = 'n/a';
                 $state = 'n/a';
                 $wf = KTWorkflowUtil::getWorkflowForDocument($document);
                 if (!is_null($wf) && !PEAR::isError($wf)) {
                     $workflow = $wf->getHumanName();
                     $ws = KTWorkflowUtil::getWorkflowStateForDocument($document);
                     if (!is_null($ws) && !PEAR::isError($ws)) {
                         $state = $ws->getHumanName();
                     }
                 }
                 if ($wsversion >= 2) {
                     $docTypeId = $document->getDocumentTypeID();
                     $documentType = DocumentType::get($docTypeId);
                     $oemDocumentNo = $document->getOemNo();
                     if (empty($oemDocumentNo)) {
                         $oemDocumentNo = 'n/a';
                     }
                     $array = array('id' => (int) $document->getId(), 'item_type' => 'D', 'custom_document_no' => 'n/a', 'oem_document_no' => $oemDocumentNo, 'title' => $document->getName(), 'document_type' => $documentType->getName(), 'filename' => $document->getFileName(), 'filesize' => $document->getFileSize(), 'created_by' => is_null($created_by) ? 'n/a' : $created_by->getName(), 'created_date' => $created_date, 'checked_out_by' => is_null($checked_out_by) ? 'n/a' : $checked_out_by->getName(), 'checked_out_date' => $checked_out_date, 'modified_by' => is_null($modified_by) ? 'n/a' : $modified_by->getName(), 'modified_date' => $modified_date, 'owned_by' => is_null($owned_by) ? 'n/a' : $owned_by->getName(), 'version' => $document->getMajorVersionNumber() . '.' . $document->getMinorVersionNumber(), 'content_id' => $document->getContentVersionId(), 'is_immutable' => $document->getImmutable() ? 'true' : 'false', 'permissions' => KTAPI_Document::get_permission_string($document), 'workflow' => $workflow, 'workflow_state' => $state, 'mime_type' => $mime_cache[$mimetypeid]['type'], 'mime_icon_path' => $mime_cache[$mimetypeid]['icon'], 'mime_display' => $mime_cache[$mimetypeid]['display'], 'storage_path' => $document->getStoragePath());
                     if ($wsversion >= 3) {
                         $document->switchToRealCore();
                         $array['linked_document_id'] = $document->getLinkedDocumentId();
                         $document->switchToLinkedCore();
                         if ($document->isSymbolicLink()) {
                             $array['item_type'] = "S";
                         }
                     }
                     $array['items'] = array();
                     if ($wsversion < 3 || strpos($what, 'D') !== false && !$document->isSymbolicLink() || $document->isSymbolicLink() && strpos($what, 'S') !== false) {
                         $contents[] = $array;
                     }
                 } else {
                     $contents[] = array('id' => (int) $document->getId(), 'item_type' => 'D', 'title' => $document->getName(), 'creator' => is_null($created_by) ? 'n/a' : $created_by->getName(), 'checkedoutby' => is_null($checked_out_by) ? 'n/a' : $checked_out_by->getName(), 'modifiedby' => is_null($modified_by) ? 'n/a' : $modified_by->getName(), 'filename' => $document->getFileName(), 'size' => $document->getFileSize(), 'major_version' => $document->getMajorVersionNumber(), 'minor_version' => $document->getMinorVersionNumber(), 'storage_path' => $document->getStoragePath(), 'mime_type' => $mime_cache[$mimetypeid]['type'], 'mime_icon_path' => $mime_cache[$mimetypeid]['icon'], 'mime_display' => $mime_cache[$mimetypeid]['display'], 'items' => array(), 'workflow' => $workflow, 'workflow_state' => $state);
                 }
             }
         }
     }
     return $contents;
 }
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 do_deletePermission()
 {
     $id = KTUtil::arrayGet($_REQUEST, 'id');
     if (empty($id)) {
         return $this->errorRedirectToMain(_kt("Both names not given"));
     }
     $oPerm = KTPermission::get($id);
     if (PEAR::isError($oPerm)) {
         return $this->errorRedirectToMain(_kt("Error finding permission"));
     }
     if ($oPerm->getBuiltIn() === true) {
         return $this->errorRedirectToMain(_kt("Can't delete built-in permission"));
     }
     $res = $oPerm->delete();
     if (PEAR::isError($res)) {
         return $this->errorRedirectToMain(_kt("Error deleting permission"));
     }
     return $this->successRedirectToMain(_kt("Permission deleted"));
 }
 /**
  * Gets a list of linked documents
  *
  * @author KnowledgeTree Team
  * @access public
  * @return array|PEAR_Error Returns a list of linked documents on success | a PEAR_Error on failure
  */
 function get_linked_documents()
 {
     $sql = "\n\t\tSELECT\n\t\t\tdl.child_document_id as document_id,\n\t\t\tdmv.name as title,\n\t\t\tdcv.size,\n\t\t\tw.name as workflow,\n\t\t\tws.name as workflow_state,\n\t\t\tdlt.name as link_type, dtl.name as document_type,\n\t\t\tdcv.major_version, dcv.minor_version, d.oem_no\n\t\tFROM\n\t\t\tdocument_link dl\n\t\t\tINNER JOIN document_link_types dlt ON dl.link_type_id=dlt.id\n\t\t\tINNER JOIN documents d ON dl.child_document_id=d.id\n\t\t\tINNER JOIN document_metadata_version dmv ON d.metadata_version_id=dmv.id\n\t\t\tINNER JOIN document_content_version dcv ON dmv.content_version_id=dcv.id\n\t\t\tINNER JOIN document_types_lookup dtl ON dtl.id=dmv.document_type_id\n\t\t\tLEFT OUTER JOIN workflow_documents wd ON d.id=wd.document_id\n\t\t\tLEFT OUTER JOIN workflows w ON w.id=wd.workflow_id\n\t\t\tLEFT OUTER JOIN workflow_states ws ON wd.state_id=ws.id\n\t\tWHERE\n\t\t\tdl.parent_document_id={$this->documentid}\n\n\t\t";
     $rows = DBUtil::getResultArray($sql);
     if (PEAR::isError($rows)) {
         return $rows;
     }
     $result = array();
     $read_permission =& KTPermission::getByName(KTAPI_PERMISSION_READ);
     $user = $this->ktapi->get_user();
     foreach ($rows as $row) {
         $document = Document::get($row['document_id']);
         if (PEAR::isError($document) || is_null($document)) {
             continue;
         }
         if (!KTPermissionUtil::userHasPermissionOnItem($user, $read_permission, $document)) {
             continue;
         }
         $oem_no = $row['oem_no'];
         if (empty($oem_no)) {
             $oem_no = 'n/a';
         }
         $result[] = array('document_id' => (int) $row['document_id'], 'custom_document_no' => 'n/a', 'oem_document_no' => $oem_no, 'title' => $row['title'], 'document_type' => $row['document_type'], 'version' => (double) ($row['major_version'] . '.' . $row['minor_version']), 'filesize' => (int) $row['size'], 'workflow' => empty($row['workflow']) ? 'n/a' : $row['workflow'], 'workflow_state' => empty($row['workflow_state']) ? 'n/a' : $row['workflow_state'], 'link_type' => empty($row['link_type']) ? 'unknown' : $row['link_type']);
     }
     return $result;
 }
Example #21
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 _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 #23
0
 function do_update()
 {
     $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);
     }
     $aFoo = $_REQUEST['foo'];
     $aPermissions = KTPermission::getList();
     /*
     		--- This section has been commented out to remove these checks when permissions
     		--- are updated.
     		---------------------------------------------------------------------------------
     
     		//-------------------
     //This section is used to make sure that a user doesn't disable the admin groups
     //Manage security permission or the Manage Security permission of a group they
     //are currently a member of.
     
     // Check which groups have permission to manage security
     $aNewGroups = (isset($aFoo[4]['group']) ? $aFoo[4]['group'] : array());
     $aNewRoles = (isset($aFoo[4]['role']) ? $aFoo[4]['role'] : array());
     
     $iUserId = $this->oUser->getId();
     
     //Check that they aren't removing the sys admin Manage Security permission
     //1 in this case is the admin group.
     if(!in_array('1', $aNewGroups))
     {
     	$this->addErrorMessage(_kt('You cannot remove the Manage Security permission from the System Administrators Group'));
         $this->redirectTo('edit', 'fFolderId=' . $this->oFolder->getId());
         exit(0);
     }
     
     
     //Check that they aren't removing the Manage Security permission from a group
     //They are a member of.
     if(!GroupUtil::checkUserInGroups($iUserId, array(1)))
     {
     	        //Ensure the user is not removing his/her own permission to update the folder permissions (manage security)
     	        if(!in_array(-3, $aNewRoles))
     	        {
     
     	            if(!GroupUtil::checkUserInGroups($iUserId, $aNewGroups))
     	            {
     	                // If user no longer has permission, return an error.
     	                $this->addErrorMessage(_kt('You cannot remove the Manage Security permission from a group you belong to.'));
     	                $this->redirectTo('edit', 'fFolderId=' . $this->oFolder->getId());
     	                exit(0);
     	            }
     
     	        }
     }
     		//-----------------
     */
     require_once KT_LIB_DIR . '/documentmanagement/observers.inc.php';
     $oPO = KTPermissionObject::get($this->oFolder->getPermissionObjectId());
     foreach ($aPermissions as $oPermission) {
         $iPermId = $oPermission->getId();
         $aAllowed = KTUtil::arrayGet($aFoo, $iPermId, array());
         KTPermissionUtil::setPermissionForId($oPermission, $oPO, $aAllowed);
     }
     $oTransaction = KTFolderTransaction::createFromArray(array('folderid' => $this->oFolder->getId(), 'comment' => _kt('Updated 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);
     $po =& new JavascriptObserver($this);
     $po->start();
     $oChannel =& KTPermissionChannel::getSingleton();
     $oChannel->addObserver($po);
     KTPermissionUtil::updatePermissionLookupForPO($oPO);
     $this->commitTransaction();
     $this->addInfoMessage(_kt('Permissions on folder updated'));
     $po->redirect(KTUtil::addQueryString($_SERVER['PHP_SELF'], 'action=edit&fFolderId=' . $this->oFolder->getId()));
     exit(0);
 }
Example #24
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 #25
0
 function do_allocatepermissions()
 {
     $oTemplate = $this->oValidator->validateTemplate('ktcore/workflow/admin/allocate_permissions');
     $oForm = $this->form_managepermissions();
     $this->breadcrumbs_security();
     $this->aBreadcrumbs[] = array('name' => _kt("Document Permissions"), 'url' => KTUtil::addQueryStringSelf($this->meldPersistQuery("fStateId=", "permissionsoverview", true)));
     $this->aBreadcrumbs[] = array('name' => $this->oState->getHumanName(), 'url' => KTUtil::addQueryStringSelf($this->meldPersistQuery("", "managepermissions", true)));
     $this->oPage->setBreadcrumbDetails(_kt("Allocate Permissions"));
     $aUsefulPermissions = KTPermission::getDocumentRelevantList();
     $aPermissionGrid = array();
     $aStatePermAssigns = KTWorkflowStatePermissionAssignment::getByState($this->oState);
     foreach ($aStatePermAssigns as $oPermAssign) {
         $aPermissionGrid[$oPermAssign->getPermissionId()] = $oPermAssign;
     }
     $aPermissionsToJSON = array();
     foreach ($aUsefulPermissions as $oP) {
         $perm_id = $oP->getId();
         if ($aPermissionGrid[$perm_id]) {
             $aPermissionsToJSON[] = array('id' => $oP->getId(), 'name' => $oP->getHumanName());
         }
     }
     $oJSON = new Services_JSON();
     $sJSONPermissions = $oJSON->encode($aPermissionsToJSON);
     $oTemplate->setData(array('context' => $this, 'perm_grid' => $aPermissionGrid, 'perms' => $aUsefulPermissions, 'form' => $oForm, 'jsonpermissions' => $sJSONPermissions, 'args' => $this->meldPersistQuery("", "setpermissionallocations", true)));
     return $oTemplate->render();
 }
 function generateWorkflowTriggers()
 {
     require_once KT_LIB_DIR . '/workflow/workflowutil.inc.php';
     // get all the transitions, and add a trigger to the util with the appropriate settings.
     $KTWFTriggerReg =& KTWorkflowTriggerRegistry::getSingleton();
     $aTransitions = KTWorkflowTransition::getList();
     foreach ($aTransitions as $oTransition) {
         // guard perm
         $iGuardPerm = $oTransition->getGuardPermissionId();
         if (!is_null($iGuardPerm)) {
             $sNamespace = 'ktcore.workflowtriggers.permissionguard';
             $oPerm = KTPermission::get($iGuardPerm);
             $oTrigger = $KTWFTriggerReg->getWorkflowTrigger($sNamespace);
             $oTriggerConfig = KTWorkflowTriggerInstance::createFromArray(array('transitionid' => KTUtil::getId($oTransition), 'namespace' => $sNamespace, 'config' => array('perms' => array($oPerm->getName()))));
         }
         // guard group
         $iGuardGroup = $oTransition->getGuardGroupId();
         if (!is_null($iGuardGroup)) {
             $sNamespace = 'ktcore.workflowtriggers.groupguard';
             $oTrigger = $KTWFTriggerReg->getWorkflowTrigger($sNamespace);
             $oTriggerConfig = KTWorkflowTriggerInstance::createFromArray(array('transitionid' => KTUtil::getId($oTransition), 'namespace' => $sNamespace, 'config' => array('group_id' => $iGuardGroup)));
         }
         // guard role
         $iGuardRole = $oTransition->getGuardRoleId();
         if (!is_null($iGuardRole)) {
             $sNamespace = 'ktcore.workflowtriggers.roleguard';
             $oTrigger = $KTWFTriggerReg->getWorkflowTrigger($sNamespace);
             $oTriggerConfig = KTWorkflowTriggerInstance::createFromArray(array('transitionid' => KTUtil::getId($oTransition), 'namespace' => $sNamespace, 'config' => array('role_id' => $iGuardRole)));
         }
         // guard condition
         $iGuardCondition = $oTransition->getGuardConditionId();
         if (!is_null($iGuardCondition)) {
             $sNamespace = 'ktcore.workflowtriggers.conditionguard';
             $oTrigger = $KTWFTriggerReg->getWorkflowTrigger($sNamespace);
             $oTriggerConfig = KTWorkflowTriggerInstance::createFromArray(array('transitionid' => KTUtil::getId($oTransition), 'namespace' => $sNamespace, 'config' => array('condition_id' => $iGuardCondition)));
         }
     }
 }
Example #27
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;
}
 /**
  * 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";
     }
 }
Example #29
0
<?php

require_once "../../config/dmsDefaults.php";
require_once KT_LIB_DIR . "/permissions/permission.inc.php";
error_reporting(E_ALL);
// var_dump(KTHelpReplacement::get(1));
$res = KTPermission::createFromArray(array());