5 * This applies database files from
6 * a) OLD - {MODULE}/DataObjects/XXXX.{dbtype}.sql
8 * b) NEW - {MODULE}/sql/XXX.sql (SHARED or translable)
9 * and {MODULE}/{dbtype}/XXX.sql (SHARED or translable)
14 require_once 'Pman.php';
15 class Pman_Core_UpdateDatabase extends Pman
18 static $cli_desc = "Update SQL - Beta (it will run updateData of all modules)";
20 static $cli_opts = array(
23 'desc' => 'prefix for the password (eg. fred > xxx4fred - prefix is xxx4)',
30 'desc' => 'only run the updateData - do not run import the tables and procedures.',
37 'add-company' => array(
38 'desc' => 'add a company name of the company',
44 'add-company-with-type' => array(
45 'desc' => 'the type of company (default OWNER)',
52 'desc' => 'Initialize the database (pg only supported)',
58 'only-module-sql' => array(
59 'desc' => 'Only run sql import on this modules - eg. Core',
64 'skip-mysql-checks' => array(
65 'desc' => 'Skip mysql checks',
70 'procedures-only' => array(
71 'desc' => 'Only import procedures (not supported by most modules yet) - ignores sql directory',
77 'json-person' => array(
78 'desc' => 'Person JSON file',
85 'desc' => 'Debug the database',
93 var $emailTemplates = array(
94 'ADMIN_PASSWORD_RESET' => array(
95 'bcc_group' => 'Administrators',
96 'test_class' => 'Pman/Core/DataObjects/Core_person',
99 'description' => '99. Management System Password Reset'
104 static function cli_opts()
107 $ret = self::$cli_opts;
108 $ff = HTML_FlexyFramework::get();
110 $mods = $a->modulesList();
111 foreach($mods as $m) {
113 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
114 if (!file_exists($fd)) {
120 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
121 $ar = $cls->getStaticProperties();
122 if (isset($ar['cli_opts'])) {
124 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
132 var $disabled = array();
137 var $local_base_url = false;
139 var $emailTemplates = array(
140 'EVENT_ERRORS_REPORT' => array(
141 'bcc_group' => 'Empty Group',
142 'test_class' => 'Pman/Admin/Report/SendEventErrors',
143 'to_group' => 'Administrators',
145 'description' => '9. System Error Messages',
146 'template_dir' => '/Pman/Admin/templates/mail/'
150 var $required_extensions = array(
158 $ff = HTML_FlexyFramework::get();
159 if (!empty($ff->cli)) {
164 parent::getAuth(); // load company!
165 $au = $this->getAuthUser();
166 if (!$au || $au->company()->comptype != 'OWNER') {
167 $this->jerr("Not authenticated", array('authFailure' => true));
169 $this->authUser = $au;
173 function get($args, $opts=array())
175 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
177 $this->checkSystem();
179 $this->verifyExtensions($this->required_extensions);
181 if (class_exists('PDO_DataObjects_Introspection')) {
182 PDO_DataObject_Introspection::$cache = array();
184 echo "Generate DB cache\n";
185 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
186 echo "Generated DB cache\n";
187 $ff = HTML_FlexyFramework::get();
189 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
190 die("Please setup Pman[local_base_url]\n");
193 $this->local_base_url = $ff->Pman['local_base_url'];
195 if(!empty($ff->Core_Notify)){
196 // require_once 'Pman/Core/NotifySmtpCheck.php';
197 // $x = new Pman_Core_NotifySmtpCheck();
201 $this->disabled = explode(',', $ff->disable);
203 //$this->fixSequencesPgsql();exit;
206 if (!empty($opts['debug'])) {
207 DB_DataObject::DebugLevel($opts['debug']);
210 // ask all the modules to verify the opts
211 echo "Checking options\n";
212 $this->checkOpts($opts);
214 $response = $this->curl("http://localhost{$this->local_base_url}/Core/UpdateDatabase/VerifyExtensions");
215 $json = json_decode($response, true);
217 if(empty($json['data']) || $json['data'] != 'DONE'){
218 echo "\nError: Missing php extensions:\n";
220 echo "Please install the above extensions and restart the apache.\n";
226 echo "Checking Setup Requirements\n";
227 require_once 'Pman/Core/UpdateDatabase/VerifyConfig.php';
228 $sq = new Pman_Core_UpdateDatabase_VerifyConfig();
229 $ret = $sq->get($args, $opts);
232 echo implode("\n", $ret) . "\n";
236 // do this first, so the innodb change + utf8 fixes column max sizes
238 // this will trigger errors about freetext indexes - we will have to remove them manually.?
239 // otherwise we need to do an sql query to find them, then remove them (not really worth it as it only affects really old code..)
241 $this->runExtensions();
244 if (empty($opts['data-only'])) {
247 if (!empty($opts['only-module-sql'])) {
253 $this->runUpdateModulesData();
255 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
256 // make sure we have a good cache...?
258 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
261 $this->runExtensions();
263 $this->clearApacheDataobjectsCache();
265 $this->clearApacheAssetCache();
269 echo "\nUpdate Completed SUCCESS\n";
273 * imports SQL files from all DataObjects directories....
275 * except any matching /migrate/
280 // loop through all the modules, and see if they have a importSQL method?
283 $ff = HTML_Flexyframework::get();
285 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
287 //$this->{'import' . $url['scheme']}($url);
289 $dbtype = $dburl['scheme'];
292 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
297 $ar = $this->modulesList();
302 if(in_array($m, $this->disabled)){
303 echo "module $m is disabled \n";
307 echo "Importing SQL from module $m\n";
308 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
313 // check to see if the class has
317 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
318 if($m != 'Core' && file_exists($file)){
321 $class = "Pman_{$m}_UpdateDatabase";
323 if(method_exists($x, 'importModuleSQL')){
324 echo "Importing SQL from module $m using Module::importModuleSQL\n";
325 $x->opts = $this->opts;
326 $x->rootDir = $this->rootDir;
327 $x->importModuleSQL($dburl);
332 echo "Importing SQL from module $m\n";
335 // if init has been called
337 if (!empty($this->opts['init'])) {
338 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
344 $fd = $this->rootDir. "/Pman/$m/DataObjects";
346 $this->{$dirmethod}($dburl, $fd);
349 // new -- sql directory..
350 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
351 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
352 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
354 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
355 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
359 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
360 if (class_exists('PDO_DataObjects_Introspection')) {
361 PDO_DataObject_Introspection::$cache = array();
363 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
365 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
366 $this->{'fixSequences'. $dbtype}();
379 /** -------------- code to handle importing a whole directory of files into the database ------- **/
382 function importpgsqldir($url, $dir, $disable_triggers = false)
384 $ff = HTML_FlexyFramework::get();
386 require_once 'System.php';
387 $cat = System::which('cat');
388 $psql = System::which('psql');
391 if (!empty($url['pass'])) {
392 putenv("PGPASSWORD=". $url['pass']);
396 ' -h ' . $url['host'] .
397 ' -U' . escapeshellarg($url['user']) .
398 ' ' . basename($url['path']);
401 echo $psql_cmd . "\n" ;
402 echo "scan : $dir\n";
405 $files = array($dir);
410 $files = glob($dir.'/*.sql');
411 uksort($files, 'strcasecmp');
413 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
414 //usort($files, $lsort);
417 foreach($files as $bfn) {
420 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
423 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
424 && !preg_match('#\.pg\.sql#i', basename($bfn))
425 ) { // skip migration scripts at present..
430 if (!preg_match('/pgsql/', basename($dir) )) {
431 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
432 $fn = $this->convertToPG($bfn);
436 // files ending in .pg.sql are native postgres files.. ## depricated
439 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
441 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
457 * mysql - does not support conversions.
461 function importmysqlidir($dburl, $dir) {
462 return $this->importmysqldir($dburl, $dir);
465 function importmysqldir($dburl, $dir)
468 $this->fixMysqlInnodb(); /// run once
470 echo "Import MYSQL :: $dir\n";
473 require_once 'System.php';
474 $cat = System::which('cat');
475 $mysql = System::which('mysql');
479 $mysql_cmd = $mysql .
480 ' -h ' . $dburl['host'] .
481 ' -u' . escapeshellarg($dburl['user']) .
482 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
483 ' ' . basename($dburl['path']);
484 //echo $mysql_cmd . "\n" ;
486 $files = glob($dir.'/*.sql');
487 uksort($files, 'strcasecmp');
490 foreach($files as $fn) {
493 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
496 // .my.sql but not .pg.sql
497 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
498 && !preg_match('#\.my\.sql#i', basename($fn))
499 ) { // skip migration scripts at present..
502 if (!strlen(trim($fn))) {
506 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
508 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
511 $fp = popen($cmd, "r");
514 // send the current file part to the browser
515 $line = trim(fgets($fp, 1024));
520 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
521 echo " ---- {$line}\n"; flush();
525 switch($matches[1]) {
526 case 1017: // cause by renaming table -- old one does not exist..
527 case 1050: // create tables triggers this..
528 case 1060: // Duplicate column name
529 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
530 case 1091: // drop index -- name does not exist.. might hide errors..
532 case 1146: // drop a index on an unknown table.. - happens rarely...
533 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
539 echo " ---- {$line}\n"; flush();
543 // 1051: // Unknown table -- normally drop = add iff exists..
544 echo "File: $fn\n$line\n";
560 * simple regex based convert mysql to pgsql...
562 function convertToPG($src)
564 //echo "Convert $src\n";
566 $fn = $this->tempName('sql');
568 $ret = array( ); // pad it a bit.
569 $extra = array("", "" );
572 foreach(file($src) as $l) {
575 if (!strlen($l) || $l[0] == '#') {
579 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
582 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
583 $tbl = 'shop_' . strtolower($m[1]);
584 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
586 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
587 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
590 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
591 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
592 $extra[] = "create sequence {$tbl}_seq;";
596 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
597 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
600 // enum value -- use the text instead..
602 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
603 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
605 // ignore the alter enum
606 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
610 // UNIQUE KEY .. ignore
611 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
612 $last = array_pop($ret);
613 $ret[] = trim($last, ",");
617 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
621 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
625 // INDEX lookup ..ignore
626 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
627 $last = array_pop($ret);
628 $ret[] = trim($last, ",");
633 // CREATE INDEX ..ignore
634 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
635 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
640 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
642 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
643 $l = preg_replace('# blob#i', ' TEXT', $l);
644 $l = preg_replace('# longtext#i', ' TEXT', $l);
645 $l = preg_replace('# tinyint#i', ' INT', $l);
651 $ret = array_merge($extra,$ret);
652 // echo implode("\n", $ret); exit;
654 file_put_contents($fn, implode("\n", $ret));
660 function checkOpts($opts)
664 foreach($opts as $o=>$v) {
665 if (!preg_match('/^json-/', $o) || empty($v)) {
668 if (!file_exists($v)) {
669 die("File does not exist : OPTION --{$o} = {$v} \n");
673 $modules = array_reverse($this->modulesList());
675 // move 'project' one to the end...
677 foreach ($modules as $module){
678 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
679 if($module == 'Core' || !file_exists($file)){
683 $class = "Pman_{$module}_UpdateDatabase";
685 if(!method_exists($x, 'checkOpts')){
688 $x->checkOpts($opts);
692 static function jsonImportFromArray($opts)
694 foreach($opts as $o=>$v) {
695 if (!preg_match('/^json-/', $o) || empty($v)) {
698 $type = str_replace('_', '-', substr($o,5));
700 $data= json_decode(file_get_contents($v),true);
701 $pg = HTML_FlexyFramework::get()->page;
702 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
712 function runUpdateModulesData()
714 if (class_exists('PDO_DataObjects_Introspection')) {
715 PDO_DataObject_Introspection::$cache = array();
717 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
719 if(!in_array('Core', $this->disabled)){
720 echo "Running jsonImportFromArray\n";
721 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
724 echo "Running updateData on modules\n";
730 $modules = array_reverse($this->modulesList());
732 // move 'project' one to the end...
734 foreach ($modules as $module){
735 if(in_array($module, $this->disabled)){
738 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
739 if($module == 'Core' || !file_exists($file)){
744 $class = "Pman_{$module}_UpdateDatabase";
746 if(!method_exists($x, 'updateData')){
756 function updateDataEnums()
758 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
760 $enum = DB_DataObject::Factory('core_enum');
761 //DB_DAtaObject::debugLevel(1);
766 'name' => 'COMPTYPE',
767 'display_name' => 'Company Types',
768 'is_system_enum' => 1,
772 'display_name' => 'Owner',
773 'seqid' => 999, // last...
774 'is_system_enum' => 1,
781 'name' => 'HtmlEditor.font-family',
782 'display_name' => 'HTML Editor font families',
783 'is_system_enum' => 1,
786 'name' => 'Helvetica,Arial,sans-serif',
787 'display_name' => 'Helvetica',
792 'name' => 'Courier New',
793 'display_name' => 'Courier',
798 'display_name' => 'Tahoma',
802 'name' => 'Times New Roman,serif',
803 'display_name' => 'Times',
808 'display_name' => 'Verdana',
821 function updateDataGroups()
824 $groups = DB_DataObject::factory('core_group');
825 $groups->initGroups();
827 $groups->initDatabase($this,array(
829 'name' => 'bcc-email', // group who are bcc'ed on all requests.
830 'type' => 0, // system
831 'display_name' => 'Standard BCC Group'
834 'name' => 'system-email-from',
835 'type' => 0, // system
836 'display_name' => 'Standard System Email From Group'
839 'name' => 'core-person-signup-bcc',
840 'type' => 0, // system
841 'display_name' => 'Standard Person Signup BCC Group'
844 'name' => 'Empty Group', // use for no bcc emails.
846 'display_name' => 'Standard Empty Group'
853 function updateDataCompanies()
856 // fix comptypes enums..
857 $c = DB_DataObject::Factory('core_company');
859 $c->selectAdd('distinct(comptype) as comptype');
863 comptype != 'undefined'
865 comptype != 'undefine'
869 foreach($c->fetchAll('comptype') as $cts) {
871 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
874 $c = DB_DataObject::Factory('core_enum');
877 //DB_DataObject::debugLevel(1);
879 $c = DB_DataObject::Factory('core_company');
881 UPDATE {$c->tableName()}
883 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
896 function updateDataEmails()
898 foreach ($this->emailTemplates as $k => $mail) {
900 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
910 function initEmails($templateDir, $emails, $mapping = false)
912 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
914 $pg = HTML_FlexyFramework::get()->page;
915 foreach($emails as $name=>$data) {
916 $cm = DB_DataObject::factory('core_email');
917 $update = $cm->get('name', $name);
920 if (empty($cm->bcc_group_id)) {
921 if (empty($data['bcc_group'])) {
922 $this->jerr("missing bcc_group for template $name");
925 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
928 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
931 if (!$g->members('email') && $g->name != 'Empty Group') {
932 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
935 $cm->bcc_group_id = $g->id;
937 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
938 //if (empty($cm->test_class)) {
939 if (empty($data['test_class'])) {
940 $this->jerr("missing test_class for template $name");
943 $cm->test_class = $data['test_class'];
945 if(isset($cm->to_group_id)) {
950 !empty($data['to_group']) &&
951 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
953 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
955 if (empty($gp->id)) {
956 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
959 $cm->to_group_id = $gp->id;
963 isset($data['active']) && !isset($cm->active)
965 $cm->active = $data['active'];
969 * Set description to email.
970 * However we do not update if it is been set.
972 if(empty($cm->description) && !empty($data['description'])){
973 $cm->description = $cm->escape($data['description']);
976 require_once $cm->test_class . '.php';
978 $clsname = str_replace('/','_', $cm->test_class);
980 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
981 $got_it = $method->isStatic();
982 } catch(Exception $e) {
987 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
991 echo "email: {$name} - checked\n";
992 continue; /// we do not import the body content of templates that exist...
999 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1003 'file' => $templateDir. $name .'.html'
1006 if (!empty($data['master'])) {
1007 $opts['master'] = $templateDir . $master .'.html';
1009 require_once 'Pman/Core/Import/Core_email.php';
1010 $x = new Pman_Core_Import_Core_email();
1012 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1014 echo "email: {$name} - CREATED\n";
1019 function updateData()
1022 if (class_exists('PDO_DataObjects_Introspection')) {
1023 PDO_DataObject_Introspection::$cache = array();
1025 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1027 $this->updateDataEnums();
1028 $this->updateDataGroups();
1029 $this->updateDataCompanies();
1031 $this->updateDataEmails();
1033 $c = DB_DataObject::Factory('I18n');
1037 function fixMysqlInnodb()
1040 static $done_check = false;
1046 if (!empty($this->opts['skip-mysql-checks'])) {
1049 // innodb in single files is far more efficient that MYD or one big innodb file.
1050 // first check if database is using this format.
1051 $db = DB_DataObject::factory('core_enum');
1052 $db->query("show variables like 'innodb_file_per_table'");
1054 if ($db->Value == 'OFF') {
1055 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1058 $db = DB_DataObject::factory('core_enum');
1059 $db->query("select version() as version");
1062 if (version_compare($db->version, '5.7', '>=' )) {
1064 $db = DB_DataObject::factory('core_enum');
1065 $db->query("show variables like 'sql_mode'");
1068 $modes = explode(",", $db->Value);
1070 // these are 'new' problems with mysql.
1072 in_array('NO_ZERO_IN_DATE', $modes) ||
1073 in_array('NO_ZERO_DATE', $modes) ||
1074 in_array('STRICT_TRANS_TABLES', $modes) ||
1075 !in_array('ALLOW_INVALID_DATES', $modes)
1077 die("Error: set sql_mode include 'ALLOW_INVALID_DATES', remove 'NO_ZERO_IN_DATE' AND 'STRICT_TRANS_TABLES' AND 'NO_ZERO_DATE' in my.cnf\n\n".
1078 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1083 $done_check = true;;
1094 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1096 function fixSequencesMysql()
1101 function fixSequencesPgsql()
1105 //DB_DataObject::debugLevel(1);
1106 $cs = DB_DataObject::factory('core_enum');
1110 CASE WHEN strpos(seq_name, '.') > 0 THEN
1113 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1116 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1117 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1121 n.nspname AS schema_name,
1122 c.relname AS table_name,
1123 a.attname AS column_name,
1124 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1126 JOIN pg_attribute a ON (c.oid=a.attrelid)
1127 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1128 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1129 WHERE has_schema_privilege(n.oid,'USAGE')
1130 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1131 AND has_table_privilege(c.oid,'SELECT')
1132 AND (NOT a.attisdropped)
1133 AND d.adsrc ~ '^nextval'
1137 CASE WHEN strpos(seq_name, '.') > 0 THEN
1138 substring(seq_name, 1,strpos(seq_name,'.')-1)
1143 GROUP BY seq_name HAVING count(*)=1
1146 while ($cs->fetch()) {
1149 foreach($cmds as $cmd) {
1150 $cs = DB_DataObject::factory('core_enum');
1154 $cs = DB_DataObject::factory('core_enum');
1156 SELECT 'SELECT SETVAL(' ||
1157 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1158 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1164 WHERE S.relkind = 'S'
1166 AND D.refobjid = T.oid
1167 AND D.refobjid = C.attrelid
1168 AND D.refobjsubid = C.attnum
1169 AND NS.oid = T.relnamespace
1173 while ($cs->fetch()) {
1176 foreach($cmds as $cmd) {
1177 $cs = DB_DataObject::factory('core_enum');
1184 var $extensions = array(
1189 function runExtensions()
1192 $ff = HTML_Flexyframework::get();
1194 $dburl = parse_url($ff->database);
1196 $dbtype = $dburl['scheme'];
1198 foreach($this->extensions as $ext) {
1200 $scls = ucfirst($dbtype). $ext;
1201 $cls = __CLASS__ . '_'. $scls;
1202 $fn = implode('/',explode('_', $cls)).'.php';
1203 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1214 function checkSystem($req = false, $pref = false)
1216 // most of these are from File_Convert...
1218 // these are required - and have simple dependancies.
1219 require_once 'System.php';
1220 $req = $req !== false ? $req : array(
1225 'rsvg-convert', //librsvg2-bin
1228 'gifsicle', // used for gif conversions
1233 // these are prefered - but may have complicated depenacies
1234 $pref = $pref !== false ? $pref : array(
1238 'html2text', // not availabe in debian squeeze
1239 'pdftocairo', //poppler-utils - not available in debian squeeze.
1249 foreach($req as $r) {
1250 if (!System::which($r)) {
1256 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1258 foreach($pref as $r) {
1259 if (!System::which($r)) {
1265 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1272 function clearApacheDataobjectsCache()
1274 echo "Clearing Database Cache\n";
1275 // this needs to clear it's own cache along with remote one..
1277 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1278 $response = $this->curl($url);
1280 $json = json_decode($response, true);
1282 if(empty($json['data']) || $json['data'] != 'DONE'){
1283 echo "fetching $url\n";
1284 echo "GOT:" . $response. "\n";
1285 echo "Clear DataObjects Cache failed\n";
1292 function clearApacheAssetCache()
1294 echo "Clearing Asset Cache\n";
1295 $response = $this->curl(
1296 "http://localhost{$this->local_base_url}/Core/Asset",
1297 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1300 $json = json_decode($response, true);
1302 if(empty($json['success']) || !$json['success']) {
1303 echo $response. "\n";
1304 echo "CURL Clear Asset cache failed\n";
1311 function curl($url, $request = array(), $method = 'GET')
1313 if($method == 'GET'){
1314 $request = http_build_query($request);
1315 $url = $url . "?" . $request;
1318 $ch = curl_init($url);
1320 if ($method == 'POST') {
1322 curl_setopt($ch, CURLOPT_POST, 1);
1323 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1326 curl_setopt($ch, CURLOPT_HTTPHEADER,
1327 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1331 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1333 curl_setopt($ch, CURLOPT_HEADER, false);
1334 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1335 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1336 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1338 $response = curl_exec($ch);
1345 static function verifyExtensions($extensions)
1349 foreach ($extensions as $e){
1351 if(empty($e) || extension_loaded($e)) {
1355 $error[] = "Error: Please install php extension: {$e}";
1361 $ff = HTML_FLexyFramework::get();
1363 $ff->page->jerr(implode('\n', $error));