Exemple #1
0
 function getHandler()
 {
     $sQuery = 'SELECT selection_ns FROM ' . KTUtil::getTableName('trigger_selection');
     $sQuery .= ' WHERE event_ns = ?';
     $aParams = array('ktstandard.workflowassociation.handler');
     $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'selection_ns');
     return $res;
 }
 function is_active($oUser)
 {
     if (!Permission::userIsSystemAdministrator($oUser)) {
         return false;
     }
     $sql = "select count(*) as no from document_text";
     $no = DBUtil::getOneResultKey($sql, 'no');
     if ($no == 0) {
         return false;
     }
     $this->migratingDocuments = $no;
     return true;
 }
Exemple #3
0
 function outputHelpImage($sSubPath)
 {
     // FIXME there are error cases here ...
     $aPathInfo = KTHelp::_getLocationInfo($sSubPath);
     if (PEAR::isError($aPathInfo)) {
         return $aPathInfo;
     }
     // gets caught further up the stack
     $pi = pathinfo($aPathInfo['external']);
     $mime_type = "";
     $sExtension = KTUtil::arrayGet($pi, 'extension');
     if (!empty($sExtension)) {
         $mime_type = DBUtil::getOneResultKey(array("SELECT mimetypes FROM " . KTUtil::getTableName('mimetypes') . " WHERE LOWER(filetypes) = ?", $sExtension), "mimetypes");
     }
     header("Content-Type: {$mime_type}");
     header("Content-Length: " . filesize($fspath));
     readfile($fspath);
     // does this output it?!
     exit(0);
 }
 function KTWorkflowAssociationDelegator()
 {
     $oKTTriggerRegistry = KTTriggerRegistry::getSingleton();
     $aTriggers = $oKTTriggerRegistry->getTriggers('workflow', 'objectModification');
     // if we have _some_ triggers.
     if (!empty($aTriggers)) {
         $sQuery = 'SELECT selection_ns FROM ' . KTUtil::getTableName('trigger_selection');
         $sQuery .= ' WHERE event_ns = ?';
         $aParams = array('ktstandard.workflowassociation.handler');
         $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'selection_ns');
         if (PEAR::isError($res)) {
             $this->_handler = new KTWorkflowAssociationHandler();
         }
         if (array_key_exists($res, $aTriggers)) {
             $this->_handler = new $aTriggers[$res][0]();
         } else {
             $this->_handler = new KTWorkflowAssociationHandler();
         }
     } else {
         $this->_handler = new KTWorkflowAssociationHandler();
     }
 }
Exemple #5
0
 /**
  * Get the mime type primary key for a specific mime type
  *
  * @param string detected mime type
  * @param string filename
  * @return int mime type primary key if found, else default mime type primary key (text/plain)
  */
 function getMimeTypeID($sMimeType, $sFileName, $sTempFile = null)
 {
     global $default;
     $sTable = KTUtil::getTableName('mimetypes');
     // check by file extension
     $sExtension = KTMime::stripAllButExtension($sFileName);
     $res = DBUtil::getOneResultKey(array("SELECT id FROM " . $sTable . " WHERE LOWER(filetypes) = ?", array($sExtension)), 'id');
     if (PEAR::isError($res) || empty($res)) {
         // pass ?!
     } else {
         return $res;
     }
     // get the mime type id
     if (isset($sMimeType)) {
         $res = DBUtil::getResultArray(array("SELECT id FROM " . $sTable . " WHERE mimetypes = ?", array($sMimeType)));
         if (PEAR::isError($res)) {
             // pass ?!
         }
         if (count($res) != 0) {
             return $res[0]['id'];
         }
     }
     if (!is_null($sTempFile)) {
         // The default is a binary file, so if mime magic can resolve better, lets try...
         $sMimeType = KTMime::getMimeTypeFromFile($sTempFile);
         if (!empty($sMimeType)) {
             $res = DBUtil::getResultArray(array("SELECT id FROM " . $sTable . " WHERE mimetypes = ?", array($sMimeType)));
             if (PEAR::isError($res)) {
                 // pass ?!
             }
             if (count($res) != 0) {
                 return $res[0]['id'];
             }
         }
     }
     //otherwise return the default mime type
     return KTMime::getDefaultMimeTypeID();
 }
Exemple #6
0
 function _getFieldIdForMetadataId($iMetadata)
 {
     $sTable = 'metadata_lookup';
     $sQuery = "SELECT document_field_id FROM " . $sTable . " WHERE id = ?";
     $aParams = array($iMetadata);
     $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'document_field_id');
     if (PEAR::isError($res)) {
         return false;
     }
     return $res;
 }
 /**
  * Given a specific permission object, find the object (Folder or
  * Document) that is the root of that permission object - the one
  * object that has this permission object, but its parent has a
  * different one.
  */
 function findRootObjectForPermissionObject($oPO)
 {
     global $default;
     /*
      * If there are any folders with the permission object, then it
      * is set by _a_ folder.  All folders found will have a common
      * ancestor folder, which will be the one with:
      *
      * Potential hack: The shortest parent_folder_ids
      *
      * Potential non-hack: Choose random folder, check parent for
      * permission object recurringly until it changes.  Last success
      * is the ancestor parent...
      */
     $sQuery = "SELECT id FROM {$default->folders_table} WHERE permission_object_id = ? ORDER BY LENGTH(parent_folder_ids) LIMIT 1";
     $aParams = array($oPO->getID());
     $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
     if (!is_null($res)) {
         return Folder::get($res);
     }
     $sQuery = "SELECT id FROM {$default->documents_table} WHERE permission_object_id = ? LIMIT 1";
     $aParams = array($oPO->getID());
     $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
     if (!is_null($res)) {
         return Document::get($res);
     }
     return false;
 }
 function _folderOrDocument($sPath)
 {
     global $default;
     $sFileName = basename($sPath);
     $sFolderPath = dirname($sPath);
     $aFolderNames = split('/', $sFolderPath);
     $iFolderID = 0;
     $aRemaining = $aFolderNames;
     while (count($aRemaining)) {
         $sFolderName = $aRemaining[0];
         $aRemaining = array_slice($aRemaining, 1);
         if ($sFolderName === '') {
             continue;
         }
         $sQuery = 'SELECT id FROM folders WHERE parent_id = ? AND name = ?';
         $aParams = array($iFolderID, $sFolderName);
         $id = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
         if (PEAR::isError($id)) {
             // XXX: log error
             return false;
         }
         if (is_null($id)) {
             // Some intermediary folder path doesn't exist
             return false;
         }
         $default->log->error('iFolderID set to ' . print_r($id, true));
         $iFolderID = (int) $id;
     }
     $sQuery = sprintf('SELECT d.id 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)' . ' WHERE d.folder_id = ? AND dc.filename = ?', KTUtil::getTableName(documents), KTUtil::getTableName('document_metadata_version'), KTUtil::getTableName('document_content_version'));
     $aParams = array($iFolderID, $sFileName);
     $iDocumentID = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
     if (PEAR::isError($iDocumentID)) {
         // XXX: log error
         return false;
     }
     if ($iDocumentID === null) {
         $sQuery = 'SELECT id FROM folders WHERE parent_id = ? AND name = ?';
         $aParams = array($iFolderID, $sFileName);
         $id = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
         if (PEAR::isError($id)) {
             // XXX: log error
             return false;
         }
         if (is_null($id)) {
             if ($sFileName === '') {
                 return array($iFolderID, null);
             }
             // XXX: log error
             return array($iFolderID, false);
         }
         return array($id, null);
     }
     return array($iFolderID, (int) $iDocumentID);
 }
 /**
  * function to check if the fieldset exists in the database
  *
  * @return boolean
  */
 function tagFieldsetExists()
 {
     $sQuery = 'SELECT fs.id AS id FROM fieldsets AS fs ' . 'WHERE namespace = \'tagcloud\'';
     $iFieldset = DBUtil::getOneResultKey(array($sQuery), 'id');
     if (PEAR::isError($iFieldset)) {
         global $default;
         $default->log->error('Tag Cloud plugin - error checking tag fieldset: ' . $iFieldset->getMessage());
         return $iFieldset;
     }
     if (is_numeric($iFieldset)) {
         return $iFieldset;
     } else {
         return false;
     }
 }
 function createFolderDetailsPermission()
 {
     $sPermissionsTable = KTUtil::getTableName('permissions');
     $bExists = DBUtil::getOneResultKey("SELECT COUNT(id) AS cnt FROM {$sPermissionsTable} WHERE name = 'ktcore.permissions.folder_details'", 'cnt');
     if ($bExists) {
         return;
     }
     DBUtil::startTransaction();
     $aPermissionInfo = array('human_name' => 'Core: Folder Details', 'name' => 'ktcore.permissions.folder_details', 'built_in' => true);
     $res = DBUtil::autoInsert($sPermissionsTable, $aPermissionInfo);
     if (PEAR::isError($res)) {
         return $res;
     }
     $iFolderDetailsPermissionId = $res;
     $sQuery = "SELECT id FROM {$sPermissionsTable} WHERE name = ?";
     $aParams = array("ktcore.permissions.read");
     $iReadPermissionId = DBUtil::getOneResultKey(array($sQuery, $aParams), "id");
     $sPermissionAssignmentsTable = KTUtil::getTableName('permission_assignments');
     $sQuery = "SELECT permission_object_id, permission_descriptor_id FROM {$sPermissionAssignmentsTable} WHERE permission_id = ?";
     $aParams = array($iReadPermissionId);
     $aRows = DBUtil::getResultArray(array($sQuery, $aParams));
     foreach ($aRows as $aRow) {
         $aRow['permission_id'] = $iFolderDetailsPermissionId;
         DBUtil::autoInsert($sPermissionAssignmentsTable, $aRow);
     }
     $sDocumentTable = KTUtil::getTableName('documents');
     $sFolderTable = KTUtil::getTableName('folders');
     DBUtil::runQuery("UPDATE {$sDocumentTable} SET permission_lookup_id = NULL");
     DBUtil::runQuery("UPDATE {$sFolderTable} SET permission_lookup_id = NULL");
     DBUtil::commit();
 }
 /**
  * Make a zseq report
  *
  * @param string $tables
  * @param string $filename
  */
 private function capture_zseqs($tables, $filename)
 {
     $zseqs = '<h1>Table Counter Report</h1>';
     $zseqs .= '<table border=1 cellpadding=0 cellspacing=0>';
     $zseqs .= '<tr><td>Table<td>Max ID<td>ZSEQ<td>Status';
     foreach ($tables as $ztablename) {
         if (substr($ztablename, 0, 5) != 'zseq_') {
             continue;
         }
         $tablename = substr($ztablename, 5);
         $sql = "SELECT max(id) as maxid FROM {$tablename}";
         $maxid = DBUtil::getOneResultKey($sql, 'maxid');
         $sql = "SELECT id FROM {$ztablename}";
         $zseqid = DBUtil::getOneResultKey($sql, 'id');
         $note = is_null($maxid) || $maxid <= $zseqid ? 'OK' : 'FAIL';
         if ($note == 'FAIL' && $maxid > $zseqid) {
             $note = 'COUNTER PROBLEM! maxid should be less than or equal to zseq';
         }
         if (PEAR::isError($maxid)) {
             $maxid = '??';
             $note = "STRANGE - DB ERROR ON {$tablename}";
         }
         if (PEAR::isError($zseqid)) {
             $zseqid = '??';
             $note = "STRANGE - DB ERROR ON {$ztablename}";
         }
         if (is_null($maxid)) {
             $maxid = 'empty';
         }
         if (is_null($zseqid)) {
             $zseqid = 'empty';
             $note = "STRANGE - ZSEQ SHOULD NOT BE EMPTY ON {$ztablename}";
         }
         $zseqs .= "<tr><td>{$tablename}<td>{$maxid}<td>{$zseqid}<td>{$note}\r\n";
     }
     $zseqs .= "</table>";
     file_put_contents($filename, $zseqs);
 }
 /**
  * Checks whether a conditional fieldset has the necessary
  * relationships set up to be usable - this means that for each
  * field, no matter how it is reached, there is at least one option
  * available to choose.
  */
 function checkConditionalFieldsetCompleteness($oFieldset)
 {
     $oFieldset =& KTUtil::getObject('KTFieldset', $oFieldset);
     if ($oFieldset->getIsConditional() == false) {
         // If we're not conditional, we are fine.
         return true;
     }
     /*
      * First, ensure at least one master field item has a behaviour
      * assigned to it.  That allows at least one item in the master
      * field to be chosen.
      */
     $iMasterFieldId = $oFieldset->getMasterFieldId();
     $sTable = KTUtil::getTableName('field_value_instances');
     $sLookupTable = KTUtil::getTableName('metadata_lookup');
     $aQuery = array("SELECT COUNT(FVI.id) AS cnt FROM {$sTable} AS FVI LEFT JOIN {$sLookupTable} AS ML ON (FVI.field_value_id = ML.id) WHERE FVI.field_id = ? AND ML.disabled = 0", array($iMasterFieldId));
     $iCount = DBUtil::getOneResultKey($aQuery, 'cnt');
     if (PEAR::isError($iCount)) {
         return $iCount;
     }
     $GLOBALS['default']->log->debug("Number of value instances for master field: {$iCount}");
     if ($iCount == 0) {
         $GLOBALS['default']->log->debug("Number of value instances for master field is zero, failing");
         return PEAR::raiseError(_kt("Master field has no values which are assigned to behaviours."));
     }
     $GLOBALS['default']->log->debug("Number of value instances for master field is positive, continuing");
     // fix for KTS-1023
     // check that each master-field value has a valueinstance assigned.
     $sTable = KTUtil::getTableName('metadata_lookup');
     $aQuery = array("SELECT COUNT(id) AS cnt FROM {$sTable} WHERE document_field_id = ? AND disabled = 0 ", array($iMasterFieldId));
     $iValCount = DBUtil::getOneResultKey($aQuery, 'cnt');
     // assumes that there cannot be more than 1 value instance for each master-field-value.
     if ($iValCount != $iCount) {
         return PEAR::raiseError(sprintf(_kt('%d values for the Master Field are not assigned to behaviours.'), $iValCount - $iCount));
     }
     /*
      * Plan: For each behaviour that is assigned on the system,
      * ensure that it allows at least one value instance in each of
      * the fields that it needs to affect.
      */
     $sTable = KTUtil::getTableName('field_value_instances');
     $sFieldTable = KTUtil::getTableName('document_fields');
     $aQuery = array("SELECT DISTINCT FV.behaviour_id AS behaviour_id FROM {$sTable} AS FV INNER JOIN {$sFieldTable} AS F ON FV.field_id = F.id WHERE F.parent_fieldset = ? AND FV.behaviour_id IS NOT NULL", array($oFieldset->getId()));
     $aBehaviourIds = DBUtil::getResultArrayKey($aQuery, 'behaviour_id');
     if (PEAR::isError($aBehaviourIds)) {
         return $aBehaviourIds;
     }
     foreach ($aBehaviourIds as $iBehaviourId) {
         $GLOBALS['default']->log->debug("Checking behaviour id: " . $iBehaviourId);
         $oBehaviour =& KTFieldBehaviour::get($iBehaviourId);
         $sBehaviourName = $oBehaviour->getName();
         $sBehaviourHumanName = $oBehaviour->getHumanName();
         $iParentFieldId = $oBehaviour->getFieldId();
         $GLOBALS['default']->log->debug("   field is " . $iParentFieldId);
         $aNextFields = KTMetadataUtil::getChildFieldIds($iParentFieldId);
         $oParentField =& DocumentField::get($iParentFieldId);
         $sParentFieldName = $oParentField->getName();
         $GLOBALS['default']->log->debug("   next fields must include " . print_r($aNextFields, true));
         $sTable = KTUtil::getTableName('field_behaviour_options');
         $aQuery = array("SELECT DISTINCT field_id FROM {$sTable} WHERE behaviour_id = ?", array($iBehaviourId));
         $aFields = DBUtil::getResultArrayKey($aQuery, 'field_id');
         $GLOBALS['default']->log->debug("   actual fields are " . print_r($aNextFields, true));
         /*
         foreach ($aNextFields as $iFieldId) {
             if (!in_array($iFieldId, $aFields)) {
                 $GLOBALS['default']->log->debug("   field $iFieldId is not included, failing");
                 $oChildField =& DocumentField::get($iFieldId);
                 $sChildFieldName = $oChildField->getName();
                 return PEAR::raiseError("Child field $sChildFieldName of parent field $sParentFieldName has no selectable values in behaviour $sBehaviourHumanName ($sBehaviourName)");
         
         }
         */
     }
     $GLOBALS['default']->log->debug("Got through: passed!");
     return true;
 }
Exemple #13
0
 /**
  * Using the name, the role can be resolved.
  *
  * @author KnowledgeTree Team
  * @access public
  * @static
  * @param string $name
  * @return KTAPI_Role Returns null if  there is no match.
  */
 public static function getByName($name)
 {
     $sql = 'SELECT id FROM roles WHERE name=?';
     $id = DBUtil::getOneResultKey(array($sql, array($name)), 'id');
     if (PEAR::isError($id)) {
         return $id;
     }
     $role = Role::get($id);
     return new KTAPI_Role($role);
 }
 function readResource($sPath)
 {
     global $default;
     $php_file = ".php";
     if (substr($sPath, -strlen($php_file)) === $php_file) {
         require_once $php_file;
     } else {
         $pi = pathinfo($sPath);
         $mime_type = "";
         $sExtension = KTUtil::arrayGet($pi, 'extension');
         if (!empty($sExtension)) {
             $mime_type = DBUtil::getOneResultKey(array("SELECT mimetypes FROM " . $default->mimetypes_table . " WHERE LOWER(filetypes) = ?", $sExtension), "mimetypes");
         }
         if (empty($mime_type)) {
             $mime_type = "application/octet-stream";
         }
         $sFullPath = KT_DIR . '/plugins' . $sPath;
         header("Content-Type: {$mime_type}");
         header("Content-Length: " . filesize($sFullPath));
         readfile($sFullPath);
     }
 }
 function renderData($aDataRow)
 {
     $iDocumentId =& $aDataRow['document']->getId();
     $aLocs = array();
     $bFound = true;
     $iLastFound = 0;
     $iNumFound = 0;
     while ($bFound && $iNumFound < 5) {
         $sQuery = "SELECT LOCATE(?, document_text, ?) AS posi FROM document_searchable_text WHERE document_id = ?";
         $aParams = array($this->sSearch, $iLastFound + 1, $iDocumentId);
         $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'posi');
         if (PEAR::isError($res)) {
             var_dump($res);
             exit(0);
         }
         if (empty($res)) {
             break;
         }
         $iNumFound++;
         $iLastFound = $res;
         $bFound = $res;
         if ($iLastFound) {
             $aLocs[] = $iLastFound;
         }
     }
     $iBack = 20;
     $iForward = 50;
     $aTexts = array();
     foreach ($aLocs as $iLoc) {
         $iThisForward = $iForward;
         $iThisBack = $iBack;
         if ($iLoc - $iBack < 0) {
             $iThisForward = $iForward + $iLoc;
             $iThisBack = 0;
             $iLoc = 1;
         }
         $sQuery = "SELECT SUBSTRING(document_text FROM ? FOR ?) AS text FROM document_searchable_text WHERE document_id = ?";
         $aParams = array($iLoc - $iThisBack, $iThisForward + $iThisBack, $iDocumentId);
         $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'text');
         if (PEAR::isError($res)) {
             var_dump($res);
             exit(0);
         }
         $res = htmlentities($res);
         $aSearch = array(sprintf('#(%s)#i', $this->sSearch));
         $aReplace = array('&nbsp; <span class="searchresult" style="color: red">\\1</span> &nbsp;');
         $sText = preg_replace($aSearch, $aReplace, $res);
         $aFirstSpace = array(strpos($sText, " "), strpos($sText, "\n"));
         $iFirstSpace = false;
         foreach ($aFirstSpace as $iPos) {
             if ($iFirstSpace === false) {
                 $iFirstSpace = $iPos;
                 continue;
             }
             if ($iPos === false) {
                 continue;
             }
             if ($iPos < $iFirstSpace) {
                 $iFirstSpace = $iPos;
             }
         }
         if ($iFirstSpace === false) {
             $iFirstSpace = -1;
         }
         $iLastSpace = strrpos($sText, " ");
         $sText = substr($sText, $iFirstSpace + 1, $iLastSpace - $iFirstSpace - 1);
         $sText = str_replace("&nbsp; ", "", $sText);
         $sText = str_replace(" &nbsp;", "", $sText);
         $aTexts[] = $sText;
     }
     $sFullTexts = join(" &hellip; ", $aTexts);
     return sprintf('<div>%s</div><div class="searchresults" style="margin-top: 0.5em; color: grey">%s</div>', parent::renderData($aDataRow), $sFullTexts);
 }
 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;
 }
 function &getAllocationsForDocumentAndRole($iDocumentId, $iRoleId)
 {
     $raTable = KTUtil::getTableName('document_role_allocations');
     $dTable = KTUtil::getTableName('documents');
     $sQuery = "SELECT ra.id as `id` FROM " . $raTable . " AS ra " . ' LEFT JOIN ' . $dTable . ' AS d ON (d.id = ra.document_id) ' . ' WHERE d.id = ?' . ' AND ra.role_id = ?';
     $aParams = array($iDocumentId, $iRoleId);
     $iAllocId = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
     if (PEAR::isError($iAllocId)) {
         return null;
     }
     if (false) {
         print '<pre>';
         var_dump($iAllocId);
         print '';
         print $sQuery;
         print '</pre>';
     }
     // magic for the Owner role here.
     if (empty($iAllocId) && $iRoleId == -2) {
         $permDescriptor = null;
         // THIS OBJECT MUST NEVER BE MODIFIED, without first calling CREATE.
         $oFakeAlloc = new DocumentRoleAllocation();
         $oFakeAlloc->setDocumentId($iDocumentId);
         $oFakeAlloc->setRoleId($iRoleId);
         $oFakeAlloc->setPermissionDescriptorId($permDescriptor);
         //var_dump($oFakeAlloc);
         return $oFakeAlloc;
     } else {
         if (empty($iAllocId)) {
             return null;
         }
     }
     return DocumentRoleAllocation::get($iAllocId);
 }
Exemple #18
0
function checkPassword($username, $password)
{
    global $default;
    $sTable = KTUtil::getTableName('users');
    $sQuery = "SELECT count(*) AS match_count FROM {$sTable} WHERE username = ? AND password = ?";
    $aParams = array($username, md5($password));
    $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'match_count');
    if (PEAR::isError($res)) {
        return false;
    } else {
        $sTable = KTUtil::getTableName('users_groups_link');
        $sQuery = "SELECT count(*) AS match_count FROM {$sTable} WHERE user_id = ? AND group_id = 1";
        $aParams = array($res);
        $res = DBUtil::getOneResultKey(array($sQuery, $aParams), 'match_count');
        if (PEAR::isError($res)) {
            return false;
        } else {
            return $res == 1;
        }
    }
}
 function testConditionOnFolder($oSearch, $oFolder)
 {
     $oSearch =& KTUtil::getObject('KTSavedSearch', $oSearch);
     $iFolderId = KTUtil::getId($oFolder);
     /*
      * Make a new criteria set, an AND of the existing criteria set
      * and the sql statement requiring that D.id be the document id
      * given to us.
      */
     $aCriteriaSet = array("join" => "AND", "subgroup" => array($oSearch->getSearch(), array("join" => "AND", "values" => array(array("sql" => array("F.id = ?", array($iFolderId)))))));
     $aOptions = array('select' => 'COUNT(DISTINCT(F.id)) AS cnt');
     $aQuery = KTSearchUtil::criteriaToFolderQuery($aCriteriaSet, null, null, $aOptions);
     if (PEAR::isError($aQuery)) {
         // caused by no permissions being set.
         return false;
     }
     $cnt = DBUtil::getOneResultKey($aQuery, 'cnt');
     if (PEAR::isError($cnt)) {
         return $cnt;
     }
     if (is_null($cnt)) {
         return false;
     }
     if (!is_numeric($cnt)) {
         return PEAR::raiseError(_kt("Non-integer returned when looking for count"));
     }
     return $cnt > 0;
 }
Exemple #20
0
 function getExternalFeedUrl($iFeedId)
 {
     $sQuery = "SELECT url FROM plugin_rss WHERE id = ?";
     $aParams = array($iFeedId);
     $sFeedUrl = DBUtil::getOneResultKey(array($sQuery, $aParams), 'url');
     if (PEAR::isError($sFeedUrl)) {
         // XXX: log error
         return false;
     }
     if ($sFeedUrl) {
         return $sFeedUrl;
     }
 }
 function getDocumentCount()
 {
     $aOptions = array('select' => 'count(DISTINCT DTS.document_id) AS cnt');
     $aQuery = $this->getQuery($aOptions);
     if (PEAR::isError($aQuery)) {
         return 0;
     }
     $iRet = DBUtil::getOneResultKey($aQuery, 'cnt');
     return $iRet;
 }
 public function getIndexStatistics()
 {
     $optimisationDate = KTUtil::getSystemSetting('luceneOptimisationDate', '');
     $noOptimisation = false;
     if ($optimisationDate == '') {
         $optimisationDate = _kt('N/A');
         $optimisationPeriod = $optimisationDate;
     } else {
         $optimisationPeriod = KTUtil::computePeriodToDate($optimisationDate, null, true);
         $noOptimisation = $optimisationPeriod['days'] > 2;
         $optimisationPeriod = $optimisationPeriod['str'];
         $optimisationDate = date('Y-m-d H:i:s', $optimisationDate);
     }
     $indexingDate = KTUtil::getSystemSetting('luceneIndexingDate', '');
     if ($indexingDate == '') {
         $indexingDate = _kt('N/A');
         $indexingPeriod = $indexingDate;
     } else {
         $indexingPeriod = KTUtil::computePeriodToDate($indexingDate);
         $indexingDate = date('Y-m-d H:i:s', $indexingDate);
     }
     $index = Indexer::get();
     $docsInIndex = $index->getDocumentsInIndex();
     // we are only interested in documents that are active
     $sql = "SELECT count(*) as docsInQueue FROM index_files i inner join documents d on i.document_id = d.id where (i.status_msg is null or i.status_msg = '') and d.status_id=1";
     $docsInQueue = DBUtil::getOneResultKey($sql, 'docsInQueue');
     $sql = "SELECT count(*) as errorsInQueue FROM index_files i inner join documents d on i.document_id = d.id  where (i.status_msg is not null or i.status_msg <> '') and d.status_id=1";
     $errorsInQueue = DBUtil::getOneResultKey($sql, 'errorsInQueue');
     $sql = "SELECT count(*) as docsInRepository FROM documents where status_id=1";
     $docsInRepository = DBUtil::getOneResultKey($sql, 'docsInRepository');
     if ($docsInRepository == 0) {
         $indexingCoverage = '0.00%';
         $queueCoverage = $indexingCoverage;
     } else {
         // compute indexing coverage
         $indexingCoverage = _kt('Not Available');
         if (is_numeric($docsInIndex)) {
             $indexingCoverage = $docsInIndex * 100 / $docsInRepository;
             $indexingCoverage = number_format($indexingCoverage, 2, '.', ',') . '%';
         }
         // compute queue coverage
         $queueCoverage = _kt('Not Available');
         if (is_numeric($docsInQueue)) {
             $queueCoverage = $docsInQueue * 100 / $docsInRepository;
             $queueCoverage = number_format($queueCoverage, 2, '.', ',') . '%';
         }
     }
     $stats = array('optimisationDate' => $optimisationDate, 'optimisationPeriod' => $optimisationPeriod, 'indexingDate' => $indexingDate, 'indexingPeriod' => $indexingPeriod, 'docsInIndex' => $docsInIndex, 'docsInQueue' => $docsInQueue, 'errorsInQueue' => $errorsInQueue, 'docsInRepository' => $docsInRepository, 'indexingCoverage' => $indexingCoverage, 'queueCoverage' => $queueCoverage, 'noOptimisation' => $noOptimisation);
     return $stats;
 }
 function &getByLookupAndParentBehaviour($oLookup, $oBehaviour, $aOptions = null)
 {
     $iLookupId = KTUtil::getId($oLookup);
     $iBehaviourId = KTUtil::getId($oBehaviour);
     $GLOBALS['default']->log->debug('KTValueInstance::getByLookupAndParentBehaviour: lookup id is ' . print_r($iLookupId, true));
     $GLOBALS['default']->log->debug('KTValueInstance::getByLookupAndParentBehaviour: behaviour id is ' . $iBehaviourId);
     $sInstanceTable = KTUtil::getTableName('field_value_instances');
     $sBehaviourOptionsTable = KTUtil::getTableName('field_behaviour_options');
     $aQuery = array("SELECT instance_id FROM {$sBehaviourOptionsTable} AS BO INNER JOIN\n            {$sInstanceTable} AS I ON BO.instance_id = I.id WHERE\n            BO.behaviour_id = ? AND I.field_value_id = ?", array($iBehaviourId, $iLookupId));
     $iId = DBUtil::getOneResultKey($aQuery, 'instance_id');
     if (PEAR::isError($iId)) {
         $GLOBALS['default']->log->error('KTValueInstance::getByLookupAndParentBehaviour: error from db is: ' . print_r($iId, true));
         return $iId;
     }
     if (is_null($iId)) {
         return null;
     }
     $GLOBALS['default']->log->debug('KTValueInstance::getByLookupAndParentBehaviour: id of instance is ' . $iId);
     if (KTUtil::arrayGet($aOptions, 'ids')) {
         return $iId;
     }
     return KTValueInstance::get($iId);
 }
 *
 */
require_once '../config/dmsDefaults.php';
require_once KT_DIR . '/lib/upgrades/upgrade.inc.php';
if (!($default->dbAdminUser && $default->dbAdminPass)) {
    print "You need to set up the administrator user for your database.\n";
    print "Consult docs/UPGRADE.txt for more information\n";
    exit(1);
}
if (PEAR::isError($default->_admindb)) {
    print "Your database administrator user credentials can not login.\n";
    print "Consult docs/UPGRADE.txt for more information.\n";
    exit(1);
}
$query = sprintf('SELECT value FROM %s WHERE name = "knowledgeTreeVersion"', $default->system_settings_table);
$lastVersion = DBUtil::getOneResultKey($query, 'value');
$currentVersion = $default->systemVersion;
$action = $_SERVER['argv'][1];
if (empty($action)) {
    $action = 'show';
}
$upgrades = describeUpgrade($lastVersion, $currentVersion);
$i = 1;
foreach ($upgrades as $step) {
    print "Upgrade step {$i}: " . $step->getDescription();
    $bApplied = $step->isAlreadyApplied();
    $i++;
    if ($bApplied) {
        print " (already applied)\n";
        continue;
    }
 function do_resetPassword()
 {
     $email = $_REQUEST['email'];
     $user = $_REQUEST['username'];
     $password = $_REQUEST['password'];
     $confirm = $_REQUEST['confirm'];
     if (!($password == $confirm)) {
         return _kt('The passwords do not match, please re-enter them.');
     }
     $password = md5($password);
     // Get user from db
     $sQuery = 'SELECT id FROM users WHERE username = ? AND email = ?';
     $aParams = array($user, $email);
     $id = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
     if (!is_numeric($id) || $id < 1) {
         //PEAR::isError($res) || is_null($res)){
         return _kt('Please check that you have entered a valid username and email address.');
     }
     // Check expiry
     $expiry = KTUtil::getSystemSetting('password_reset_expire-' . $id);
     if ($expiry < time()) {
         return _kt('The password reset key has expired, please send a new request.');
     }
     // Update password
     $res = DBUtil::autoUpdate('users', array('password' => $password), $id);
     if (PEAR::isError($res) || is_null($res)) {
         return _kt('Your password could not be reset, please try again.');
     }
     // Unset expiry date and key
     KTUtil::setSystemSetting('password_reset_expire-' . $id, '');
     KTUtil::setSystemSetting('password_reset_key-' . $id, '');
     // Email confirmation
     $url = KTUtil::addQueryStringSelf('');
     $subject = APP_NAME . ': ' . _kt('password successfully reset');
     $body = '<dd><p>';
     $body .= _kt('Your password has been successfully reset, click the link below to login.');
     $body .= "</p><p><a href = '{$url}'>" . _kt('Login') . '</a></p></dd>';
     $oEmail = new Email();
     $res = $oEmail->send($email, $subject, $body);
     if ($res === true) {
         return _kt('Your password has been successfully reset.');
     }
     return _kt('An error occurred while sending the email, please try again or contact the System Administrator.');
 }
 /**
  * postValidate method for trigger
  *
  * @return unknown
  */
 function postValidate()
 {
     global $default;
     $oDocument =& $this->aInfo['document'];
     $aMeta =& $this->aInfo['aOptions'];
     // get document id
     $iDocId = $oDocument->getID();
     // get all tags that are linked to the document
     $sQuery = 'SELECT tw.id FROM tag_words AS tw, document_tags AS dt, documents AS d ' . 'WHERE dt.tag_id = tw.id ' . 'AND dt.document_id = d.id ' . 'AND d.id = ?';
     $aParams = array($iDocId);
     $aTagId = DBUtil::getResultArray(array($sQuery, $aParams));
     if (PEAR::isError($aTagId)) {
         // XXX: log error
         return false;
     }
     // if there are any related tags proceed
     if ($aTagId) {
         // delete all entries from document_tags table for the document
         $sQuery = 'DELETE FROM document_tags ' . 'WHERE document_id = ?';
         $aParams = array($iDocId);
         $removed = DBUtil::runQuery(array($sQuery, $aParams));
         if (PEAR::isError($removed)) {
             // XXX: log error
             return false;
         }
     }
     // proceed to add the tags as per normal
     $sQuery = 'SELECT df.id AS id FROM document_fields AS df ' . 'WHERE df.name = \'Tag\'';
     $sTags = DBUtil::getOneResultKey(array($sQuery), 'id');
     if (PEAR::isError($sTags)) {
         // XXX: log error
         return false;
     }
     $tagString = '';
     if ($sTags) {
         // it is actually correct using $aMeta. It is different to the add trigger above...
         if (count($aMeta) > 0) {
             foreach ($aMeta as $aMetaData) {
                 $oProxy = $aMetaData[0];
                 if ($oProxy->iId == $sTags) {
                     $tagString = $aMetaData[1];
                     break;
                 }
             }
         }
         if ($tagString != '') {
             $words_table = KTUtil::getTableName('tag_words');
             $tagString = str_replace('  ', ' ', $tagString);
             $tags = explode(',', $tagString);
             $aTagIds = array();
             foreach ($tags as $sTag) {
                 $sTag = trim($sTag);
                 if (mb_detect_encoding($sTag) == 'ASCII') {
                     $sTag = strtolower($sTag);
                 }
                 $res = DBUtil::getOneResult(array("SELECT id FROM {$words_table} WHERE tag = ?", array($sTag)));
                 if (PEAR::isError($res)) {
                     return $res;
                 }
                 if (is_null($res)) {
                     $id =& DBUtil::autoInsert($words_table, array('tag' => $sTag));
                     $aTagIds[$sTag] = $id;
                 } else {
                     $aTagIds[$sTag] = $res['id'];
                 }
             }
             $doc_tags = KTUtil::getTableName('document_tags');
             foreach ($aTagIds as $sTag => $tagid) {
                 DBUtil::autoInsert($doc_tags, array('document_id' => $iDocId, 'tag_id' => $tagid), array('noid' => true));
             }
         }
     }
 }
Exemple #27
0
<p>Database connectivity successful.</p>

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

<?php 
}
?>

  </body>
</html>
 function isAlreadyApplied()
 {
     if (!$this->_upgradeTableInstalled()) {
         return false;
     }
     $query = "SELECT id FROM upgrades WHERE descriptor = ? AND result = ?";
     $params = array($this->getDescriptor(), true);
     $res = DBUtil::getOneResultKey(array($query, $params), 'id');
     if (PEAR::isError($res)) {
         return $res;
     }
     if (is_null($res)) {
         return false;
     }
     return true;
 }
 /**
  * GET method helper
  * Method takes a directory path and checks whether it refers to a document or folder. The relevant folder and/or document id is returned.
  *
  * @param $path string The directory path
  * @return array or bool Either returns an array of folder/document id's or false if an error occurred
  */
 function _folderOrDocument($path)
 {
     global $default;
     $this->ktwebdavLog("Entering _folderOrDocument. path is " . $path, 'info', true);
     /* ** Get the directory path and the folder/document being acted on ** */
     $sFileName = basename($path);
     // for windows replace backslash with forwardslash
     $sFolderPath = str_replace("\\", '/', dirname($path));
     /* ** Get the starting point for recursing through the directory structure
        FolderId = 0 if we're in the root folder
        FolderId = 1 the starting point for locating any other folder ** */
     if ($sFolderPath == "/" || $sFolderPath == "/ktwebdav") {
         $this->ktwebdavLog("This is the root folder.", 'info', true);
         $sFolderPath = $this->rootFolder;
         $iFolderID = 0;
     } else {
         $iFolderID = 1;
     }
     if ($sFileName == "ktwebdav.php") {
         $this->ktwebdavLog("This is the root folder file.", 'info', true);
         $sFileName = '';
     }
     $this->ktwebdavLog("sFileName is " . $sFileName, 'info', true);
     $this->ktwebdavLog("sFolderName is " . $sFolderPath, 'info', true);
     $this->ktwebdavLog("iFolderID is " . $iFolderID, 'info', true);
     /* ** Break up the directory path into its component directory's,
        recurse through the directory's to find the correct id of the current directory.
        Avoids situations where several directory's have the same name. ** */
     $aFolderNames = split('/', $sFolderPath);
     $this->ktwebdavLog("aFolderNames are: " . print_r($aFolderNames, true), 'info', true);
     $aRemaining = $aFolderNames;
     while (count($aRemaining)) {
         $sFolderName = $aRemaining[0];
         $aRemaining = array_slice($aRemaining, 1);
         if (empty($sFolderName)) {
             continue;
         }
         // FIXME: Direct database access
         if ($iFolderID == 0) {
             $sQuery = "SELECT id FROM folders WHERE parent_id is null AND name = ?";
             $aParams = array($sFolderName);
         } else {
             $sQuery = "SELECT id FROM folders WHERE parent_id = ? AND name = ?";
             $aParams = array($iFolderID, $sFolderName);
         }
         $id = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
         if (PEAR::isError($id)) {
             $this->ktwebdavLog("A DB error occurred in _folderOrDocument", 'info', true);
             return false;
         }
         if (is_null($id)) {
             // Some intermediary folder path doesn't exist
             $this->ktwebdavLog("Some intermediary folder does not exist in _folderOrDocument", 'error', true);
             return array(false, false);
         }
         $iFolderID = (int) $id;
         $this->ktwebdavLog("iFolderID set to " . $iFolderID, 'info', true);
     }
     /* ** Get the document id using the basename and parent folder id as parameters.
        If an id is obtained then the path refers to a document.
        If no id is returned then the path refers to a folder or a non-existing document. ** */
     // FIXME: Direct database access
     //        $sQuery = "SELECT id FROM documents WHERE folder_id = ? AND filename = ? AND status_id = 1";
     $sQuery = "SELECT D.id ";
     $sQuery .= "FROM documents AS D ";
     $sQuery .= "LEFT JOIN document_metadata_version AS DM ";
     $sQuery .= "ON D.metadata_version_id = DM.id ";
     $sQuery .= "LEFT JOIN document_content_version AS DC ";
     $sQuery .= "ON DM.content_version_id = DC.id ";
     $sQuery .= "WHERE D.folder_id = ? AND DC.filename = ? AND D.status_id=1";
     $aParams = array($iFolderID, $sFileName);
     $iDocumentID = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
     if (PEAR::isError($iDocumentID)) {
         $this->ktwebdavLog("iDocumentID error in _folderOrDocument", 'info', true);
         return false;
     }
     /* ** If the path refers to a folder or a non-existing document,
        Get the folder id using the basename and parent folder id as parameters.
        If an id is obtained then the path refers to an existing folder.
        If no id is returned and the basename is empty then path refers to the root folder.
        If no id is returned and the basename is not empty, then the path refers to either a non-existing folder or document. ** */
     if ($iDocumentID === null) {
         $this->ktwebdavLog("iDocumentID is null", 'info', true);
         // FIXME: Direct database access
         $sQuery = "SELECT id FROM folders WHERE parent_id = ? AND name = ?";
         $aParams = array($iFolderID, $sFileName);
         $id = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
         if (PEAR::isError($id)) {
             $this->ktwebdavLog("A DB(2) error occurred in _folderOrDocument", 'info', true);
             return false;
         }
         if (is_null($id)) {
             if ($sFileName == '') {
                 return array($iFolderID, null);
             }
             $this->ktwebdavLog("id is null in _folderOrDocument", 'info', true);
             return array($iFolderID, false);
         }
         if (substr($path, -1) !== "/") {
             $this->ktwebdavLog("Setting Location Header to " . "Location: " . $_SERVER["PHP_SELF"] . "/", 'info', true);
             header("Location: " . $_SERVER["PHP_SELF"] . "/");
         }
         $this->ktwebdavLog("DEBUG: return id " . $id, 'info', true);
         return array($id, null);
     }
     return array($iFolderID, (int) $iDocumentID);
 }
Exemple #30
0
 /**
  * Gets the file type / extension based on the mimetype id
  *
  * @param int $iMimeTypeID
  */
 function getFileType($iMimeTypeID)
 {
     $sTable = KTUtil::getTableName('mimetypes');
     $sQuery = "SELECT filetypes FROM " . $sTable . " WHERE id = ?";
     $aQuery = array($sQuery, array($iMimeTypeID));
     $ext = DBUtil::getOneResultKey($aQuery, 'filetypes');
     return $ext;
 }