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();
268 $core_group = DB_DataObject::factory('core_group');
269 $core_group->get('name', 'Administrators');
270 if(!empty($core_group->memberCount())) {
272 $core_company = DB_DataObject::factory('core_company');
273 $core_company->get('comptype', 'OWNER');
277 foreach ($this->emailTemplates as $k => $mail) {
278 $mail_dir = $this->client_path.'/mail/';
280 if (!file_exists($mail_dir."{$k}.html")) {
281 $mail_dir = $ff->page->rootDir. '/Pman/Core/templates/mail/';
297 echo "\nUpdate Completed SUCCESS\n";
301 * imports SQL files from all DataObjects directories....
303 * except any matching /migrate/
308 // loop through all the modules, and see if they have a importSQL method?
311 $ff = HTML_Flexyframework::get();
313 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
315 //$this->{'import' . $url['scheme']}($url);
317 $dbtype = $dburl['scheme'];
320 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
325 $ar = $this->modulesList();
330 if(in_array($m, $this->disabled)){
331 echo "module $m is disabled \n";
335 echo "Importing SQL from module $m\n";
336 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
341 // check to see if the class has
345 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
346 if($m != 'Core' && file_exists($file)){
349 $class = "Pman_{$m}_UpdateDatabase";
351 if(method_exists($x, 'importModuleSQL')){
352 echo "Importing SQL from module $m using Module::importModuleSQL\n";
353 $x->opts = $this->opts;
354 $x->rootDir = $this->rootDir;
355 $x->importModuleSQL($dburl);
360 echo "Importing SQL from module $m\n";
363 // if init has been called
365 if (!empty($this->opts['init'])) {
366 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
372 $fd = $this->rootDir. "/Pman/$m/DataObjects";
374 $this->{$dirmethod}($dburl, $fd);
377 // new -- sql directory..
378 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
379 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
380 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
382 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
383 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
387 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
388 if (class_exists('PDO_DataObjects_Introspection')) {
389 PDO_DataObject_Introspection::$cache = array();
391 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
393 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
394 $this->{'fixSequences'. $dbtype}();
407 /** -------------- code to handle importing a whole directory of files into the database ------- **/
410 function importpgsqldir($url, $dir, $disable_triggers = false)
412 $ff = HTML_FlexyFramework::get();
414 require_once 'System.php';
415 $cat = System::which('cat');
416 $psql = System::which('psql');
419 if (!empty($url['pass'])) {
420 putenv("PGPASSWORD=". $url['pass']);
424 ' -h ' . $url['host'] .
425 ' -U' . escapeshellarg($url['user']) .
426 ' ' . basename($url['path']);
429 echo $psql_cmd . "\n" ;
430 echo "scan : $dir\n";
433 $files = array($dir);
438 $files = glob($dir.'/*.sql');
439 uksort($files, 'strcasecmp');
441 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
442 //usort($files, $lsort);
445 foreach($files as $bfn) {
448 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
451 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
452 && !preg_match('#\.pg\.sql#i', basename($bfn))
453 ) { // skip migration scripts at present..
458 if (!preg_match('/pgsql/', basename($dir) )) {
459 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
460 $fn = $this->convertToPG($bfn);
464 // files ending in .pg.sql are native postgres files.. ## depricated
467 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
469 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
485 * mysql - does not support conversions.
489 function importmysqlidir($dburl, $dir) {
490 return $this->importmysqldir($dburl, $dir);
493 function importmysqldir($dburl, $dir)
496 $this->fixMysqlInnodb(); /// run once
498 echo "Import MYSQL :: $dir\n";
501 require_once 'System.php';
502 $cat = System::which('cat');
503 $mysql = System::which('mysql');
507 $mysql_cmd = $mysql .
508 ' -h ' . $dburl['host'] .
509 ' -u' . escapeshellarg($dburl['user']) .
510 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
511 ' ' . basename($dburl['path']);
512 //echo $mysql_cmd . "\n" ;
514 $files = glob($dir.'/*.sql');
515 uksort($files, 'strcasecmp');
518 foreach($files as $fn) {
521 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
524 // .my.sql but not .pg.sql
525 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
526 && !preg_match('#\.my\.sql#i', basename($fn))
527 ) { // skip migration scripts at present..
530 if (!strlen(trim($fn))) {
534 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
536 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
539 $fp = popen($cmd, "r");
542 // send the current file part to the browser
543 $line = trim(fgets($fp, 1024));
548 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
549 echo " ---- {$line}\n"; flush();
553 switch($matches[1]) {
554 case 1017: // cause by renaming table -- old one does not exist..
555 case 1050: // create tables triggers this..
556 case 1060: // Duplicate column name
557 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
558 case 1091: // drop index -- name does not exist.. might hide errors..
560 case 1146: // drop a index on an unknown table.. - happens rarely...
561 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
567 echo " ---- {$line}\n"; flush();
571 // 1051: // Unknown table -- normally drop = add iff exists..
572 echo "File: $fn\n$line\n";
588 * simple regex based convert mysql to pgsql...
590 function convertToPG($src)
592 //echo "Convert $src\n";
594 $fn = $this->tempName('sql');
596 $ret = array( ); // pad it a bit.
597 $extra = array("", "" );
600 foreach(file($src) as $l) {
603 if (!strlen($l) || $l[0] == '#') {
607 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
610 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
611 $tbl = 'shop_' . strtolower($m[1]);
612 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
614 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
615 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
618 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
619 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
620 $extra[] = "create sequence {$tbl}_seq;";
624 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
625 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
628 // enum value -- use the text instead..
630 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
631 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
633 // ignore the alter enum
634 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
638 // UNIQUE KEY .. ignore
639 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
640 $last = array_pop($ret);
641 $ret[] = trim($last, ",");
645 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
649 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
653 // INDEX lookup ..ignore
654 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
655 $last = array_pop($ret);
656 $ret[] = trim($last, ",");
661 // CREATE INDEX ..ignore
662 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
663 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
668 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
670 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
671 $l = preg_replace('# blob#i', ' TEXT', $l);
672 $l = preg_replace('# longtext#i', ' TEXT', $l);
673 $l = preg_replace('# tinyint#i', ' INT', $l);
679 $ret = array_merge($extra,$ret);
680 // echo implode("\n", $ret); exit;
682 file_put_contents($fn, implode("\n", $ret));
688 function checkOpts($opts)
692 foreach($opts as $o=>$v) {
693 if (!preg_match('/^json-/', $o) || empty($v)) {
696 if (!file_exists($v)) {
697 die("File does not exist : OPTION --{$o} = {$v} \n");
701 $modules = array_reverse($this->modulesList());
703 // move 'project' one to the end...
705 foreach ($modules as $module){
706 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
707 if($module == 'Core' || !file_exists($file)){
711 $class = "Pman_{$module}_UpdateDatabase";
713 if(!method_exists($x, 'checkOpts')){
716 $x->checkOpts($opts);
720 static function jsonImportFromArray($opts)
722 foreach($opts as $o=>$v) {
723 if (!preg_match('/^json-/', $o) || empty($v)) {
726 $type = str_replace('_', '-', substr($o,5));
728 $data= json_decode(file_get_contents($v),true);
729 $pg = HTML_FlexyFramework::get()->page;
730 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
740 function runUpdateModulesData()
742 if (class_exists('PDO_DataObjects_Introspection')) {
743 PDO_DataObject_Introspection::$cache = array();
745 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
747 if(!in_array('Core', $this->disabled)){
748 echo "Running jsonImportFromArray\n";
749 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
752 echo "Running updateData on modules\n";
758 $modules = array_reverse($this->modulesList());
760 // move 'project' one to the end...
762 foreach ($modules as $module){
763 if(in_array($module, $this->disabled)){
766 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
767 if($module == 'Core' || !file_exists($file)){
772 $class = "Pman_{$module}_UpdateDatabase";
774 if(!method_exists($x, 'updateData')){
784 function updateDataEnums()
786 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
788 $enum = DB_DataObject::Factory('core_enum');
789 //DB_DAtaObject::debugLevel(1);
794 'name' => 'COMPTYPE',
795 'display_name' => 'Company Types',
796 'is_system_enum' => 1,
800 'display_name' => 'Owner',
801 'seqid' => 999, // last...
802 'is_system_enum' => 1,
809 'name' => 'HtmlEditor.font-family',
810 'display_name' => 'HTML Editor font families',
811 'is_system_enum' => 1,
814 'name' => 'Helvetica,Arial,sans-serif',
815 'display_name' => 'Helvetica',
820 'name' => 'Courier New',
821 'display_name' => 'Courier',
826 'display_name' => 'Tahoma',
830 'name' => 'Times New Roman,serif',
831 'display_name' => 'Times',
836 'display_name' => 'Verdana',
849 function updateDataGroups()
852 $groups = DB_DataObject::factory('core_group');
853 $groups->initGroups();
855 $groups->initDatabase($this,array(
857 'name' => 'bcc-email', // group who are bcc'ed on all requests.
858 'type' => 0, // system
859 'display_name' => 'Standard BCC Group'
862 'name' => 'system-email-from',
863 'type' => 0, // system
864 'display_name' => 'Standard System Email From Group'
867 'name' => 'core-person-signup-bcc',
868 'type' => 0, // system
869 'display_name' => 'Standard Person Signup BCC Group'
872 'name' => 'Empty Group', // use for no bcc emails.
874 'display_name' => 'Standard Empty Group'
881 function updateDataCompanies()
884 // fix comptypes enums..
885 $c = DB_DataObject::Factory('core_company');
887 $c->selectAdd('distinct(comptype) as comptype');
891 comptype != 'undefined'
893 comptype != 'undefine'
897 foreach($c->fetchAll('comptype') as $cts) {
899 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
902 $c = DB_DataObject::Factory('core_enum');
905 //DB_DataObject::debugLevel(1);
907 $c = DB_DataObject::Factory('core_company');
909 UPDATE {$c->tableName()}
911 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
924 function updateDataEmails()
926 foreach ($this->emailTemplates as $k => $mail) {
928 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
938 function initEmails($templateDir, $emails, $mapping = false)
940 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
942 $pg = HTML_FlexyFramework::get()->page;
943 foreach($emails as $name=>$data) {
944 $cm = DB_DataObject::factory('core_email');
945 $update = $cm->get('name', $name);
948 if (empty($cm->bcc_group_id)) {
949 if (empty($data['bcc_group'])) {
950 $this->jerr("missing bcc_group for template $name");
953 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
956 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
959 if (!$g->members('email') && $g->name != 'Empty Group') {
960 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
963 $cm->bcc_group_id = $g->id;
965 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
966 //if (empty($cm->test_class)) {
967 if (empty($data['test_class'])) {
968 $this->jerr("missing test_class for template $name");
971 $cm->test_class = $data['test_class'];
973 if(isset($cm->to_group_id)) {
978 !empty($data['to_group']) &&
979 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
981 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
983 if (empty($gp->id)) {
984 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
987 $cm->to_group_id = $gp->id;
991 isset($data['active']) && !isset($cm->active)
993 $cm->active = $data['active'];
997 * Set description to email.
998 * However we do not update if it is been set.
1000 if(empty($cm->description) && !empty($data['description'])){
1001 $cm->description = $cm->escape($data['description']);
1004 require_once $cm->test_class . '.php';
1006 $clsname = str_replace('/','_', $cm->test_class);
1008 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
1009 $got_it = $method->isStatic();
1010 } catch(Exception $e) {
1015 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
1019 echo "email: {$name} - checked\n";
1020 continue; /// we do not import the body content of templates that exist...
1027 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1031 'file' => $templateDir. $name .'.html'
1034 if (!empty($data['master'])) {
1035 $opts['master'] = $templateDir . $master .'.html';
1037 require_once 'Pman/Core/Import/Core_email.php';
1038 $x = new Pman_Core_Import_Core_email();
1040 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1042 echo "email: {$name} - CREATED\n";
1047 function updateData()
1050 if (class_exists('PDO_DataObjects_Introspection')) {
1051 PDO_DataObject_Introspection::$cache = array();
1053 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1055 $this->updateDataEnums();
1056 $this->updateDataGroups();
1057 $this->updateDataCompanies();
1059 $this->updateDataEmails();
1061 $c = DB_DataObject::Factory('I18n');
1065 function fixMysqlInnodb()
1068 static $done_check = false;
1074 if (!empty($this->opts['skip-mysql-checks'])) {
1077 // innodb in single files is far more efficient that MYD or one big innodb file.
1078 // first check if database is using this format.
1079 $db = DB_DataObject::factory('core_enum');
1080 $db->query("show variables like 'innodb_file_per_table'");
1082 if ($db->Value == 'OFF') {
1083 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1086 $db = DB_DataObject::factory('core_enum');
1087 $db->query("select version() as version");
1090 if (version_compare($db->version, '5.7', '>=' )) {
1092 $db = DB_DataObject::factory('core_enum');
1093 $db->query("show variables like 'sql_mode'");
1096 $modes = explode(",", $db->Value);
1098 // these are 'new' problems with mysql.
1100 in_array('NO_ZERO_IN_DATE', $modes) ||
1101 in_array('NO_ZERO_DATE', $modes) ||
1102 in_array('STRICT_TRANS_TABLES', $modes) ||
1103 !in_array('ALLOW_INVALID_DATES', $modes)
1105 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".
1106 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1111 $done_check = true;;
1122 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1124 function fixSequencesMysql()
1129 function fixSequencesPgsql()
1133 //DB_DataObject::debugLevel(1);
1134 $cs = DB_DataObject::factory('core_enum');
1138 CASE WHEN strpos(seq_name, '.') > 0 THEN
1141 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1144 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1145 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1149 n.nspname AS schema_name,
1150 c.relname AS table_name,
1151 a.attname AS column_name,
1152 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1154 JOIN pg_attribute a ON (c.oid=a.attrelid)
1155 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1156 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1157 WHERE has_schema_privilege(n.oid,'USAGE')
1158 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1159 AND has_table_privilege(c.oid,'SELECT')
1160 AND (NOT a.attisdropped)
1161 AND d.adsrc ~ '^nextval'
1165 CASE WHEN strpos(seq_name, '.') > 0 THEN
1166 substring(seq_name, 1,strpos(seq_name,'.')-1)
1171 GROUP BY seq_name HAVING count(*)=1
1174 while ($cs->fetch()) {
1177 foreach($cmds as $cmd) {
1178 $cs = DB_DataObject::factory('core_enum');
1182 $cs = DB_DataObject::factory('core_enum');
1184 SELECT 'SELECT SETVAL(' ||
1185 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1186 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1192 WHERE S.relkind = 'S'
1194 AND D.refobjid = T.oid
1195 AND D.refobjid = C.attrelid
1196 AND D.refobjsubid = C.attnum
1197 AND NS.oid = T.relnamespace
1201 while ($cs->fetch()) {
1204 foreach($cmds as $cmd) {
1205 $cs = DB_DataObject::factory('core_enum');
1212 var $extensions = array(
1217 function runExtensions()
1220 $ff = HTML_Flexyframework::get();
1222 $dburl = parse_url($ff->database);
1224 $dbtype = $dburl['scheme'];
1226 foreach($this->extensions as $ext) {
1228 $scls = ucfirst($dbtype). $ext;
1229 $cls = __CLASS__ . '_'. $scls;
1230 $fn = implode('/',explode('_', $cls)).'.php';
1231 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1242 function checkSystem($req = false, $pref = false)
1244 // most of these are from File_Convert...
1246 // these are required - and have simple dependancies.
1247 require_once 'System.php';
1248 $req = $req !== false ? $req : array(
1253 'rsvg-convert', //librsvg2-bin
1256 'gifsicle', // used for gif conversions
1261 // these are prefered - but may have complicated depenacies
1262 $pref = $pref !== false ? $pref : array(
1266 'html2text', // not availabe in debian squeeze
1267 'pdftocairo', //poppler-utils - not available in debian squeeze.
1277 foreach($req as $r) {
1278 if (!System::which($r)) {
1284 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1286 foreach($pref as $r) {
1287 if (!System::which($r)) {
1293 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1300 function clearApacheDataobjectsCache()
1302 echo "Clearing Database Cache\n";
1303 // this needs to clear it's own cache along with remote one..
1305 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1306 $response = $this->curl($url);
1308 $json = json_decode($response, true);
1310 if(empty($json['data']) || $json['data'] != 'DONE'){
1311 echo "fetching $url\n";
1312 echo "GOT:" . $response. "\n";
1313 echo "Clear DataObjects Cache failed\n";
1320 function clearApacheAssetCache()
1322 echo "Clearing Asset Cache\n";
1323 $response = $this->curl(
1324 "http://localhost{$this->local_base_url}/Core/Asset",
1325 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1328 $json = json_decode($response, true);
1330 if(empty($json['success']) || !$json['success']) {
1331 echo $response. "\n";
1332 echo "CURL Clear Asset cache failed\n";
1339 function curl($url, $request = array(), $method = 'GET')
1341 if($method == 'GET'){
1342 $request = http_build_query($request);
1343 $url = $url . "?" . $request;
1346 $ch = curl_init($url);
1348 if ($method == 'POST') {
1350 curl_setopt($ch, CURLOPT_POST, 1);
1351 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1354 curl_setopt($ch, CURLOPT_HTTPHEADER,
1355 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1359 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1361 curl_setopt($ch, CURLOPT_HEADER, false);
1362 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1363 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1364 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1366 $response = curl_exec($ch);
1373 static function verifyExtensions($extensions)
1377 foreach ($extensions as $e){
1379 if(empty($e) || extension_loaded($e)) {
1383 $error[] = "Error: Please install php extension: {$e}";
1389 $ff = HTML_FLexyFramework::get();
1391 $ff->page->jerr(implode('\n', $error));