1<?php 2/** 3 * DokuWiki Plugin sqlite (Helper Component) 4 * 5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html 6 * @author Andreas Gohr <gohr@cosmocode.de> 7 */ 8 9// must be run within Dokuwiki 10if (!defined('DOKU_INC')) die(); 11 12if (!defined('DOKU_LF')) define('DOKU_LF', "\n"); 13if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t"); 14if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/'); 15 16if (!defined('DOKU_EXT_SQLITE')) define('DOKU_EXT_SQLITE', 'sqlite'); 17if (!defined('DOKU_EXT_PDO')) define('DOKU_EXT_PDO', 'pdo'); 18 19 20class helper_plugin_sqlite extends DokuWiki_Plugin { 21 var $db = null; 22 var $dbname = ''; 23 var $extension = false; 24 function getInfo() { 25 return confToHash(dirname(__FILE__).'plugin.info.txt'); 26 } 27 28 /** 29 * constructor 30 */ 31 function helper_plugin_sqlite(){ 32 33 if(!$this->extension) 34 { 35 if (!extension_loaded('sqlite')) { 36 $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : ''; 37 if(function_exists('dl')) @dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX); 38 } 39 40 if(function_exists('sqlite_open')){ 41 $this->extension = DOKU_EXT_SQLITE; 42 } 43 } 44 45 if(!$this->extension) 46 { 47 if (!extension_loaded('pdo_sqlite')) { 48 $prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : ''; 49 if(function_exists('dl')) @dl($prefix . 'pdo_sqlite.' . PHP_SHLIB_SUFFIX); 50 } 51 52 if(class_exists('pdo')){ 53 $this->extension = DOKU_EXT_PDO; 54 } 55 } 56 57 if(!$this->extension) 58 { 59 msg('SQLite & PDO SQLite support missing in this PHP install - plugin will not work',-1); 60 } 61 } 62 63 /** 64 * Initializes and opens the database 65 * 66 * Needs to be called right after loading this helper plugin 67 */ 68 function init($dbname,$updatedir){ 69 global $conf; 70 71 // check for already open DB 72 if($this->db){ 73 if($this->dbname == $dbname){ 74 // db already open 75 return true; 76 } 77 // close other db 78 if($this->extension == DOKU_EXT_SQLITE) 79 { 80 sqlite_close($this->db); 81 } 82 else 83 { 84 $this->db->close(); 85 } 86 $this->db = null; 87 $this->dbname = ''; 88 } 89 90 $this->dbname = $dbname; 91 92 $fileextension = '.sqlite'; 93 if($this->extension == DOKU_EXT_PDO) 94 { 95 $fileextension = '.sqlite3'; 96 } 97 98 $this->dbfile = $conf['metadir'].'/'.$dbname.$fileextension; 99 100 $init = (!@file_exists($this->dbfile) || ((int) @filesize($this->dbfile)) < 3); 101 102 if($this->extension == DOKU_EXT_SQLITE) 103 { 104 $error=''; 105 $this->db = sqlite_open($this->dbfile, 0666, $error); 106 if(!$this->db){ 107 msg("SQLite: failed to open SQLite ".$this->dbname." database ($error)",-1); 108 return false; 109 } 110 111 // register our custom aggregate function 112 sqlite_create_aggregate($this->db,'group_concat', 113 array($this,'_sqlite_group_concat_step'), 114 array($this,'_sqlite_group_concat_finalize'), 2); 115 } 116 else 117 { 118 $dsn = 'sqlite:'.$this->dbfile; 119 120 try { 121 $this->db = new PDO($dsn); 122 } catch (PDOException $e) { 123 msg("SQLite: failed to open SQLite ".$this->dbname." database (".$e->getMessage().")",-1); 124 return false; 125 } 126 $this->db->sqliteCreateAggregate('group_concat', 127 array($this,'_pdo_group_concat_step'), 128 array($this,'_pdo_group_concat_finalize')); 129 } 130 131 $this->_updatedb($init,$updatedir); 132 return true; 133 } 134 135 /** 136 * Return the current Database Version 137 */ 138 function _currentDBversion(){ 139 $sql = "SELECT val FROM opts WHERE opt = 'dbversion';"; 140 $res = $this->query($sql); 141 if(!$res) return false; 142 $row = $this->res2row($res,0); 143 return (int) $row['val']; 144 } 145 /** 146 * Update the database if needed 147 * 148 * @param bool $init - true if this is a new database to initialize 149 * @param string $updatedir - Database update infos 150 */ 151 function _updatedb($init,$updatedir){ 152 if($init){ 153 $current = 0; 154 }else{ 155 $current = $this->_currentDBversion(); 156 if(!$current){ 157 msg('SQLite: no DB version found. '.$this->dbname.' DB probably broken.',-1); 158 return false; 159 } 160 } 161 162 // in case of init, add versioning table 163 if($init){ 164 if(!$this->_runupdatefile(dirname(__FILE__).'/db.sql',0)){ 165 if($this->extension == DOKU_EXT_SQLITE) 166 { 167 msg('SQLite: '.$this->dbname.' database upgrade failed for version '.$i, -1); 168 } 169 return false; 170 } 171 } 172 173 $latest = (int) trim(io_readFile($updatedir.'/latest.version')); 174 175 // all up to date? 176 if($current >= $latest) return true; 177 for($i=$current+1; $i<=$latest; $i++){ 178 $file = sprintf($updatedir.'/update%04d.sql',$i); 179 if(file_exists($file)){ 180 if(!$this->_runupdatefile($file,$i)){ 181 msg('SQLite: '.$this->dbname.' database upgrade failed for version '.$i, -1); 182 183 184 return false; 185 } 186 } 187 } 188 return true; 189 } 190 191 /** 192 * Updates the database structure using the given file to 193 * the given version. 194 */ 195 function _runupdatefile($file,$version){ 196 $sql = io_readFile($file,false); 197 198 $sql = explode(";",$sql); 199 array_unshift($sql,'BEGIN TRANSACTION'); 200 array_push($sql,"INSERT OR REPLACE INTO opts (val,opt) VALUES ($version,'dbversion')"); 201 array_push($sql,"COMMIT TRANSACTION"); 202 203 foreach($sql as $s){ 204 $s = preg_replace('!^\s*--.*$!m', '', $s); 205 $s = trim($s); 206 if(!$s) continue; 207 208 209 $res = $this->query("$s;"); 210 if ($res === false) { 211 if($this->extension == DOKU_EXT_SQLITE) 212 { 213 sqlite_query($this->db, 'ROLLBACK TRANSACTION'); 214 return false; 215 } 216 } 217 } 218 219 return ($version == $this->_currentDBversion()); 220 } 221 222 /** 223 * Emulate ALTER TABLE 224 * 225 * The ALTER TABLE syntax is parsed and then emulated using a 226 * temporary table 227 * 228 * @author <jon@jenseng.com> 229 * @link http://code.jenseng.com/db/ 230 * @author Andreas Gohr <gohr@cosmocode.de> 231 */ 232 function _altertable($table,$alterdefs){ 233 234 // load original table definition SQL 235 $result = $this->query("SELECT sql,name,type 236 FROM sqlite_master 237 WHERE tbl_name = '$table' 238 AND type = 'table'"); 239 240 if(($result === false) || ($this->extension == DOKU_EXT_SQLITE && sqlite_num_rows($result)<=0)){ 241 msg("ALTER TABLE failed, no such table '".hsc($table)."'",-1); 242 return false; 243 } 244 245 if($this->extension == DOKU_EXT_SQLITE ) 246 { 247 $row = sqlite_fetch_array($result); 248 } 249 else 250 { 251 $row = $result->fetch(PDO::FETCH_ASSOC); 252 } 253 254 if($row === false){ 255 msg("ALTER TABLE failed, table '".hsc($table)."' had no master data",-1); 256 return false; 257 } 258 259 260 // prepare temporary table SQL 261 $tmpname = 't'.time(); 262 $origsql = trim(preg_replace("/[\s]+/"," ", 263 str_replace(",",", ", 264 preg_replace('/\)$/',' )', 265 preg_replace("/[\(]/","( ",$row['sql'],1))))); 266 $createtemptableSQL = 'CREATE TEMPORARY '.substr(trim(preg_replace("'".$table."'",$tmpname,$origsql,1)),6); 267 $createindexsql = array(); 268 269 // load indexes to reapply later 270 $result = $this->query("SELECT sql,name,type 271 FROM sqlite_master 272 WHERE tbl_name = '$table' 273 AND type = 'index'"); 274 if(!$result){ 275 $indexes = array(); 276 }else{ 277 $indexes = $this->res2arr($result); 278 } 279 280 281 $i = 0; 282 $defs = preg_split("/[,]+/",$alterdefs,-1,PREG_SPLIT_NO_EMPTY); 283 $prevword = $table; 284 $oldcols = preg_split("/[,]+/",substr(trim($createtemptableSQL),strpos(trim($createtemptableSQL),'(')+1),-1,PREG_SPLIT_NO_EMPTY); 285 $newcols = array(); 286 287 for($i=0;$i<sizeof($oldcols);$i++){ 288 $colparts = preg_split("/[\s]+/",$oldcols[$i],-1,PREG_SPLIT_NO_EMPTY); 289 $oldcols[$i] = $colparts[0]; 290 $newcols[$colparts[0]] = $colparts[0]; 291 } 292 $newcolumns = ''; 293 $oldcolumns = ''; 294 reset($newcols); 295 while(list($key,$val) = each($newcols)){ 296 $newcolumns .= ($newcolumns?', ':'').$val; 297 $oldcolumns .= ($oldcolumns?', ':'').$key; 298 } 299 $copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table; 300 $dropoldsql = 'DROP TABLE '.$table; 301 $createtesttableSQL = $createtemptableSQL; 302 303 foreach($defs as $def){ 304 $defparts = preg_split("/[\s]+/",$def,-1,PREG_SPLIT_NO_EMPTY); 305 $action = strtolower($defparts[0]); 306 switch($action){ 307 case 'add': 308 if(sizeof($defparts) < 2){ 309 msg('ALTER TABLE: not enough arguments for ADD statement',-1); 310 return false; 311 } 312 $createtesttableSQL = substr($createtesttableSQL,0,strlen($createtesttableSQL)-1).','; 313 for($i=1;$i<sizeof($defparts);$i++) 314 $createtesttableSQL.=' '.$defparts[$i]; 315 $createtesttableSQL.=')'; 316 break; 317 318 case 'change': 319 if(sizeof($defparts) <= 3){ 320 msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').($defparts[2]?' '.$defparts[2]:'').'": syntax error',-1); 321 return false; 322 } 323 324 if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){ 325 if($newcols[$defparts[1]] != $defparts[1]){ 326 msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1); 327 return false; 328 } 329 $newcols[$defparts[1]] = $defparts[2]; 330 $nextcommapos = strpos($createtesttableSQL,',',$severpos); 331 $insertval = ''; 332 for($i=2;$i<sizeof($defparts);$i++) 333 $insertval.=' '.$defparts[$i]; 334 if($nextcommapos) 335 $createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos); 336 else 337 $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')'; 338 } else { 339 msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1); 340 return false; 341 } 342 break; 343 case 'drop': 344 if(sizeof($defparts) < 2){ 345 msg('ALTER TABLE: near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error',-1); 346 return false; 347 } 348 if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){ 349 $nextcommapos = strpos($createtesttableSQL,',',$severpos); 350 if($nextcommapos) 351 $createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1); 352 else 353 $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')'; 354 unset($newcols[$defparts[1]]); 355 }else{ 356 msg('ALTER TABLE: unknown column "'.$defparts[1].'" in "'.$table.'"',-1); 357 return false; 358 } 359 break; 360 default: 361 msg('ALTER TABLE: near "'.$prevword.'": syntax error',-1); 362 return false; 363 } 364 $prevword = $defparts[sizeof($defparts)-1]; 365 } 366 367 // this block of code generates a test table simply to verify that the 368 // columns specifed are valid in an sql statement 369 // this ensures that no reserved words are used as columns, for example 370 $res = $this->query($createtesttableSQL); 371 if($res === false) return false; 372 373 $droptempsql = 'DROP TABLE '.$tmpname; 374 $res = $this->query($droptempsql); 375 if($res === false) return false; 376 377 378 $createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'",$table,$createtesttableSQL,1)),17); 379 $newcolumns = ''; 380 $oldcolumns = ''; 381 reset($newcols); 382 while(list($key,$val) = each($newcols)){ 383 $newcolumns .= ($newcolumns?', ':'').$val; 384 $oldcolumns .= ($oldcolumns?', ':'').$key; 385 } 386 387 $copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname; 388 389 $res = $this->query($createtemptableSQL); //create temp table 390 if($res === false) return false; 391 $res = $this->query($copytotempsql); //copy to table 392 if($res === false) return false; 393 $res = $this->query($dropoldsql); //drop old table 394 if($res === false) return false; 395 396 $res = $this->query($createnewtableSQL); //recreate original table 397 if($res === false) return false; 398 $res = $this->query($copytonewsql); //copy back to original table 399 if($res === false) return false; 400 401 foreach($indexes as $index){ // readd indexes 402 $res = $this->query($index['sql']); 403 if($res === false) return false; 404 } 405 406 $res = $this->query($droptempsql); //drop temp table 407 if($res === false) return false; 408 409 return $res; // return a valid resource 410 } 411 412 /** 413 * Execute a query with the given parameters. 414 * 415 * Takes care of escaping 416 * 417 * @param string $sql - the statement 418 * @param arguments... 419 */ 420 function query(){ 421 if(!$this->db) return false; 422 423 // get function arguments 424 $args = func_get_args(); 425 $sql = trim(array_shift($args)); 426 $sql = rtrim($sql,';'); 427 428 if(!$sql){ 429 msg('No SQL statement given',-1); 430 return false; 431 } 432 433 if(is_array($args[0])) $args = $args[0]; 434 $argc = count($args); 435 436 // check number of arguments 437 if($argc < substr_count($sql,'?')){ 438 msg('Not enough arguments passed for statement. '. 439 'Expected '.substr_count($sql,'?').' got '. 440 $argc.' - '.hsc($sql),-1); 441 return false; 442 } 443 444 // explode at wildcard, then join again 445 $parts = explode('?',$sql,$argc+1); 446 $args = array_map(array($this,'quote_string'),$args); 447 $sql = ''; 448 449 while( ($part = array_shift($parts)) !== null ){ 450 $sql .= $part; 451 $sql .= array_shift($args); 452 } 453 454 // intercept ALTER TABLE statements 455 $match = null; 456 if(preg_match('/^ALTER\s+TABLE\s+([\w\.]+)\s+(.*)/i',$sql,$match)){ 457 return $this->_altertable($match[1],$match[2]); 458 } 459 460 // execute query 461 $err = ''; 462 if($this->extension == DOKU_EXT_SQLITE ) 463 { 464 $res = @sqlite_query($this->db,$sql,SQLITE_ASSOC,$err); 465 if($err){ 466 msg($err.':<br /><pre>'.hsc($sql).'</pre>',-1); 467 return false; 468 }elseif(!$res){ 469 msg(sqlite_error_string(sqlite_last_error($this->db)). 470 ':<br /><pre>'.hsc($sql).'</pre>',-1); 471 return false; 472 } 473 } 474 else 475 { 476 $result = false; 477 478 $res = $this->db->query($sql); 479 480 if(!$res){ 481 $err = $this->db->errorInfo(); 482 msg($err[2].':<br /><pre>'.hsc($sql).'</pre>',-1); 483 return false; 484 } 485 } 486 return $res; 487 } 488 489 /** 490 * Returns a complete result set as array 491 */ 492 function res2arr($res){ 493 $data = array(); 494 if($this->extension == DOKU_EXT_SQLITE ) 495 { 496 if(!sqlite_num_rows($res)) return $data; 497 sqlite_rewind($res); 498 while(($row = sqlite_fetch_array($res)) !== false){ 499 $data[] = $row; 500 } 501 } 502 else 503 { 504 $data = $res->fetchAll(PDO::FETCH_ASSOC); 505 if(!count(data)) 506 { 507 return false; 508 } 509 } 510 return $data; 511 } 512 513 /** 514 * Return the wanted row from a given result set as 515 * associative array 516 */ 517 function res2row($res,$rownum=0){ 518 if($this->extension == DOKU_EXT_SQLITE ) 519 { 520 if(!@sqlite_seek($res,$rownum)){ 521 return false; 522 } 523 return sqlite_fetch_array($res); 524 } 525 else 526 { 527 //very dirty replication of the same functionality (really must look at cursors) 528 $data = array(); 529 //do we need to rewind? 530 $data = $res->fetchAll(PDO::FETCH_ASSOC); 531 if(!count(data)) 532 { 533 return false; 534 } 535 536 if(!isset($data[$rownum])) 537 { 538 return false; 539 } 540 else 541 { 542 return $data[$rownum]; 543 } 544 } 545 } 546 547 /** 548 * Return the first value from the first row. 549 */ 550 function res2single($res) 551 { 552 if($this->extension == DOKU_EXT_SQLITE ) 553 { 554 return sqlite_fetch_single($res); 555 } 556 else 557 { 558 $data = $res->fetchAll(PDO::FETCH_NUM); 559 if(!count(data)) 560 { 561 return false; 562 } 563 return $data[0][0]; 564 } 565 } 566 567 /** 568 * Join the given values and quote them for SQL insertion 569 */ 570 function quote_and_join($vals,$sep=',') { 571 $vals = array_map(array('helper_plugin_sqlite','quote_string'),$vals); 572 return join($sep,$vals); 573 } 574 575 /** 576 * Run sqlite_escape_string() on the given string and surround it 577 * with quotes 578 */ 579 function quote_string($string){ 580 if($this->extension == DOKU_EXT_SQLITE ) 581 { 582 return "'".sqlite_escape_string($string)."'"; 583 } 584 else 585 { 586 return $this->db->quote($string); 587 } 588 } 589 590 591 /** 592 * Escape string for sql 593 */ 594 function escape_string($str) 595 { 596 if($this->extension == DOKU_EXT_SQLITE ) 597 { 598 return sqlite_escape_string($str); 599 } 600 else 601 { 602 return trim($this->db->quote($str), "'"); 603 } 604 } 605 606 607 608 /** 609 * Aggregation function for SQLite 610 * 611 * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine 612 */ 613 function _sqlite_group_concat_step(&$context, $string, $separator = ',') { 614 $context['sep'] = $separator; 615 $context['data'][] = $string; 616 } 617 618 /** 619 * Aggregation function for SQLite 620 * 621 * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine 622 */ 623 function _sqlite_group_concat_finalize(&$context) { 624 $context['data'] = array_unique($context['data']); 625 return join($context['sep'],$context['data']); 626 } 627 628 629 /** 630 * Aggregation function for SQLite via PDO 631 * 632 * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine 633 */ 634 function _pdo_group_concat_step(&$context, $rownumber, $string, $separator = ',') { 635 if(is_null($context)) 636 { 637 $context = array( 638 'sep' => $separator, 639 'data' => array() 640 ); 641 } 642 643 $context['data'][] = $string; 644 return $context; 645 } 646 647 /** 648 * Aggregation function for SQLite via PDO 649 * 650 * @link http://devzone.zend.com/article/863-SQLite-Lean-Mean-DB-Machine 651 */ 652 function _pdo_group_concat_finalize(&$context, $rownumber) 653 { 654 if(!is_array($context)) 655 { 656 return null; 657 } 658 $context['data'] = array_unique($context['data']); 659 return join($context['sep'],$context['data']); 660 } 661 662 /** 663 * Keep separate instances for every call to keep database connections 664 */ 665 function isSingleton() { 666 return false; 667 } 668 669 /** 670 * fetch the next row as zero indexed array 671 */ 672 function res_fetch_array($res) 673 { 674 if($this->extension == DOKU_EXT_SQLITE ) 675 { 676 return sqlite_fetch_array($res, SQLITE_NUM); 677 } 678 else 679 { 680 return $res->fetch(PDO::FETCH_NUM); 681 } 682 } 683 684 685 /** 686 * fetch the next row as assocative array 687 */ 688 function res_fetch_assoc($res) 689 { 690 if($this->extension == DOKU_EXT_SQLITE ) 691 { 692 return sqlite_fetch_array($res, SQLITE_ASSOC); 693 } 694 else 695 { 696 return $res->fetch(PDO::FETCH_ASSOC); 697 } 698 } 699 700 701 /** 702 * Count the number of records in rsult 703 */ 704 function res2count($res) { 705 if($this->extension == DOKU_EXT_SQLITE ) 706 { 707 return sqlite_num_rows($res); 708 } 709 else 710 { 711 $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i'; 712 if (preg_match($regex, $res->queryString, $output) > 0) { 713 $stmt = $this->db->query("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM); 714 715 return $stmt->fetchColumn(); 716 } 717 718 return false; 719 } 720 } 721 722 723 /** 724 * Count the number of records changed last time 725 */ 726 function countChanges($db, $res) 727 { 728 if($this->extension == DOKU_EXT_SQLITE ) 729 { 730 return sqlite_changes($db); 731 } 732 else 733 { 734 return $res->rowCount(); 735 } 736 } 737} 738 739// vim:ts=4:sw=4:et:enc=utf-8: 740