protected function registerServer($host, $port) { $result = $this->memcache->addServer($host, $port); if (!$result) { LogHelper::log_error(t('[@cacheType] Could not add server (@host:@port)', array('@cacheType' => self::$CACHE__TYPE, '@host' => $host, '@port' => $port))); } return $result; }
public function __destruct() { // because it is executed in destructor we should not allow exceptions to reach PHP script execution engine // otherwise execution of the script will halt try { $this->flush(); } catch (Exception $e) { LogHelper::log_error($e); } parent::__destruct(); }
public static function detectDatasetSourceType(DatasetMetaData $dataset) { if (isset($dataset->assembler)) { return self::DATASET_SOURCE_TYPE__DYNAMIC; } elseif (isset($dataset->source)) { $source = trim($dataset->source); $isTableName = strpos($source, ' ') === FALSE; return $isTableName ? self::DATASET_SOURCE_TYPE__TABLE : self::DATASET_SOURCE_TYPE__SUBQUERY; } LogHelper::log_error($dataset); throw new IllegalArgumentException(t('Could not detect type of dataset source for the dataset: @datasetName', array('@datasetName' => $dataset->publicName))); }
public static function mergeWith(&$instance, $source, $mergeCompositeProperty = FALSE) { if (isset($source)) { if (is_object($source) || is_array($source)) { foreach ($source as $name => $value) { // source does not have value for the property if (!isset($value)) { continue; } // we do not support composite properties if (is_object($value) || is_array($value)) { if ($mergeCompositeProperty) { if (!isset($instance->{$name})) { $instance->{$name} = NULL; } if (is_object($value)) { // support for an object self::mergeWith($instance->{$name}, $value, TRUE); } else { if (ArrayHelper::isIndexedArray($value)) { // support for an indexed array $a = NULL; foreach ($value as $index => $v) { $o = NULL; self::mergeWith($o, $v, TRUE); $a[$index] = $o; } $instance->{$name} = $a; } else { // support for an associative array self::mergeWith($instance->{$name}, $value, TRUE); } } } continue; } // overriding is not allowed if (isset($instance->{$name}) && $instance->{$name} != $value) { LogHelper::log_error(t("'@propertyName' property already contains value: @existingPropertyValue. Merge cannot be performed with new value: @newPropertyValue", array('@propertyName' => $name, '@existingPropertyValue' => $instance->{$name}, '@newPropertyValue' => $value))); throw new UnsupportedOperationException(t("'@propertyName' property already contains value. Merge cannot be performed", array('@propertyName' => $name))); } $instance->{$name} = $value; } } else { $instance = $source; } } return $instance; }
public function render ( $data ) { ob_start(); if ( isset($_REQUEST['cache']) ) { header('Cache-Control: no-transform,public,max-age=300,s-maxage=900'); header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); } else { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); } header('Content-Description: File Transfer'); header("Content-Type: application/octet-stream"); header("Content-Transfer-Encoding: binary"); header('Content-Disposition: attachment; filename="' . $this->filename . '.xls"'); $objPHPExcel = new PHPExcel(); $rowNumber = 1; if ( is_array($data) ) { foreach ( $data as $row ) { $col = 'A'; foreach ( $row as $cell ) { $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell); $col++; } $rowNumber++; } } else { LogHelper::log_error('Expecting array of data for export'); LogHelper::log_error($data); } // Save as an Excel BIFF (xls) file $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); gd_get_session_messages(); // log and clear any messages $output = ob_get_clean(); if ( !isset($_SERVER['HTTP_ACCEPT_ENCODING']) || empty($_SERVER['HTTP_ACCEPT_ENCODING']) ) { // the content length may vary if the server is using compression header('Content-Length: '.strlen($output)); } return $output; }
public static function checkValueAsWord($value) { if (!isset($value)) { return; } $result = preg_match('/^[a-zA-Z_]\\w*$/', $value); if ($result === FALSE) { $lastError = preg_last_error(); LogHelper::log_error(t("'@value' could not be validated as a word: Regular expression error: @lastError", array('@value' => $value, '@lastError' => $lastError))); } elseif ($result == 0) { LogHelper::log_error(t("'@value' is not a word", array('@value' => $value))); } else { return; } throw new IllegalArgumentException(t("'@value' is not a word", array('@value' => $value))); }
public static function getExportColumnName ( $uiMetaDataName, MetaModel $metamodel ) { if ( trim($uiMetaDataName) == '' ) { $message = t('Empty columnName discovered'); drupal_set_message($message, 'warning'); LogHelper::log_warn($message); return $uiMetaDataName; } list($elementNameSpace, $name) = AbstractDatasetUIMetaDataGenerator::splitElementUIMetaDataName($uiMetaDataName); switch ( $elementNameSpace ) { case AbstractAttributeUIMetaData::NAME_SPACE: list($referencedDimensionName, $dimensionColumnName) = ParameterNameHelper::split($name); list($datasetName, $dimensionName) = ReferencePathHelper::splitReference($referencedDimensionName); if (isset($datasetName)) { $adjustedReferencedDimensionName = ReferencePathHelper::assembleReference(self::getExportDatasetName($datasetName,$metamodel), $dimensionName); $name = ParameterNameHelper::assemble($adjustedReferencedDimensionName, $dimensionColumnName); } break; case AbstractMeasureUIMetaData::NAME_SPACE: list($datasetName, $measureName) = ReferencePathHelper::splitReference($name); if (isset($datasetName)) { $name = ReferencePathHelper::assembleReference(self::getExportDatasetName($datasetName,$metamodel), $measureName); } break; case FormulaUIMetaData::NAME_SPACE: list($datasetName, $formulaName) = ReferencePathHelper::splitReference($name); if (isset($datasetName)) { $name = ReferencePathHelper::assembleReference(self::getExportDatasetName($datasetName,$metamodel), $formulaName); } break; default: $message = t('Unsupported UI Meta Data name space: @uiMetaDataName', array('@uiMetaDataName' => $uiMetaDataName)); LogHelper::log_error($message); throw new UnsupportedOperationException($message); } return AbstractDatasetUIMetaDataGenerator::prepareElementUIMetaDataName($elementNameSpace, $name); }
/** * This file is part of the Checkbook NYC financial transparency software. * * Copyright (C) 2012, 2013 New York City * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ function get_node_field_value($node, $propertyName, $index = 0, $storageSuffixName = 'value', $required = FALSE) { $value = NULL; $nodePropertyValue = isset($node->{$propertyName}) ? $node->{$propertyName} : NULL; if (isset($nodePropertyValue[$node->language][$index][$storageSuffixName])) { $value = $nodePropertyValue[$node->language][$index][$storageSuffixName]; if (is_string($value)) { $value = trim($value); if (strlen($value) === 0) { $value = NULL; } } } if ($required && !isset($value)) { LogHelper::log_error($node); throw new IllegalArgumentException(t('@propertyName@index has not been set for the node: @nodeId', array('@nodeId' => $node->nid, '@propertyName' => $propertyName, '@index' => $index == 0 ? '' : t('[@index]', array('@index' => $index))))); } return $value; }
public function render ( $data ) { ob_start(); if ( isset($_REQUEST['cache']) ) { header('Cache-Control: no-transform,public,max-age=300,s-maxage=900'); header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); } else { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); } header('Content-Description: File Transfer'); header("Content-Type: text/csv"); header('Content-Disposition: attachment; filename="' . $this->filename . '.csv"'); $outStream = fopen("php://output", 'w'); if ( is_array($data) ) { foreach ( $data as $item ) { if ( is_array($item) ) { fputcsv($outStream, $item, ',', '"'); } else { LogHelper::log_error('Expecting array of data for export'); LogHelper::log_error($item); } } } else { LogHelper::log_error('Expecting array of data for export'); LogHelper::log_error($data); } fclose($outStream); gd_get_session_messages(); // log and clear any messages $output = ob_get_clean(); if ( !isset($_SERVER['HTTP_ACCEPT_ENCODING']) || empty($_SERVER['HTTP_ACCEPT_ENCODING']) ) { // the content length may vary if the server is using compression header('Content-Length: '.strlen($output)); } return $output; }
public static function addUniqueValue(array &$array = NULL, $value) { if (isset($value)) { if (is_array($value)) { LogHelper::log_error(t("[@value] should not be an array", array('@value' => implode(', ', $value)))); throw new IllegalArgumentException(t('Value should not be an array')); } if (isset($array)) { if (array_search($value, $array) === FALSE) { $array[] = $value; return TRUE; } } else { $array[] = $value; return TRUE; } } return FALSE; }
public function assemble(ColumnMetaData $column) { $expression = NULL; if ($column->persistence == FormulaMetaData::PERSISTENCE__CALCULATED) { $this->columnAssemblingStack = array(); array_push($this->columnAssemblingStack, $column->name); try { if (!isset($column->source)) { throw new IllegalStateException(t('Formula expression is not provided')); } $language = isset($column->expressionLanguage) ? $column->expressionLanguage : NULL; $parser = new FormulaExpressionParser($language); $expression = $parser->expressionLanguageHandler->clean($column->source); $expression = $parser->parse($expression, array($this, 'replaceColumnNames')); $expression = $parser->insertMarker('', 0, $expression, TRUE); $lexemes = $parser->expressionLanguageHandler->lex($expression); $syntaxTree = $parser->expressionLanguageHandler->parse($lexemes); $expression = $parser->expressionLanguageHandler->generate($syntaxTree); } catch (Exception $e) { LogHelper::log_error($e); throw new IllegalStateException(t( "Cannot assemble expression for %columnName formula: %error", array('%columnName' => $column->publicName, '%error' => $e->getMessage()))); } array_pop($this->columnAssemblingStack); } else { $expression = $column->name; } return $expression; }
public function getWarningBody(array $options = array()) { $body = '<div class="report-container" id="reportId-' . intval($this->ReportConfig->getId()) .'" class="report">'; $messages = '<li>The report is configured incorrectly</li><li>The report is using a column that was removed from the system</li>'; if (isset($options['error'])) { $messages .= '<li>' . $options['error'] . '</li>'; if (isset($_SESSION['messages'])) { if (isset($_SESSION['messages']['error'])) { foreach ($_SESSION['messages']['error'] as $error) { $messages .= '<li>' . $error . '</li>'; LogHelper::log_error($error); } } unset($_SESSION['messages']); } } $body .= '<div class="alert alert-warning alert-dismissible" role="alert" style="text-align: left;"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><h4>The report could not be rendered!</h4>Possible causes may include any of the following:<ol>'.$messages.'</ol></div>'; return $body.'</div>'; }
protected function castValueImpl($value) { // do not use procedural style. We need an exception in case of error try { $dt = new DateTime($value); } catch (Exception $e) { LogHelper::log_error($e); throw new IllegalArgumentException(t('Failed to parse datetime string: %value', array('%value' => $value))); } return $dt->format($this->getFormat()); }
/** * @param $form * @param $form_state * @throws Exception */ function gd_sync_import_update_form_submit ( $form, &$form_state ) { try { $content = json_decode($form_state['values']['content']); if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception('Invalid JSON'); } $importContext = new GD\Sync\Import\ImportContext(array('datasourceName'=>$form_state['values']['datasourceName'],'operation'=>'update')); $importStream = new GD\Sync\Import\ImportStream(); $importStream->set(null,$content); $importController = new \GD\Sync\Import\ImportController(); $importController->import($importStream,$importContext); drupal_set_message('Datasource Updated Successfully'); } catch ( Exception $e ) { LogHelper::log_error($e); drupal_set_message($e->getMessage(),'error'); } }
/** * Report preview for admin * @return void */ function gd_dashboard_report_page_preview () { if ( empty($_POST['dashboard']) || empty($_POST['report']) && empty($_POST['ds']) ) { $message = 'Missing required params for preview'; LogHelper::log_error($message); echo $message; } else { /** * Dashboard */ $dashboard = json_decode($_POST['dashboard']); /** * Report */ $report = json_decode($_POST['report']); gd_datasource_set_active($_POST['ds']); $DashboardConfig = new GD_DashboardConfig($dashboard); foreach ( $DashboardConfig->items as $item ) { if ( $report->id == $item->content ) { $options = array('admin' => true); $html = $DashboardConfig->getItemReportView($item, $options); print $DashboardConfig->getDashboardCustomView() . $html->header . $html->body . $html->footer; } } } drupal_exit(); }
LogHelper::log_error($e); $errors[] = $e->getMessage(); } } else if ( $action == 'Delete' ) { try { gd_datasource_unpublish($datasourceName); drupal_set_message("Topic successfully deleted","status"); drupal_goto("account_datamart_statistics_charts"); } catch ( Exception $e ) { LogHelper::log_error($e); $errors[] = $e->getMessage(); } } } } ?> <!DOCTYPE html> <html lang="en"> <head> <?php global $theme; $path = drupal_get_path('theme', 'govdash_core'); ?> <link rel="stylesheet" href="/sites/all/libraries/bootstrap/css/bootstrap.min.css" />
protected function checkDocumentExistence($record, $isExceptionThrown) { $wasDocumentProcessed = !isset($record->error); if (!$wasDocumentProcessed) { $message = t( 'Error processing record@id: @error@errorReason', array('@id' => (isset($record->id) ? " (id: '$record->id')" : (isset($record->key) ? " (key: '$record->key')" : '')), '@error' => $record->error, '@errorReason' => (isset($record->reason) ? " - \"$record->reason\"" : ''))); LogHelper::log_error($record); if ($isExceptionThrown) { throw new Exception($message); } } return $wasDocumentProcessed; }
public function release() { if (isset($this->mh)) { while (($handler = reset($this->handlers)) !== FALSE) { try { $this->releaseHandler($handler); } catch (Exception $ne) { LogHelper::log_error($ne); } } curl_multi_close($this->mh); $this->mh = NULL; } }
return; }*/ $dir .= '/' . $conf['check_book']['ref_data_dir']; if (!file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) { LogHelper::log_error("Could not prepare directory {$dir} for generating reference data."); echo $failure; return; } /*if(!is_link($dir) && !@chmod($dir,0777)){ LogHelper::log_error("Could not change permissions to 777 for $dir."); echo $failure; return; }*/ foreach ($ref_data_queries as $file_name => $ref_data_query) { $file = DRUPAL_ROOT . '/' . $dir . '/' . $file_name . '.csv'; $command = $conf['check_book']['data_feeds']['command'] . " -c \"\\\\COPY (" . $ref_data_query . ") TO '" . $file . "' WITH DELIMITER ',' CSV HEADER QUOTE '\\\"' ESCAPE '\\\"' \" "; try { LogHelper::log_notice("Command for generating {$file_name} ref data: " . $command); shell_exec($command); LogHelper::log_notice("Completed executing DB query for {$file_name}. " . (is_file($file) ? "Generated file : {$file}" : "Could not generate file for {$file_name}")); } catch (Exception $e) { $value = TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM; TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM = NULL; LogHelper::log_error($e); LogHelper::log_error("Erorr executing DB query for generating {$file_name} ref data: " . $command . ". Exception is: " . $e); TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM = $value; echo $failure; return; } } echo $success;
protected function prepareDatasetRecords4Submission(DataControllerCallContext $callcontext, $request) { $preparedRecords = NULL; $datasetName = $request->getDatasetName(); $isOperationInsert = $request->getOperationName() == DatasetInsertRequest::$OPERATION__INSERT; $isOperationDelete = $request->getOperationName() == DatasetDeleteRequest::$OPERATION__DELETE; $recordMetaData = $request->recordsHolder->recordMetaData; $keyColumn = $recordMetaData->findKeyColumn(); $keyColumnName = isset($keyColumn) ? $keyColumn->name : NULL; $documentIds = NULL; if ($request->recordsHolder instanceof IndexedRecordsHolder) { $columnCount = $recordMetaData->getColumnCount(); foreach ($request->recordsHolder->records as $record) { $preparedRecord = NULL; for ($i = 0; $i < $columnCount; $i++) { $column = $recordMetaData->columns[$i]; $columnValue = $record[$i]; if (isset($columnValue)) { $preparedRecord->{$column->name} = $columnValue; } } // preparing document identifier if (!isset($preparedRecord->_id) && isset($keyColumnName)) { $preparedRecord->_id = $preparedRecord->$keyColumnName; } // collecting document identifiers to load last revisions if (!$isOperationInsert) { if (isset($preparedRecord->_id)) { $documentIds[] = $preparedRecord->_id; } else { LogHelper::log_error($preparedRecord); throw new IllegalArgumentException(t('Could not find document identifier for the document')); } } $preparedRecords[] = $preparedRecord; } } else { foreach ($request->recordsHolder->records as $record) { // preparing document identifier if (!isset($record->_id) && isset($keyColumnName)) { $record->_id = $record->$keyColumnName; } // collecting document identifiers to load last revisions if (!$isOperationInsert) { if (isset($record->_id)) { $documentIds[] = $record->_id; } else { LogHelper::log_error($record); throw new IllegalArgumentException(t('Could not find document identifier for the document')); } } $preparedRecords[] = $record; } } if (!$isOperationInsert) { // loading previous revisions $revisions = NULL; if (isset($documentIds)) { $revisionRequest = new DatasetQueryRequest($datasetName); $revisionRequest->addQueryValues(0, '_id', $documentIds); $revisionResponse = $this->queryDataset($callcontext, $revisionRequest, NULL); if (isset($revisionResponse)) { foreach ($revisionResponse as $revision) { $revisions[$revision->_id] = $revision->_rev; } } } foreach ($preparedRecords as $record) { // setting revision if ((isset($revisions) && isset($revisions[$record->_id]))) { $record->_rev = $revisions[$record->_id]; } else { throw new IllegalArgumentException(t( 'Could not find last revision for the document: @id', array('@id' => $record->_id))); } if ($isOperationDelete) { $record->_deleted = TRUE; } } } return $preparedRecords; }
/** * Executes the shell commands with error logging * @param $commands */ private function processCommands($commands) { $current_command = ""; try { foreach ($commands as $command) { $current_command = $command; shell_exec($command); } } catch (Exception $e) { $value = TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM; TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM = NULL; LogHelper::log_error($e); $msg = "Command used to generate the file: " . $current_command; $msg .= "Error generating DB command: " . $e->getMessage(); LogHelper::log_error($msg); TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM = $value; } }
protected function detectRoutes(ReferenceLink $rootLink, array $referencePaths) { $routeId = 0; foreach ($referencePaths as $referencePath => $required) { // preparing possible routes $referenceRoutes = $rootLink->prepareRoutes($referencePath); // selecting 'the best' route $selectedRoute = NULL; if (isset($referenceRoutes)) { foreach ($referenceRoutes as $directReferenceFlag => $routes) { foreach ($routes as $route) { if (!isset($selectedRoute) || ($selectedRoute->weight > $route->weight)) { $selectedRoute = $route; } } } } if (isset($selectedRoute)) { $rootLink->assignRouteId($selectedRoute, $routeId); $routeId++; } elseif ($required) { $metamodel = data_controller_get_metamodel(); LogHelper::log_error(t('Could not execute reference path: @referencePath', array('@referencePath' => $referencePath))); list($referencedDatasetName) = ReferencePathHelper::splitReference($referencePath); $referencedDataset = $metamodel->getDataset($referencedDatasetName); throw new IllegalArgumentException(t( '%datasetNameA and %datasetNameB datasets are not connected', array('%datasetNameA' => $rootLink->dataset->publicName, '%datasetNameB' => $referencedDataset->publicName))); } } }
protected function storeValuesImpl(array $values, $expirationTime) { $errorCacheEntryNames = NULL; $adjustedExpirationTime = $expirationTime; if (!isset($adjustedExpirationTime)) { $adjustedExpirationTime = 0; } $storableValues = $deletableCacheEntryNames = NULL; foreach ($values as $cacheEntryName => $value) { if (isset($value)) { $storableValues[$cacheEntryName] = $value; } else { $deletableCacheEntryNames[] = $cacheEntryName; } } if (isset($deletableCacheEntryNames)) { foreach ($deletableCacheEntryNames as $deletableCacheEntryName) { $result = $this->memcached->delete($deletableCacheEntryName); if (($result === FALSE) && ($this->memcached->getResultCode() != Memcached::RES_NOTFOUND)) { $errorCacheEntryNames[] = $deletableCacheEntryName; LogHelper::log_error(t( '[@cacheType] Internal error during value deletion: @message', array('@cacheType' => self::CACHE__TYPE, '@message' => $this->memcached->getResultMessage()))); } } } if (isset($storableValues)) { $result = $this->memcached->setMulti($storableValues, $adjustedExpirationTime); if ($result === FALSE) { LogHelper::log_error(t( '[@cacheType] Internal error during value storing: @message', array('@cacheType' => self::CACHE__TYPE, '@message' => $this->memcached->getResultMessage()))); ArrayHelper::appendValue($errorCacheEntryNames, array_keys($storableValues)); } } return $errorCacheEntryNames; }
public static function checkPositiveInteger($value) { if (!isset($value)) { return; } DataTypeFactory::getInstance()->checkValueType(self::DATA_TYPE, $value); if ($value <= 0) { LogHelper::log_error(t("'@value' has to be positive integer", array('@value' => $value))); throw new IllegalArgumentException(t('Value has to be positive integer')); } }
/** * Given the query, creates a command to connect to the db and generate the output file, returns the filename * @param $query * @return string */ function getJobCommand($query) { global $conf; //map csv headers $columnMappings = $this->requestDataSet->displayConfiguration->csv->elementsColumn; $columnMappings = (array) $columnMappings; //Handle referenced columns foreach ($columnMappings as $key => $value) { if (strpos($value, "@") !== false) { $column_parts = explode("@", $value); $columnMappings[$key] = $column_parts[0]; } } $columnMappings = array_flip($columnMappings); $end = strpos($query, 'FROM'); $select_part = substr($query, 0, $end); $select_part = str_replace("SELECT", "", $select_part); $sql_parts = explode(",", $select_part); $new_select_part = "SELECT "; foreach ($sql_parts as $sql_part) { $sql_part = trim($sql_part); $column = $sql_part; $alias = ""; //Remove "AS" if (strpos($sql_part, "AS") !== false) { $pos = strpos($column, " AS"); $sql_part = substr($sql_part, 0, $pos); } //get only column if (strpos($sql_part, ".") !== false) { $alias = substr($sql_part, 0, 3); $column = substr($sql_part, 3); } //Handle derived columns switch ($column) { case "prime_vendor_name": $new_column = "CASE WHEN " . $alias . $column . " IS NULL THEN 'N/A' ELSE " . $alias . $column . " END"; $new_select_part .= $new_column . ' AS \\"' . $columnMappings[$column] . '\\",' . "\n"; break; case "minority_type_name": $new_column = "CASE \n"; $new_column .= "WHEN " . $alias . $column . " = 2 THEN 'Black American' \n"; $new_column .= "WHEN " . $alias . $column . " = 3 THEN 'Hispanic American' \n"; $new_column .= "WHEN " . $alias . $column . " = 7 THEN 'Non-M/WBE' \n"; $new_column .= "WHEN " . $alias . $column . " = 9 THEN 'Women' \n"; $new_column .= "WHEN " . $alias . $column . " = 11 THEN 'Individuals and Others' \n"; $new_column .= "ELSE 'Asian American' END"; $new_select_part .= $new_column . ' AS \\"' . $columnMappings[$column] . '\\",' . "\n"; break; case "vendor_type": $new_column = "CASE WHEN " . $alias . $column . " ~* 's' THEN 'Yes' ELSE 'No' END"; $new_select_part .= $new_column . ' AS \\"' . $columnMappings[$column] . '\\",' . "\n"; break; default: $new_select_part .= $alias . $column . ' AS \\"' . $columnMappings[$column] . '\\",' . "\n"; break; } } $new_select_part = rtrim($new_select_part, ",\n"); $query = substr_replace($query, $new_select_part, 0, $end); try { $fileDir = _checkbook_project_prepare_data_feeds_file_output_dir(); $filename = _checkbook_project_generate_uuid() . '.csv'; $tmpDir = isset($conf['check_book']['tmpdir']) && is_dir($conf['check_book']['tmpdir']) ? rtrim($conf['check_book']['tmpdir'], '/') : '/tmp'; $command = $conf['check_book']['data_feeds']['command']; if (!is_writable($tmpDir)) { LogHelper::log_error("{$tmpDir} is not writable. Please make sure this is writable to generate export file."); return $filename; } $tempOutputFile = $tmpDir . '/' . $filename; $outputFile = DRUPAL_ROOT . '/' . $fileDir . '/' . $filename; $cmd = $command . " -c \"\\\\COPY (" . $query . ") TO '" . $tempOutputFile . "' WITH DELIMITER ',' CSV HEADER \" "; shell_exec($cmd); $move_cmd = "mv {$tempOutputFile} {$outputFile}"; shell_exec($move_cmd); } catch (Exception $e) { $value = TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM; TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM = NULL; LogHelper::log_error($e); $msg = "Command used to generate the file: " . $command; $msg .= "Error generating DB command: " . $e->getMessage(); LogHelper::log_error($msg); TextLogMessageTrimmer::$LOGGED_TEXT_LENGTH__MAXIMUM = $value; } return $filename; }
public function checkValueType($datatype, $value) { $handler = $this->getHandler($datatype); $allowedHandlerType = DATA_TYPE__PRIMITIVE | $handler->getHandlerType(); $detectedDataType = $this->autoDetectDataType($value, $allowedHandlerType); // checking if there is exact match if (isset($detectedDataType) && $datatype != $detectedDataType) { // checking if the types are compatible $selectedByDataType = $handler->selectCompatible($detectedDataType); $selectedByDetectedDataType = $this->getHandler($detectedDataType)->selectCompatible($datatype); if (isset($selectedByDataType) || isset($selectedByDetectedDataType)) { // the types are compatible } else { LogHelper::log_error(t("'@value' is of type '@detectedDataType'. Requested type is '@requestedDataType'", array('@requestedDataType' => $datatype, '@detectedDataType' => $detectedDataType, '@value' => $value))); throw new IllegalArgumentException(t("Value is not of type '@datatype'", array('@datatype' => $datatype))); } } }
/** * For records under 200,000, user will download the file immediately. * An entry will be made in both the custom_queue_job & custom_queue_request. * * @return string * @throws Exception */ function queueImmediateRequest() { try { // validateRequest: if (!$this->validateRequest()) { return $this->response; } if (!isset($this->requestDataSet)) { // Prepare dataSet: $this->setRequestDataSet(); } $queue_request_token = NULL; // Get queue request: $queue_criteria = $this->getQueueCriteria($this->requestSearchCriteria->getCriteria()); $sql_query = get_db_query(TRUE, $this->requestDataSet->name, $this->requestDataSet->columns, $this->requestDataSet->parameters, $this->requestDataSet->sortColumn, $this->requestDataSet->startWith, $this->requestDataSet->limit, NULL); if (isset($this->requestDataSet->adjustSql)) { eval($this->requestDataSet->adjustSql); } $token = $this->generateToken(); $criteria = $this->requestSearchCriteria->getCriteria(); // Prepare new queue request: $queue_request['token'] = $token; $queue_request['name'] = strtolower($criteria['global']['type_of_data']); $queue_request['request'] = $queue_criteria; $queue_request['request_criteria'] = json_encode($criteria); $queue_request['status'] = 4; // N/A - no file to generate if ($this->requestSearchCriteria->getUserCriteria()) { $queue_request['user_criteria'] = json_encode($this->requestSearchCriteria->getUserCriteria()); } $queue_request['data_command'] = $sql_query; QueueUtil::createImmediateNewQueueRequest($queue_request); return $token; } catch (Exception $e) { LogHelper::log_error('Error Processing Queue Request: ' . $e); throw new Exception('Error Processing Queue Request.'); } }
protected function checkAssemblingStarted() { if ($this->assembled) { LogHelper::log_error(t('Meta Model assembling has not been started')); } }
public function registerCube(CubeMetaData $cube) { $this->checkAssemblingStarted(); if (!isset($cube->name)) { LogHelper::log_error($cube); throw new IllegalArgumentException(t('Cube name has not been defined')); } $cubeName = $cube->name; NameSpaceHelper::checkAlias($cubeName); if (isset($this->cubes[$cubeName])) { if ($cube->temporary) { unset($this->cubes[$cubeName]); } else { throw new IllegalArgumentException(t('Cube with name @cubeName has already been defined', array('@cubeName' => $cube->publicName))); } } if (!$cube->temporary) { // we support only one cube per dataset $cube2 = $this->findCubeByDatasetName($cube->sourceDatasetName); if (isset($cube2)) { throw new IllegalArgumentException(t("Found several cubes for '@datasetName' dataset: ['@cubeName1', '@cubeName2']", array('@datasetName' => $cube->sourceDatasetName, '@cubeName1' => $cube->publicName, '@cubeName2' => $cube2->publicName))); } } $this->cubes[$cubeName] = $cube; }
function gd_health_medic_admin_api_treatment () { try { $response = 'OK'; switch ($_SERVER['REQUEST_METHOD']) { case 'GET' : break; case 'POST' : gd_health_medic_treatment_apply(json_decode($_POST['affected']), $_POST['treatment']); break; default: throw new Exception('Unsupported request method.'); } } catch ( Exception $e ) { drupal_add_http_header('Status', '500 System Error'); gd_get_session_messages(); LogHelper::log_error($e); $response = $e->getMessage(); } echo json_encode($response); drupal_exit(); }