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