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 ' -u' . escapeshellarg($dburl['user']) .
502 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
503 ' ' . basename($dburl['path']);
504 //echo $mysql_cmd . "\n" ;
506 $files = glob($dir.'/*.sql');
507 uksort($files, 'strcasecmp');
510 foreach($files as $fn) {
513 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
516 // .my.sql but not .pg.sql
517 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
518 && !preg_match('#\.my\.sql#i', basename($fn))
519 ) { // skip migration scripts at present..
522 if (!strlen(trim($fn))) {
526 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
528 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
531 $fp = popen($cmd, "r");
534 // send the current file part to the browser
535 $line = trim(fgets($fp, 1024));
540 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
541 echo " ---- {$line}\n"; flush();
545 switch($matches[1]) {
546 case 1017: // cause by renaming table -- old one does not exist..
547 case 1050: // create tables triggers this..
548 case 1060: // Duplicate column name
549 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
550 case 1091: // drop index -- name does not exist.. might hide errors..
552 case 1146: // drop a index on an unknown table.. - happens rarely...
553 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
559 echo " ---- {$line}\n"; flush();
563 // 1051: // Unknown table -- normally drop = add iff exists..
564 echo "File: $fn\n$line\n";
580 * simple regex based convert mysql to pgsql...
582 function convertToPG($src)
584 //echo "Convert $src\n";
586 $fn = $this->tempName('sql');
588 $ret = array( ); // pad it a bit.
589 $extra = array("", "" );
592 foreach(file($src) as $l) {
595 if (!strlen($l) || $l[0] == '#') {
599 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
602 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
603 $tbl = 'shop_' . strtolower($m[1]);
604 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
606 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
607 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
610 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
611 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
612 $extra[] = "create sequence {$tbl}_seq;";
616 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
617 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
620 // enum value -- use the text instead..
622 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
623 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
625 // ignore the alter enum
626 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
630 // UNIQUE KEY .. ignore
631 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
632 $last = array_pop($ret);
633 $ret[] = trim($last, ",");
637 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
641 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
645 // INDEX lookup ..ignore
646 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
647 $last = array_pop($ret);
648 $ret[] = trim($last, ",");
653 // CREATE INDEX ..ignore
654 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
655 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
660 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
662 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
663 $l = preg_replace('# blob#i', ' TEXT', $l);
664 $l = preg_replace('# longtext#i', ' TEXT', $l);
665 $l = preg_replace('# tinyint#i', ' INT', $l);
671 $ret = array_merge($extra,$ret);
672 // echo implode("\n", $ret); exit;
674 file_put_contents($fn, implode("\n", $ret));
680 function checkOpts($opts)
684 foreach($opts as $o=>$v) {
685 if (!preg_match('/^json-/', $o) || empty($v)) {
688 if (!file_exists($v)) {
689 die("File does not exist : OPTION --{$o} = {$v} \n");
693 $modules = array_reverse($this->modulesList());
695 // move 'project' one to the end...
697 foreach ($modules as $module){
698 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
699 if($module == 'Core' || !file_exists($file)){
703 $class = "Pman_{$module}_UpdateDatabase";
705 if(!method_exists($x, 'checkOpts')){
708 $x->checkOpts($opts);
712 static function jsonImportFromArray($opts)
714 foreach($opts as $o=>$v) {
715 if (!preg_match('/^json-/', $o) || empty($v)) {
718 $type = str_replace('_', '-', substr($o,5));
720 $data= json_decode(file_get_contents($v),true);
721 $pg = HTML_FlexyFramework::get()->page;
722 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
732 function runUpdateModulesData()
734 if (class_exists('PDO_DataObjects_Introspection')) {
735 PDO_DataObject_Introspection::$cache = array();
737 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
739 if(!in_array('Core', $this->disabled)){
740 echo "Running jsonImportFromArray\n";
741 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
744 echo "Running updateData on modules\n";
750 $modules = array_reverse($this->modulesList());
752 // move 'project' one to the end...
754 foreach ($modules as $module){
755 if(in_array($module, $this->disabled)){
758 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
759 if($module == 'Core' || !file_exists($file)){
764 $class = "Pman_{$module}_UpdateDatabase";
766 if(!method_exists($x, 'updateData')){
776 function updateDataEnums()
778 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
780 $enum = DB_DataObject::Factory('core_enum');
781 //DB_DAtaObject::debugLevel(1);
786 'name' => 'COMPTYPE',
787 'display_name' => 'Company Types',
788 'is_system_enum' => 1,
792 'display_name' => 'Owner',
793 'seqid' => 999, // last...
794 'is_system_enum' => 1,
801 'name' => 'HtmlEditor.font-family',
802 'display_name' => 'HTML Editor font families',
803 'is_system_enum' => 1,
806 'name' => 'Helvetica,Arial,sans-serif',
807 'display_name' => 'Helvetica',
812 'name' => 'Courier New',
813 'display_name' => 'Courier',
818 'display_name' => 'Tahoma',
822 'name' => 'Times New Roman,serif',
823 'display_name' => 'Times',
828 'display_name' => 'Verdana',
841 function updateDataGroups()
844 $groups = DB_DataObject::factory('core_group');
845 $groups->initGroups();
847 $groups->initDatabase($this,array(
849 'name' => 'bcc-email', // group who are bcc'ed on all requests.
850 'type' => 0, // system
851 'display_name' => 'Standard BCC Group'
854 'name' => 'system-email-from',
855 'type' => 0, // system
856 'display_name' => 'Standard System Email From Group'
859 'name' => 'core-person-signup-bcc',
860 'type' => 0, // system
861 'display_name' => 'Standard Person Signup BCC Group'
864 'name' => 'Empty Group', // use for no bcc emails.
866 'display_name' => 'Standard Empty Group'
873 function updateDataCompanies()
876 // fix comptypes enums..
877 $c = DB_DataObject::Factory('core_company');
879 $c->selectAdd('distinct(comptype) as comptype');
883 comptype != 'undefined'
885 comptype != 'undefine'
889 foreach($c->fetchAll('comptype') as $cts) {
891 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
894 $c = DB_DataObject::Factory('core_enum');
897 //DB_DataObject::debugLevel(1);
899 $c = DB_DataObject::Factory('core_company');
901 UPDATE {$c->tableName()}
903 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
916 function updateDataEmails()
918 if (!empty($this->opts['skip-email-import'])) {
921 foreach ($this->emailTemplates as $k => $mail) {
923 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
933 function initEmails($templateDir, $emails, $mapping = false)
935 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
937 $pg = HTML_FlexyFramework::get()->page;
938 foreach($emails as $name=>$data) {
939 $cm = DB_DataObject::factory('core_email');
940 $update = $cm->get('name', $name);
943 if (empty($cm->bcc_group_id)) {
944 if (empty($data['bcc_group'])) {
945 $this->jerr("missing bcc_group for template $name");
948 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
951 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
954 if (!$g->members('email') && $g->name != 'Empty Group') {
955 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
958 $cm->bcc_group_id = $g->id;
960 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
961 //if (empty($cm->test_class)) {
962 if (empty($data['test_class'])) {
963 $this->jerr("missing test_class for template $name");
966 $cm->test_class = $data['test_class'];
968 if(isset($cm->to_group_id)) {
973 !empty($data['to_group']) &&
974 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
976 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
978 if (empty($gp->id)) {
979 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
982 $cm->to_group_id = $gp->id;
986 isset($data['active']) && !isset($cm->active)
988 $cm->active = $data['active'];
992 * Set description to email.
993 * However we do not update if it is been set.
995 if(empty($cm->description) && !empty($data['description'])){
996 $cm->description = $cm->escape($data['description']);
999 require_once $cm->test_class . '.php';
1001 $clsname = str_replace('/','_', $cm->test_class);
1003 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
1004 $got_it = $method->isStatic();
1005 } catch(Exception $e) {
1010 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
1014 echo "email: {$name} - checked\n";
1015 continue; /// we do not import the body content of templates that exist...
1022 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1026 'file' => $templateDir. $name .'.html'
1029 if (!empty($data['master'])) {
1030 $opts['master'] = $templateDir . $master .'.html';
1032 require_once 'Pman/Core/Import/Core_email.php';
1033 $x = new Pman_Core_Import_Core_email();
1035 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1037 echo "email: {$name} - CREATED\n";
1042 function updateData()
1045 if (class_exists('PDO_DataObjects_Introspection')) {
1046 PDO_DataObject_Introspection::$cache = array();
1048 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1050 $this->updateDataEnums();
1051 $this->updateDataGroups();
1052 $this->updateDataCompanies();
1054 $this->updateDataEmails();
1056 $c = DB_DataObject::Factory('I18n');
1060 function fixMysqlInnodb()
1063 static $done_check = false;
1069 if (!empty($this->opts['skip-mysql-checks'])) {
1072 // innodb in single files is far more efficient that MYD or one big innodb file.
1073 // first check if database is using this format.
1074 $db = DB_DataObject::factory('core_enum');
1075 $db->query("show variables like 'innodb_file_per_table'");
1077 if ($db->Value == 'OFF') {
1078 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1081 $db = DB_DataObject::factory('core_enum');
1082 $db->query("select version() as version");
1085 if (version_compare($db->version, '5.7', '>=' )) {
1087 $db = DB_DataObject::factory('core_enum');
1088 $db->query("show variables like 'sql_mode'");
1091 $modes = explode(",", $db->Value);
1093 // these are 'new' problems with mysql.
1095 in_array('NO_ZERO_IN_DATE', $modes) ||
1096 in_array('NO_ZERO_DATE', $modes) ||
1097 in_array('STRICT_TRANS_TABLES', $modes) ||
1098 !in_array('ALLOW_INVALID_DATES', $modes)
1100 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".
1101 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1106 $done_check = true;;
1117 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1119 function fixSequencesMysql()
1124 function fixSequencesPgsql()
1128 //DB_DataObject::debugLevel(1);
1129 $cs = DB_DataObject::factory('core_enum');
1133 CASE WHEN strpos(seq_name, '.') > 0 THEN
1136 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1139 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1140 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1144 n.nspname AS schema_name,
1145 c.relname AS table_name,
1146 a.attname AS column_name,
1147 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1149 JOIN pg_attribute a ON (c.oid=a.attrelid)
1150 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1151 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1152 WHERE has_schema_privilege(n.oid,'USAGE')
1153 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1154 AND has_table_privilege(c.oid,'SELECT')
1155 AND (NOT a.attisdropped)
1156 AND d.adsrc ~ '^nextval'
1160 CASE WHEN strpos(seq_name, '.') > 0 THEN
1161 substring(seq_name, 1,strpos(seq_name,'.')-1)
1166 GROUP BY seq_name HAVING count(*)=1
1169 while ($cs->fetch()) {
1172 foreach($cmds as $cmd) {
1173 $cs = DB_DataObject::factory('core_enum');
1177 $cs = DB_DataObject::factory('core_enum');
1179 SELECT 'SELECT SETVAL(' ||
1180 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1181 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1187 WHERE S.relkind = 'S'
1189 AND D.refobjid = T.oid
1190 AND D.refobjid = C.attrelid
1191 AND D.refobjsubid = C.attnum
1192 AND NS.oid = T.relnamespace
1196 while ($cs->fetch()) {
1199 foreach($cmds as $cmd) {
1200 $cs = DB_DataObject::factory('core_enum');
1207 var $extensions = array(
1212 function runExtensions()
1215 $ff = HTML_Flexyframework::get();
1217 $dburl = parse_url($ff->database);
1219 $dbtype = $dburl['scheme'];
1220 $dbtype = ($dbtype == 'mysqli') ? 'mysql' : $dbtype;
1222 foreach($this->extensions as $ext) {
1224 $scls = ucfirst($dbtype). $ext;
1225 $cls = __CLASS__ . '_'. $scls;
1226 $fn = implode('/',explode('_', $cls)).'.php';
1228 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1231 echo "Running : {$fn}\n";
1240 function checkSystem($req = false, $pref = false)
1242 // most of these are from File_Convert...
1244 // these are required - and have simple dependancies.
1245 require_once 'System.php';
1246 $req = $req !== false ? $req : array(
1251 'rsvg-convert', //librsvg2-bin
1254 'gifsicle', // used for gif conversions
1259 // these are prefered - but may have complicated depenacies
1260 $pref = $pref !== false ? $pref : array(
1264 'html2text', // not availabe in debian squeeze
1265 'pdftocairo', //poppler-utils - not available in debian squeeze.
1275 foreach($req as $r) {
1276 if (!System::which($r)) {
1282 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1284 foreach($pref as $r) {
1285 if (!System::which($r)) {
1291 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1298 function clearApacheDataobjectsCache()
1301 // this needs to clear it's own cache along with remote one..
1303 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1305 echo "Clearing Database Cache : http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache\n";
1307 $response = $this->curl($url);
1309 $json = json_decode($response, true);
1311 if(empty($json['data']) || $json['data'] != 'DONE'){
1312 echo "fetching $url\n";
1313 echo "GOT:" . $response. "\n";
1314 echo "Clear DataObjects Cache failed\n";
1321 function clearApacheAssetCache()
1323 echo "Clearing Asset Cache : http://localhost{$this->local_base_url}/Core/Asset\n";
1324 $response = $this->curl(
1325 "http://localhost{$this->local_base_url}/Core/Asset",
1326 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1329 $json = json_decode($response, true);
1331 if(empty($json['success']) || !$json['success']) {
1332 echo $response. "\n";
1333 echo "CURL Clear Asset cache failed\n";
1340 function curl($url, $request = array(), $method = 'GET')
1342 if($method == 'GET'){
1343 $request = http_build_query($request);
1344 $url = $url . "?" . $request;
1347 $ch = curl_init($url);
1349 if ($method == 'POST') {
1351 curl_setopt($ch, CURLOPT_POST, 1);
1352 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1355 curl_setopt($ch, CURLOPT_HTTPHEADER,
1356 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1360 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1362 curl_setopt($ch, CURLOPT_HEADER, false);
1363 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1364 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1365 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1367 $response = curl_exec($ch);
1374 static function verifyExtensions($extensions)
1378 foreach ($extensions as $e){
1380 if(empty($e) || extension_loaded($e)) {
1384 $error[] = "Error: Please install php extension: {$e}";
1390 $ff = HTML_FLexyFramework::get();
1392 $ff->page->jerr(implode('\n', $error));