1<?php
2/**
3 * DokuWiki Plugin postgresqlquery (Syntax Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  George Pirogov <i1557@yandex.ru>
7 */
8
9// must be run within Dokuwiki
10if (!defined('DOKU_INC')) die();
11
12class syntax_plugin_pgsqlquery extends DokuWiki_Syntax_Plugin {
13
14    public function getType() {
15        return 'substition';
16    }
17
18    public function getSort() {
19        return 11;
20    }
21
22    public function connectTo($mode)
23    {
24        $this->Lexer->addEntryPattern('<pgsql>', $mode, 'plugin_pgsqlquery');
25    }
26
27    public function postConnect()
28    {
29        $this->Lexer->addExitPattern('</pgsql>','plugin_pgsqlquery');
30    }
31
32    /**
33     * Handle matches of the sqlquery syntax
34     *
35     * @param string          $match   The match of the syntax
36     * @param int             $state   The state of the handler
37     * @param int             $pos     The position in the document
38     * @param Doku_Handler    $handler The handler
39     * @return array Data for the renderer
40     */
41    public function handle($match, $state, $pos, Doku_Handler $handler)
42    {
43        switch ( $state )
44        {
45              case DOKU_LEXER_ENTER:
46              $data = array();
47              return $data;
48              break;
49
50              case DOKU_LEXER_UNMATCHED:
51        			return array('sqlquery' => $match);
52              break;
53
54              case DOKU_LEXER_EXIT:
55              $data = array();
56              return $data;
57              break;
58
59        }
60
61        $data = array();
62        return $data;
63    }
64
65    /**
66     * Render xhtml output or metadata
67     *
68     * @param string         $mode      Renderer mode (supported modes: xhtml)
69     * @param Doku_Renderer  $renderer  The renderer
70     * @param array          $data      The data from the handler() function
71     * @return bool If rendering was successful.
72     */
73    public function render($mode, Doku_Renderer $renderer, $data)
74    {
75        if ( $mode != 'xhtml' ) return false;
76
77        if ( !empty( $data['sqlquery'] ) )
78        {
79            // получаем параметры конфигурации
80            $host     = $this->getConf('Host');
81            $DB       = $this->getConf('DB');
82            $user     = $this->getConf('user');
83            $password = $this->getConf('password');
84
85            // получаем запрос
86            $querystring = $data['sqlquery'];
87
88            // подключаемся к базе
89            $dsn = "pgsql:host=$host;dbname=$DB;user=$user;password=$password";
90
91            try
92            {
93            	// create a PostgreSQL database connection
94            	$link = new PDO($dsn);
95
96            	// display a message if connected to the PostgreSQL successfully
97            	if( $link )
98                {
99                    // делаем запрос
100                    $stmt = $link->query($querystring);
101                    // получаем кол-во столбцов и строк
102                    $ncols = $stmt->columnCount();
103                    $nrows = $stmt->rowCount();
104
105                    // строим таблицу
106                    $renderer->doc .= "<table id=\"sqlquerytable\" class=\"inline\">";
107                    $renderer->doc .= "<thead><tr>";
108
109                    // строим заголовок
110                    for ($i=0; $i < $ncols; $i++)
111                    {
112                        $meta_data = $stmt->getColumnMeta($i);
113                        $renderer->doc .= "<th>";
114                        $renderer->doc .= $meta_data['name'];
115                        $renderer->doc .= "</th>";
116                    }
117
118                    // строим содержимое таблицы
119                    $renderer->doc .= "<tbody>";
120
121                    while ($row = $stmt->fetch(PDO::FETCH_NUM))
122                    {
123                        $renderer->doc .= "<tr>";
124                        // строим строку
125                        for ( $c=0; $c < $ncols; $c++ )
126                        {
127                            $renderer->doc .= "<td>";
128                            $renderer->doc .= $row[$c];
129                            $renderer->doc .= "</td>";
130                        }
131                        $renderer->doc .= "</tr>";
132                    }
133
134                    // закрываем таблицу
135                    $renderer->doc .= "</tbody></table>";
136                    $renderer->doc .= "</tr></thead>";
137                    $renderer->doc .= "</tbody></table>";
138                }
139
140            }
141            catch (PDOException $e)
142            {
143            	// report error message
144            	$renderer->doc .= "Can't connect to database. Error: ".$e->getMessage();
145            }
146
147        } // of sqlquery not empty
148
149        return true;
150
151    } // of render function
152}
153
154// vim:ts=4:sw=4:et:
155