function do_main()
 {
     $this->oPage->setBreadcrumbDetails(_kt("transactions"));
     $this->oPage->setTitle(_kt('Folder transactions'));
     $folder_data = array();
     $folder_data["folder_id"] = $this->oFolder->getId();
     $this->oPage->setSecondaryTitle($this->oFolder->getName());
     $aTransactions = array();
     // FIXME do we really need to use a raw db-access here?  probably...
     $sQuery = "SELECT DTT.name AS transaction_name, FT.transaction_namespace, U.name AS user_name, FT.comment AS comment, FT.datetime AS datetime " . "FROM " . KTUtil::getTableName("folder_transactions") . " AS FT LEFT JOIN " . KTUtil::getTableName("users") . " AS U ON FT.user_id = U.id " . "LEFT JOIN " . KTUtil::getTableName("transaction_types") . " AS DTT ON DTT.namespace = FT.transaction_namespace " . "WHERE FT.folder_id = ? ORDER BY FT.datetime DESC";
     $aParams = array($this->oFolder->getId());
     $res = DBUtil::getResultArray(array($sQuery, $aParams));
     if (PEAR::isError($res)) {
         var_dump($res);
         // FIXME be graceful on failure.
         exit(0);
     }
     // FIXME roll up view transactions
     $aTransactions = $res;
     // Set the namespaces where not in the transactions lookup
     foreach ($aTransactions as $key => $transaction) {
         if (empty($transaction['transaction_name'])) {
             $aTransactions[$key]['transaction_name'] = $this->_getActionNameForNamespace($transaction['transaction_namespace']);
         }
     }
     // render pass.
     $this->oPage->title = _kt("Folder History");
     $oTemplating =& KTTemplating::getSingleton();
     $oTemplate = $oTemplating->loadTemplate("kt3/view_folder_history");
     $aTemplateData = array("context" => $this, "folder_id" => $folder_id, "folder" => $this->oFolder, "transactions" => $aTransactions);
     return $oTemplate->render($aTemplateData);
 }
 function do_main()
 {
     $this->oPage->setSecondaryTitle($this->oDocument->getName());
     $this->oPage->setBreadcrumbDetails(_kt('history'));
     $aTransactions = array();
     // FIXME create a sane "view user information" page somewhere.
     // FIXME do we really need to use a raw db-access here?  probably...
     $sQuery = 'SELECT DTT.name AS transaction_name, DT.transaction_namespace, U.name AS user_name, DT.version AS version, DT.comment AS comment, DT.datetime AS datetime ' . 'FROM ' . KTUtil::getTableName('document_transactions') . ' AS DT INNER JOIN ' . KTUtil::getTableName('users') . ' AS U ON DT.user_id = U.id ' . 'LEFT JOIN ' . KTUtil::getTableName('transaction_types') . ' AS DTT ON DTT.namespace = DT.transaction_namespace ' . 'WHERE DT.document_id = ? ORDER BY DT.datetime DESC';
     $aParams = array($this->oDocument->getId());
     $res = DBUtil::getResultArray(array($sQuery, $aParams));
     if (PEAR::isError($res)) {
         var_dump($res);
         // FIXME be graceful on failure.
         exit(0);
     }
     $aTransactions = $res;
     // Set the namespaces where not in the transactions lookup
     foreach ($aTransactions as $key => $transaction) {
         if (empty($transaction['transaction_name'])) {
             $aTransactions[$key]['transaction_name'] = $this->_getActionNameForNamespace($transaction['transaction_namespace']);
         }
     }
     // render pass.
     $this->oPage->setTitle(_kt('Document History'));
     $oTemplate = $this->oValidator->validateTemplate('ktcore/document/transaction_history');
     $aTemplateData = array('context' => $this, 'document_id' => $this->oDocument->getId(), 'document' => $this->oDocument, 'transactions' => $aTransactions);
     return $oTemplate->render($aTemplateData);
 }
 /**
  * Get the configuration settings
  *
  * @return array
  */
 function getSettings()
 {
     $query = "SELECT g.display_name AS group_display, g.description AS group_description,\n            s.id, s.display_name, s.description, s.value, s.default_value, s.type, s.options\n            FROM config_groups g\n            INNER JOIN config_settings s ON g.name = s.group_name\n            WHERE category = '{$this->category}' AND s.can_edit = 1\n            ORDER BY g.name, s.item";
     $results = DBUtil::getResultArray($query);
     if (PEAR::isError($results)) {
         $this->addErrorMessage(sprintf(_kt("The configuration settings could not be retrieved: %s"), $results->getMessage()));
         return array();
     }
     return $results;
 }
 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);
     }
 }
 function getSupportedMimeTypesDB($sExtractorName)
 {
     $sQuery = "SELECT MT.mimetypes  FROM mime_extractors as ME LEFT JOIN mime_types as MT ON " . "(ME.id = MT.extractor_id) WHERE ME.name = ?";
     $aQuery = array($sQuery, array($sExtractorName));
     $aTempRes = DBUtil::getResultArray($aQuery);
     $aRes = array();
     for ($i = 0; $i < count($aTempRes); $i++) {
         if (!in_array($aTempRes[$i]['mimetypes'], $aRes)) {
             $aRes[] = $aTempRes[$i]['mimetypes'];
         }
     }
     return $aRes;
 }
 function display_viewlet()
 {
     $oKTTemplating =& KTTemplating::getSingleton();
     $oTemplate =& $oKTTemplating->loadTemplate("ktcore/document/viewlets/workflow");
     if (is_null($oTemplate)) {
         return "";
     }
     $oWorkflowState = KTWorkflowState::get($this->oDocument->getWorkflowStateId());
     if (PEAR::isError($oWorkflowState)) {
         return "";
     }
     $aDisplayTransitions = array();
     $aTransitions = KTWorkflowUtil::getTransitionsForDocumentUser($this->oDocument, $this->oUser);
     if (empty($aTransitions)) {
         return "";
     }
     // Check if the document has been checked out
     $bIsCheckedOut = $this->oDocument->getIsCheckedOut();
     $iId = $this->oDocument->getId();
     if ($bIsCheckedOut) {
         // If document is checked out, don't link into the workflow.
         $aDisplayTransitions = array();
     } else {
         foreach ($aTransitions as $oTransition) {
             if (is_null($oTransition) || PEAR::isError($oTransition)) {
                 continue;
             }
             $aDisplayTransitions[] = array('url' => KTUtil::ktLink('action.php', 'ktcore.actions.document.workflow', array("fDocumentId" => $iId, "action" => "quicktransition", "fTransitionId" => $oTransition->getId())), 'name' => $oTransition->getName());
         }
     }
     //Retreive the comment for the previous transition
     $aCommentQuery = array("SELECT comment FROM document_transactions\n            where transaction_namespace='ktcore.transactions.workflow_state_transition'\n            AND document_id = ?\n            ORDER BY id DESC LIMIT 1;");
     $aCommentQuery[] = array($iId);
     $aTransitionComments = DBUtil::getResultArray($aCommentQuery);
     $oLatestTransitionComment = null;
     if (!empty($aTransitionComments)) {
         $aRow = $aTransitionComments[0];
         $oLatestTransitionComment = $aRow['comment'];
         $iCommentPosition = strpos($oLatestTransitionComment, ':');
         //comment found after first colon in string
         if ($iCommentPosition > 0) {
             $oLatestTransitionComment = substr($oLatestTransitionComment, $iCommentPosition + 2, strlen($oLatestTransitionComment) - $iCommentPosition);
         } else {
             $oLatestTransitionComment = null;
         }
     }
     $oTemplate->setData(array('context' => $this, 'bIsCheckedOut' => $bIsCheckedOut, 'transitions' => $aDisplayTransitions, 'state_name' => $oWorkflowState->getName(), 'comment' => $oLatestTransitionComment));
     return $oTemplate->render();
 }
 /**
  * Get any dashlets added since the user's last login
  *
  * @param object $oUser
  */
 function getNewDashlets($oUser, $sCurrent)
 {
     $new = array();
     $inactive = array();
     static $sInactive = '';
     $sIgnore = !empty($sInactive) ? $sCurrent . ',' . $sInactive : $sCurrent;
     // Get all dashlets that haven't already been displayed to the user and are active for the user
     $query = "SELECT h.classname, h.pathname, h.plugin FROM plugin_helper h\n            INNER JOIN plugins p ON (h.plugin = p.namespace)\n            WHERE p.disabled = 0 AND classtype = 'dashlet' ";
     if (!empty($sIgnore)) {
         $query .= " AND h.classname NOT IN ({$sIgnore})";
     }
     $res = DBUtil::getResultArray($query);
     // If the query is not empty, get the dashlets and return the new active ones
     // Add the inactive ones the list.
     if (!PEAR::isError($res) && !empty($res)) {
         $oRegistry =& KTPluginRegistry::getSingleton();
         foreach ($res as $item) {
             $name = $item['classname'];
             $filename = $item['pathname'];
             $sPluginName = $item['plugin'];
             require_once $filename;
             $oPlugin =& $oRegistry->getPlugin($sPluginName);
             $oDashlet = new $name();
             $oDashlet->setPlugin($oPlugin);
             if ($oDashlet->is_active($oUser)) {
                 $new[] = $name;
             } else {
                 $inactive[] = "'{$name}'";
             }
         }
         // Add new inactive dashlets
         $sNewInactive = implode(',', $inactive);
         $sInactive = !empty($sInactive) ? $sInactive . ',' . $sNewInactive : $sNewInactive;
         return $new;
     }
     return '';
 }
 /**
  * Given a behaviour, return an array of lookup ids (Metadata->id)
  * that are available for each of the columns/fields that this
  * behaviour's column affects.
  *
  * Return value:
  *
  * Associative array keyed by field_id, value is an array of lookup
  * ids.
  *
  * array(
  *      1 => array(1, 2, 3, 4),
  *      ...
  * );
  */
 function getNextValuesForBehaviour($oBehaviour)
 {
     $oBehaviour =& KTUtil::getObject('KTFieldBehaviour', $oBehaviour);
     $aValues = array();
     $sTable = KTUtil::getTableName('field_behaviour_options');
     $aChildFieldIds = KTMetadataUtil::getChildFieldIds($oBehaviour->getFieldId());
     foreach ($aChildFieldIds as $iFieldId) {
         $aValues[$iFieldId] = array();
     }
     $aQuery = array("SELECT field_id, instance_id FROM {$sTable} WHERE behaviour_id = ?", array($oBehaviour->getId()));
     $aRows = DBUtil::getResultArray($aQuery);
     if (PEAR::isError($aRows)) {
         return $aRows;
     }
     foreach ($aRows as $aRow) {
         $oInstance =& KTValueInstance::get($aRow['instance_id']);
         // need to wean out the disabled values.
         // now get the metadata value.
         $oMetadata = MetaData::get($oInstance->getFieldValueId());
         if (PEAR::isError($oMetadata)) {
             continue;
             // invalid link.  bugger.
         }
         if ($oMetadata->getDisabled()) {
             continue;
             // disabled.
         }
         $aValues[$aRow['field_id']][] = $oInstance->getFieldValueId();
     }
     return $aValues;
 }
Exemple #9
0
 /**
  * Executes a database query
  *
  * @access private
  * @global object $default Default config settings
  * @param string $op The operation to perform
  * @param array $group
  * @return array $results
  */
 private function exec_db_query($op, $group)
 {
     if (empty($group)) {
         return array();
     }
     $exprbuilder = new SQLQueryBuilder($this->getContext());
     $exprbuilder->setIncludeStatus($this->incl_status);
     if (count($group) == 1) {
         $sql = $exprbuilder->buildComplexQuery($group[0]);
     } else {
         $sql = $exprbuilder->buildSimpleQuery($op, $group);
     }
     if (empty($sql)) {
         return array();
     }
     $results = array();
     global $default;
     $default->log->debug("SEARCH SQL: {$sql}");
     $rs = DBUtil::getResultArray($sql);
     if (PEAR::isError($rs)) {
         throw new Exception($rs->getMessage());
     }
     if (count($group) == 1) {
         //$default->log->debug("CASE 1");
         $oCriteria = $this->checkComplexQuery($group[0]);
     } else {
         //$default->log->debug("CASE 2");
         foreach ($group as $expr) {
             $left = $expr->left();
             $right = $expr->right();
             $default->log->debug("FIELD-IS: " . $left->isOpExpr());
             $fieldname = $left->getField();
             $value = addslashes($right->getValue());
             $rsField = DBUtil::getResultArray("SELECT * FROM document_fields WHERE name = \"{$fieldname}\";");
             if ($rsField[0]['data_type'] == 'LARGE TEXT') {
                 $iCriteria = array();
                 $iCriteria[0] = array();
                 $iCriteria[0]['field'] = $fieldname;
                 $iCriteria[0]['value'] = $value;
                 $iCriteria[0]['not'] = $expr->not();
                 $oCriteria[] = $iCriteria[0];
                 /*$not = $expr->not()?' NOT ':'';
                 
                             		if (strpos($value, ' ') !== false)
                 						$default->log->debug("CRITERION: $not$fieldname:\"$value\"");
                 					else
                 						$default->log->debug("CRITERION: $not$fieldname:$value");*/
             }
             //$default->log->debug("FIELD-TYPE: " . $oCriteria[0]['field']);
         }
     }
     //$default->log->debug("TOTAL CRITERIA: " . count($oCriteria));
     foreach ($rs as $item) {
         $id = $item['id'];
         $rank = $exprbuilder->getRanking($item);
         if (!array_key_exists($id, $results) || $rank > $results[$id]->Rank) {
             if ($this->context == ExprContext::DOCUMENT) {
                 if (count($oCriteria) > 0 && $this->checkValues($id, $oCriteria) || count($oCriteria) == 0) {
                     $results[$id] = new DocumentResultItem($id, $rank, $item['title'], $exprbuilder->getResultText($item), null, $this->incl_status);
                 }
             } else {
                 $results[$id] = new FolderResultItem($id, $rank, $item['title'], $exprbuilder->getResultText($item));
             }
         }
     }
     return $results;
 }
Exemple #10
0
 function getFolderTransactions($aFolderIds)
 {
     $sFolderIds = implode(', ', $aFolderIds);
     $sQuery = "SELECT FT.datetime AS datetime, 'Folder' AS type, F.name, F.full_path AS fullpath,\n    \t   DTT.name AS transaction_name, U.name AS user_name, FT.comment AS comment\n    \t   FROM folder_transactions AS FT LEFT JOIN users AS U ON FT.user_id = U.id\n    \t   LEFT JOIN document_transaction_types_lookup AS DTT ON DTT.namespace = FT.transaction_namespace\n    \t   LEFT JOIN folders AS F ON FT.folder_id = F.id\n    \t   WHERE FT.folder_id IN ({$sFolderIds})\n    \t   ORDER BY FT.datetime DESC\n    \t   LIMIT 4";
     $aFolderTransactions = DBUtil::getResultArray($sQuery);
     return $aFolderTransactions;
 }
 public function migrateDocuments($max = null)
 {
     global $default;
     $default->log->info(_kt('migrateDocuments: starting'));
     if (!$this->doesDiagnosticsPass(true)) {
         $default->log->info(_kt('migrateDocuments: stopping - diagnostics problem. The dashboard will provide more information.'));
         return;
     }
     if (KTUtil::getSystemSetting('migrationComplete') == 'true') {
         $default->log->info(_kt('migrateDocuments: stopping - migration is complete.'));
         return;
     }
     $config =& KTConfig::getSingleton();
     if (is_null($max)) {
         $max = $config->get('indexer/batchMigrateDocument', 500);
     }
     $lockFile = $config->get('cache/cacheDirectory') . '/migration.lock';
     if (is_file($lockFile)) {
         $default->log->info(_kt('migrateDocuments: stopping - migration lockfile detected.'));
         return;
     }
     touch($lockFile);
     $startTime = KTUtil::getSystemSetting('migrationStarted');
     if (is_null($startTime)) {
         KTUtil::setSystemSetting('migrationStarted', time());
     }
     $maxLoops = 5;
     $max = ceil($max / $maxLoops);
     $start = KTUtil::getBenchmarkTime();
     $noDocs = false;
     $numDocs = 0;
     for ($loop = 0; $loop < $maxLoops; $loop++) {
         $sql = "SELECT\n        \t\t\tdocument_id, document_text\n\t\t\t\tFROM\n\t\t\t\t\tdocument_text\n\t\t\t\tORDER BY document_id\n \t\t\t\t\tLIMIT {$max}";
         $result = DBUtil::getResultArray($sql);
         if (PEAR::isError($result)) {
             $default->log->info(_kt('migrateDocuments: db error'));
             break;
         }
         $docs = count($result);
         if ($docs == 0) {
             $noDocs = true;
             break;
         }
         $numDocs += $docs;
         foreach ($result as $docinfo) {
             $docId = $docinfo['document_id'];
             $document = Document::get($docId);
             if (PEAR::isError($document) || is_null($document)) {
                 $sql = "DELETE FROM document_text WHERE document_id={$docId}";
                 DBUtil::runQuery($sql);
                 $default->log->error(sprintf(_kt('migrateDocuments: Could not get document %d\'s document! Removing content!'), $docId));
                 continue;
             }
             $version = $document->getMajorVersionNumber() . '.' . $document->getMinorVersionNumber();
             $targetFile = tempnam($tempPath, 'ktindexer');
             if (file_put_contents($targetFile, $docinfo['document_text']) === false) {
                 $default->log->error(sprintf(_kt('migrateDocuments: Cannot write to \'%s\' for document id %d'), $targetFile, $docId));
                 continue;
             }
             // free memory asap ;)
             unset($docinfo['document_text']);
             $title = $document->getName();
             $indexStatus = $this->indexDocumentAndDiscussion($docId, $targetFile, $title, $version);
             if ($indexStatus) {
                 $sql = "DELETE FROM document_text WHERE document_id={$docId}";
                 DBUtil::runQuery($sql);
             } else {
                 $default->log->error(sprintf(_kt("migrateDocuments: Problem indexing document %d"), $docId));
             }
             @unlink($targetFile);
         }
     }
     @unlink($lockFile);
     $time = KTUtil::getBenchmarkTime() - $start;
     KTUtil::setSystemSetting('migrationTime', KTUtil::getSystemSetting('migrationTime', 0) + $time);
     KTUtil::setSystemSetting('migratedDocuments', KTUtil::getSystemSetting('migratedDocuments', 0) + $numDocs);
     $default->log->info(sprintf(_kt('migrateDocuments: stopping - done in %d seconds!'), $time));
     if ($noDocs) {
         $default->log->info(_kt('migrateDocuments: Completed!'));
         KTUtil::setSystemSetting('migrationComplete', 'true');
         schedulerUtil::deleteByName('Index Migration');
         $default->log->debug(_kt('migrateDocuments: Disabling \'Index Migration\' task by removing scheduler entry.'));
     }
 }
 /**
  * Check if this is a new installation
  *
  */
 function checkNewInstall()
 {
     // The date and time of installation is not stored anywhere so we work around it
     // On installation the run_time of all tasks is set to '2007-10-01', so we check if all the tasks have the same run_time date with time set to 00:00:00
     // We then set run_time to the current date, ensuring the time is not 00.
     $query = 'SELECT count(*) as cnt, run_time FROM scheduler_tasks s GROUP BY run_time';
     $res = DBUtil::getResultArray($query);
     if (PEAR::isError($res)) {
         return false;
     }
     // if they aren't all the same return false - not a fresh install
     $iCnt = count($res);
     if ($iCnt > 1) {
         return false;
     }
     // Check if the time is 00
     $sRunTime = $res[0]['run_time'];
     $aRunTime = explode(' ', $sRunTime);
     if (!isset($aRunTime[1]) || empty($aRunTime[1])) {
         // set install date
         schedulerUtil::setInstallDate();
         return true;
     }
     if ($aRunTime[1] == '00:00:00') {
         // set install date
         schedulerUtil::setInstallDate();
         return true;
     }
     return false;
 }
 /**
  * Registers metdata fields in system.
  *
  */
 private function registerMetdataFields()
 {
     $sql = "SELECT\n\t\t\t\t\tfs.name as fieldset, f.name as field, fs.id as fsid, f.id as fid, f.data_type\n\t\t\t\tFROM\n\t\t\t\t\tfieldsets fs\n\t\t\t\t\tINNER JOIN document_fields f ON f.parent_fieldset=fs.id\n\t\t\t\tWHERE\n\t\t\t\t\tfs.disabled=0";
     $result = DBUtil::getResultArray($sql);
     foreach ($result as $record) {
         $fieldset = addslashes($record['fieldset']);
         $field = addslashes($record['field']);
         $fieldsetid = $record['fsid'];
         $fieldid = $record['fid'];
         $type = $record['data_type'];
         $classname = "MetadataField{$fieldid}";
         $classdefn = "\n\t\t\t\tclass {$classname} extends MetadataField\n\t\t\t\t{\n\t\t\t\t\tpublic function __construct()\n\t\t\t\t\t{\n\t\t\t\t\t\tparent::__construct('{$fieldset}','{$field}',{$fieldsetid}, {$fieldid});" . ($type == 'INT' ? '$this->isValueQuoted(false);' : '') . "\n\t\t\t\t\t}\n\t\t\t\t}";
         eval($classdefn);
         $field = new $classname();
         $this->registerField($field);
     }
 }
 /**
  * Method to get the list of affected filetypes when an extractor is not available
  * @param string $extractor Name of the Extractor
  * @return string List of Affected filetypes
  */
 public function affectedTypes($extractor)
 {
     // Create SQL
     $sql = "SELECT filetypes FROM mime_types INNER JOIN mime_extractors ON (extractor_id = mime_extractors.id)\n            WHERE mime_extractors.name = ?";
     // Create Query
     $aQuery = array($sql, array($extractor));
     // Get Results from DB
     $aTempRes = DBUtil::getResultArray($aQuery);
     $str = '';
     // Prepare into a string
     if (count($aTempRes) > 0) {
         $comma = '';
         foreach ($aTempRes as $mime) {
             $str .= $comma . $mime['filetypes'];
             $comma = ', ';
         }
     }
     return $str;
 }
 private function loadProcessors()
 {
     // Get list of registered processors (plugins)
     $query = 'SELECT h.* FROM plugin_helper h
         INNER JOIN plugins p ON (p.namespace = h.plugin)
     	WHERE p.disabled = 0 AND h.classtype = "processor"';
     $results = DBUtil::getResultArray($query);
     if (PEAR::isError($results)) {
         global $default;
         $default->log->debug('documentProcessor: error loading processors') . ' - ' . $results->getMessage();
         return false;
     }
     if (empty($results)) {
         return false;
     }
     $processors = array();
     foreach ($results as $item) {
         $path = KTUtil::isAbsolutePath($item['pathname']) ? $item['pathname'] : KT_DIR . DIRECTORY_SEPARATOR . $item['pathname'];
         require_once $path;
         $processors[] = new $item['classname']();
     }
     usort($processors, 'orderProcessors');
     return $processors;
 }
 /**
  * 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 #17
0
 /**
  *give the mimetype name and get the friendly names and the extensions
  *
  */
 function getFriendlyNameAndExtension($sMimeType)
 {
     $sTable = KTUtil::getTableName('mimetypes');
     $sQuery = "SELECT friendly_name, filetypes FROM " . $sTable . " WHERE mimetypes = ?";
     $aQuery = array($sQuery, array($sMimeType));
     $res = DBUtil::getResultArray($aQuery);
     return $res;
 }
Exemple #18
0
 /**
  * Drop all indexes and foreign key constraints from the system.
  *
  * @return int The number of elements cleared.
  */
 private function getDBSchema()
 {
     $this->schema = array();
     $result = DBUtil::getResultArray('SHOW TABLES');
     $tables = array();
     foreach ($result as $table) {
         $keys = array_keys($table);
         $tablename = $table[$keys[0]];
         if (substr($tablename, 0, 5) == 'zseq_') {
             continue;
         }
         $stmt = DBUtil::getResultArray("SHOW CREATE TABLE {$tablename};");
         $keys = array_keys($stmt[0]);
         $sql = $stmt[0][$keys[1]];
         $this->schema[$tablename] = $sql;
     }
 }
Exemple #19
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'));
 }
 /**
  * Reset the order of the columns
  *
  */
 function reorderColumns($sViewNamespace)
 {
     // Get the columns in the order they'll appear - first by position then by id
     $sql = "SELECT id, position FROM column_entries\n\t       WHERE view_namespace = ?\n\t       ORDER BY position, id ASC";
     $aParams = array($sViewNamespace);
     $result = DBUtil::getResultArray(array($sql, $aParams));
     if (PEAR::isError($result) || empty($result)) {
         return false;
     }
     // Set all positions to be unique and in order
     foreach ($result as $key => $column) {
         $position = $column['position'];
         // If the column position is correct in the order, continue
         if ($position == $key) {
             continue;
         }
         // Reset the position
         $aFields = array();
         $aFields['position'] = $key;
         $res = DBUtil::autoUpdate('column_entries', $aFields, $column['id']);
     }
     return true;
 }
 /**
  * Get list of plugins
  *
  * @param string $filename
  */
 private function capture_plugins($filename)
 {
     $sql = 'select namespace,path, disabled, unavailable,friendly_name from plugins';
     $result = DBUtil::getResultArray($sql);
     $plugins = "<h1>Plugin Status Report</h1>";
     $plugins .= '<table border=1 cellpadding=0 cellspacing=0u	>';
     $plugins .= '<tr><th>Display Name<th>Availability<th>Namespace<th>Path';
     foreach ($result as $rec) {
         $fileexists = file_exists(KT_DIR . '/' . $rec['path']) ? '' : '<font color="red">';
         $status = $rec['disabled'] == 0 ? '<font color="green">' : '<font color="orange">';
         $unavailable = $rec['unavailable'] == 0 ? 'available' : '<font color="orange">unavailable';
         $plugins .= '<tr>';
         $plugins .= '<td>' . $status . $rec['friendly_name'];
         $plugins .= '<td>' . $unavailable;
         $plugins .= '<td>' . $rec['namespace'];
         $plugins .= '<td>' . $fileexists . $rec['path'] . "\r\n";
     }
     $plugins .= '</table>';
     $plugins .= '<br>Plugin name is <font color=green>green</font> if  enabled  and <font color=orange>orange</font> if disabled .';
     $plugins .= '<br>Availability indicates that KnowledgeTree has detected the plugin not to be available.';
     $plugins .= '<br>Path is coloured <font color=red>red</font> if the plugin file cannot be resolved. If the path is not resolved, it should be flagged unavailable.';
     file_put_contents($filename, $plugins);
 }
 /**
  * This returns the transaction history for the document.
  *
  * @author KnowledgeTree Team
  * @access public
  * @return array The list of transactions | a PEAR_Error on failure
  */
 function get_transaction_history()
 {
     $sQuery = 'SELECT DTT.name AS transaction_name, U.name AS username, DT.version AS version, DT.comment AS comment, DT.datetime AS datetime ' . 'FROM ' . KTUtil::getTableName('document_transactions') . ' AS DT INNER JOIN ' . KTUtil::getTableName('users') . ' AS U ON DT.user_id = U.id ' . 'INNER JOIN ' . KTUtil::getTableName('transaction_types') . ' AS DTT ON DTT.namespace = DT.transaction_namespace ' . 'WHERE DT.document_id = ? ORDER BY DT.datetime DESC';
     $aParams = array($this->documentid);
     $transactions = DBUtil::getResultArray(array($sQuery, $aParams));
     if (is_null($transactions) || PEAR::isError($transactions)) {
         return new KTAPI_Error(KTAPI_ERROR_INTERNAL_ERROR, $transactions);
     }
     $config = KTConfig::getSingleton();
     $wsversion = $config->get('webservice/version', LATEST_WEBSERVICE_VERSION);
     foreach ($transactions as $key => $transaction) {
         $transactions[$key]['version'] = (double) $transaction['version'];
     }
     return $transactions;
 }
 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();
 }
Exemple #24
0
                $sqlaction = 'optimize table';
                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.');
Exemple #25
0
function getTaskList()
{
    $now = date('Y-m-d H:i:s');
    //time();
    $query = "SELECT * FROM scheduler_tasks WHERE is_complete = 0 AND run_time < '{$now}' AND status != 'disabled'";
    $result = DBUtil::getResultArray($query);
    if (PEAR::isError($result)) {
        return false;
    }
    return $result;
}
 function getDocuments($iBatchSize, $iBatchStart, $sSortColumn, $sSortOrder, $sJoinClause = null, $aJoinParams = null)
 {
     $aOptions = array('select' => 'DISTINCT DTS.document_id AS id');
     $res = $this->getQuery($aOptions);
     if (PEAR::isError($res)) {
         return array();
     }
     list($sQuery, $aParams) = $res;
     $sQuery .= ' ORDER BY ' . $sSortColumn . ' ' . $sSortOrder . ' ';
     $sQuery .= " LIMIT {$iBatchStart}, {$iBatchSize}";
     $q = array($sQuery, $aParams);
     $res = DBUtil::getResultArray($q);
     return $res;
 }
 /**
  * Get the status of an item in the queue
  * 0 = new item; 1 = in progress; 2 = completed; 3 = error;
  *
  * @param string $code
  * @return Queue array
  */
 public function getItemStatus($code)
 {
     $sql = array();
     $sql[] = 'SELECT status, errors FROM download_queue WHERE code = ?';
     $sql[] = $code;
     $result = DBUtil::getResultArray($sql);
     return $result;
 }
Exemple #28
0
 /**
  * Load the actions, portlets, etc as part of the parent plugin
  *
  */
 function load()
 {
     // Include any required resources, javascript files, etc
     $res = $this->run_setup();
     if (!$res) {
         return false;
     }
     // Get actions, portlets, etc, create arrays as part of plugin
     $query = "SELECT * FROM plugin_helper h WHERE plugin = '{$this->sNamespace}'";
     $aPluginHelpers = DBUtil::getResultArray($query);
     if (!empty($aPluginHelpers)) {
         foreach ($aPluginHelpers as $plugin) {
             $sName = $plugin['namespace'];
             $sParams = $plugin['object'];
             $aParams = explode('|', $sParams);
             $sClassType = $plugin['classtype'];
             switch ($sClassType) {
                 case 'portlet':
                     $aLocation = unserialize($aParams[0]);
                     if ($aLocation != false) {
                         $aParams[0] = $aLocation;
                     }
                     $this->_aPortlets[$sName] = $aParams;
                     break;
                 case 'trigger':
                     $this->_aTriggers[$sName] = $aParams;
                     break;
                 case 'action':
                     $this->_aActions[$sName] = $aParams;
                     break;
                 case 'page':
                     $this->_aPages[$sName] = $aParams;
                     break;
                 case 'authentication_provider':
                     $this->_aAuthenticationProviders[$sName] = $aParams;
                     break;
                 case 'admin_category':
                     $this->_aAdminCategories[$sName] = $aParams;
                     break;
                 case 'admin_page':
                     $this->_aAdminPages[$sName] = $aParams;
                     break;
                 case 'dashlet':
                     $this->_aDashlets[$sName] = $aParams;
                     break;
                 case 'i18n':
                     $this->_ai18n[$sName] = $aParams;
                     break;
                 case 'i18nlang':
                     $this->_ai18nLang[$sName] = $aParams;
                     break;
                 case 'language':
                     $this->_aLanguage[$sName] = $aParams;
                     break;
                 case 'help_language':
                     $this->_aHelpLanguage[$sName] = $aParams;
                     break;
                 case 'workflow_trigger':
                     $this->_aWFTriggers[$sName] = $aParams;
                     break;
                 case 'column':
                     $this->_aColumns[$sName] = $aParams;
                     break;
                 case 'view':
                     $this->_aViews[$sName] = $aParams;
                     break;
                 case 'notification_handler':
                     $this->_aNotificationHandlers[$sName] = $aParams;
                     break;
                 case 'template_location':
                     $this->_aTemplateLocations[$sName] = $aParams;
                     break;
                 case 'criterion':
                     $aInit = unserialize($aParams[3]);
                     if ($aInit != false) {
                         $aParams[3] = $aInit;
                     }
                     $this->_aCriteria[$sName] = $aParams;
                     break;
                 case 'widget':
                     $this->_aWidgets[$sName] = $aParams;
                     break;
                 case 'validator':
                     $this->_aValidators[$sName] = $aParams;
                     break;
                 case 'interceptor':
                     $this->_aInterceptors[$sName] = $aParams;
                     break;
             }
         }
     }
     return true;
 }
Exemple #29
0
 function readConfig()
 {
     //Load config data from the database
     $sQuery = 'select group_name, item, value, default_value from config_settings';
     $confResult = DBUtil::getResultArray($sQuery);
     if (PEAR::isError($confResult)) {
         return $confResult;
     }
     // Update the config array - overwrite the current settings with the settings in the database.
     foreach ($confResult as $confItem) {
         $this->setns($confItem['group_name'], $confItem['item'], $confItem['value'], $confItem['default_value']);
     }
     $this->populateDefault();
 }
 function getTransactionsMatchingQuery($oUser, $sJoinClause, $aExternalWhereClauses, $aExternalWhereParams, $aOptions = null)
 {
     $sSelectItems = 'DTT.name AS transaction_name, U.name AS user_name, DT.version AS version, DT.comment AS comment, DT.datetime AS datetime, D.id as document_id, DT.transaction_namespace as namespace';
     $sBaseJoin = "FROM " . KTUtil::getTableName("document_transactions") . " AS DT " . "INNER JOIN " . KTUtil::getTableName("users") . " AS U ON DT.user_id = U.id " . "INNER JOIN " . KTUtil::getTableName("transaction_types") . " AS DTT ON DTT.namespace = DT.transaction_namespace " . "INNER JOIN " . KTUtil::getTableName("documents") . " AS D ON D.id = DT.document_id ";
     // now we're almost at partialquery like status.
     $perm_res = KTSearchUtil::permissionToSQL($oUser, 'ktcore.permissions.read');
     if (PEAR::isError($perm_res)) {
         return $perm_res;
     }
     list($sPermissionString, $aPermissionParams, $sPermissionJoin) = $perm_res;
     // compile the final list
     $aFinalWhere = kt_array_merge(array($sPermissionString, 'D.creator_id IS NOT NULL'), $aExternalWhereClauses, array('D.status_id = ?'));
     $aFinalWhereParams = kt_array_merge($aPermissionParams, $aExternalWhereParams, array(LIVE));
     if (!is_array($aOptions)) {
         $aOptions = (array) $aOptions;
     }
     $sOrderBy = KTUtil::arrayGet($aOptions, 'orderby', 'DT.datetime DESC');
     // compile these.
     // NBM: do we need to wrap these in ()?
     $sWhereClause = implode(' AND ', $aFinalWhere);
     if (!empty($sWhereClause)) {
         $sWhereClause = 'WHERE ' . $sWhereClause;
     }
     $sQuery = sprintf("SELECT %s %s %s %s %s ORDER BY %s", $sSelectItems, $sBaseJoin, $sPermissionJoin, $sJoinClause, $sWhereClause, $sOrderBy);
     //var_dump(array($sQuery, $aFinalWhereParams));
     $res = DBUtil::getResultArray(array($sQuery, $aFinalWhereParams));
     //var_dump($res); exit(0);
     return $res;
 }