- CS
[m6w6/ext-http] / lib / PgLobStream.php
1 <?php
2
3 /**
4 * PostgreSQL LOB stream
5 * $Id$
6 *
7 * Usage:
8 * <code>
9 * // GET /image.php?image=1234
10 * if (PgLobStream::$loId = (int) $_GET['image']) {
11 * if ($lob = fopen('pglob://dbname=database user=mike', 'r')) {
12 * HttpResponse::setContentType('image/jpeg');
13 * HttpResponse::setStream($lob);
14 * HttpResponse::send();
15 * }
16 * }
17 * </code>
18 *
19 * @copyright Michael Wallner, <mike@iworks.at>
20 * @license BSD, revised
21 * @package pecl/http
22 * @version $Revision$
23 */
24 class PgLobStream
25 {
26 private $dbh;
27 private $loh;
28 private $lon;
29 private $size = 0;
30
31 public static $loId;
32
33 function stream_open($path, $mode)
34 {
35 $path = trim(parse_url($path, PHP_URL_HOST));
36
37 if ($path) {
38 if ($this->dbh = pg_connect($path)) {
39 if (pg_query($this->dbh, 'BEGIN')) {
40 if (is_resource($this->loh = pg_lo_open($this->dbh, $this->lon = self::$loId, $mode))) {
41 pg_lo_seek($this->loh, 0, PGSQL_SEEK_END);
42 $this->size = (int) pg_lo_tell($this->loh);
43 pg_lo_seek($this->loh, 0, PGSQL_SEEK_SET);
44 return true;
45 }
46 }
47 }
48 }
49 return false;
50 }
51
52 function stream_read($length)
53 {
54 return pg_lo_read($this->loh, $length);
55 }
56
57 function stream_seek($offset, $whence = PGSQL_SEEK_SET)
58 {
59 return pg_lo_seek($this->loh, $offset, $whence);
60 }
61
62 function stream_tell()
63 {
64 return pg_lo_tell($this->loh);
65 }
66
67 function stream_eof()
68 {
69 return pg_lo_tell($this->loh) >= $this->size;
70 }
71
72 function stream_flush()
73 {
74 return true;
75 }
76
77 function stream_stat()
78 {
79 return array('size' => $this->size, 'ino' => $this->lon);
80 }
81
82 function stream_write($data)
83 {
84 return pg_lo_write($this->loh, $data);
85 }
86
87 function stream_close()
88 {
89 if (pg_lo_close($this->loh)) {
90 return pg_query($this->dbh, 'COMMIT');
91 } else {
92 pg_query($this->dbh, 'ROLLBACK');
93 return false;
94 }
95 }
96 }
97
98 stream_register_wrapper('pglob', 'PgLobStream');
99
100 ?>