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