function transform()
 {
     global $default;
     $iMimeTypeId = $this->oDocument->getMimeTypeId();
     $sMimeType = KTMime::getMimeTypeName($iMimeTypeId);
     $sFileName = $this->oDocument->getFileName();
     $aTestTypes = array('application/octet-stream', 'application/zip', 'application/x-zip');
     if (in_array($sMimeType, $aTestTypes)) {
         $sExtension = KTMime::stripAllButExtension($sFileName);
         $sTable = KTUtil::getTableName('mimetypes');
         $sQuery = "SELECT id, mimetypes FROM {$sTable} WHERE LOWER(filetypes) = ?";
         $aParams = array($sExtension);
         $aRow = DBUtil::getOneResult(array($sQuery, $aParams));
         if (PEAR::isError($aRow)) {
             $default->log->debug("ODI: error in query: " . print_r($aRow, true));
             return;
         }
         if (empty($aRow)) {
             $default->log->debug("ODI: query returned entry");
             return;
         }
         $id = $aRow['id'];
         $mimetype = $aRow['mimetypes'];
         $default->log->debug("ODI: query returned: " . print_r($aRow, true));
         if (in_array($mimetype, $aTestTypes)) {
             // Haven't changed, really not an OpenDocument file...
             return;
         }
         if ($id) {
             $this->oDocument->setMimeTypeId($id);
             $this->oDocument->update();
         }
     }
     parent::transform();
 }
 /**
  * Setup the plugin: add the processor, viewlet action and template location
  *
  */
 function setup()
 {
     $plugin_dir = dirname(__FILE__) . DIRECTORY_SEPARATOR;
     $dir = $plugin_dir . 'thumbnails.php';
     $this->registerProcessor('thumbnailGenerator', 'thumbnails.generator.processor', $dir);
     $this->registerAction('documentviewlet', 'ThumbnailViewlet', 'thumbnail.viewlets', $dir);
     require_once KT_LIB_DIR . '/templating/templating.inc.php';
     $oTemplating =& KTTemplating::getSingleton();
     $oTemplating->addLocation('thumbnails', $plugin_dir . 'templates', 'thumbnails.generator.processor.plugin');
     // check for existing config settings entry and only add if not already present
     $sql = 'SELECT id FROM `config_settings` WHERE group_name = "externalBinary" AND item = "convertPath"';
     $result = DBUtil::getOneResult($sql);
     if (PEAR::isError($result) || empty($result)) {
         DBUtil::runQuery('INSERT INTO `config_settings` (group_name, display_name, description, item, value, default_value, type, options, can_edit) ' . 'VALUES ("externalBinary", "convert", "The path to the ImageMagick \\"convert\\" binary", "convertPath", "default", "convert", ' . '"string", NULL, 1);');
     }
 }
 /**
  * Set all tables in the DB to auto increment, thereby removing the use of the zseq tables
  */
 function addAutoIncrementToTables()
 {
     static $doneTables = array();
     global $default;
     DBUtil::setupAdminDatabase();
     $db = $default->_admindb;
     // Get all tables in the database
     $query = "SHOW TABLES";
     $tableList = DBUtil::getResultArray($query, $db);
     // Loop through tables and add auto increment
     foreach ($tableList as $tableArr) {
         $key = key($tableArr);
         $tableName = $tableArr[$key];
         if (in_array($tableName, $doneTables)) {
             // already been set - skip
             continue;
         }
         $doneTables[] = $tableName;
         if (strpos($tableName, 'zseq_', 0) !== false) {
             // ignore zseq tables
             continue;
         }
         $query = "SELECT max(id) FROM {$tableName}";
         $aId = DBUtil::getOneResult($query);
         // If there's no result, then the table may be empty
         if (!PEAR::isError($aId)) {
             $id = (int) $aId['max(id)'] + 1;
             $query = "UPDATE {$tableName} SET id = {$id} WHERE id = 0";
             $res = DBUtil::runQuery($query, $db);
         } else {
             $default->log->error('Add auto_increment, fail on get max id: ' . $aId->getMessage());
         }
         // Update the table, set id to auto_increment
         $query = "ALTER TABLE {$tableName} CHANGE `id` `id` int (11) NOT NULL AUTO_INCREMENT";
         $res = DBUtil::runQuery($query, $db);
         if (PEAR::isError($res)) {
             $default->log->error('Add auto_increment, fail on change id to auto_increment: ' . $res->getMessage());
             // try again with mediumint
             $query = "ALTER TABLE {$tableName} CHANGE `id` `id` mediumint (9) NOT NULL AUTO_INCREMENT";
             $res = DBUtil::runQuery($query, $db);
         }
     }
 }
 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;
 }
 /**
  * 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 #6
0
 function _getIconPath($iMimeTypeId)
 {
     $sQuery = 'SELECT icon_path FROM mime_types WHERE id = ?';
     $res = DBUtil::getOneResult(array($sQuery, array($iMimeTypeId)));
     if ($res['icon_path'] !== null) {
         return $res['icon_path'];
     } else {
         return 'unspecified_type';
     }
 }
 function _mimeHelper($iMimeTypeId)
 {
     // FIXME lazy cache this.
     // FIXME extend mime_types to have something useful to say.
     $sQuery = 'SELECT * FROM mime_types WHERE id = ?';
     $res = DBUtil::getOneResult(array($sQuery, array($iMimeTypeId)));
     if (PEAR::isError($res)) {
         return _kt('unknown type');
     }
     if (!empty($res['friendly_name'])) {
         return _kt($res['friendly_name']);
     } else {
         return sprintf(_kt('%s File'), strtoupper($res['filetypes']));
     }
 }
 public function loadDocumentInfo()
 {
     global $default;
     $sql = "SELECT\n\t\t\t\t\td.folder_id, f.full_path, f.name, dcv.size as filesize, dcv.major_version,\n\t\t\t\t\tdcv.minor_version, dcv.filename, cou.name as checkoutuser, w.human_name as workflow, ws.human_name as workflowstate,\n\t\t\t\t\tmt.mimetypes as mimetype, md.mime_doc as mimedoc, d.checkedout, mbu.name as modifiedbyuser, d.modified,\n\t\t\t\t\tcbu.name as createdbyuser, ou.name as owneruser, d.immutable, d.status_id, d.created,dcv.storage_path, dtl.name as document_type,\n\t\t\t\t\tmt.icon_path as mime_icon_path, mt.friendly_name as mime_display, d.oem_no, dmv.name as title\n\t\t\t\tFROM\n\t\t\t\t\tdocuments d\n\t\t\t\t\tINNER JOIN document_metadata_version dmv ON d.metadata_version_id = dmv.id\n\t\t\t\t\tINNER JOIN document_content_version dcv ON dmv.content_version_id = dcv.id\n\t\t\t\t\tINNER JOIN mime_types mt ON dcv.mime_id=mt.id\n\t\t\t\t\tLEFT JOIN document_types_lookup dtl ON dtl.id=dmv.document_type_id\n\t\t\t\t\tLEFT JOIN folders f ON f.id=d.folder_id\n\t\t\t\t\tLEFT JOIN users cou ON d.checked_out_user_id=cou.id\n\t\t\t\t\tLEFT JOIN workflows w ON dmv.workflow_id=w.id\n\t\t\t\t\tLEFT JOIN workflow_states ws ON dmv.workflow_state_id = ws.id\n\t\t\t\t\tLEFT JOIN mime_documents md ON mt.mime_document_id = md.id\n\t\t\t\t\tLEFT JOIN users mbu ON d.modified_user_id=mbu.id\n\t\t\t\t\tLEFT JOIN users cbu ON d.creator_id=cbu.id\n\t\t\t\t\tLEFT JOIN users ou ON d.owner_id=ou.id\n\t\t\t\tWHERE\n\t\t\t\t\td.id={$this->id}";
     if ($this->inclStatus) {
         $sql .= " AND d.status_id = 1";
     }
     $result = DBUtil::getOneResult($sql);
     if (PEAR::isError($result) || empty($result)) {
         $this->live = false;
         if (PEAR::isError($result)) {
             throw new Exception('Database exception! There appears to be an error in the system: ' . $result->getMessage());
         }
         $default->log->error('QueryResultItem: $result is null');
         $msg = 'The database did not have a record matching the result from the document indexer. This may occur if there is an inconsistency between the document indexer and the repository. The indexer needs to be repaired.';
         $default->log->error('QueryResultItem: ' . $msg);
         // TODO: repair process where we scan documents in index, and delete those for which there is nothing in the repository
         throw new IndexerInconsistencyException(sprintf(_kt('%s'), $msg));
     }
     // document_id, relevance, text, title
     $this->documentType = $result['document_type'];
     $this->filename = $result['filename'];
     $this->filesize = KTUtil::filesizeToString($result['filesize']);
     $this->folderId = $result['folder_id'];
     $this->title = $result['title'];
     $this->createdBy = $result['createdbyuser'];
     $this->dateCreated = $result['created'];
     $this->modifiedBy = $result['modifiedbyuser'];
     $this->dateModified = $result['modified'];
     $this->checkedOutUser = $result['checkoutuser'];
     $this->dateCheckedout = $result['checkedout'];
     $this->owner = $result['owneruser'];
     $this->version = $result['major_version'] . '.' . $result['minor_version'];
     $this->immutable = $result['immutable'] + 0 ? _kt('Immutable') : '';
     $this->workflow = $result['workflow'];
     $this->workflowState = $result['workflowstate'];
     $this->oemDocumentNo = $result['oem_no'];
     if (empty($this->oemDocumentNo)) {
         $this->oemDocumentNo = 'n/a';
     }
     if (is_null($result['name'])) {
         $this->fullpath = '(orphaned)';
     } else {
         $this->fullpath = $result['full_path'];
     }
     $this->mimeType = $result['mimetype'];
     $this->mimeIconPath = $result['mime_icon_path'];
     if (empty($this->mimeIconPath)) {
         $this->mimeIconPath = 'unspecified_type';
     }
     $this->mimeDisplay = $result['mime_display'];
     $this->storagePath = $result['storage_path'];
     $this->status = Document::getStatusString($result['status_id']);
 }
 /**
  * Get the updated position of the column
  *
  * @param int $iId
  * @return int
  */
 function getNewPosition($iId)
 {
     // Get the new position
     $sql = "SELECT id, position FROM column_entries\n    \t       WHERE id = ?";
     $aParams = array($iId);
     $result = DBUtil::getOneResult(array($sql, $aParams));
     if (PEAR::isError($result) || empty($result)) {
         return false;
     }
     return $result['position'];
 }
Exemple #10
0
/**
 * Check if the last user logging in from the same IP as the current user timed out in the last hour.
 *
 * @param unknown_type $userId
 * @return unknown
 */
function checkLastSessionUserID($userId)
{
    // Get the current users IP Address
    $sIp = '%' . $_SERVER['REMOTE_ADDR'];
    // Get the time for a day ago and an hour ago
    $dif = time() - 24 * 60 * 60;
    $sDayAgo = date('Y-m-d H:i:s', $dif);
    $dif2 = time() - 60 * 60;
    $sHourAgo = date('Y-m-d H:i:s', $dif2);
    // Get the session id for the last user to log in from the current IP address within the last day
    // Use the session id to find if that user logged out or timed out within the last hour.
    $sQuery = 'SELECT user_id, action_namespace FROM user_history
        WHERE datetime > ? AND
        session_id = (SELECT session_id FROM user_history WHERE comments LIKE ? AND datetime > ? ORDER BY id DESC LIMIT 1)
        ORDER BY id DESC LIMIT 1';
    $aParams = array($sHourAgo, $sIp, $sDayAgo);
    $res = DBUtil::getOneResult(array($sQuery, $aParams));
    if (PEAR::isError($res) || empty($res)) {
        return false;
    }
    // Check whether the user timed out and whether it was the current user or a different one
    if ($res['action_namespace'] == 'ktcore.user_history.timeout' && $res['user_id'] != $userId) {
        return true;
    }
    return false;
}
Exemple #11
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.
     // }
 }
 function _upgradeTableInstalled()
 {
     $query = "SELECT COUNT(id) FROM upgrades";
     $res = DBUtil::getOneResult($query);
     if (PEAR::isError($res)) {
         return false;
     }
     return true;
 }
 /**
  * This function will return a folder by it's name (not ID)
  *
  * @author KnowledgeTree Team
  * @access public
  * @param KTAPI $ktapi
  * @param string $foldername
  * @param int $folderid
  * @return KTAPI_Folder
  */
 function _get_folder_by_name($ktapi, $foldername, $folderid)
 {
     $foldername = trim($foldername);
     if (empty($foldername)) {
         return new PEAR_Error('A valid folder name must be specified.');
     }
     $split = explode('/', $foldername);
     foreach ($split as $foldername) {
         if (empty($foldername)) {
             continue;
         }
         $foldername = KTUtil::replaceInvalidCharacters($foldername);
         $foldername = sanitizeForSQL($foldername);
         $sql = "SELECT id FROM folders WHERE\n\t\t\t\t\t(name='{$foldername}' and parent_id={$folderid}) OR\n\t\t\t\t\t(name='{$foldername}' and parent_id is null and {$folderid}=1)";
         $row = DBUtil::getOneResult($sql);
         if (is_null($row) || PEAR::isError($row)) {
             return new KTAPI_Error(KTAPI_ERROR_FOLDER_INVALID, $row);
         }
         $folderid = $row['id'];
     }
     return KTAPI_Folder::get($ktapi, $folderid);
 }
 function copy($oDocument, $oDestinationFolder, $sReason = null, $sDestinationDocName = null)
 {
     // 1. generate a new triad of content, metadata and core objects.
     // 2. update the storage path.
     //print '--------------------------------- BEFORE';
     //print_r($oDocument);
     // TODO: this is not optimal. we have get() functions that will do SELECT when we already have the data in arrays
     // get the core record to be copied
     $sDocumentTable = KTUtil::getTableName('documents');
     $sQuery = 'SELECT * FROM ' . $sDocumentTable . ' WHERE id = ?';
     $aParams = array($oDocument->getId());
     $aCoreRow = DBUtil::getOneResult(array($sQuery, $aParams));
     // we unset the id as a new one will be created on insert
     unset($aCoreRow['id']);
     // get a copy of the latest metadata version for the copied document
     $iOldMetadataId = $aCoreRow['metadata_version_id'];
     $sMetadataTable = KTUtil::getTableName('document_metadata_version');
     $sQuery = 'SELECT * FROM ' . $sMetadataTable . ' WHERE id = ?';
     $aParams = array($iOldMetadataId);
     $aMDRow = DBUtil::getOneResult(array($sQuery, $aParams));
     // we unset the id as a new one will be created on insert
     unset($aMDRow['id']);
     // set the name for the document, possibly using name collission
     if (empty($sDestinationDocName)) {
         $aMDRow['name'] = KTDocumentUtil::getUniqueDocumentName($oDestinationFolder, $aMDRow['name']);
     } else {
         $aMDRow['name'] = $sDestinationDocName;
     }
     // get a copy of the latest content version for the copied document
     $iOldContentId = $aMDRow['content_version_id'];
     $sContentTable = KTUtil::getTableName('document_content_version');
     $sQuery = 'SELECT * FROM ' . $sContentTable . ' WHERE id = ?';
     $aParams = array($iOldContentId);
     $aContentRow = DBUtil::getOneResult(array($sQuery, $aParams));
     // we unset the id as a new one will be created on insert
     unset($aContentRow['id']);
     // set the filename for the document, possibly using name collission
     if (empty($sDestinationDocName)) {
         $aContentRow['filename'] = KTDocumentUtil::getUniqueFilename($oDestinationFolder, $aContentRow['filename']);
     } else {
         $aContentRow['filename'] = $sDestinationDocName;
     }
     // create the new document record
     $aCoreRow['modified'] = date('Y-m-d H:i:s');
     $aCoreRow['folder_id'] = $oDestinationFolder->getId();
     // new location.
     $id = DBUtil::autoInsert($sDocumentTable, $aCoreRow);
     if (PEAR::isError($id)) {
         return $id;
     }
     $iNewDocumentId = $id;
     // create the new metadata record
     $aMDRow['document_id'] = $iNewDocumentId;
     $aMDRow['description'] = $aMDRow['name'];
     $id = DBUtil::autoInsert($sMetadataTable, $aMDRow);
     if (PEAR::isError($id)) {
         return $id;
     }
     $iNewMetadataId = $id;
     // the document metadata version is still pointing to the original
     $aCoreUpdate = array();
     $aCoreUpdate['metadata_version_id'] = $iNewMetadataId;
     $aCoreUpdate['metadata_version'] = 0;
     // create the new content version
     $aContentRow['document_id'] = $iNewDocumentId;
     $id = DBUtil::autoInsert($sContentTable, $aContentRow);
     if (PEAR::isError($id)) {
         return $id;
     }
     $iNewContentId = $id;
     // the metadata content version is still pointing to the original
     $aMetadataUpdate = array();
     $aMetadataUpdate['content_version_id'] = $iNewContentId;
     $aMetadataUpdate['metadata_version'] = 0;
     // apply the updates to the document and metadata records
     $res = DBUtil::autoUpdate($sDocumentTable, $aCoreUpdate, $iNewDocumentId);
     if (PEAR::isError($res)) {
         return $res;
     }
     $res = DBUtil::autoUpdate($sMetadataTable, $aMetadataUpdate, $iNewMetadataId);
     if (PEAR::isError($res)) {
         return $res;
     }
     // now, we have a semi-sane document object. get it.
     $oNewDocument = Document::get($iNewDocumentId);
     //print '--------------------------------- AFTER';
     //print_r($oDocument);
     //print '======';
     //print_r($oNewDocument);
     // copy the metadata from old to new.
     $res = KTDocumentUtil::copyMetadata($oNewDocument, $iOldMetadataId);
     if (PEAR::isError($res)) {
         return $res;
     }
     // Ensure the copied document is not checked out
     $oNewDocument->setIsCheckedOut(false);
     $oNewDocument->setCheckedOutUserID(-1);
     // finally, copy the actual file.
     $oStorage =& KTStorageManagerUtil::getSingleton();
     $res = $oStorage->copy($oDocument, $oNewDocument);
     $oOriginalFolder = Folder::get($oDocument->getFolderId());
     $iOriginalFolderPermissionObjectId = $oOriginalFolder->getPermissionObjectId();
     $iDocumentPermissionObjectId = $oDocument->getPermissionObjectId();
     if ($iDocumentPermissionObjectId === $iOriginalFolderPermissionObjectId) {
         $oNewDocument->setPermissionObjectId($oDestinationFolder->getPermissionObjectId());
     }
     $res = $oNewDocument->update();
     if (PEAR::isError($res)) {
         return $res;
     }
     KTPermissionUtil::updatePermissionLookup($oNewDocument);
     if (is_null($sReason)) {
         $sReason = '';
     }
     $oDocumentTransaction = new DocumentTransaction($oDocument, sprintf(_kt("Copied to folder \"%s\". %s"), $oDestinationFolder->getName(), $sReason), 'ktcore.transactions.copy');
     $oDocumentTransaction->create();
     $oSrcFolder = Folder::get($oDocument->getFolderID());
     $oDocumentTransaction = new DocumentTransaction($oNewDocument, sprintf(_kt("Copied from original in folder \"%s\". %s"), $oSrcFolder->getName(), $sReason), 'ktcore.transactions.copy');
     $oDocumentTransaction->create();
     $oKTTriggerRegistry = KTTriggerRegistry::getSingleton();
     $aTriggers = $oKTTriggerRegistry->getTriggers('copyDocument', 'postValidate');
     foreach ($aTriggers as $aTrigger) {
         $sTrigger = $aTrigger[0];
         $oTrigger = new $sTrigger();
         $aInfo = array('document' => $oNewDocument, 'old_folder' => $oSrcFolder, 'new_folder' => $oDestinationFolder);
         $oTrigger->setInfo($aInfo);
         $ret = $oTrigger->postValidate();
         if (PEAR::isError($ret)) {
             return $ret;
         }
     }
     // fire subscription alerts for the copied document
     $oSubscriptionEvent = new SubscriptionEvent();
     $oFolder = Folder::get($oDocument->getFolderID());
     $oSubscriptionEvent->MoveDocument($oDocument, $oDestinationFolder, $oSrcFolder, 'CopiedDocument');
     return $oNewDocument;
 }
Exemple #15
0
    public function is_latest_version($documentID, $contentID)
    {
        $sql = 'SELECT COUNT(document_content_version.id) AS newdocumentcount
		FROM document_content_version
		WHERE document_content_version.document_id ="' . $documentID . '" AND
		document_content_version.id > "' . $contentID . '"';
        $row = DBUtil::getOneResult($sql);
        $row = (int) $row['newdocumentcount'];
        if ($row > 0) {
            $response['is_latest'] = 'FALSE';
        } else {
            $response['is_latest'] = 'TRUE';
        }
        $response['status_code'] = 0;
        return $response;
    }
 function extractText($sourceFile, $extension, $mimeType)
 {
     static $extractors = array();
     // get extractor
     $query = "select me.id, me.name from mime_types mt\n            INNER JOIN mime_extractors me ON mt.extractor_id = me.id\n            WHERE filetypes = '{$extension}'";
     $res = DBUtil::getOneResult($query);
     // On first run the mime_extractors table is empty - populate it for the tests
     if (empty($res) || PEAR::isError($res)) {
         $this->indexer->registerTypes(true);
         $query = "select me.id, me.name from mime_types mt\n                INNER JOIN mime_extractors me ON mt.extractor_id = me.id\n                WHERE filetypes = '{$extension}'";
         $res = DBUtil::getOneResult($query);
     }
     // Instantiate extractor
     if (array_key_exists($res['name'], $extractors)) {
         $extractor = $extractors[$res['name']];
     } else {
         $extractor = $this->indexer->getExtractor($res['name']);
         $extractors[$res['name']] = $extractor;
     }
     $this->assertNotNull($extractor);
     if (empty($extractor)) {
         return '';
     }
     // Extract content
     $targetFile = tempnam($this->tempPath, 'ktindexer');
     $extractor->setSourceFile($this->path . $sourceFile);
     $extractor->setTargetFile($targetFile);
     $extractor->setMimeType($mimeType);
     $extractor->setExtension($extension);
     $extractor->extractTextContent();
     $text = file_get_contents($targetFile);
     $text = $this->filterText($text);
     @unlink($targetFile);
     return $text;
 }
 public static function checkDownloadSize($object)
 {
     return true;
     if ($object instanceof Document || $object instanceof DocumentProxy) {
     }
     if ($object instanceof Folder || $object instanceof FolderProxy) {
         $id = $object->iId;
         // If we're working with the root folder
         if ($id = 1) {
             $sql = 'SELECT count(*) as cnt FROM documents where folder_id = 1';
         } else {
             $sql[] = "SELECT count(*) as cnt FROM documents where parent_folder_ids like '%,?' OR parent_folder_ids like '%,?,%' OR folder_id = ?";
             $sql[] = array($id, $id, $id);
         }
         /*
         SELECT count(*) FROM documents d
         INNER JOIN document_metadata_version m ON d.metadata_version_id = m.id
         INNER JOIN document_content_version c ON m.content_version_id = c.id
         where (d.parent_folder_ids like '%,12' OR d.parent_folder_ids like '%,12,%' OR d.folder_id = 12) AND d.status_id < 3 AND size > 100000
         */
         $result = DBUtil::getOneResult($sql);
         if ($result['cnt'] > 10) {
             return true;
         }
     }
     return false;
 }
Exemple #18
0
 /**
  * Returns the saved query is resolved from HTTP GET fSavedSearchId field.
  *
  * @return mixed False if error, else string.
  */
 private function getSavedExpression()
 {
     if (is_null($this->savedSearchId)) {
         $this->errorRedirectToParent(_kt('The saved search id was not passed correctly.'));
     }
     $_SESSION['search2_savedid'] = $this->savedSearchId;
     $sql = "SELECT name, expression FROM search_saved WHERE type='S' AND id={$this->savedSearchId}";
     if (!$this->sysAdmin) {
         $sql .= "  and ( user_id={$this->curUserId} OR shared=1 ) ";
     }
     $query = DBUtil::getOneResult($sql);
     if (PEAR::isError($query)) {
         $this->errorRedirectToParent(_kt('The saved search could not be resolved.'));
     }
     $_SESSION['search2_savedname'] = $query['name'];
     return array($query['name'], $query['expression']);
 }
 /**
  * Recursively generates forward slash deliminated string giving full path of document
  * from file system root url
  */
 function _generateFullFolderPath($iFolderId)
 {
     //if the folder is not the root folder
     if (empty($iFolderId)) {
         return;
     }
     $sTable = KTUtil::getTableName('folders');
     $sQuery = sprintf("SELECT name, parent_id FROM %s WHERE Id = ?", $sTable);
     $aParams = array($iFolderId);
     $aRow = DBUtil::getOneResult(array($sQuery, $aParams));
     return KTDocumentCore::_generateFullFolderPath($aRow["parent_id"]) . "/" . $aRow["name"];
 }
 function _mimeHelper($iMimeTypeId)
 {
     // FIXME lazy cache this.
     $sQuery = 'SELECT icon_path FROM mime_types WHERE id = ?';
     $res = DBUtil::getOneResult(array($sQuery, array($iMimeTypeId)));
     if ($res[0] !== null) {
         return $res[0];
     } else {
         return 'unspecified_type';
     }
 }
Exemple #21
0
 /**
  * Register the plugin in the DB
  *
  * @param unknown_type $sClassName
  * @param unknown_type $path
  * @param unknown_type $object
  * @param unknown_type $type
  */
 function registerPluginHelper($sNamespace, $sClassName, $path, $object, $view, $type)
 {
     $sql = "SELECT id FROM plugin_helper WHERE namespace = '{$sNamespace}' AND classtype = '{$type}'";
     $res = DBUtil::getOneResult($sql);
     $aValues = array();
     $aValues['namespace'] = $sNamespace;
     $aValues['plugin'] = !empty($this->sNamespace) ? $this->sNamespace : $sNamespace;
     $aValues['classname'] = $sClassName;
     $aValues['pathname'] = $path;
     $aValues['object'] = $object;
     $aValues['viewtype'] = $view;
     $aValues['classtype'] = $type;
     // if record exists - update it.
     if (!empty($res)) {
         $id = $res['id'];
         $updateRes = DBUtil::autoUpdate('plugin_helper', $aValues, $id);
         if (PEAR::isError($updateRes)) {
             return $updateRes;
         }
         return true;
     }
     // Insert into DB
     $res = DBUtil::autoInsert('plugin_helper', $aValues);
     if (PEAR::isError($res)) {
         return $res;
     }
     return true;
 }
 /**
  * Returns an active session based on the session string and the ip address if supplied.
  *
  * @author KnowledgeTree Team
  * @access public
  * @param KTAPI $ktapi Instance of the KTAPI object
  * @param string $session The session string
  * @param string $ip The users ip address
  * @param string $app Optional. The originating application type - Default is ws => webservices | webapp => The web application
  * @return KTAPI_Session|PEAR_Error Returns the session object | a PEAR_Error on failure
  */
 function &get_active_session(&$ktapi, $session, $ip, $app = 'ws')
 {
     $sql = "SELECT id, user_id FROM active_sessions WHERE session_id='{$session}' and apptype='{$app}'";
     if (!empty($ip)) {
         $sql .= " AND ip='{$ip}'";
     }
     $row = DBUtil::getOneResult($sql);
     if (is_null($row) || PEAR::isError($row)) {
         return new KTAPI_Error(KTAPI_ERROR_SESSION_INVALID, $row);
     }
     $sessionid = $row['id'];
     $userid = $row['user_id'];
     $user =& User::get($userid);
     if (is_null($user) || PEAR::isError($user)) {
         return new KTAPI_Error(KTAPI_ERROR_USER_INVALID, $user);
     }
     $now = date('Y-m-d H:i:s');
     $sql = "UPDATE active_sessions SET lastused='{$now}' WHERE id={$sessionid}";
     DBUtil::runQuery($sql);
     if ($user->isAnonymous()) {
         $session =& new KTAPI_AnonymousSession($ktapi, $user, $session, $sessionid, $ip);
     } else {
         $session =& new KTAPI_UserSession($ktapi, $user, $session, $sessionid, $ip);
     }
     return $session;
 }
Exemple #23
0
                break;
            case 'help':
                print "Usage: dbmaint.php repair|check|optimize\n";
                exit;
            case 'check':
            default:
                $action = 'check';
                $sqlaction = 'check table';
                break;
        }
    }
}
$default->log->info("DB Maintenance... \nAction selected: {$action}");
$sql = "show tables";
$tables = DBUtil::getResultArray($sql);
if (!empty($tables)) {
    foreach ($tables as $table) {
        $key = array_keys($table);
        $tablename = $table[$key[0]];
        $sql = "{$sqlaction} {$tablename};";
        $result = DBUtil::getOneResult($sql);
        if (PEAR::isError($result)) {
            $default->log->error('Attempted: ' . $sql);
            $default->log->error(' *: ' . $result->getMessage());
            continue;
        }
        $default->log->info('Running: ' . $sql . ' - ' . $result['Msg_text']);
    }
}
$default->log->info('Done.');
exit;
Exemple #24
0
 /**
  * Returns the id for a link type or an error object.
  *
  * @author KnowledgeTree Team
  * @access public
  * @param string $linktype The link type
  * @return integer|object $result SUCCESS - the link type id | FAILURE - an error object
  */
 public function get_link_type_id($linktype)
 {
     $sql = array("SELECT id FROM document_link_types WHERE name=?", $linktype);
     $row = DBUtil::getOneResult($sql);
     if (is_null($row) || PEAR::isError($row)) {
         $result = new PEAR_Error(KTAPI_ERROR_DOCUMENT_LINK_TYPE_INVALID);
     } else {
         $result = $row['id'];
     }
     return $result;
 }