*/
// must be run within Dokuwiki
if (!defined('DOKU_INC')) die();
class syntax_plugin_pgsqlquery extends DokuWiki_Syntax_Plugin {
public function getType() {
return 'substition';
}
public function getSort() {
return 11;
}
public function connectTo($mode)
{
$this->Lexer->addEntryPattern('', $mode, 'plugin_pgsqlquery');
}
public function postConnect()
{
$this->Lexer->addExitPattern('','plugin_pgsqlquery');
}
/**
* Handle matches of the sqlquery syntax
*
* @param string $match The match of the syntax
* @param int $state The state of the handler
* @param int $pos The position in the document
* @param Doku_Handler $handler The handler
* @return array Data for the renderer
*/
public function handle($match, $state, $pos, Doku_Handler $handler)
{
switch ( $state )
{
case DOKU_LEXER_ENTER:
$data = array();
return $data;
break;
case DOKU_LEXER_UNMATCHED:
return array('sqlquery' => $match);
break;
case DOKU_LEXER_EXIT:
$data = array();
return $data;
break;
}
$data = array();
return $data;
}
/**
* Render xhtml output or metadata
*
* @param string $mode Renderer mode (supported modes: xhtml)
* @param Doku_Renderer $renderer The renderer
* @param array $data The data from the handler() function
* @return bool If rendering was successful.
*/
public function render($mode, Doku_Renderer $renderer, $data)
{
if ( $mode != 'xhtml' ) return false;
if ( !empty( $data['sqlquery'] ) )
{
// получаем параметры конфигурации
$host = $this->getConf('Host');
$DB = $this->getConf('DB');
$user = $this->getConf('user');
$password = $this->getConf('password');
// получаем запрос
$querystring = $data['sqlquery'];
// подключаемся к базе
$dsn = "pgsql:host=$host;dbname=$DB;user=$user;password=$password";
try
{
// create a PostgreSQL database connection
$link = new PDO($dsn);
// display a message if connected to the PostgreSQL successfully
if( $link )
{
// делаем запрос
$stmt = $link->query($querystring);
// получаем кол-во столбцов и строк
$ncols = $stmt->columnCount();
$nrows = $stmt->rowCount();
// строим таблицу
$renderer->doc .= "
";
$renderer->doc .= "";
// строим заголовок
for ($i=0; $i < $ncols; $i++)
{
$meta_data = $stmt->getColumnMeta($i);
$renderer->doc .= "";
$renderer->doc .= $meta_data['name'];
$renderer->doc .= " | ";
}
// строим содержимое таблицы
$renderer->doc .= "
";
while ($row = $stmt->fetch(PDO::FETCH_NUM))
{
$renderer->doc .= "";
// строим строку
for ( $c=0; $c < $ncols; $c++ )
{
$renderer->doc .= "";
$renderer->doc .= $row[$c];
$renderer->doc .= " | ";
}
$renderer->doc .= "
";
}
// закрываем таблицу
$renderer->doc .= "
";
$renderer->doc .= "";
$renderer->doc .= "";
}
}
catch (PDOException $e)
{
// report error message
$renderer->doc .= "Can't connect to database. Error: ".$e->getMessage();
}
} // of sqlquery not empty
return true;
} // of render function
}
// vim:ts=4:sw=4:et: