Bug: Live query chart always zero
[phpmyadmin/tyronm.git] / libraries / blobstreaming.lib.php
blobd3827f9a2da585bd284c807d01952396680f3b6a
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * @package BLOBStreaming
5 */
7 /**
8 * Initializes PBMS database
10 * @return bool
12 function initPBMSDatabase()
14 $query = "create database IF NOT EXISTS pbms;"; // If no other choice then try this.
16 * The user may not have privileges to create the 'pbms' database
17 * so if it doesn't exist then we perform a select on a pbms system
18 * table in an already existing database which will cause the PBMS
19 * daemon to create the 'pbms' database.
21 $db_array = PMA_DBI_fetch_result('SHOW DATABASES;');
22 if (! empty($db_array)) {
23 $target = "";
24 foreach ($db_array as $current_db) {
25 if ($current_db == 'pbms') {
26 return true;
28 if ($target == "") {
29 if (($current_db != 'pbxt') && ($current_db != 'mysql') && ($current_db != 'information_schema')) {
30 $target = $current_db;
35 if ($target != "") {
36 $query = "select * from $target.pbms_metadata_header"; // If it exists this table will not contain much
40 $result = PMA_DBI_query($query );
41 if (! $result) {
42 return false;
44 return true;
47 /**
48 * checks whether the necessary plugins for BLOBStreaming exist
50 * @access public
51 * @return boolean
53 function checkBLOBStreamingPlugins()
55 if (PMA_cacheGet('skip_blobstreaming', true) === true) {
56 return false;
59 // load PMA configuration
60 $PMA_Config = $GLOBALS['PMA_Config'];
62 // return if unable to load PMA configuration
63 if (empty($PMA_Config)) {
64 return false;
67 // If we don't know that we can skip blobstreaming, we continue
68 // verifications; anyway, in case we won't skip blobstreaming,
69 // we still need to set some variables in non-persistent settings,
70 // which is done via $PMA_Config->set().
72 /** Retrieve current server configuration;
73 * at this point, $PMA_Config->get('Servers') contains the server parameters
74 * as explicitely defined in config.inc.php, so it cannot be used; it's
75 * better to use $GLOBALS['cfg']['Server'] which contains the explicit
76 * parameters merged with the default ones
79 $serverCfg = $GLOBALS['cfg']['Server'];
81 // return if unable to retrieve current server configuration
82 if (! $serverCfg) {
83 return false;
86 // if PHP extension in use is 'mysql', specify element 'PersistentConnections'
87 if ($serverCfg['extension'] == "mysql") {
88 $serverCfg['PersistentConnections'] = $PMA_Config->settings['PersistentConnections'];
91 // if connection type is TCP, unload socket variable
92 if (strtolower($serverCfg['connect_type']) == "tcp") {
93 $serverCfg['socket'] = "";
96 $has_blobstreaming = false;
97 if (PMA_MYSQL_INT_VERSION >= 50109) {
99 // Retrieve MySQL plugins
100 $existing_plugins = PMA_DBI_fetch_result('SHOW PLUGINS');
102 foreach ($existing_plugins as $one_existing_plugin) {
103 // check if required plugins exist
104 if ( strtolower($one_existing_plugin['Library']) == 'libpbms.so'
105 && $one_existing_plugin['Status'] == "ACTIVE") {
106 $has_blobstreaming = true;
107 break;
110 unset($existing_plugins, $one_existing_plugin);
113 // set variable indicating BS plugin existence
114 $PMA_Config->set('BLOBSTREAMING_PLUGINS_EXIST', $has_blobstreaming);
116 if ($has_blobstreaming) {
117 $bs_variables = PMA_BS_GetVariables();
119 // if no BS variables exist, set plugin existence to false and return
120 if (count($bs_variables) <= 0) {
121 $PMA_Config->set('BLOBSTREAMING_PLUGINS_EXIST', false);
122 PMA_cacheSet('skip_blobstreaming', true, true);
123 return false;
124 } // end if (count($bs_variables) <= 0)
126 // Check that the required pbms functions exist:
127 if ((function_exists("pbms_connect") == false) ||
128 (function_exists("pbms_error") == false) ||
129 (function_exists("pbms_close") == false) ||
130 (function_exists("pbms_is_blob_reference") == false) ||
131 (function_exists("pbms_get_info") == false) ||
132 (function_exists("pbms_get_metadata_value") == false) ||
133 (function_exists("pbms_add_metadata") == false) ||
134 (function_exists("pbms_read_stream") == false)) {
136 // We should probably notify the user that they need to install
137 // the pbms client lib and PHP extension to make use of blob streaming.
138 $PMA_Config->set('BLOBSTREAMING_PLUGINS_EXIST', false);
139 PMA_cacheSet('skip_blobstreaming', true, true);
140 return false;
143 if (function_exists("pbms_connection_pool_size")) {
144 if ( isset($PMA_Config->settings['pbms_connection_pool_size'])) {
145 $pool_size = $PMA_Config->settings['pbms_connection_pool_size'];
146 if ($pool_size == "") {
147 $pool_size = 1;
149 } else {
150 $pool_size = 1;
152 pbms_connection_pool_size($pool_size);
155 // get BS server port
156 $BS_PORT = $bs_variables['pbms_port'];
158 // if no BS server port or 'pbms' database exists, set plugin existance to false and return
159 if ((! $BS_PORT) || (! initPBMSDatabase())) {
160 $PMA_Config->set('BLOBSTREAMING_PLUGINS_EXIST', false);
161 PMA_cacheSet('skip_blobstreaming', true, true);
162 return false;
163 } // end if (!$BS_PORT)
165 // Ping PBMS: the database doesn't need to exist for this to work.
166 if (pbms_connect($serverCfg['host'], $BS_PORT, "anydb") == false) {
167 $PMA_Config->set('BLOBSTREAMING_PLUGINS_EXIST', false);
168 PMA_cacheSet('skip_blobstreaming', true, true);
169 return false;
171 pbms_close();
173 if (function_exists("pbms_pconnect")) {
174 $PMA_Config->set('PBMS_PCONNECT_EXISTS', true);
175 } else {
176 $PMA_Config->set('PBMS_PCONNECT_EXISTS', false);
179 // add selected BS, CURL and fileinfo library variables to PMA configuration
180 $PMA_Config->set('BLOBSTREAMING_PORT', $BS_PORT);
181 $PMA_Config->set('BLOBSTREAMING_HOST', $serverCfg['host']);
182 $PMA_Config->set('BLOBSTREAMING_SERVER', $serverCfg['host'] . ':' . $BS_PORT);
183 $PMA_Config->set('PHP_PBMS_EXISTS', false);
184 $PMA_Config->set('FILEINFO_EXISTS', false);
186 // check if PECL's fileinfo library exist
187 $finfo = null;
189 if (function_exists("finfo_open")) {
190 $finfo = finfo_open(FILEINFO_MIME);
193 // fileinfo library exists, set necessary variable and close resource
194 if (! empty($finfo)) {
195 $PMA_Config->set('FILEINFO_EXISTS', true);
196 finfo_close($finfo);
197 } // end if (!empty($finfo))
199 } else {
200 PMA_cacheSet('skip_blobstreaming', true, true);
201 return false;
202 } // end if ($has_blobstreaming)
204 return true;
208 * returns a list of BLOBStreaming variables used by MySQL
210 * @access public
211 * @return array - list of BLOBStreaming variables
213 function PMA_BS_GetVariables()
215 // load PMA configuration
216 $PMA_Config = $GLOBALS['PMA_Config'];
218 // return if unable to load PMA configuration
219 if (empty($PMA_Config))
220 return NULL;
222 // run query to retrieve BS variables
223 $query = "SHOW VARIABLES LIKE '%pbms%'";
224 $result = PMA_DBI_query($query);
226 $BS_Variables = array();
228 // while there are records to retrieve
229 while ($data = @PMA_DBI_fetch_assoc($result))
230 $BS_Variables[$data['Variable_name']] = $data['Value'];
232 // return BS variables
233 return $BS_Variables;
237 * Retrieves and shows PBMS error.
239 * @return nothing
241 function PMA_BS_ReportPBMSError($msg)
243 $tmp_err = pbms_error();
244 PMA_showMessage(__('PBMS error') . " $msg $tmp_err");
248 * Tries to connect to PBMS server.
250 * @param string $db_name Database name
251 * @param bool $quiet Whether to report errors
253 * @return bool Connection status.
255 function PMA_do_connect($db_name, $quiet)
257 $PMA_Config = $GLOBALS['PMA_Config'];
259 // return if unable to load PMA configuration
260 if (empty($PMA_Config)) {
261 return false;
264 // generate bs reference link
265 $pbms_host = $PMA_Config->get('BLOBSTREAMING_HOST');
266 $pbms_port = $PMA_Config->get('BLOBSTREAMING_PORT');
268 if ($PMA_Config->get('PBMS_PCONNECT_EXISTS')) {
269 // Open a persistent connection.
270 $ok = pbms_pconnect($pbms_host, $pbms_port, $db_name);
271 } else {
272 $ok = pbms_connect($pbms_host, $pbms_port, $db_name);
275 if ($ok == false) {
276 if ($quiet == false) {
277 PMA_BS_ReportPBMSError(__('PBMS connection failed:') . " pbms_connect($pbms_host, $pbms_port, $db_name)");
279 return false;
281 return true;
285 * Disconnects from PBMS server.
287 * @return nothing
289 function PMA_do_disconnect()
291 pbms_close();
295 * Checks whether the BLOB reference looks valid
297 * @param string $bs_reference BLOB reference
298 * @param string $db_name Database name
300 * @return bool True on success.
302 function PMA_BS_IsPBMSReference($bs_reference, $db_name)
304 if (PMA_cacheGet('skip_blobstreaming', true)) {
305 return false;
308 // You do not really need a connection to the PBMS Daemon
309 // to check if a reference looks valid but unfortunalty the API
310 // requires one at this point so until the API is updated
311 // we need to epen one here. If you use pool connections this
312 // will not be a performance problem.
313 if (PMA_do_connect($db_name, false) == false) {
314 return false;
317 $ok = pbms_is_blob_reference($bs_reference);
318 return $ok ;
321 //------------
322 function PMA_BS_CreateReferenceLink($bs_reference, $db_name)
324 if (PMA_do_connect($db_name, false) == false) {
325 return __('Error');
328 if (pbms_get_info(trim($bs_reference)) == false) {
329 PMA_BS_ReportPBMSError(__('PBMS get BLOB info failed:') . " pbms_get_info($bs_reference)");
330 PMA_do_disconnect();
331 return __('Error');
334 $content_type = pbms_get_metadata_value("Content-Type");
335 if ($content_type == false) {
336 $br = trim($bs_reference);
337 PMA_BS_ReportPBMSError("PMA_BS_CreateReferenceLink('$br', '$db_name'): " . __('PBMS get BLOB Content-Type failed'));
340 PMA_do_disconnect();
342 if (! $content_type) {
343 $content_type = "image/jpeg";
346 $bs_url = PMA_BS_getURL($bs_reference);
347 if (empty($bs_url)) {
348 PMA_BS_ReportPBMSError(__('No blob streaming server configured!'));
349 return 'Error';
352 $output = $content_type;
354 // specify custom HTML for various content types
355 switch ($content_type) {
356 // no content specified
357 case NULL:
358 $output = "NULL";
359 break;
360 // image content
361 case 'image/jpeg':
362 case 'image/png':
363 $output .= ' (<a href="' . $bs_url . '" target="new">' . __('View image') . '</a>)';
364 break;
365 // audio content
366 case 'audio/mpeg':
367 $output .= ' (<a href="#" onclick="popupBSMedia(\'' . PMA_generate_common_url() . '\',\'' . urlencode($bs_reference) . '\', \'' . urlencode($content_type) . '\',' . ($is_custom_type ? 1 : 0) . ', 640, 120)">' . __('Play audio'). '</a>)';
368 break;
369 // video content
370 case 'application/x-flash-video':
371 case 'video/mpeg':
372 $output .= ' (<a href="#" onclick="popupBSMedia(\'' . PMA_generate_common_url() . '\',\'' . urlencode($bs_reference) . '\', \'' . urlencode($content_type) . '\',' . ($is_custom_type ? 1 : 0) . ', 640, 480)">' . __('View video') . '</a>)';
373 break;
374 // unsupported content. specify download
375 default:
376 $output .= ' (<a href="' . $bs_url . '" target="new">' . __('Download file'). '</a>)';
379 return $output;
383 * In the future there may be server variables to turn on/off PBMS
384 * BLOB streaming on a per table or database basis. So in anticipation of this
385 * PMA_BS_IsTablePBMSEnabled() passes in the table and database name even though
386 * they are not currently needed.
388 * @param string $db_name
389 * @param string $tbl_name
390 * @param string $tbl_type
391 * @return bool
393 function PMA_BS_IsTablePBMSEnabled($db_name, $tbl_name, $tbl_type)
395 if (PMA_cacheGet('skip_blobstreaming', true)) {
396 return false;
399 if ((isset($tbl_type) == false) || (strlen($tbl_type) == 0)) {
400 return false;
403 // load PMA configuration
404 $PMA_Config = $GLOBALS['PMA_Config'];
406 // return if unable to load PMA configuration
407 if (empty($PMA_Config)) {
408 return false;
411 if (! $PMA_Config->get('BLOBSTREAMING_PLUGINS_EXIST')) {
412 return false;
415 // This information should be cached rather than selecting it each time.
416 //$query = "SELECT count(*) FROM information_schema.TABLES T, pbms.pbms_enabled E where T.table_schema = ". PMA_backquote($db_name) . " and T.table_name = ". PMA_backquote($tbl_name) . " and T.engine = E.name";
417 $query = "SELECT count(*) FROM pbms.pbms_enabled E where E.name = '" . PMA_sqlAddSlashes($tbl_type) . "'";
418 $result = PMA_DBI_query($query);
420 $data = PMA_DBI_fetch_row($result);
421 if ($data[0] == 1) {
422 return true;
425 return false;
428 //------------
429 function PMA_BS_UpLoadFile($db_name, $tbl_name, $file_type, $file_name)
432 if (PMA_cacheGet('skip_blobstreaming', true)) {
433 return false;
436 if (PMA_do_connect($db_name, false) == false) {
437 return false;
440 $fh = fopen($file_name, 'r');
441 if (! $fh) {
442 PMA_do_disconnect();
443 PMA_showMessage(sprintf(__('Could not open file: %s'), $file_name));
444 return false;
447 pbms_add_metadata("Content-Type", $file_type);
449 $pbms_blob_url = pbms_read_stream($fh, filesize($file_name), $tbl_name);
450 if (! $pbms_blob_url) {
451 PMA_BS_ReportPBMSError("pbms_read_stream()");
454 fclose($fh);
455 PMA_do_disconnect();
456 return $pbms_blob_url;
459 //------------
460 function PMA_BS_SetContentType($db_name, $bsTable, $blobReference, $contentType)
462 if (PMA_cacheGet('skip_blobstreaming', true)) {
463 return false;
466 // This is a really ugly way to do this but currently there is nothing better.
467 // In a future version of PBMS the system tables will be redesigned to make this
468 // more efficient.
469 $query = "SELECT Repository_id, Repo_blob_offset FROM pbms_reference WHERE Blob_url='" . PMA_sqlAddSlashes($blobReference) . "'";
470 //error_log(" PMA_BS_SetContentType: $query\n", 3, "/tmp/mylog");
471 $result = PMA_DBI_query($query);
472 //error_log(" $query\n", 3, "/tmp/mylog");
474 // if record exists
475 if ($data = PMA_DBI_fetch_assoc($result)) {
476 $where = "WHERE Repository_id=" . $data['Repository_id'] . " AND Repo_blob_offset=" . $data['Repo_blob_offset'] ;
477 $query = "SELECT name from pbms_metadata $where";
478 $result = PMA_DBI_query($query);
480 if (PMA_DBI_num_rows($result) == 0) {
481 $query = "INSERT into pbms_metadata Values( ". $data['Repository_id'] . ", " . $data['Repo_blob_offset'] . ", 'Content_type', '" . PMA_sqlAddSlashes($contentType) . "')";
482 } else {
483 $query = "UPDATE pbms_metadata SET name = 'Content_type', Value = '" . PMA_sqlAddSlashes($contentType) . "' $where";
485 //error_log("$query\n", 3, "/tmp/mylog");
486 PMA_DBI_query($query);
487 } else {
488 return false;
490 return true;
493 //------------
494 function PMA_BS_IsHiddenTable($table)
496 if ($table === 'pbms_repository' || $table === 'pbms_reference' || $table === 'pbms_metadata'
497 || $table === 'pbms_metadata_header' || $table === 'pbms_dump') {
498 return true;
500 return false;
503 //------------
504 function PMA_BS_getURL($reference)
506 // load PMA configuration
507 $PMA_Config = $GLOBALS['PMA_Config'];
508 if (empty($PMA_Config)) {
509 return false;
512 // retrieve BS server variables from PMA configuration
513 $bs_server = $PMA_Config->get('BLOBSTREAMING_SERVER');
514 if (empty($bs_server)) {
515 return false;
518 $bs_url = PMA_linkURL('http://' . $bs_server . '/' . rtrim($reference));
519 return $bs_url;