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 'skip-email-import' => array(
71 'desc' => 'Skip email import',
76 'procedures-only' => array(
77 'desc' => 'Only import procedures (not supported by most modules yet) - ignores sql directory',
82 'disable-create-triggers' => array(
83 'desc' => 'So not create the mysql triggers',
89 'json-person' => array(
90 'desc' => 'Person JSON file',
97 'desc' => 'Debug the database',
106 static function cli_opts()
109 $ret = self::$cli_opts;
110 $ff = HTML_FlexyFramework::get();
112 $mods = $a->modulesList();
113 foreach($mods as $m) {
115 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
116 if (!file_exists($fd)) {
122 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
123 $ar = $cls->getStaticProperties();
124 if (isset($ar['cli_opts'])) {
126 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
134 var $disabled = array();
139 var $local_base_url = false;
141 var $emailTemplates = array(
142 'EVENT_ERRORS_REPORT' => array(
143 'bcc_group' => 'Empty Group',
144 'test_class' => 'Pman/Admin/Report/SendEventErrors',
145 'to_group' => 'Administrators',
147 'description' => '9.2 System Error Messages',
148 'template_dir' => '/Pman/Admin/templates/mail/'
150 'ADMIN_PASSWORD_RESET' => array(
151 'bcc_group' => 'Administrators',
152 'test_class' => 'Pman/Core/DataObjects/Core_person',
155 'description' => '9.1 Management System Password Reset',
156 'template_dir' => '/Pman/Core/templates/mail/'
162 var $required_extensions = array(
170 $ff = HTML_FlexyFramework::get();
171 if (!empty($ff->cli)) {
176 parent::getAuth(); // load company!
177 $au = $this->getAuthUser();
178 if (!$au || $au->company()->comptype != 'OWNER') {
179 $this->jerr("Not authenticated", array('authFailure' => true));
181 $this->authUser = $au;
185 function get($args, $opts=array())
187 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
189 $this->checkSystem();
191 $this->verifyExtensions($this->required_extensions);
193 if (class_exists('PDO_DataObjects_Introspection')) {
194 PDO_DataObject_Introspection::$cache = array();
196 echo "Generate DB cache\n";
197 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
198 echo "Generated DB cache\n";
199 $ff = HTML_FlexyFramework::get();
201 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
202 die("Please setup Pman[local_base_url]\n");
205 $this->local_base_url = $ff->Pman['local_base_url'];
207 if(!empty($ff->Core_Notify)){
208 // require_once 'Pman/Core/NotifySmtpCheck.php';
209 // $x = new Pman_Core_NotifySmtpCheck();
213 $this->disabled = explode(',', $ff->disable);
215 //$this->fixSequencesPgsql();exit;
218 if (!empty($opts['debug'])) {
219 DB_DataObject::DebugLevel($opts['debug']);
222 // ask all the modules to verify the opts
223 echo "Checking options\n";
224 $this->checkOpts($opts);
226 $response = $this->curl("http://localhost{$this->local_base_url}/Core/UpdateDatabase/VerifyExtensions");
227 $json = json_decode($response, true);
229 if(empty($json['data']) || $json['data'] != 'DONE'){
230 echo "\nError: Missing php extensions:\n";
232 echo "Please install the above extensions and restart the apache.\n";
238 echo "Checking Setup Requirements\n";
239 require_once 'Pman/Core/UpdateDatabase/VerifyConfig.php';
240 $sq = new Pman_Core_UpdateDatabase_VerifyConfig();
241 $ret = $sq->get($args, $opts);
244 echo implode("\n", $ret) . "\n";
248 // do this first, so the innodb change + utf8 fixes column max sizes
250 // this will trigger errors about freetext indexes - we will have to remove them manually.?
251 // 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..)
252 echo "Run extensions\n";
254 $this->runExtensions();
257 if (empty($opts['data-only'])) {
261 if (!empty($opts['only-module-sql'])) {
265 echo "run Update Modules Data\n";
267 $this->runUpdateModulesData();
269 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
270 // make sure we have a good cache...?
272 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
275 $this->runExtensions();
277 $this->clearApacheDataobjectsCache();
279 $this->clearApacheAssetCache();
289 echo "\nUpdate Completed SUCCESS\n";
293 * imports SQL files from all DataObjects directories....
295 * except any matching /migrate/
300 // loop through all the modules, and see if they have a importSQL method?
303 $ff = HTML_Flexyframework::get();
305 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
307 //$this->{'import' . $url['scheme']}($url);
309 $dbtype = $dburl['scheme'];
312 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
317 $ar = $this->modulesList();
322 if(in_array($m, $this->disabled)){
323 echo "module $m is disabled \n";
327 echo "Importing SQL from module $m\n";
328 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
333 // check to see if the class has
337 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
338 if($m != 'Core' && file_exists($file)){
341 $class = "Pman_{$m}_UpdateDatabase";
343 if(method_exists($x, 'importModuleSQL')){
344 echo "Importing SQL from module $m using Module::importModuleSQL\n";
345 $x->opts = $this->opts;
346 $x->rootDir = $this->rootDir;
347 $x->importModuleSQL($dburl);
352 echo "Importing SQL from module $m\n";
355 // if init has been called
357 if (!empty($this->opts['init'])) {
358 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
364 $fd = $this->rootDir. "/Pman/$m/DataObjects";
366 $this->{$dirmethod}($dburl, $fd);
369 // new -- sql directory..
370 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
371 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
372 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
374 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
375 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
379 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
380 if (class_exists('PDO_DataObjects_Introspection')) {
381 PDO_DataObject_Introspection::$cache = array();
383 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
385 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
386 $this->{'fixSequences'. $dbtype}();
399 /** -------------- code to handle importing a whole directory of files into the database ------- **/
402 function importpgsqldir($url, $dir, $disable_triggers = false)
404 $ff = HTML_FlexyFramework::get();
406 require_once 'System.php';
407 $cat = System::which('cat');
408 $psql = System::which('psql');
411 if (!empty($url['pass'])) {
412 putenv("PGPASSWORD=". $url['pass']);
416 ' -h ' . $url['host'] .
417 ' -U' . escapeshellarg($url['user']) .
418 ' ' . basename($url['path']);
421 echo $psql_cmd . "\n" ;
422 echo "scan : $dir\n";
425 $files = array($dir);
430 $files = glob($dir.'/*.sql');
431 uksort($files, 'strcasecmp');
433 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
434 //usort($files, $lsort);
437 foreach($files as $bfn) {
440 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
443 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
444 && !preg_match('#\.pg\.sql#i', basename($bfn))
445 ) { // skip migration scripts at present..
450 if (!preg_match('/pgsql/', basename($dir) )) {
451 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
452 $fn = $this->convertToPG($bfn);
456 // files ending in .pg.sql are native postgres files.. ## depricated
459 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
461 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
477 * mysql - does not support conversions.
481 function importmysqlidir($dburl, $dir) {
482 return $this->importmysqldir($dburl, $dir);
485 function importmysqldir($dburl, $dir)
488 $this->fixMysqlInnodb(); /// run once
490 echo "Import MYSQL :: $dir\n";
493 require_once 'System.php';
494 $cat = System::which('cat');
495 $mysql = System::which('mysql');
499 $mysql_cmd = $mysql .
500 ' -h ' . $dburl['host'] .
501 (empty($dburl['port']) ? '' : " -P{$dburl['port']} ") .
502 ' -u' . escapeshellarg($dburl['user']) .
503 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
504 ' ' . basename($dburl['path']);
505 //echo $mysql_cmd . "\n" ;
507 $files = glob($dir.'/*.sql');
508 uksort($files, 'strcasecmp');
511 foreach($files as $fn) {
514 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
517 // .my.sql but not .pg.sql
518 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
519 && !preg_match('#\.my\.sql#i', basename($fn))
520 ) { // skip migration scripts at present..
523 if (!strlen(trim($fn))) {
527 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
529 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
532 $fp = popen($cmd, "r");
535 // send the current file part to the browser
536 $line = trim(fgets($fp, 1024));
541 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
542 echo " ---- {$line}\n"; flush();
546 switch($matches[1]) {
547 case 1017: // cause by renaming table -- old one does not exist..
548 case 1050: // create tables triggers this..
549 case 1060: // Duplicate column name
550 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
551 case 1091: // drop index -- name does not exist.. might hide errors..
553 case 1146: // drop a index on an unknown table.. - happens rarely...
554 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
560 echo " ---- {$line}\n"; flush();
564 // 1051: // Unknown table -- normally drop = add iff exists..
565 echo "File: $fn\n$line\n";
581 * simple regex based convert mysql to pgsql...
583 function convertToPG($src)
585 //echo "Convert $src\n";
587 $fn = $this->tempName('sql');
589 $ret = array( ); // pad it a bit.
590 $extra = array("", "" );
593 foreach(file($src) as $l) {
596 if (!strlen($l) || $l[0] == '#') {
600 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
603 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
604 $tbl = 'shop_' . strtolower($m[1]);
605 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
607 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
608 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
611 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
612 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
613 $extra[] = "create sequence {$tbl}_seq;";
617 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
618 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
621 // enum value -- use the text instead..
623 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
624 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
626 // ignore the alter enum
627 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
631 // UNIQUE KEY .. ignore
632 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
633 $last = array_pop($ret);
634 $ret[] = trim($last, ",");
638 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
642 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
646 // INDEX lookup ..ignore
647 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
648 $last = array_pop($ret);
649 $ret[] = trim($last, ",");
654 // CREATE INDEX ..ignore
655 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
656 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
661 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
663 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
664 $l = preg_replace('# blob#i', ' TEXT', $l);
665 $l = preg_replace('# longtext#i', ' TEXT', $l);
666 $l = preg_replace('# tinyint#i', ' INT', $l);
672 $ret = array_merge($extra,$ret);
673 // echo implode("\n", $ret); exit;
675 file_put_contents($fn, implode("\n", $ret));
681 function checkOpts($opts)
685 foreach($opts as $o=>$v) {
686 if (!preg_match('/^json-/', $o) || empty($v)) {
689 if (!file_exists($v)) {
690 die("File does not exist : OPTION --{$o} = {$v} \n");
694 $modules = array_reverse($this->modulesList());
696 // move 'project' one to the end...
698 foreach ($modules as $module){
699 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
700 if($module == 'Core' || !file_exists($file)){
704 $class = "Pman_{$module}_UpdateDatabase";
706 if(!method_exists($x, 'checkOpts')){
709 $x->checkOpts($opts);
713 static function jsonImportFromArray($opts)
715 foreach($opts as $o=>$v) {
716 if (!preg_match('/^json-/', $o) || empty($v)) {
719 $type = str_replace('_', '-', substr($o,5));
721 $data= json_decode(file_get_contents($v),true);
722 $pg = HTML_FlexyFramework::get()->page;
723 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
733 function runUpdateModulesData()
735 if (class_exists('PDO_DataObjects_Introspection')) {
736 PDO_DataObject_Introspection::$cache = array();
738 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
740 if(!in_array('Core', $this->disabled)){
741 echo "Running jsonImportFromArray\n";
742 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
745 echo "Running updateData on modules\n";
751 $modules = array_reverse($this->modulesList());
753 // move 'project' one to the end...
755 foreach ($modules as $module){
756 if(in_array($module, $this->disabled)){
759 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
760 if($module == 'Core' || !file_exists($file)){
765 $class = "Pman_{$module}_UpdateDatabase";
767 if(!method_exists($x, 'updateData')){
770 $x->rootDir = $this->rootDir;
778 function updateDataEnums()
780 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
782 $enum = DB_DataObject::Factory('core_enum');
783 //DB_DAtaObject::debugLevel(1);
788 'name' => 'COMPTYPE',
789 'display_name' => 'Company Types',
790 'is_system_enum' => 1,
794 'display_name' => 'Owner',
795 'seqid' => 999, // last...
796 'is_system_enum' => 1,
803 'name' => 'HtmlEditor.font-family',
804 'display_name' => 'HTML Editor font families',
805 'is_system_enum' => 1,
808 'name' => 'Helvetica,Arial,sans-serif',
809 'display_name' => 'Helvetica',
814 'name' => 'Courier New',
815 'display_name' => 'Courier',
820 'display_name' => 'Tahoma',
824 'name' => 'Times New Roman,serif',
825 'display_name' => 'Times',
830 'display_name' => 'Verdana',
843 function updateDataGroups()
846 $groups = DB_DataObject::factory('core_group');
847 $groups->initGroups();
849 $groups->initDatabase($this,array(
851 'name' => 'bcc-email', // group who are bcc'ed on all requests.
852 'type' => 0, // system
854 'display_name' => 'Standard BCC Group'
857 'name' => 'system-email-from',
858 'type' => 0, // system
860 'display_name' => 'Standard System Email From Group'
863 'name' => 'core-person-signup-bcc',
864 'type' => 0, // system
866 'display_name' => 'Standard Person Signup BCC Group'
869 'name' => 'Empty Group', // use for no bcc emails.
872 'display_name' => 'Standard Empty Group'
879 function updateDataCompanies()
882 // fix comptypes enums..
883 $c = DB_DataObject::Factory('core_company');
885 $c->selectAdd('distinct(comptype) as comptype');
889 comptype != 'undefined'
891 comptype != 'undefine'
895 foreach($c->fetchAll('comptype') as $cts) {
897 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
900 $c = DB_DataObject::Factory('core_enum');
903 //DB_DataObject::debugLevel(1);
905 $c = DB_DataObject::Factory('core_company');
907 UPDATE {$c->tableName()}
909 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
922 function updateDataEmails()
924 if (!empty($this->opts['skip-email-import'])) {
927 foreach ($this->emailTemplates as $k => $mail) {
930 !empty($mail['template_dir']) ? "{$this->rootDir}{$mail['template_dir']}" : '',
937 function initEmails($templateDir, $emails, $mapping = false)
939 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
941 $pg = HTML_FlexyFramework::get()->page;
942 foreach($emails as $name=>$data) {
943 $cm = DB_DataObject::factory('core_email');
944 $update = $cm->get('name', $name);
947 if (empty($cm->bcc_group_id)) {
948 if (empty($data['bcc_group'])) {
949 $this->jerr("missing bcc_group for template $name");
952 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
955 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
958 if (!$g->members('email') && $g->name != 'Empty Group') {
959 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
962 $cm->bcc_group_id = $g->id;
964 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
965 //if (empty($cm->test_class)) {
966 if (empty($data['test_class'])) {
967 $this->jerr("missing test_class for template $name");
970 $cm->test_class = $data['test_class'];
972 if(isset($cm->to_group_id)) {
977 !empty($data['to_group']) &&
978 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
980 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
982 if (empty($gp->id)) {
983 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
986 $cm->to_group_id = $gp->id;
990 isset($data['active']) && !isset($cm->active)
992 $cm->active = $data['active'];
996 * Set description to email.
997 * However we do not update if it is been set.
999 if(empty($cm->description) && !empty($data['description'])){
1000 $cm->description = $cm->escape($data['description']);
1003 require_once $cm->test_class . '.php';
1005 $clsname = str_replace('/','_', $cm->test_class);
1007 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
1008 $got_it = $method->isStatic();
1009 } catch(Exception $e) {
1014 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
1018 echo "email: {$name} - checked\n";
1019 continue; /// we do not import the body content of templates that exist...
1026 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1031 if (!empty($templateDir)) {
1032 $opts['file'] = $templateDir. $name .'.html';
1034 if (!empty($data['raw_content'])) {
1035 $opts['raw_content'] = $data['raw_content'];
1036 $opts['name'] = $name;
1038 if (!empty($data['master'])) {
1039 $opts['master'] = $templateDir . $master .'.html';
1041 require_once 'Pman/Core/Import/Core_email.php';
1042 $x = new Pman_Core_Import_Core_email();
1044 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1046 echo "email: {$name} - CREATED\n";
1051 function updateData()
1054 if (class_exists('PDO_DataObjects_Introspection')) {
1055 PDO_DataObject_Introspection::$cache = array();
1057 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1059 $this->updateDataEnums();
1060 $this->updateDataGroups();
1061 $this->updateDataCompanies();
1063 $this->updateDataEmails();
1065 $c = DB_DataObject::Factory('I18n');
1069 function fixMysqlInnodb()
1072 static $done_check = false;
1078 if (!empty($this->opts['skip-mysql-checks'])) {
1081 // innodb in single files is far more efficient that MYD or one big innodb file.
1082 // first check if database is using this format.
1083 $db = DB_DataObject::factory('core_enum');
1084 $db->query("show variables like 'innodb_file_per_table'");
1086 if ($db->Value == 'OFF') {
1087 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1090 $db = DB_DataObject::factory('core_enum');
1091 $db->query("select version() as version");
1094 if (version_compare($db->version, '5.7', '>=' )) {
1096 $db = DB_DataObject::factory('core_enum');
1097 $db->query("show variables like 'sql_mode'");
1100 $modes = explode(",", $db->Value);
1102 // these are 'new' problems with mysql.
1104 in_array('NO_ZERO_IN_DATE', $modes) ||
1105 in_array('NO_ZERO_DATE', $modes) ||
1106 in_array('STRICT_TRANS_TABLES', $modes) ||
1107 !in_array('ALLOW_INVALID_DATES', $modes)
1109 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".
1110 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1115 $done_check = true;;
1126 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1128 function fixSequencesMysql()
1133 function fixSequencesPgsql()
1137 //DB_DataObject::debugLevel(1);
1138 $cs = DB_DataObject::factory('core_enum');
1142 CASE WHEN strpos(seq_name, '.') > 0 THEN
1145 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1148 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1149 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1153 n.nspname AS schema_name,
1154 c.relname AS table_name,
1155 a.attname AS column_name,
1156 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1158 JOIN pg_attribute a ON (c.oid=a.attrelid)
1159 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1160 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1161 WHERE has_schema_privilege(n.oid,'USAGE')
1162 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1163 AND has_table_privilege(c.oid,'SELECT')
1164 AND (NOT a.attisdropped)
1165 AND d.adsrc ~ '^nextval'
1169 CASE WHEN strpos(seq_name, '.') > 0 THEN
1170 substring(seq_name, 1,strpos(seq_name,'.')-1)
1175 GROUP BY seq_name HAVING count(*)=1
1178 while ($cs->fetch()) {
1181 foreach($cmds as $cmd) {
1182 $cs = DB_DataObject::factory('core_enum');
1186 $cs = DB_DataObject::factory('core_enum');
1188 SELECT 'SELECT SETVAL(' ||
1189 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1190 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1196 WHERE S.relkind = 'S'
1198 AND D.refobjid = T.oid
1199 AND D.refobjid = C.attrelid
1200 AND D.refobjsubid = C.attnum
1201 AND NS.oid = T.relnamespace
1205 while ($cs->fetch()) {
1208 foreach($cmds as $cmd) {
1209 $cs = DB_DataObject::factory('core_enum');
1216 var $extensions = array(
1221 function runExtensions()
1224 $ff = HTML_Flexyframework::get();
1226 $dburl = parse_url($ff->database);
1228 $dbtype = $dburl['scheme'];
1229 $dbtype = ($dbtype == 'mysqli') ? 'mysql' : $dbtype;
1231 foreach($this->extensions as $ext) {
1233 $scls = ucfirst($dbtype). $ext;
1234 $cls = __CLASS__ . '_'. $scls;
1235 $fn = implode('/',explode('_', $cls)).'.php';
1237 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1240 echo "Running : {$fn}\n";
1249 function checkSystem($req = false, $pref = false)
1251 // most of these are from File_Convert...
1253 // these are required - and have simple dependancies.
1254 require_once 'System.php';
1255 $req = $req !== false ? $req : array(
1260 'rsvg-convert', //librsvg2-bin
1263 'gifsicle', // used for gif conversions
1267 // these are prefered - but may have complicated depenacies
1268 $pref = $pref !== false ? $pref : array(
1272 'html2text', // not availabe in debian squeeze
1273 'pdftocairo', //poppler-utils - not available in debian squeeze.
1283 foreach($req as $r) {
1284 if (!System::which($r)) {
1290 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1292 foreach($pref as $r) {
1293 if (!System::which($r)) {
1299 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1306 function clearApacheDataobjectsCache()
1309 // this needs to clear it's own cache along with remote one..
1311 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1313 echo "Clearing Database Cache : http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache\n";
1315 $response = $this->curl($url);
1317 $json = json_decode($response, true);
1319 if(empty($json['data']) || $json['data'] != 'DONE'){
1320 echo "fetching $url\n";
1321 echo "GOT:" . $response. "\n";
1322 echo "Clear DataObjects Cache failed\n";
1329 function clearApacheAssetCache()
1331 echo "Clearing Asset Cache : http://localhost{$this->local_base_url}/Core/Asset\n";
1332 $response = $this->curl(
1333 "http://localhost{$this->local_base_url}/Core/Asset",
1334 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1337 $json = json_decode($response, true);
1339 if(empty($json['success']) || !$json['success']) {
1340 echo $response. "\n";
1341 echo "CURL Clear Asset cache failed\n";
1348 function curl($url, $request = array(), $method = 'GET')
1350 if($method == 'GET'){
1351 $request = http_build_query($request);
1352 $url = $url . "?" . $request;
1355 $ch = curl_init($url);
1357 if ($method == 'POST') {
1359 curl_setopt($ch, CURLOPT_POST, 1);
1360 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1363 curl_setopt($ch, CURLOPT_HTTPHEADER,
1364 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1368 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1370 curl_setopt($ch, CURLOPT_HEADER, false);
1371 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1372 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1373 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1375 $response = curl_exec($ch);
1382 static function verifyExtensions($extensions)
1386 foreach ($extensions as $e){
1388 if(empty($e) || extension_loaded($e)) {
1392 $error[] = "Error: Please install php extension: {$e}";
1398 $ff = HTML_FLexyFramework::get();
1400 $ff->page->jerr(implode('\n', $error));