function setOptions($aOptions = null)
 {
     $this->aOptions = kt_array_merge($this->aOptions, $aOptions);
     $this->sortable = KTUtil::arrayGet($this->aOptions, 'sortable', $this->sortable);
     $this->return_url = KTUtil::arrayGet($this->aOptions, 'return_url', $this->return_url);
     $this->sort_on = KTUtil::arrayGet($this->aOptions, 'sort_on', $this->sort_on);
     $this->sort_direction = KTUtil::arrayGet($this->aOptions, 'sort_on', $this->sort_direction);
 }
 /**
  * Returns the Metadata Fieldsets for the given DocumentId
  * @return KTForm 
  *
  */
 function getTypeMetadataFieldsets($iDocumentTypeID)
 {
     //Creating the form
     $oForm = new KTForm();
     $oFReg =& KTFieldsetRegistry::getSingleton();
     $activesets = KTFieldset::getForDocumentType($iDocumentTypeID);
     foreach ($activesets as $oFieldset) {
         $widgets = kt_array_merge($widgets, $oFReg->widgetsForFieldset($oFieldset, 'fieldset_' . $oFieldset->getId(), $this->oDocument));
         $validators = kt_array_merge($validators, $oFReg->validatorsForFieldset($oFieldset, 'fieldset_' . $oFieldset->getId(), $this->oDocument));
     }
     $oForm->setWidgets($widgets);
     $oForm->setValidators($validators);
     return $oForm->renderWidgets();
 }
Example #3
0
 function getInternalFeed($iUserId)
 {
     $documents = KTrss::getDocuments($iUserId);
     $folders = KTrss::getFolders($iUserId);
     if (is_null($documents)) {
         $documents = array();
     }
     if (is_null($folders)) {
         $folders = array();
     }
     $response = '';
     $aFullList = kt_array_merge($documents, $folders);
     if (!empty($aFullList)) {
         $internalFeed = KTrss::arrayToXML($aFullList);
         $response = rss2arrayBlock($internalFeed);
     }
     return $response;
 }
 function hasUsers($aUsers)
 {
     $sTable = KTUtil::getTableName('permission_descriptor_users');
     if (count($aUsers) === 0) {
         return false;
     }
     $aUserIDs = array();
     foreach ($aUsers as $oUser) {
         $aUserIDs[] = $oUser->getID();
     }
     $sUserIDs = DBUtil::paramArray($aUserIDs);
     $sQuery = "SELECT COUNT(user_id) AS num FROM {$sTable}\n            WHERE descriptor_id = ? AND user_id IN ({$sUserIDs})";
     $aParams = array($this->getID());
     $aParams = kt_array_merge($aParams, $aUserIDs);
     $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'num');
     if (PEAR::isError($res)) {
         return $res;
     }
     if ((int) $res === 0) {
         return false;
     }
     return true;
 }
Example #5
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;
 }
 function fieldsetsForDocument($oDocument, $iTypeOverride = null)
 {
     global $default;
     $oDocument = KTUtil::getObject('Document', $oDocument);
     $iMetadataVersionId = $oDocument->getMetadataVersionId();
     $iDocumentTypeId = $oDocument->getDocumentTypeId();
     if (!is_null($iTypeOverride)) {
         $iDocumentTypeId = $iTypeOverride;
     }
     $sQuery = "SELECT DISTINCT F.id AS fieldset_id " . "FROM {$default->document_metadata_version_table} AS DM INNER JOIN document_fields_link AS DFL ON DM.id = DFL.metadata_version_id " . "INNER JOIN {$default->document_fields_table} AS DF ON DF.ID = DFL.document_field_id " . "INNER JOIN {$default->fieldsets_table} AS F ON F.id = DF.parent_fieldset " . "WHERE DM.id = ?" . "AND F.disabled = false";
     $aParam = array($iMetadataVersionId);
     $aDocumentFieldsetIds = DBUtil::getResultArrayKey(array($sQuery, $aParam), 'fieldset_id');
     $aGenericFieldsetIds = KTFieldset::getGenericFieldsets(array('ids' => true));
     $aSpecificFieldsetIds = KTFieldset::getForDocumentType($iDocumentTypeId, array('ids' => true));
     $aFieldsetIds = kt_array_merge($aDocumentFieldsetIds, $aGenericFieldsetIds, $aSpecificFieldsetIds);
     $aFieldsetIds = array_unique($aFieldsetIds);
     sort($aFieldsetIds);
     $aRet = array();
     foreach ($aFieldsetIds as $iID) {
         $aRet[] = call_user_func(array('KTFieldset', 'get'), $iID);
     }
     return $aRet;
 }
 function do_new()
 {
     $this->oPage->setBreadcrumbDetails(_kt("New Link"));
     $this->oPage->setTitle(_kt("New Link"));
     $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 add a document link'), sprintf("fDocumentId=%d", $this->oDocument->getId()));
         exit(0);
     }
     $oParentDocument =& $this->oDocument;
     if (PEAR::isError($oParentDocument)) {
         $this->errorRedirectToMain(_kt('Invalid parent document selected.'));
         exit(0);
     }
     $oFolder = Folder::get(KTUtil::arrayGet($_REQUEST, 'fFolderId', $oParentDocument->getFolderID()));
     if (PEAR::isError($oFolder) || $oFolder == false) {
         $this->errorRedirectToMain(_kt('Invalid folder selected.'));
         exit(0);
     }
     $iFolderId = $oFolder->getId();
     // Setup the collection for move display.
     $collection = new AdvancedCollection();
     $aBaseParams = array('fDocumentId' => $oParentDocument->getId());
     $oCR =& KTColumnRegistry::getSingleton();
     $col = $oCR->getColumn('ktcore.columns.selection');
     $aColOptions = array();
     $aColOptions['qs_params'] = kt_array_merge($aBaseParams, array('fFolderId' => $oFolder->getId()));
     $aColOptions['show_folders'] = false;
     $aColOptions['show_documents'] = true;
     $aColOptions['rangename'] = 'linkselection[]';
     $col->setOptions($aColOptions);
     $collection->addColumn($col);
     $col = $oCR->getColumn('ktdocumentlinks.columns.title');
     $col->setOptions(array('qs_params' => kt_array_merge($aBaseParams, array('action' => 'new', 'fFolderId' => $oFolder->getId()))));
     $collection->addColumn($col);
     $qObj = new BrowseQuery($iFolderId);
     $collection->setQueryObject($qObj);
     $aOptions = $collection->getEnvironOptions();
     //$aOptions['is_browse'] = true;
     $aResultUrl = $aBaseParams;
     $aResultUrl['fFolderId'] = $oFolder->getId();
     $aResultUrl['action'] = 'new';
     $aOptions['result_url'] = KTUtil::addQueryString($_SERVER['PHP_SELF'], $aResultUrl);
     $collection->setOptions($aOptions);
     $aURLParams = $aBaseParams;
     $aURLParams['action'] = 'new';
     $aBreadcrumbs = KTUtil::generate_breadcrumbs($oFolder, $iFolderId, $aURLParams);
     // Add an electronic signature
     global $default;
     if ($default->enableESignatures) {
         $sUrl = KTPluginUtil::getPluginPath('electronic.signatures.plugin', true);
         $heading = _kt('You are attempting to add a document link');
         $submit['type'] = 'button';
         $submit['onclick'] = "javascript: showSignatureForm('{$sUrl}', '{$heading}', 'ktcore.transactions.add_link', 'document', 'document_add_link_form', 'submit', {$oParentDocument->iId});";
     } else {
         $submit['type'] = 'submit';
         $submit['onclick'] = '';
     }
     $aTemplateData = array('context' => $this, 'folder' => $oFolder, 'parent' => $oParentDocument, 'breadcrumbs' => $aBreadcrumbs, 'collection' => $collection, 'link_types' => LinkType::getList("id > 0"), 'submit' => $submit);
     $oTemplate =& $this->oValidator->validateTemplate('ktstandard/action/link');
     return $oTemplate->render($aTemplateData);
 }
Example #8
0
 function do_login()
 {
     $aExtra = array();
     $oUser =& KTInterceptorRegistry::checkInterceptorsForAuthenticated();
     if (is_a($oUser, 'User')) {
         $res = $this->performLogin($oUser);
         if ($res) {
             $oUser = array($res);
         }
     }
     if (is_array($oUser)) {
         foreach ($oUser as $oError) {
             if (is_a($oError, 'KTNoLocalUser')) {
                 $aExtra = kt_array_merge($aExtra, $oError->aExtra);
             }
         }
     }
     KTInterceptorRegistry::checkInterceptorsForTakeOver();
     $this->check();
     global $default;
     $language = KTUtil::arrayGet($_REQUEST, 'language');
     if (empty($language)) {
         $language = $default->defaultLanguage;
     }
     setcookie("kt_language", $language, 2147483647, '/');
     $redirect = strip_tags(KTUtil::arrayGet($_REQUEST, 'redirect'));
     $url = $_SERVER["PHP_SELF"];
     $queryParams = array();
     if (!empty($redirect)) {
         $queryParams[] = 'redirect=' . urlencode($redirect);
     }
     $username = KTUtil::arrayGet($_REQUEST, 'username');
     $password = KTUtil::arrayGet($_REQUEST, 'password');
     if (empty($username)) {
         $this->simpleRedirectToMain(_kt('Please enter your username.'), $url, $queryParams);
     }
     $oUser =& User::getByUsername($username);
     if (PEAR::isError($oUser) || $oUser === false) {
         if (is_a($oUser, 'ktentitynoobjects')) {
             $this->handleUserDoesNotExist($username, $password, $aExtra);
         }
         $this->simpleRedirectToMain(_kt('Login failed.  Please check your username and password, and try again.'), $url, $queryParams);
         exit(0);
     }
     if (empty($password)) {
         $this->simpleRedirectToMain(_kt('Please enter your password.'), $url, $queryParams);
     }
     $authenticated = KTAuthenticationUtil::checkPassword($oUser, $password);
     if (PEAR::isError($authenticated)) {
         $this->simpleRedirectToMain(_kt('Authentication failure.  Please try again.'), $url, $queryParams);
         exit(0);
     }
     if ($authenticated !== true) {
         $this->simpleRedirectToMain(_kt('Login failed.  Please check your username and password, and try again.'), $url, $queryParams);
         exit(0);
     }
     $res = $this->performLogin($oUser);
     if ($res) {
         $this->simpleRedirectToMain($res->getMessage(), $url, $queryParams);
         exit(0);
     }
 }
Example #9
0
 function do_viewComparison()
 {
     $document_data = array();
     $document_id = KTUtil::arrayGet($_REQUEST, 'fDocumentId');
     if ($document_id === null) {
         $this->oPage->addError(sprintf(_kt("No document was requested.  Please <a href=\"%s\">browse</a> for one."), KTBrowseUtil::getBrowseBaseUrl()));
         return $this->do_error();
     }
     $document_data['document_id'] = $document_id;
     $base_version = KTUtil::arrayGet($_REQUEST, 'fBaseVersion');
     // try get the document.
     $oDocument =& Document::get($document_id, $base_version);
     if (PEAR::isError($oDocument)) {
         $this->oPage->addError(sprintf(_kt("The base document you attempted to retrieve is invalid.   Please <a href=\"%s\">browse</a> for one."), KTBrowseUtil::getBrowseBaseUrl()));
         return $this->do_error();
     }
     if (!Permission::userHasDocumentReadPermission($oDocument)) {
         // FIXME inconsistent.
         $this->oPage->addError(_kt('You are not allowed to view this document'));
         return $this->permissionDenied();
     }
     $this->oDocument =& $oDocument;
     $this->oPage->setSecondaryTitle($oDocument->getName());
     $aOptions = array('documentaction' => 'viewDocument', 'folderaction' => 'browse');
     $this->aBreadcrumbs = kt_array_merge($this->aBreadcrumbs, KTBrowseUtil::breadcrumbsForDocument($oDocument, $aOptions));
     $this->oPage->setBreadcrumbDetails(_kt('compare versions'));
     $comparison_version = KTUtil::arrayGet($_REQUEST, 'fComparisonVersion');
     if ($comparison_version === null) {
         $this->oPage->addError(sprintf(_kt("No comparison version was requested.  Please <a href=\"%s\">select a version</a>."), KTUtil::addQueryStringSelf('action=history&fDocumentId=' . $document_id)));
         return $this->do_error();
     }
     $oComparison =& Document::get($oDocument->getId(), $comparison_version);
     if (PEAR::isError($oComparison)) {
         $this->errorRedirectToMain(_kt('Invalid document to compare against.'));
     }
     $comparison_data = array();
     $comparison_data['document_id'] = $oComparison->getId();
     $document_data['document'] = $oDocument;
     $comparison_data['document'] = $oComparison;
     $document_data['document_type'] =& DocumentType::get($oDocument->getDocumentTypeID());
     $comparison_data['document_type'] =& DocumentType::get($oComparison->getDocumentTypeID());
     // follow twice:  once for normal, once for comparison.
     $is_valid_doctype = true;
     if (PEAR::isError($document_data['document_type'])) {
         $this->oPage->addError(_kt('The document you requested has an invalid <strong>document type</strong>.  Unfortunately, this means that we cannot effectively display it.'));
         $is_valid_doctype = false;
     }
     // we want to grab all the md for this doc, since its faster that way.
     $mdlist =& DocumentFieldLink::getList(array('metadata_version_id = ?', array($base_version)));
     $field_values = array();
     foreach ($mdlist as $oFieldLink) {
         $field_values[$oFieldLink->getDocumentFieldID()] = $oFieldLink->getValue();
     }
     $document_data['field_values'] = $field_values;
     $mdlist =& DocumentFieldLink::getList(array('metadata_version_id = ?', array($comparison_version)));
     $field_values = array();
     foreach ($mdlist as $oFieldLink) {
         $field_values[$oFieldLink->getDocumentFieldID()] = $oFieldLink->getValue();
     }
     $comparison_data['field_values'] = $field_values;
     // Fieldset generation.
     //
     //   we need to create a set of FieldsetDisplay objects
     //   that adapt the Fieldsets associated with this lot
     //   to the view (i.e. ZX3).   Unfortunately, we don't have
     //   any of the plumbing to do it, so we handle this here.
     $fieldsets = array();
     // we always have a generic.
     array_push($fieldsets, new GenericFieldsetDisplay());
     // FIXME can we key this on fieldset namespace?  or can we have duplicates?
     // now we get the other fieldsets, IF there is a valid doctype.
     if ($is_valid_doctype) {
         // these are the _actual_ fieldsets.
         $fieldsetDisplayReg =& KTFieldsetDisplayRegistry::getSingleton();
         // and the generics
         $activesets = KTFieldset::getGenericFieldsets();
         foreach ($activesets as $oFieldset) {
             $displayClass = $fieldsetDisplayReg->getHandler($oFieldset->getNamespace());
             array_push($fieldsets, new $displayClass($oFieldset));
         }
         $activesets = KTFieldset::getForDocumentType($oDocument->getDocumentTypeID());
         foreach ($activesets as $oFieldset) {
             $displayClass = $fieldsetDisplayReg->getHandler($oFieldset->getNamespace());
             array_push($fieldsets, new $displayClass($oFieldset));
         }
     }
     // FIXME handle ad-hoc fieldsets.
     $this->addPortlets();
     $oTemplate = $this->oValidator->validateTemplate('ktcore/document/compare');
     $aTemplateData = array('context' => $this, 'document_id' => $document_id, 'document' => $oDocument, 'document_data' => $document_data, 'comparison_data' => $comparison_data, 'comparison_document' => $oComparison, 'fieldsets' => $fieldsets);
     //var_dump($aTemplateData['comparison_data']);
     return $oTemplate->render($aTemplateData);
 }
Example #10
0
 /**
  * Converts a criteria set into a SQL query that (by default)
  * returns the ids of documents that fulfil the criteria.
  *
  * $aOptions is a dictionary that can contain:
  *      - select - a string that contains the list of columns
  *        selected in the query
  *      - join - a string that contains join conditions to satisfy
  *        the select string passed or limit the documents included
  *
  * A list with the following elements is returned:
  *      - String containing the parameterised SQL query
  *      - Array containing the parameters for the SQL query
  */
 function criteriaToQuery($aCriteriaSet, $oUser, $sPermissionName, $aOptions = null)
 {
     global $default;
     $sSelect = KTUtil::arrayGet($aOptions, 'select', 'D.id AS document_id');
     $sInitialJoin = KTUtil::arrayGet($aOptions, 'join', '');
     if (is_array($sInitialJoin)) {
         $aInitialJoinParams = $sInitialJoin[1];
         $sInitialJoin = $sInitialJoin[0];
     }
     $res = KTSearchUtil::criteriaSetToSQL($aCriteriaSet);
     if (PEAR::isError($res)) {
         return $res;
     }
     list($sSQLSearchString, $aCritParams, $sCritJoinSQL) = $res;
     $sToSearch = KTUtil::arrayGet($aOrigReq, 'fToSearch', 'Live');
     // actually never present in this version.
     $res = KTSearchUtil::permissionToSQL($oUser, $sPermissionName);
     if (PEAR::isError($res)) {
         // only occurs if the group has no permissions.
         return $res;
     } else {
         list($sPermissionString, $aPermissionParams, $sPermissionJoin) = $res;
     }
     /*
      * This is to overcome the problem where $sPermissionString (or
      * even $sSQLSearchString) is empty, leading to leading or
      * trailing ANDs.
      */
     $aPotentialWhere = array($sPermissionString, 'SL.name = ?', "({$sSQLSearchString})");
     $aWhere = array();
     foreach ($aPotentialWhere as $sWhere) {
         if (empty($sWhere)) {
             continue;
         }
         if ($sWhere == "()") {
             continue;
         }
         $aWhere[] = $sWhere;
     }
     $sWhere = "";
     if ($aWhere) {
         $sWhere = "\tWHERE " . join(" AND ", $aWhere);
     }
     //$sQuery = DBUtil::compactQuery("
     $sQuery = sprintf("\n    SELECT\n        %s\n    FROM\n        %s AS D\n        LEFT JOIN %s AS DM ON D.metadata_version_id = DM.id\n        LEFT JOIN %s AS DC ON DM.content_version_id = DC.id\n        INNER JOIN {$default->status_table} AS SL on D.status_id=SL.id\n        %s\n        %s\n        %s\n        %s", $sSelect, KTUtil::getTableName('documents'), KTUtil::getTableName('document_metadata_version'), KTUtil::getTableName('document_content_version'), $sInitialJoin, $sCritJoinSQL, $sPermissionJoin, $sWhere);
     // GROUP BY D.id
     $aParams = array();
     $aParams = kt_array_merge($aParams, $aInitialJoinParams);
     $aParams = kt_array_merge($aParams, $aPermissionParams);
     $aParams[] = $sToSearch;
     $aParams = kt_array_merge($aParams, $aCritParams);
     return array($sQuery, $aParams);
 }
Example #11
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 #12
0
 function json_getUsers()
 {
     $oConfig = KTConfig::getSingleton();
     $bOnlyOwnGroup = $oConfig->get('email/onlyOwnGroups', false);
     $sFilter = KTUtil::arrayGet($_REQUEST, 'filter', false);
     $aUserList = array('off' => _kt('-- Please filter --'));
     if ($sFilter && trim($sFilter)) {
         $sWhere = sprintf('name LIKE \'%%%s%%\' AND disabled = \'0\'', $sFilter);
         if ($bOnlyOwnGroup != true) {
             $aUsers = User::getEmailUsers($sWhere);
         } else {
             $aGroups = GroupUtil::listGroupsForUser($this->oUser);
             $aMembers = array();
             foreach ($aGroups as $oGroup) {
                 $aMembers = kt_array_merge($aMembers, $oGroup->getMembers());
             }
             $aUsers = array();
             $aUserIds = array();
             foreach ($aMembers as $oUser) {
                 if (in_array($oUser->getId(), $aUserIds)) {
                     continue;
                 }
                 $aUsers[] = $oUser;
             }
         }
         $aUserList = array();
         foreach ($aUsers as $u) {
             $aUserList[$u->getId()] = $u->getName();
         }
     }
     return $aUserList;
 }
Example #13
0
 function persistParams($aParamKeys)
 {
     $this->aPersistParams = kt_array_merge($this->aPersistParams, $aParamKeys);
 }
 function do_main()
 {
     $this->aBreadcrumbs[] = array('url' => $_SERVER['PHP_SELF'], 'name' => _kt('Archived Documents'));
     $this->oPage->setBreadcrumbDetails(_kt('browse'));
     $oFolder = Folder::get(KTUtil::arrayGet($_REQUEST, 'fFolderId', 1));
     if (PEAR::isError($oFolder)) {
         $this->errorRedirectToMain(_kt('Invalid folder selected.'));
         exit(0);
     }
     // Setup the collection for restore display.
     $aBaseParams = array();
     $collection = new AdvancedCollection();
     $oCR =& KTColumnRegistry::getSingleton();
     $col = $oCR->getColumn('ktcore.columns.selection');
     $aColOptions = array();
     //$aColOptions['qs_params'] = kt_array_merge($aBaseParams, array('fFolderId'=>$oFolder->getId()));
     $aColOptions['show_folders'] = false;
     $aColOptions['show_documents'] = true;
     $aColOptions['rangename'] = '_d[]';
     $col->setOptions($aColOptions);
     $collection->addColumn($col);
     $col = $oCR->getColumn('ktcore.columns.title');
     //$col->setOptions(array('qs_params'=>kt_array_merge($aBaseParams, array('action' => 'new', 'fFolderId'=>$oFolder->getId()))));
     $col->setOptions(array('link_documents' => false));
     $collection->addColumn($col);
     //$qObj = new BrowseQuery($iFolderId);
     $qObj = new ArchivedBrowseQuery($oFolder->getId());
     $collection->setQueryObject($qObj);
     $aOptions = $collection->getEnvironOptions();
     $aOptions['result_url'] = KTUtil::addQueryString($_SERVER['PHP_SELF'], array(kt_array_merge($aBaseParams, array('fFolderId' => $oFolder->getId()))));
     $collection->setOptions($aOptions);
     $aURLParams = $aBaseParams;
     $aURLParams['action'] = 'restore';
     $aBreadcrumbs = KTUtil::generate_breadcrumbs($oFolder, $iFolderId, $aURLParams);
     $aTemplateData = array('context' => $this, 'folder' => $oFolder, 'breadcrumbs' => $aBreadcrumbs, 'collection' => $collection);
     $oTemplate =& $this->oValidator->validateTemplate('ktcore/document/admin/archivebrowse');
     return $oTemplate->render($aTemplateData);
 }
Example #15
0
 /**
  * Regenerate permissions for a role.
  *
  * Adapted from KTRoleAllocationPlugin::regeneratePermissionsForRole()
  *
  * @author KnowledgeTree Team
  * @access public
  * @access private
  * @param int $iRoleId
  */
 private function _regeneratePermissionsForRole($iRoleId)
 {
     $object = $this->folderItem->getObject();
     $iStartFolderId = $object->getId();
     /*
      * 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.'));
         }
         $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);
         }
         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()));
         }
         foreach ($aDocList as $oDoc) {
             if (!PEAR::isError($oDoc)) {
                 KTPermissionUtil::updatePermissionLookup($oDoc);
             }
         }
     }
 }
Example #16
0
 function copy($oSrcFolder, $oDestFolder, $oUser, $sReason, $sDestFolderName = NULL, $copyAll = true)
 {
     $sDestFolderName = empty($sDestFolderName) ? $oSrcFolder->getName() : $sDestFolderName;
     if (KTFolderUtil::exists($oDestFolder, $sDestFolderName)) {
         return PEAR::raiseError(_kt("Folder with the same name already exists in the new parent folder"));
     }
     //
     // FIXME the failure cleanup code here needs some serious work.
     //
     $oPerm = KTPermission::getByName('ktcore.permissions.read');
     $oBaseFolderPerm = KTPermission::getByName('ktcore.permissions.addFolder');
     if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oBaseFolderPerm, $oDestFolder)) {
         return PEAR::raiseError(_kt('You are not allowed to create folders in the destination.'));
     }
     // Check if the source folder inherits its permissions
     // Get source PO id and its parent PO id
     $iSrcPoId = $oSrcFolder->getPermissionObjectID();
     $oSrcParent = Folder::get($oSrcFolder->getParentID());
     $iSrcParentPoId = $oSrcParent->getPermissionObjectID();
     // If the folder defines its own permissions then we copy the permission object
     // If the source folder inherits permissions we must change it to inherit from the new parent folder
     $bInheritPermissions = false;
     if ($iSrcPoId == $iSrcParentPoId) {
         $bInheritPermissions = true;
     }
     $aFolderIds = array();
     // of oFolder
     $aDocuments = array();
     // of oDocument
     $aFailedDocuments = array();
     // of String
     $aFailedFolders = array();
     // of String
     $aRemainingFolders = array($oSrcFolder->getId());
     DBUtil::startTransaction();
     while (!empty($aRemainingFolders) && $copyAll) {
         $iFolderId = array_pop($aRemainingFolders);
         $oFolder = Folder::get($iFolderId);
         if (PEAR::isError($oFolder) || $oFolder == false) {
             DBUtil::rollback();
             return PEAR::raiseError(sprintf(_kt('Failure resolving child folder with id = %d.'), $iFolderId));
         }
         // don't just stop ... plough on.
         if (KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oFolder)) {
             $aFolderIds[] = $iFolderId;
         } else {
             $aFailedFolders[] = $oFolder->getName();
         }
         // child documents
         $aChildDocs = Document::getList(array('folder_id = ?', array($iFolderId)));
         foreach ($aChildDocs as $oDoc) {
             if (KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDoc)) {
                 $aDocuments[] = $oDoc;
             } else {
                 $aFailedDocuments[] = $oDoc->getName();
             }
         }
         // child folders.
         $aCFIds = Folder::getList(array('parent_id = ?', array($iFolderId)), array('ids' => true));
         $aRemainingFolders = kt_array_merge($aRemainingFolders, $aCFIds);
     }
     if (!empty($aFailedDocuments) || !empty($aFailedFolders)) {
         $sFD = '';
         $sFF = '';
         if (!empty($aFailedDocuments)) {
             $sFD = _kt('Documents: ') . implode(', ', $aFailedDocuments) . '. ';
         }
         if (!empty($aFailedFolders)) {
             $sFF = _kt('Folders: ') . implode(', ', $aFailedFolders) . '.';
         }
         return PEAR::raiseError(_kt('You do not have permission to copy these items. ') . $sFD . $sFF);
     }
     // first we walk the tree, creating in the new location as we go.
     // essentially this is an "ok" pass.
     $oStorage =& KTStorageManagerUtil::getSingleton();
     $aFolderMap = array();
     $sTable = 'folders';
     $sGetQuery = 'SELECT * FROM ' . $sTable . ' WHERE id = ? ';
     $aParams = array($oSrcFolder->getId());
     $aRow = DBUtil::getOneResult(array($sGetQuery, $aParams));
     unset($aRow['id']);
     $aRow['name'] = $sDestFolderName;
     $aRow['description'] = $sDestFolderName;
     $aRow['parent_id'] = $oDestFolder->getId();
     $aRow['parent_folder_ids'] = sprintf('%s,%s', $oDestFolder->getParentFolderIDs(), $oDestFolder->getId());
     $aRow['full_path'] = $oDestFolder->getFullPath() . '/' . $aRow['name'];
     $id = DBUtil::autoInsert($sTable, $aRow);
     if (PEAR::isError($id)) {
         DBUtil::rollback();
         return $id;
     }
     $sSrcFolderId = $oSrcFolder->getId();
     $aFolderMap[$sSrcFolderId]['parent_id'] = $id;
     $aFolderMap[$sSrcFolderId]['parent_folder_ids'] = $aRow['parent_folder_ids'];
     $aFolderMap[$sSrcFolderId]['full_path'] = $aRow['full_path'];
     $aFolderMap[$sSrcFolderId]['name'] = $aRow['name'];
     $oNewBaseFolder = Folder::get($id);
     $res = $oStorage->createFolder($oNewBaseFolder);
     if (PEAR::isError($res)) {
         // it doesn't exist, so rollback and raise..
         DBUtil::rollback();
         return $res;
     }
     $aRemainingFolders = Folder::getList(array('parent_id = ?', array($oSrcFolder->getId())), array('ids' => true));
     while (!empty($aRemainingFolders) && $copyAll) {
         $iFolderId = array_pop($aRemainingFolders);
         $aParams = array($iFolderId);
         $aRow = DBUtil::getOneResult(array($sGetQuery, $aParams));
         unset($aRow['id']);
         // since we are nested, we will have solved the parent first.
         $sPrevParentId = $aRow['parent_id'];
         $aRow['parent_id'] = $aFolderMap[$aRow['parent_id']]['parent_id'];
         $aRow['parent_folder_ids'] = sprintf('%s,%s', $aFolderMap[$sPrevParentId]['parent_folder_ids'], $aRow['parent_id']);
         $aRow['full_path'] = sprintf('%s/%s', $aFolderMap[$sPrevParentId]['full_path'], $aRow['name']);
         $id = DBUtil::autoInsert($sTable, $aRow);
         if (PEAR::isError($id)) {
             $oStorage->removeFolder($oNewBaseFolder);
             DBUtil::rollback();
             return $id;
         }
         $aFolderMap[$iFolderId]['parent_id'] = $id;
         $aFolderMap[$iFolderId]['parent_folder_ids'] = $aRow['parent_folder_ids'];
         $aFolderMap[$iFolderId]['full_path'] = $aRow['full_path'];
         $aFolderMap[$iFolderId]['name'] = $aRow['name'];
         $oNewFolder = Folder::get($id);
         $res = $oStorage->createFolder($oNewFolder);
         if (PEAR::isError($res)) {
             // first delete, then rollback, then fail out.
             $oStorage->removeFolder($oNewBaseFolder);
             DBUtil::rollback();
             return $res;
         }
         $aCFIds = Folder::getList(array('parent_id = ?', array($iFolderId)), array('ids' => true));
         $aRemainingFolders = kt_array_merge($aRemainingFolders, $aCFIds);
     }
     // now we can go ahead.
     foreach ($aDocuments as $oDocument) {
         $oChildDestinationFolder = Folder::get($aFolderMap[$oDocument->getFolderID()]['parent_id']);
         $res = KTDocumentUtil::copy($oDocument, $oChildDestinationFolder);
         if (PEAR::isError($res) || $res === false) {
             $oStorage->removeFolder($oNewBaseFolder);
             DBUtil::rollback();
             return PEAR::raiseError(_kt('Delete Aborted. Unexpected failure to copydocument: ') . $oDocument->getName() . $res->getMessage());
         }
     }
     $sComment = sprintf(_kt("Folder copied from %s to %s"), $oSrcFolder->getFullPath(), $oDestFolder->getFullPath());
     if ($sReason !== null) {
         $sComment .= sprintf(_kt(" (reason: %s)"), $sReason);
     }
     $oTransaction = KTFolderTransaction::createFromArray(array('folderid' => $oFolder->getId(), 'comment' => $sComment, 'transactionNS' => 'ktcore.transactions.copy', 'userid' => $oUser->getId(), 'ip' => Session::getClientIP()));
     // If the folder inherits its permissions then we set it to inherit from the new parent folder and update permissions
     // If it defines its own then copy the permission object over
     if ($bInheritPermissions) {
         $aOptions = array('evenifnotowner' => true);
         KTPermissionUtil::inheritPermissionObject($oNewBaseFolder, $aOptions);
     } else {
         KTPermissionUtil::copyPermissionObject($oNewBaseFolder);
     }
     // and store
     DBUtil::commit();
     return true;
 }
 function _pruneAlertedUsers($aUserIds)
 {
     $returnArray = array_diff($aUserIds, $this->alertedUsers);
     $this->alertedUsers = kt_array_merge($returnArray, $this->alertedUsers);
     // now contains all users who will have been alerted.
     return $returnArray;
 }
Example #18
0
                // create rss xml for error
                $error = KTrss::errorToXML(_kt('This document has returned a empty response'));
            }
        } else {
            // create rss xml for error
            $error = KTrss::errorToXML(_kt('You are either not authorised to view details on this folder or it does not exist.' . ' Please visit http://' . $_SERVER['HTTP_HOST'] . '/' . $GLOBALS['KTRootUrl'] . '/ to browse for a valid folder.'));
        }
        if (isset($error)) {
            // if an error exist, output...else out the result
            echo $error;
        } else {
            echo $folderFeed;
        }
    } else {
        // else do normal rss parsing
        // get full list of subscribed documents and folders
        $aFullList = kt_array_merge(KTrss::getDocuments($id), KTrss::getFolders($id));
        $internalFeed = KTrss::arrayToXML($aFullList);
        echo $internalFeed;
    }
}
// Validate user credentials
function validateUser($username, $password)
{
    //return DBAuthenticator::checkPassword($username, $password);
    $oUser =& User::getByUsername($username);
    if (PEAR::isError($oUser) || is_a($oUser, 'KTEntityNoObjects')) {
        return false;
    }
    return KTAuthenticationUtil::checkPassword($oUser, $password);
}
 function check()
 {
     $this->oDocument =& $this->oValidator->validateDocument($_REQUEST['fDocumentId']);
     if (!$this->_show()) {
         return false;
     }
     $aOptions = array('final' => false, 'documentaction' => 'viewDocument', 'folderaction' => 'browse');
     $this->aBreadcrumbs = kt_array_merge($this->aBreadcrumbs, KTBrowseUtil::breadcrumbsForDocument($this->oDocument, $aOptions));
     $actions = KTDocumentActionUtil::getDocumentActionsForDocument($this->oDocument, $this->oUser, 'documentinfo');
     $oPortlet = new KTActionPortlet(sprintf(_kt('Document info')));
     $oPortlet->setActions($actions, $this->sName);
     $this->oPage->addPortlet($oPortlet);
     $actions = KTDocumentActionUtil::getDocumentActionsForDocument($this->oDocument, $this->oUser);
     $oPortlet = new KTActionPortlet(sprintf(_kt('Document actions')));
     $oPortlet->setActions($actions, $this->sName);
     $this->oPage->addPortlet($oPortlet);
     $this->oPage->setSecondaryTitle($this->oDocument->getName());
     return true;
 }
 function informUsersForState($oState, $aInformed, $oDocument, $oUser, $sComments)
 {
     // say no to duplicates.
     KTWorkflowNotification::clearNotificationsForDocument($oDocument);
     $aUsers = array();
     $aGroups = array();
     $aRoles = array();
     foreach (KTUtil::arrayGet($aInformed, 'user', array()) as $iUserId) {
         $oU = User::get($iUserId);
         if (PEAR::isError($oU) || $oU == false) {
             continue;
         } else {
             $aUsers[$oU->getId()] = $oU;
         }
     }
     foreach (KTUtil::arrayGet($aInformed, 'group', array()) as $iGroupId) {
         $oG = Group::get($iGroupId);
         if (PEAR::isError($oG) || $oG == false) {
             continue;
         } else {
             $aGroups[$oG->getId()] = $oG;
         }
     }
     foreach (KTUtil::arrayGet($aInformed, 'role', array()) as $iRoleId) {
         $oR = Role::get($iRoleId);
         if (PEAR::isError($oR) || $oR == false) {
             continue;
         } else {
             $aRoles[] = $oR;
         }
     }
     // FIXME extract this into a util - I see us using this again and again.
     // start with roles ... roles _only_ ever contain groups.
     foreach ($aRoles as $oRole) {
         // do NOT alert anonymous or Everyone roles - that would be very scary.
         $iRoleId = KTUtil::getId($oRole);
         if ($iRoleId == -3 || $iRoleId == -4) {
             continue;
         }
         // first try on the document, then the folder above it.
         $oRoleAllocation = DocumentRoleAllocation::getAllocationsForDocumentAndRole($oDocument->getId(), $iRoleId);
         if (is_null($oRoleAllocation)) {
             // if we don't get a document role, try folder role.
             $oRoleAllocation = RoleAllocation::getAllocationsForFolderAndRole($oDocument->getFolderID(), $oRole->getId());
         }
         if (is_null($oRoleAllocation) || PEAR::isError($oRoleAllocation)) {
             continue;
         }
         $aRoleUsers = $oRoleAllocation->getUsers();
         $aRoleGroups = $oRoleAllocation->getGroups();
         foreach ($aRoleUsers as $id => $oU) {
             $aUsers[$id] = $oU;
         }
         foreach ($aRoleGroups as $id => $oGroup) {
             $aGroups[$id] = $oGroup;
         }
     }
     // we now have a (potentially overlapping) set of groups, which may
     // have subgroups.
     //
     // what we need to do _now_ is build a canonical set of groups, and then
     // generate the singular user-base.
     $aGroupMembershipSet = GroupUtil::buildGroupArray();
     $aAllIds = array_keys($aGroups);
     foreach ($aGroups as $id => $oGroup) {
         $aAllIds = kt_array_merge($aGroupMembershipSet[$id], $aAllIds);
     }
     foreach ($aAllIds as $id) {
         if (!array_key_exists($id, $aGroups)) {
             $aGroups[$id] = Group::get($id);
         }
     }
     // now, merge this (again) into the user-set.
     foreach ($aGroups as $oGroup) {
         $aNewUsers = $oGroup->getMembers();
         foreach ($aNewUsers as $oU) {
             $id = $oU->getId();
             if (!array_key_exists($id, $aUsers)) {
                 $aUsers[$id] = $oU;
             }
         }
     }
     // and done.
     foreach ($aUsers as $oU) {
         if (!PEAR::isError($oU)) {
             KTWorkflowNotification::newNotificationForDocument($oDocument, $oU, $oState, $oUser, $sComments);
         }
     }
 }
 function getTransactionsMatchingQuery($oUser, $sJoinClause, $aExternalWhereClauses, $aExternalWhereParams, $aOptions = null)
 {
     $sSelectItems = 'DTT.name AS transaction_name, U.name AS user_name, DT.version AS version, DT.comment AS comment, DT.datetime AS datetime, D.id as document_id, DT.transaction_namespace as namespace';
     $sBaseJoin = "FROM " . KTUtil::getTableName("document_transactions") . " AS DT " . "INNER JOIN " . KTUtil::getTableName("users") . " AS U ON DT.user_id = U.id " . "INNER JOIN " . KTUtil::getTableName("transaction_types") . " AS DTT ON DTT.namespace = DT.transaction_namespace " . "INNER JOIN " . KTUtil::getTableName("documents") . " AS D ON D.id = DT.document_id ";
     // now we're almost at partialquery like status.
     $perm_res = KTSearchUtil::permissionToSQL($oUser, 'ktcore.permissions.read');
     if (PEAR::isError($perm_res)) {
         return $perm_res;
     }
     list($sPermissionString, $aPermissionParams, $sPermissionJoin) = $perm_res;
     // compile the final list
     $aFinalWhere = kt_array_merge(array($sPermissionString, 'D.creator_id IS NOT NULL'), $aExternalWhereClauses, array('D.status_id = ?'));
     $aFinalWhereParams = kt_array_merge($aPermissionParams, $aExternalWhereParams, array(LIVE));
     if (!is_array($aOptions)) {
         $aOptions = (array) $aOptions;
     }
     $sOrderBy = KTUtil::arrayGet($aOptions, 'orderby', 'DT.datetime DESC');
     // compile these.
     // NBM: do we need to wrap these in ()?
     $sWhereClause = implode(' AND ', $aFinalWhere);
     if (!empty($sWhereClause)) {
         $sWhereClause = 'WHERE ' . $sWhereClause;
     }
     $sQuery = sprintf("SELECT %s %s %s %s %s ORDER BY %s", $sSelectItems, $sBaseJoin, $sPermissionJoin, $sJoinClause, $sWhereClause, $sOrderBy);
     //var_dump(array($sQuery, $aFinalWhereParams));
     $res = DBUtil::getResultArray(array($sQuery, $aFinalWhereParams));
     //var_dump($res); exit(0);
     return $res;
 }
Example #22
0
 function extract_contents($sFilename, $sTempFilename)
 {
     $sCommand = KTUtil::findCommand($this->commandconfig, $this->command);
     if (empty($sCommand)) {
         return false;
     }
     $cmdline = array($sCommand);
     $cmdline = kt_array_merge($cmdline, $this->args);
     $cmdline[] = $sFilename;
     $aOptions = array();
     $aOptions['exec_wait'] = 'true';
     if ($this->use_pipes) {
         $aOptions["append"] = $sTempFilename;
     } else {
         $cmdline[] = $sTempFilename;
     }
     $aRet = KTUtil::pexec($cmdline, $aOptions);
     $this->aCommandOutput = $aRet['out'];
     $contents = file_get_contents($sTempFilename);
     return $contents;
 }
 function addColumns($aColumns)
 {
     $this->columns = kt_array_merge($this->columns, $aColumns);
 }
 function getPermissionDescriptorsForUser($oUser)
 {
     $aGroups = GroupUtil::listGroupsForUserExpand($oUser);
     $roles = array(-3);
     // everyone
     $aEveryoneDescriptors = array();
     $aAuthenticatedDescriptors = array();
     if (!$oUser->isAnonymous()) {
         // authenticated
         $roles[] = -4;
     }
     $aRoleDescriptors = KTPermissionDescriptor::getByRoles($roles, array('ids' => true));
     $aPermissionDescriptors = KTPermissionDescriptor::getByGroups($aGroups, array('ids' => true));
     $aUserDescriptors = KTPermissionDescriptor::getByUser($oUser, array('ids' => true));
     return kt_array_merge($aPermissionDescriptors, $aUserDescriptors, $aRoleDescriptors);
 }
Example #25
0
 function form_edit()
 {
     $oForm = new KTForm();
     $oForm->setOptions(array('label' => _kt('Edit Metadata'), 'submit_label' => _kt('Update Document'), 'action' => 'update', 'fail_action' => 'main', 'cancel_url' => KTBrowseUtil::getUrlForDocument($this->oDocument), 'context' => &$this, 'extraargs' => $this->meldPersistQuery("", "", true)));
     $oFReg =& KTFieldsetRegistry::getSingleton();
     $doctypeid = $this->oDocument->getDocumentTypeID();
     if ($_REQUEST['new_type']) {
         $oTestType = DocumentType::get($_REQUEST['new_type']);
         if (!PEAR::isError($oTestType)) {
             $doctypeid = $oTestType->getId();
         }
     }
     $widgets = array(array('ktcore.widgets.string', array('label' => _kt("Document Title"), 'description' => sprintf(_kt("The document title is used as the main name of a document throughout %s."), APP_NAME), 'name' => 'document_title', 'required' => true, 'value' => sanitizeForHTML($this->oDocument->getName()))));
     $validators = array(array('ktcore.validators.string', array('test' => 'document_title', 'output' => 'document_title')));
     $fieldsets = (array) KTMetadataUtil::fieldsetsForDocument($this->oDocument, $doctypeid);
     foreach ($fieldsets as $oFieldset) {
         $widgets = kt_array_merge($widgets, $oFReg->widgetsForFieldset($oFieldset, 'fieldset_' . $oFieldset->getId(), $this->oDocument));
         $validators = kt_array_merge($validators, $oFReg->validatorsForFieldset($oFieldset, 'fieldset_' . $oFieldset->getId(), $this->oDocument));
     }
     // Electronic Signature if enabled
     global $default;
     if ($default->enableESignatures) {
         $widgets[] = array('ktcore.widgets.info', array('label' => _kt('This action requires authentication'), 'description' => _kt('Please provide your user credentials as confirmation of this action.'), 'name' => 'info'));
         $widgets[] = array('ktcore.widgets.string', array('label' => _kt('Username'), 'name' => 'sign_username', 'required' => true));
         $widgets[] = array('ktcore.widgets.password', array('label' => _kt('Password'), 'name' => 'sign_password', 'required' => true));
         $widgets[] = array('ktcore.widgets.reason', array('label' => _kt('Reason'), 'name' => 'reason', 'required' => true));
         $validators[] = array('electonic.signatures.validators.authenticate', array('object_id' => $this->oDocument->iId, 'type' => 'document', 'action' => 'ktcore.transactions.edit_metadata', 'test' => 'info', 'output' => 'info'));
     }
     $oForm->setWidgets($widgets);
     $oForm->setValidators($validators);
     return $oForm;
 }
 function _getDocumentQuery($aOptions = null)
 {
     $oUser = User::get($_SESSION['userID']);
     $res = KTSearchUtil::permissionToSQL($oUser, $this->sPermissionName);
     if (PEAR::isError($res)) {
         return $res;
     }
     list($sPermissionString, $aPermissionParams, $sPermissionJoin) = $res;
     $aPotentialWhere = array($sPermissionString, 'D.folder_id = ?', 'D.status_id = ' . ARCHIVED);
     $aWhere = array();
     foreach ($aPotentialWhere as $sWhere) {
         if (empty($sWhere)) {
             continue;
         }
         if ($sWhere == '()') {
             continue;
         }
         $aWhere[] = $sWhere;
     }
     $sWhere = '';
     if ($aWhere) {
         $sWhere = "\tWHERE " . join(' AND ', $aWhere);
     }
     $sSelect = KTUtil::arrayGet($aOptions, 'select', 'D.id');
     $sQuery = sprintf('SELECT %s FROM %s AS D
             LEFT JOIN %s AS DM ON D.metadata_version_id = DM.id
             LEFT JOIN %s AS DC ON DM.content_version_id = DC.id
             %s %s', $sSelect, KTUtil::getTableName('documents'), KTUtil::getTableName('document_metadata_version'), KTUtil::getTableName('document_content_version'), $sPermissionJoin, $sWhere);
     $aParams = array();
     $aParams = kt_array_merge($aParams, $aPermissionParams);
     $aParams[] = $this->folder_id;
     return array($sQuery, $aParams);
 }
 function cleanupGroupMembership()
 {
     // 4 cases.
     $child_query = 'select L.id as link_id FROM groups_groups_link as L left outer join groups_lookup as G on (L.member_group_id = G.id) WHERE G.id IS NULL';
     $parent_query = 'select L.id as link_id FROM groups_groups_link as L left outer join groups_lookup as G on (L.parent_group_id = G.id) WHERE G.id IS NULL';
     $group_query = 'select L.id as link_id FROM users_groups_link as L left outer join groups_lookup as G on (L.group_id = G.id) WHERE G.id IS NULL';
     $user_query = 'select L.id as link_id FROM users_groups_link as L left outer join users as U on (L.user_id = U.id) WHERE U.id IS NULL';
     $bad_group_links = array();
     $res = DBUtil::getResultArrayKey(array($child_query, null), 'link_id');
     if (PEAR::isError($res)) {
         return $res;
     } else {
         $bad_group_links = $res;
     }
     $res = DBUtil::getResultArrayKey(array($parent_query, null), 'link_id');
     if (PEAR::isError($res)) {
         return $res;
     } else {
         $bad_group_links = kt_array_merge($bad_group_links, $res);
     }
     foreach ($bad_group_links as $link_id) {
         $res = DBUtil::runQuery(array("DELETE FROM groups_groups_link WHERE id = ?", $link_id));
         if (PEAR::isError($res)) {
             return $res;
         }
     }
     $res = DBUtil::getResultArrayKey(array($group_query, null), 'link_id');
     if (PEAR::isError($res)) {
         return $res;
     } else {
         $bad_user_links = $res;
     }
     $res = DBUtil::getResultArrayKey(array($user_query, null), 'link_id');
     if (PEAR::isError($res)) {
         return $res;
     } else {
         $bad_user_links = kt_array_merge($bad_user_links, $res);
     }
     foreach ($bad_user_links as $link_id) {
         $res = DBUtil::runQuery(array("DELETE FROM users_groups_link WHERE id = ?", $link_id));
         if (PEAR::isError($res)) {
             return $res;
         }
     }
     return true;
 }
Example #28
0
 function do_main()
 {
     $sCode = KTUtil::arrayGet($_REQUEST, 'code');
     $sName = KTUtil::arrayGet($_REQUEST, 'varname', 'fFolderId');
     $oWidget = unserialize($_SESSION['collection_widgets'][$sCode]);
     $oCollection = $oWidget->getCollection();
     $oFolder = Folder::get(KTUtil::arrayGet($_REQUEST, 'fFolderId', 1));
     if (PEAR::isError($oFolder)) {
         $this->errorRedirectToMain(_kt('Invalid folder selected.'));
         exit(0);
     }
     $aOptions = array('ignorepermissions' => KTBrowseUtil::inAdminMode($this->oUser, $oFolder));
     $oCollection->_queryObj->folder_id = $oFolder->getId();
     $aOptions = $oCollection->getEnvironOptions();
     $aOptions['return_url'] = KTUtil::addQueryString($_SERVER['PHP_SELF'], array('code' => $sCode, 'varname' => $sName, 'fFolderId' => $oFolder->getId()));
     $oCollection->setOptions($aOptions);
     // add the collection code to the title column QS params
     foreach ($oWidget->aCols as $ns) {
         $aColOpts = $oCollection->getColumnOptions($ns);
         $aColOpts['qs_params'] = kt_array_merge(KTUtil::arrayGet($aColOpts, 'qs_params', array()), array('code' => $sCode, 'varname' => $sName));
         $oCollection->setColumnOptions($ns, $aColOpts);
     }
     // make the breadcrumbs
     $aBreadcrumbs = $this->_generate_breadcrumbs($oFolder, $sCode, $oWidget->aBCUrlParams, $sName);
     print KTTemplating::renderTemplate('ktcore/forms/widgets/collection', array('collection' => $oCollection, 'folder' => $oFolder, 'breadcrumbs' => $aBreadcrumbs, 'targetname' => $sName));
     exit(0);
 }
Example #29
0
 /**
  * Load a config file
  * Used for the unit tests
  *
  * @param unknown_type $filename
  * @param unknown_type $bDefault
  * @return unknown
  */
 function loadFile($filename, $bDefault = false)
 {
     $c = new Config();
     $root =& $c->parseConfig($filename, "IniCommented");
     if (PEAR::isError($root)) {
         return $root;
     }
     $this->aFileRoot[$filename] =& $root;
     $conf =& $root->toArray();
     foreach ($conf["root"] as $seck => $secv) {
         $aSectionFile[$seck] = $filename;
         if (is_array($secv)) {
             foreach ($secv as $k => $v) {
                 $this->setns($seck, $k, $v);
             }
         } else {
             $this->setns(null, $seck, $secv);
         }
     }
     $this->conf = kt_array_merge($this->conf, $conf["root"]);
 }
Example #30
0
 function getMembershipReason($oUser, $oGroup)
 {
     $aGroupArray = GroupUtil::buildGroupArray();
     // short circuit
     if ($oGroup->hasMember($oUser)) {
         return sprintf(_kt('%s is a direct member.'), $oUser->getName());
     }
     $aSubgroups = (array) $aGroupArray[$oGroup->getId()];
     if (empty($aSubgroups)) {
         return null;
         // not a member, no subgroups.
     }
     $sTable = KTUtil::getTableName('users_groups');
     $sQuery = 'SELECT group_id FROM ' . $sTable . ' WHERE user_id = ? AND group_id IN (' . DBUtil::paramArray($aSubgroups) . ')';
     $aParams = array($oUser->getId());
     $aParams = kt_array_merge($aParams, $aSubgroups);
     $res = DBUtil::getOneResult(array($sQuery, $aParams));
     if (PEAR::isError($res)) {
         return $res;
     } else {
         if (is_null($res)) {
             return null;
             // not a member
         }
     }
     // else {
     $oSubgroup = Group::get($res['group_id']);
     if (PEAR::isError($oSubgroup)) {
         return $oSubgroup;
     }
     return sprintf(_kt('%s is a member of %s'), $oUser->getName(), $oSubgroup->getName());
     // could be error, but errors are caught.
     // }
 }