Exemple #1
0
 function do_update()
 {
     $sTable = KTUtil::getTableName('plugins');
     $aIds = (array) KTUtil::arrayGet($_REQUEST, 'pluginids');
     // Update disabled plugins
     $sIds = implode(',', $aIds);
     $sQuery = "UPDATE {$sTable} SET disabled = 1 WHERE id NOT IN ({$sIds})";
     DBUtil::runQuery(array($sQuery));
     // Select disabled plugins that have been enabled
     $sQuery = "SELECT * FROM {$sTable} WHERE disabled = 1 AND id IN ({$sIds})";
     $res = DBUtil::getResultArray($sQuery);
     if (!PEAR::isError($res)) {
         // Enable the disabled plugins
         $sQuery = "UPDATE {$sTable} SET disabled = 0 WHERE id IN ({$sIds})";
         DBUtil::runQuery(array($sQuery));
         // run setup for each plugin
         $aEnabled = array();
         if (!empty($res)) {
             foreach ($res as $item) {
                 $aEnabled[] = $item['id'];
             }
             $sEnabled = implode(',', $aEnabled);
             $sQuery = "SELECT h.classname, h.pathname FROM {$sTable} p\n                    INNER JOIN plugin_helper h ON (p.namespace = h.plugin)\n                    WHERE classtype = 'plugin' AND p.id IN ({$sEnabled})";
             $res = DBUtil::getResultArray($sQuery);
             if (!PEAR::isError($res)) {
                 foreach ($res as $item) {
                     $classname = $item['classname'];
                     $path = $item['pathname'];
                     if (!empty($path)) {
                         require_once $path;
                     }
                     $oPlugin = new $classname($path);
                     $oPlugin->setup();
                 }
             }
         }
     }
     KTPluginEntity::clearAllCaches();
     // FIXME!!! Plugin manager needs to be updated to deal with this situation. This code should be in the plugin.
     //enabling or disabling Tag fieldset depending on whether tag cloud plugin is enabled or disabled.
     //Get tag cloud object
     $oTagClouPlugin = KTPluginEntity::getByNamespace('ktcore.tagcloud.plugin');
     if (!PEAR::isError($oTagClouPlugin) && !is_a($oTagClouPlugin, 'KTEntityNoObjects') && !is_null($oTagClouPlugin)) {
         if ($oTagClouPlugin->getDisabled() == '1') {
             //disable tag fieldset
             $aFV = array('disabled' => true);
             $aWFV = array('namespace' => 'tagcloud');
             $res = DBUtil::whereUpdate('fieldsets', $aFV, $aWFV);
         } else {
             //enable tag fieldset
             $aFV = array('disabled' => false);
             $aWFV = array('namespace' => 'tagcloud');
             $res = DBUtil::whereUpdate('fieldsets', $aFV, $aWFV);
         }
     }
     // we reregister the plugins to ensure they are in the correct order
     KTPluginUtil::registerPlugins();
     $this->successRedirectToMain(_kt('Plugins updated'));
 }
 function postValidate()
 {
     global $default;
     $document =& $this->aInfo["document"];
     $documentid = $document->getId();
     $sql = "SELECT document_id FROM search_saved_events WHERE document_id={$documentid}";
     $rs = DBUtil::getResultArray($sql);
     if (count($rs) == 0) {
         $sql = "INSERT INTO search_saved_events (document_id) VALUES ({$documentid})";
         DBUtil::runQuery($sql);
     }
 }
 /**
  * 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);');
     }
 }
 function saveTransitionSources($oTransition, $aStateIds)
 {
     $sTable = KTUtil::getTableName('workflow_state_transitions');
     $aQuery = array("DELETE FROM {$sTable} WHERE transition_id = ?", array($oTransition->getId()));
     $res = DBUtil::runQuery($aQuery);
     if (PEAR::isError($res)) {
         return $res;
     }
     $aOptions = array('noid' => true);
     if (empty($aStateIds)) {
         return;
         // don't fail if there are no transitions.
     }
     foreach ($aStateIds as $iStateId) {
         $res = DBUtil::autoInsert($sTable, array('state_id' => $iStateId, 'transition_id' => $oTransition->getId()), $aOptions);
         if (PEAR::isError($res)) {
             return $res;
         }
     }
     return;
 }
 function replaceState($oState, $oReplacement)
 {
     $state_id = KTUtil::getId($oState);
     $replacement_id = KTUtil::getId($oReplacement);
     // we need to convert:
     //   - documents
     //   - transitions
     // before we do a delete.
     $doc = KTUtil::getTableName('document_metadata_version');
     $aDocQuery = array("UPDATE {$doc} SET workflow_state_id = ? WHERE workflow_state_id = ?", array($replacement_id, $state_id));
     $res = DBUtil::runQuery($aDocQuery);
     if (PEAR::isError($res)) {
         return $res;
     }
     $wf = KTUtil::getTableName('workflow_transitions');
     $aTransitionQuery = array("UPDATE {$wf} SET target_state_id = ? WHERE target_state_id = ?", array($replacement_id, $state_id));
     $res = DBUtil::runQuery($aTransitionQuery);
     if (PEAR::isError($res)) {
         return $res;
     }
     $wf = KTUtil::getTableName('workflow_state_transitions');
     $aTransitionQuery = array("DELETE FROM {$wf} WHERE state_id = ?", array($state_id));
     $res = DBUtil::runQuery($aTransitionQuery);
     if (PEAR::isError($res)) {
         return $res;
     }
     Document::clearAllCaches();
 }
 /**
  * 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 #7
0
function performPostUpgradeActions()
{
    // This is just to test and needs to be updated to a more sane and error resistent architrcture if it works.
    // It should idealy work the same as the upgrades.
    global $default;
    // Ensure all plugins are re-registered.
    $sql = "TRUNCATE plugin_helper";
    $res = DBUtil::runQuery($sql);
    // Clear out all caches and proxies - they need to be regenerated with the new code
    $proxyDir = $default->proxyCacheDirectory;
    KTUtil::deleteDirectory($proxyDir);
    $oKTCache = new KTCache();
    $oKTCache->deleteAllCaches();
    // Clear the configuration cache, it'll regenerate on next load
    $oKTConfig = new KTConfig();
    $oKTConfig->clearCache();
    // Unlock the scheduler
    $lockFile = $default->cacheDirectory . DIRECTORY_SEPARATOR . 'scheduler.lock';
    if (file_exists($lockFile)) {
        @unlink($lockFile);
    }
    return true;
}
 /**
  * Remove the document from the processing queue. This is normally called when it has been processed.
  *
  * @param int $docid
  */
 public static function unqueueDocFromProcessing($docid, $reason = false, $level = 'debug')
 {
     $sql = "DELETE FROM process_queue WHERE document_id={$docid}";
     $result = DBUtil::runQuery($sql);
     if ($reason !== false) {
         global $default;
         $default->log->{$level}("Processor queue: removing document {$docid} from the queue - {$reason}");
     }
 }
 /**
  * Merge new metadata with previous metadata version
  *
  * @author KnowledgeTree Team
  * @access public
  * @return void|PEAR_Error Returns nothing on success | a PEAR_Error on failure
  */
 function mergeWithLastMetadataVersion()
 {
     // keep latest metadata version
     $metadata_version = $this->document->getMetadataVersion();
     if ($metadata_version == 0) {
         // this could theoretically happen in the case we are updating metadata and sysdata, but no metadata fields are specified.
         return;
     }
     $metadata_id = $this->document->getMetadataVersionId();
     // get previous version
     $sql = "SELECT id, metadata_version FROM document_metadata_version WHERE id<{$metadata_id} AND document_id={$this->documentid} order by id desc";
     $old = DBUtil::getResultArray($sql);
     if (is_null($old) || PEAR::isError($old)) {
         return new PEAR_Error('Previous version could not be resolved');
     }
     // only interested in the first one
     $old = $old[0];
     $old_metadata_id = $old['id'];
     $old_metadata_version = $old['metadata_version'];
     DBUtil::startTransaction();
     // delete previous metadata version
     $sql = "DELETE FROM document_metadata_version WHERE id={$old_metadata_id}";
     $rs = DBUtil::runQuery($sql);
     if (PEAR::isError($rs)) {
         DBUtil::rollback();
         return $rs;
     }
     // make latest equal to previous
     $sql = "UPDATE document_metadata_version SET metadata_version={$old_metadata_version} WHERE id={$metadata_id}";
     $rs = DBUtil::runQuery($sql);
     if (PEAR::isError($rs)) {
         DBUtil::rollback();
         return $rs;
     }
     $sql = "UPDATE documents SET metadata_version={$old_metadata_version} WHERE id={$this->documentid}";
     $rs = DBUtil::runQuery($sql);
     if (PEAR::isError($rs)) {
         DBUtil::rollback();
         return $rs;
     }
     DBUtil::commit();
     $this->clearCache();
 }
 /**
  * applies queries to the database
  * @return
  * @param $filename Object
  */
 function applySQL($filename)
 {
     global $default;
     DBUtil::setupAdminDatabase();
     $db = $default->_admindb;
     $content = file_get_contents($filename);
     $aQueries = SQLFile::splitSQL($content);
     DBUtil::startTransaction();
     foreach ($aQueries as $sQuery) {
         $res = DBUtil::runQuery($sQuery, $db);
         if (PEAR::isError($res)) {
             continue;
         }
     }
     DBUtil::commit();
 }
 /**
  * Deletes a symbolic link folder
  *
  * @param Folder $folder tthe symbolic link folder to delete
  * @param User $user the current user
  * @return unknown
  */
 static function deleteSymbolicLink($folder, $user = null)
 {
     //validate input
     if (is_numeric($folder)) {
         $folder = Folder::get($folder);
     }
     if (!$folder instanceof Folder) {
         return PEAR::raiseError(_kt('Folder not specified'));
     }
     if (!$folder->isSymbolicLink()) {
         return PEAR::raiseError(_kt('Folder must be a symbolic link entity'));
     }
     if (is_null($user)) {
         $user = $_SESSION['userID'];
     }
     if (is_numeric($user)) {
         $user = User::get($user);
     }
     //check if the user has sufficient permissions
     $oPerm = KTPermission::getByName('ktcore.permissions.delete');
     if (!KTBrowseUtil::inAdminMode($user, $folder)) {
         if (!KTPermissionUtil::userHasPermissionOnItem($user, $oPerm, $folder)) {
             return PEAR::raiseError(_kt('You\'re not authorized to delete shortcuts'));
         }
     }
     // we only need to delete the folder entry for the link
     $sql = "DELETE FROM folders WHERE id=?";
     DBUtil::runQuery(array($sql, array($folder->getId())));
 }
 /**
  * Read the plugins directory and register all plugins in the database.
  */
 function doPluginRegistration()
 {
     global $default;
     KTPluginUtil::_deleteSmartyFiles();
     require_once KT_LIB_DIR . '/cache/cache.inc.php';
     $oCache =& KTCache::getSingleton();
     $oCache->deleteAllCaches();
     // Remove all entries from the plugin_helper table and refresh it.
     $query = "DELETE FROM plugin_helper";
     $res = DBUtil::runQuery($query);
     $files = array();
     $plugins = array();
     KTPluginUtil::_walk(KT_DIR . '/plugins', $files);
     foreach ($files as $sFile) {
         $plugin_ending = "Plugin.php";
         if (substr($sFile, -strlen($plugin_ending)) === $plugin_ending) {
             /* Set default priority */
             $plugins[$sFile] = KTPluginUtil::getPluginPriority($sFile);
         }
     }
     /* Sort the plugins by priority */
     asort($plugins);
     /*
     Add a check to indicate that plugin registration is occuring.
     This check has been put in place to prevent the plugin being registered on every page load.
     */
     $_SESSION['plugins_registerplugins'] = true;
     foreach ($plugins as $sFile => $priority) {
         require_once $sFile;
     }
     $_SESSION['plugins_registerplugins'] = false;
     $oRegistry =& KTPluginRegistry::getSingleton();
     $aRegistryList = $oRegistry->getPlugins();
     foreach ($aRegistryList as $oPlugin) {
         $res = $oPlugin->register();
         if (PEAR::isError($res)) {
             //var_dump($res);
             $default->log->debug('Register of plugin failed: ' . $res->getMessage());
         }
     }
     $aPluginList = KTPluginEntity::getList();
     foreach ($aPluginList as $oPluginEntity) {
         $sPath = $oPluginEntity->getPath();
         if (!KTUtil::isAbsolutePath($sPath)) {
             $sPath = sprintf("%s/%s", KT_DIR, $sPath);
         }
         if (!file_exists($sPath)) {
             $oPluginEntity->setUnavailable(true);
             $oPluginEntity->setDisabled(true);
             $res = $oPluginEntity->update();
         }
     }
     KTPluginEntity::clearAllCaches();
     KTPluginUtil::_deleteSmartyFiles();
     require_once KT_LIB_DIR . '/cache/cache.inc.php';
     $oCache =& KTCache::getSingleton();
     $oCache->deleteAllCaches();
     //KTPluginUtil::removePluginCache();
 }
Exemple #13
0
 function do_delete()
 {
     if (is_null($this->savedSearchId)) {
         $this->errorRedirectTo('manage', _kt('The saved search id was not passed correctly.'));
     }
     $sql = "DELETE FROM search_saved WHERE type='S' AND id={$this->savedSearchId}";
     if (!$this->sysAdmin) {
         $sql .= " AND user_id={$this->curUserId} ";
     }
     $res = DBUtil::runQuery($sql);
     if (DBUtil::affectedRows() == 0) {
         $message = '';
         // in case of database error, supply actual error as message
         if (PEAR::isError($res)) {
             $message = $res->getMessage();
         }
         if (!$this->sysAdmin) {
             if ($message == '') {
                 $message = 'You do not have permission to delete this search.';
             }
         } else {
             if ($message == '') {
                 $message = 'The saved search could not be deleted.';
             }
         }
         $this->errorRedirectTo('manage', _kt($message));
     }
     $this->successRedirectTo('manage', _kt('The saved search was deleted successfully.'));
 }
Exemple #14
0
 /**
  * This method deletes the saved search based on the saved search id
  *
  * @author KnowledgeTree Team
  * @access public
  * @static
  * @param integer $searchID The id of the saved search
  * @return void
  */
 public static function deleteSavedSearch($searchID)
 {
     $sysAdmin = Permission::userIsSystemAdministrator();
     $sql = "DELETE FROM search_saved WHERE type='S' AND id={$searchID}";
     if (!$sysAdmin) {
         $sql .= " AND user_id='" . $_SESSION['userID'] . "'";
     }
     DBUtil::runQuery($sql);
 }
 function renameFolder($oFolder, $sNewName)
 {
     $table = "document_content_version";
     $sQuery = "UPDATE {$table} SET storage_path = CONCAT(?, SUBSTRING(storage_path FROM ?)) WHERE storage_path LIKE ?";
     if ($oFolder->getId() == 1) {
         $sSrcFolderPath = $oFolder->getName();
         $sDestFolderPath = $sNewName;
     } else {
         $sSrcFolderPath = sprintf("%s/%s", $oFolder->getFullPath(), $oFolder->getName());
         $sDestFolderPath = sprintf("%s/%s", $oFolder->getFullPath(), $sNewName);
     }
     $aParams = array($sDestFolderPath, strlen($sSrcFolderPath) + 1, sprintf("%s%%", $sSrcFolderPath));
     $res = DBUtil::runQuery(array($sQuery, $aParams));
     if (PEAR::isError($res)) {
         return $res;
     }
     $oConfig =& KTConfig::getSingleton();
     $sSrc = sprintf("%s/%s", $oConfig->get('urls/documentRoot'), $sSrcFolderPath);
     $sDst = sprintf("%s/%s", $oConfig->get('urls/documentRoot'), $sDestFolderPath);
     $res = @rename($sSrc, $sDst);
     if (PEAR::isError($res) || $res == false) {
         print '<br /> -- unable to move ' . $sSrc . ' to ' . $sDst . '    ';
         return false;
         // return PEAR::raiseError('unable to move directory to ' . $sDst);
     }
     return true;
 }
 function _addUser($iID)
 {
     $sTable = KTUtil::getTableName('permission_descriptor_users');
     $sQuery = "INSERT INTO {$sTable} (descriptor_id, user_id) VALUES (?, ?)";
     $aParams = array($this->getID(), $iID);
     $res = DBUtil::runQuery(array($sQuery, $aParams));
     return $res;
 }
Exemple #17
0
 function transform()
 {
     $iMimeTypeId = $this->oDocument->getMimeTypeId();
     $sMimeType = KTMime::getMimeTypeName($iMimeTypeId);
     if (!array_key_exists($sMimeType, $this->mimetypes)) {
         return;
     }
     $oStorage = KTStorageManagerUtil::getSingleton();
     $sFile = $oStorage->temporaryFile($this->oDocument);
     $tempstub = 'transform';
     if ($this->command != null) {
         $tempstub = $this->command;
     }
     $oKTConfig =& KTConfig::getSingleton();
     $sBasedir = $oKTConfig->get("urls/tmpDirectory");
     $myfilename = tempnam($sBasedir, 'kt.' . $tempstub);
     if (OS_WINDOWS) {
         $intermediate = tempnam($sBasedir, 'kt.' . $tempstub);
         if (!@copy($sFile, $intermediate)) {
             return;
         }
     } else {
         $intermediate = $sFile;
     }
     $contents = $this->extract_contents($intermediate, $myfilename);
     @unlink($myfilename);
     if (OS_WINDOWS) {
         @unlink($intermediate);
     }
     if (empty($contents)) {
         return;
     }
     $aInsertValues = array('document_id' => $this->oDocument->getId(), 'document_text' => $contents);
     $sTable = KTUtil::getTableName('document_text');
     // clean up the document query "stuff".
     // FIXME this suggests that we should move the _old_ document_searchable_text across to the old-document's id if its a checkin.
     DBUtil::runQuery(array('DELETE FROM ' . $sTable . ' WHERE document_id = ?', array($this->oDocument->getId())));
     DBUtil::autoInsert($sTable, $aInsertValues, array('noid' => true));
 }
Exemple #18
0
 function updateFeed($iFeedId, $sFeedTitle, $sFeedUrl)
 {
     $sQuery = "UPDATE plugin_rss SET title=?, url=? WHERE id=?";
     $aParams = array($sFeedTitle, $sFeedUrl, $iFeedId);
     $res = DBUtil::runQuery(array($sQuery, $aParams));
     return $res;
 }
 /**
  * Inherits permission object from parent, throwing away our own
  * permission object.
  */
 function inheritPermissionObject(&$oDocumentOrFolder, $aOptions = null)
 {
     global $default;
     $oDocumentOrFolder->cacheGlobal = array();
     $bEvenIfNotOwner = KTUtil::arrayGet($aOptions, 'evenifnotowner');
     if (empty($bEvenIfNotOwner) && !KTPermissionUtil::isPermissionOwner($oDocumentOrFolder)) {
         return PEAR::raiseError(_kt("Document or Folder doesn't own its permission object"));
     }
     $iOrigPOID = $oDocumentOrFolder->getPermissionObjectID();
     $oOrigPO =& KTPermissionObject::get($iOrigPOID);
     $oFolder =& Folder::get($oDocumentOrFolder->getParentID());
     $iNewPOID = $oFolder->getPermissionObjectID();
     $oNewPO =& KTPermissionObject::get($iNewPOID);
     $oDocumentOrFolder->setPermissionObjectID($iNewPOID);
     $oDocumentOrFolder->update();
     if (is_a($oDocumentOrFolder, 'Document')) {
         // If we're a document, no niggly children to worry about.
         KTPermissionUtil::updatePermissionLookup($oDocumentOrFolder);
         return;
     }
     // if the new and old permission object and lookup ids are the same, then we might as well bail
     if ($iOrigPOID == $iNewPOID) {
         if ($oDocumentOrFolder->getPermissionLookupID() == $oFolder->getPermissionLookupID()) {
             // doing this, as this was done below... (not ideal to copy, but anyways...)
             Document::clearAllCaches();
             Folder::clearAllCaches();
             return;
         }
     }
     $iFolderID = $oDocumentOrFolder->getID();
     $sFolderIDs = Folder::generateFolderIDs($iFolderID);
     $sFolderIDs .= '%';
     $sQuery = "UPDATE {$default->folders_table} SET\n            permission_object_id = ? WHERE permission_object_id = ? AND\n            parent_folder_ids LIKE ?";
     $aParams = array($oNewPO->getID(), $oOrigPO->getID(), $sFolderIDs);
     DBUtil::runQuery(array($sQuery, $aParams));
     Folder::clearAllCaches();
     // Update all documents in the folder and in the sub-folders
     $sQuery = "UPDATE {$default->documents_table} SET\n            permission_object_id = ? WHERE permission_object_id = ? AND\n            (parent_folder_ids LIKE ? OR folder_id = ?)";
     $aParams[] = $iFolderID;
     DBUtil::runQuery(array($sQuery, $aParams));
     Document::clearAllCaches();
     KTPermissionUtil::updatePermissionLookupForPO($oNewPO);
 }
 function setEnabled($aIds)
 {
     $sTable = KTPluginEntity::_table();
     $sIds = DBUtil::paramArray($aIds);
     $sQuery = sprintf('UPDATE %s SET disabled = 1 WHERE id NOT IN (%s)', $sTable, $sIds);
     DBUtil::runQuery(array($sQuery, $aIds));
     $sQuery = sprintf('UPDATE %s SET disabled = 0 WHERE id IN (%s)', $sTable, $sIds);
     DBUtil::runQuery(array($sQuery, $aIds));
     KTPluginEntity::clearAllCaches();
 }
 function _getSubscribers($iObjectId, $iSubType)
 {
     global $default;
     // for the logging.
     if (KTLOG_CACHE) {
         $default->log->debug("_getSubscribers(id={$iObjectId}, type={$iSubType}); table=" . Subscription::getTableName($iSubType) . "; id=" . Subscription::getIdFieldName($iSubType));
     }
     $aUsers = array();
     $aNewUsers = array();
     $aSubUsers = array();
     $table = Subscription::getTableName($iSubType);
     $field = Subscription::getIdFieldName($iSubType);
     // If we're dealing with a folder then get those user who are subscribed to one of the parent folders and want notifications on sub folders
     if ($iSubType == $this->subscriptionTypes["Folder"] && $iObjectId != 1) {
         // Get parent folder ids
         $query = "SELECT parent_folder_ids FROM folders WHERE id = {$iObjectId}";
         $aParentIds = DBUtil::getResultArrayKey($query, 'parent_folder_ids');
         $parentIds = $aParentIds[0];
         // Get those users who have checked the subfolders option on the above folders
         $query = "SELECT user_id FROM {$table} WHERE {$field} IN ({$parentIds}) AND with_subfolders = 1";
         $aSubUsers = DBUtil::getResultArrayKey($query, 'user_id');
     }
     $sQuery = "SELECT user_id FROM {$table} WHERE {$field} = ?";
     $aParams = array($iObjectId);
     $aNewUsers = DBUtil::getResultArrayKey(array($sQuery, $aParams), 'user_id');
     // Add any users from parent folders
     $aNewUsers = array_merge($aNewUsers, $aSubUsers);
     $aNewUsers = array_unique($aNewUsers);
     // Remove alerted users
     $aNewUsers = $this->_pruneAlertedUsers($aNewUsers);
     $iCurrentUserId = $_SESSION['userID'];
     // notionally less efficient than the old code.  if its a big issue, can easily
     // be refactored.
     foreach ($aNewUsers as $iUserId) {
         // the user doesn't need to be notified for his/her own modifications
         if ($iUserId == $iCurrentUserId) {
             continue;
         }
         $oUser =& User::get($iUserId);
         // do a quick prune here, for performance/maintenance reasons.
         if (PEAR::isError($oUser) || $oUser == false) {
             $sQuery = "DELETE FROM " . Subscription::getTableName($iSubType) . " WHERE user_id = ?";
             $aParams = array($iUserId);
             DBUtil::runQuery(array($sQuery, $sParams));
             $default->log->error("SubscriptionEvent::fireSubscription error removing subscription for user id={$iUserId}");
         } else {
             $aUsers[] = $oUser;
         }
     }
     if (KTLOG_CACHE) {
         $default->log->debug('retrieveSubscribers found count=' . count($aUsers));
     }
     return $aUsers;
 }
 /**
  * Set the date first checked as the install date for all scheduler tasks
  *
  */
 function setInstallDate()
 {
     // get current date
     $date = date('Y-m-d H:i:s');
     $query = "UPDATE scheduler_tasks SET run_time = '{$date}'";
     DBUtil::runQuery($query);
 }
 /**
  * Removes all field ordering for the given fieldset.
  */
 function removeFieldOrdering($oFieldset)
 {
     $iFieldsetId = KTUtil::getId($oFieldset);
     $sTable = KTUtil::getTableName('field_orders');
     $aQuery = array("DELETE FROM {$sTable} WHERE fieldset_id = ?", array($iFieldsetId));
     return DBUtil::runQuery($aQuery);
 }
 /**
  * This will remove any temporary files that have not been dealt with in the correct timeframe.
  *
  */
 function cleanup()
 {
     list($year, $mon, $day, $hour, $min) = explode(':', date('Y:m:d:H:i'));
     $expirydate = date('Y-m-d H:i:s', mktime($hour, $min - $this->age, 0, $mon, $day, $year));
     $sql = "SELECT tempfilename FROM uploaded_files WHERE uploaddate<'{$expirydate}'";
     $rows = DBUtil::getResultArray($sql);
     foreach ($rows as $record) {
         $tempfilename = addslashes($record['tempfilename']);
         $sql = "DELETE FROM uploaded_files WHERE tempfilename='{$tempfilename}'";
         $rs = DBUtil::runQuery($sql);
         if (PEAR::isError($rs)) {
             continue;
         }
         @unlink($tempfilename);
     }
 }
 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;
 }
Exemple #26
0
 public static function updateQuery($iSavedId, $txtQuery, $userID)
 {
     $txtQuery = sanitizeForSQL($txtQuery);
     $iSavedId = sanitizeForSQL($iSavedId);
     $sql = "UPDATE search_saved SET expression='{$txtQuery}' WHERE id={$iSavedId}";
     if (!Permission::userIsSystemAdministrator($userID)) {
         $sql .= " AND user_id = {$userID}";
     }
     $result = DBUtil::runQuery($sql);
     if (PEAR::isError($result)) {
         AjaxSearchHelper::createResponse(AjaxSearchHelper::STATUS_INTERNAL);
     }
     AjaxSearchHelper::createResponse(AjaxSearchHelper::STATUS_SUCCESS);
 }
Exemple #27
0
<?php 
}
?>

<h2>Database connectivity</h2>

<?php 
if (PEAR::isError($dbSupport)) {
    print '<p><font color="red">Database support is not currently working.  Error is: ' . htmlentities($dbSupport->toString()) . '</font></p>';
} else {
    ?>
<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>';
 /**
  * Ends the current session.
  *
  * @author KnowledgeTree Team
  * @access public
  * @return void|PEAR_Error Returns nothing on success | a PEAR_Error on failure
  */
 function logout()
 {
     $sql = "DELETE FROM active_sessions WHERE id={$this->sessionid}";
     $result = DBUtil::runQuery($sql);
     if (PEAR::isError($result)) {
         return $result;
     }
     $this->user = null;
     $this->session = '';
     $this->sessionid = -1;
     $this->active = false;
 }
Exemple #29
0
<?php

require_once "../../config/dmsDefaults.php";
require_once KT_LIB_DIR . '/import/fsimportstorage.inc.php';
require_once KT_LIB_DIR . '/import/bulkimport.inc.php';
require_once KT_LIB_DIR . '/foldermanagement/folderutil.inc.php';
require_once KT_LIB_DIR . '/foldermanagement/Folder.inc';
require_once KT_LIB_DIR . '/users/User.inc';
$path = "Root Folder/test-move-folder";
DBUtil::runQuery("DELETE FROM documents WHERE full_path LIKE {$path}%");
DBUtil::runQuery("DELETE FROM folders WHERE full_path LIKE {$path}%");
DBUtil::runQuery("DELETE FROM folders WHERE full_path = 'Root Folder' AND name = 'test-move-folder'");
Exemple #30
0
 /**
  * Execute a db sql statement on the database.
  *
  * @param string $sql
  * @return boolean
  */
 private function _exec($sql)
 {
     global $default;
     if (!$this->persist) {
         print "{$sql}\n";
         return;
     }
     $this->log("Action: {$sql}");
     $rs = DBUtil::runQuery($sql, $default->_admindb);
     if (PEAR::isError($rs)) {
         $this->log("* " . $rs->getMessage());
         return false;
     }
     return true;
 }