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..)
253 $this->runExtensions();
256 if (empty($opts['data-only'])) {
259 if (!empty($opts['only-module-sql'])) {
265 $this->runUpdateModulesData();
267 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
268 // make sure we have a good cache...?
270 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
273 $this->runExtensions();
275 $this->clearApacheDataobjectsCache();
277 $this->clearApacheAssetCache();
287 echo "\nUpdate Completed SUCCESS\n";
291 * imports SQL files from all DataObjects directories....
293 * except any matching /migrate/
298 // loop through all the modules, and see if they have a importSQL method?
301 $ff = HTML_Flexyframework::get();
303 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
305 //$this->{'import' . $url['scheme']}($url);
307 $dbtype = $dburl['scheme'];
310 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
315 $ar = $this->modulesList();
320 if(in_array($m, $this->disabled)){
321 echo "module $m is disabled \n";
325 echo "Importing SQL from module $m\n";
326 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
331 // check to see if the class has
335 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
336 if($m != 'Core' && file_exists($file)){
339 $class = "Pman_{$m}_UpdateDatabase";
341 if(method_exists($x, 'importModuleSQL')){
342 echo "Importing SQL from module $m using Module::importModuleSQL\n";
343 $x->opts = $this->opts;
344 $x->rootDir = $this->rootDir;
345 $x->importModuleSQL($dburl);
350 echo "Importing SQL from module $m\n";
353 // if init has been called
355 if (!empty($this->opts['init'])) {
356 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
362 $fd = $this->rootDir. "/Pman/$m/DataObjects";
364 $this->{$dirmethod}($dburl, $fd);
367 // new -- sql directory..
368 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
369 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
370 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
372 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
373 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
377 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
378 if (class_exists('PDO_DataObjects_Introspection')) {
379 PDO_DataObject_Introspection::$cache = array();
381 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
383 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
384 $this->{'fixSequences'. $dbtype}();
397 /** -------------- code to handle importing a whole directory of files into the database ------- **/
400 function importpgsqldir($url, $dir, $disable_triggers = false)
402 $ff = HTML_FlexyFramework::get();
404 require_once 'System.php';
405 $cat = System::which('cat');
406 $psql = System::which('psql');
409 if (!empty($url['pass'])) {
410 putenv("PGPASSWORD=". $url['pass']);
414 ' -h ' . $url['host'] .
415 ' -U' . escapeshellarg($url['user']) .
416 ' ' . basename($url['path']);
419 echo $psql_cmd . "\n" ;
420 echo "scan : $dir\n";
423 $files = array($dir);
428 $files = glob($dir.'/*.sql');
429 uksort($files, 'strcasecmp');
431 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
432 //usort($files, $lsort);
435 foreach($files as $bfn) {
438 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
441 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
442 && !preg_match('#\.pg\.sql#i', basename($bfn))
443 ) { // skip migration scripts at present..
448 if (!preg_match('/pgsql/', basename($dir) )) {
449 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
450 $fn = $this->convertToPG($bfn);
454 // files ending in .pg.sql are native postgres files.. ## depricated
457 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
459 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
475 * mysql - does not support conversions.
479 function importmysqlidir($dburl, $dir) {
480 return $this->importmysqldir($dburl, $dir);
483 function importmysqldir($dburl, $dir)
486 $this->fixMysqlInnodb(); /// run once
488 echo "Import MYSQL :: $dir\n";
491 require_once 'System.php';
492 $cat = System::which('cat');
493 $mysql = System::which('mysql');
497 $mysql_cmd = $mysql .
498 ' -h ' . $dburl['host'] .
499 ' -u' . escapeshellarg($dburl['user']) .
500 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
501 ' ' . basename($dburl['path']);
502 //echo $mysql_cmd . "\n" ;
504 $files = glob($dir.'/*.sql');
505 uksort($files, 'strcasecmp');
508 foreach($files as $fn) {
511 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
514 // .my.sql but not .pg.sql
515 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
516 && !preg_match('#\.my\.sql#i', basename($fn))
517 ) { // skip migration scripts at present..
520 if (!strlen(trim($fn))) {
524 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
526 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
529 $fp = popen($cmd, "r");
532 // send the current file part to the browser
533 $line = trim(fgets($fp, 1024));
538 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
539 echo " ---- {$line}\n"; flush();
543 switch($matches[1]) {
544 case 1017: // cause by renaming table -- old one does not exist..
545 case 1050: // create tables triggers this..
546 case 1060: // Duplicate column name
547 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
548 case 1091: // drop index -- name does not exist.. might hide errors..
550 case 1146: // drop a index on an unknown table.. - happens rarely...
551 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
557 echo " ---- {$line}\n"; flush();
561 // 1051: // Unknown table -- normally drop = add iff exists..
562 echo "File: $fn\n$line\n";
578 * simple regex based convert mysql to pgsql...
580 function convertToPG($src)
582 //echo "Convert $src\n";
584 $fn = $this->tempName('sql');
586 $ret = array( ); // pad it a bit.
587 $extra = array("", "" );
590 foreach(file($src) as $l) {
593 if (!strlen($l) || $l[0] == '#') {
597 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
600 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
601 $tbl = 'shop_' . strtolower($m[1]);
602 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
604 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
605 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
608 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
609 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
610 $extra[] = "create sequence {$tbl}_seq;";
614 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
615 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
618 // enum value -- use the text instead..
620 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
621 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
623 // ignore the alter enum
624 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
628 // UNIQUE KEY .. ignore
629 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
630 $last = array_pop($ret);
631 $ret[] = trim($last, ",");
635 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
639 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
643 // INDEX lookup ..ignore
644 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
645 $last = array_pop($ret);
646 $ret[] = trim($last, ",");
651 // CREATE INDEX ..ignore
652 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
653 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
658 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
660 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
661 $l = preg_replace('# blob#i', ' TEXT', $l);
662 $l = preg_replace('# longtext#i', ' TEXT', $l);
663 $l = preg_replace('# tinyint#i', ' INT', $l);
669 $ret = array_merge($extra,$ret);
670 // echo implode("\n", $ret); exit;
672 file_put_contents($fn, implode("\n", $ret));
678 function checkOpts($opts)
682 foreach($opts as $o=>$v) {
683 if (!preg_match('/^json-/', $o) || empty($v)) {
686 if (!file_exists($v)) {
687 die("File does not exist : OPTION --{$o} = {$v} \n");
691 $modules = array_reverse($this->modulesList());
693 // move 'project' one to the end...
695 foreach ($modules as $module){
696 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
697 if($module == 'Core' || !file_exists($file)){
701 $class = "Pman_{$module}_UpdateDatabase";
703 if(!method_exists($x, 'checkOpts')){
706 $x->checkOpts($opts);
710 static function jsonImportFromArray($opts)
712 foreach($opts as $o=>$v) {
713 if (!preg_match('/^json-/', $o) || empty($v)) {
716 $type = str_replace('_', '-', substr($o,5));
718 $data= json_decode(file_get_contents($v),true);
719 $pg = HTML_FlexyFramework::get()->page;
720 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
730 function runUpdateModulesData()
732 if (class_exists('PDO_DataObjects_Introspection')) {
733 PDO_DataObject_Introspection::$cache = array();
735 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
737 if(!in_array('Core', $this->disabled)){
738 echo "Running jsonImportFromArray\n";
739 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
742 echo "Running updateData on modules\n";
748 $modules = array_reverse($this->modulesList());
750 // move 'project' one to the end...
752 foreach ($modules as $module){
753 if(in_array($module, $this->disabled)){
756 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
757 if($module == 'Core' || !file_exists($file)){
762 $class = "Pman_{$module}_UpdateDatabase";
764 if(!method_exists($x, 'updateData')){
774 function updateDataEnums()
776 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
778 $enum = DB_DataObject::Factory('core_enum');
779 //DB_DAtaObject::debugLevel(1);
784 'name' => 'COMPTYPE',
785 'display_name' => 'Company Types',
786 'is_system_enum' => 1,
790 'display_name' => 'Owner',
791 'seqid' => 999, // last...
792 'is_system_enum' => 1,
799 'name' => 'HtmlEditor.font-family',
800 'display_name' => 'HTML Editor font families',
801 'is_system_enum' => 1,
804 'name' => 'Helvetica,Arial,sans-serif',
805 'display_name' => 'Helvetica',
810 'name' => 'Courier New',
811 'display_name' => 'Courier',
816 'display_name' => 'Tahoma',
820 'name' => 'Times New Roman,serif',
821 'display_name' => 'Times',
826 'display_name' => 'Verdana',
839 function updateDataGroups()
842 $groups = DB_DataObject::factory('core_group');
843 $groups->initGroups();
845 $groups->initDatabase($this,array(
847 'name' => 'bcc-email', // group who are bcc'ed on all requests.
848 'type' => 0, // system
849 'display_name' => 'Standard BCC Group'
852 'name' => 'system-email-from',
853 'type' => 0, // system
854 'display_name' => 'Standard System Email From Group'
857 'name' => 'core-person-signup-bcc',
858 'type' => 0, // system
859 'display_name' => 'Standard Person Signup BCC Group'
862 'name' => 'Empty Group', // use for no bcc emails.
864 'display_name' => 'Standard Empty Group'
871 function updateDataCompanies()
874 // fix comptypes enums..
875 $c = DB_DataObject::Factory('core_company');
877 $c->selectAdd('distinct(comptype) as comptype');
881 comptype != 'undefined'
883 comptype != 'undefine'
887 foreach($c->fetchAll('comptype') as $cts) {
889 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
892 $c = DB_DataObject::Factory('core_enum');
895 //DB_DataObject::debugLevel(1);
897 $c = DB_DataObject::Factory('core_company');
899 UPDATE {$c->tableName()}
901 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
914 function updateDataEmails()
916 if (!empty($this->opts['skip-email-import'])) {
919 foreach ($this->emailTemplates as $k => $mail) {
921 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
931 function initEmails($templateDir, $emails, $mapping = false)
933 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
935 $pg = HTML_FlexyFramework::get()->page;
936 foreach($emails as $name=>$data) {
937 $cm = DB_DataObject::factory('core_email');
938 $update = $cm->get('name', $name);
941 if (empty($cm->bcc_group_id)) {
942 if (empty($data['bcc_group'])) {
943 $this->jerr("missing bcc_group for template $name");
946 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
949 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
952 if (!$g->members('email') && $g->name != 'Empty Group') {
953 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
956 $cm->bcc_group_id = $g->id;
958 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
959 //if (empty($cm->test_class)) {
960 if (empty($data['test_class'])) {
961 $this->jerr("missing test_class for template $name");
964 $cm->test_class = $data['test_class'];
966 if(isset($cm->to_group_id)) {
971 !empty($data['to_group']) &&
972 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
974 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
976 if (empty($gp->id)) {
977 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
980 $cm->to_group_id = $gp->id;
984 isset($data['active']) && !isset($cm->active)
986 $cm->active = $data['active'];
990 * Set description to email.
991 * However we do not update if it is been set.
993 if(empty($cm->description) && !empty($data['description'])){
994 $cm->description = $cm->escape($data['description']);
997 require_once $cm->test_class . '.php';
999 $clsname = str_replace('/','_', $cm->test_class);
1001 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
1002 $got_it = $method->isStatic();
1003 } catch(Exception $e) {
1008 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
1012 echo "email: {$name} - checked\n";
1013 continue; /// we do not import the body content of templates that exist...
1020 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1024 'file' => $templateDir. $name .'.html'
1027 if (!empty($data['master'])) {
1028 $opts['master'] = $templateDir . $master .'.html';
1030 require_once 'Pman/Core/Import/Core_email.php';
1031 $x = new Pman_Core_Import_Core_email();
1033 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1035 echo "email: {$name} - CREATED\n";
1040 function updateData()
1043 if (class_exists('PDO_DataObjects_Introspection')) {
1044 PDO_DataObject_Introspection::$cache = array();
1046 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1048 $this->updateDataEnums();
1049 $this->updateDataGroups();
1050 $this->updateDataCompanies();
1052 $this->updateDataEmails();
1054 $c = DB_DataObject::Factory('I18n');
1058 function fixMysqlInnodb()
1061 static $done_check = false;
1067 if (!empty($this->opts['skip-mysql-checks'])) {
1070 // innodb in single files is far more efficient that MYD or one big innodb file.
1071 // first check if database is using this format.
1072 $db = DB_DataObject::factory('core_enum');
1073 $db->query("show variables like 'innodb_file_per_table'");
1075 if ($db->Value == 'OFF') {
1076 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1079 $db = DB_DataObject::factory('core_enum');
1080 $db->query("select version() as version");
1083 if (version_compare($db->version, '5.7', '>=' )) {
1085 $db = DB_DataObject::factory('core_enum');
1086 $db->query("show variables like 'sql_mode'");
1089 $modes = explode(",", $db->Value);
1091 // these are 'new' problems with mysql.
1093 in_array('NO_ZERO_IN_DATE', $modes) ||
1094 in_array('NO_ZERO_DATE', $modes) ||
1095 in_array('STRICT_TRANS_TABLES', $modes) ||
1096 !in_array('ALLOW_INVALID_DATES', $modes)
1098 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".
1099 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1104 $done_check = true;;
1115 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1117 function fixSequencesMysql()
1122 function fixSequencesPgsql()
1126 //DB_DataObject::debugLevel(1);
1127 $cs = DB_DataObject::factory('core_enum');
1131 CASE WHEN strpos(seq_name, '.') > 0 THEN
1134 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1137 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1138 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1142 n.nspname AS schema_name,
1143 c.relname AS table_name,
1144 a.attname AS column_name,
1145 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1147 JOIN pg_attribute a ON (c.oid=a.attrelid)
1148 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1149 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1150 WHERE has_schema_privilege(n.oid,'USAGE')
1151 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1152 AND has_table_privilege(c.oid,'SELECT')
1153 AND (NOT a.attisdropped)
1154 AND d.adsrc ~ '^nextval'
1158 CASE WHEN strpos(seq_name, '.') > 0 THEN
1159 substring(seq_name, 1,strpos(seq_name,'.')-1)
1164 GROUP BY seq_name HAVING count(*)=1
1167 while ($cs->fetch()) {
1170 foreach($cmds as $cmd) {
1171 $cs = DB_DataObject::factory('core_enum');
1175 $cs = DB_DataObject::factory('core_enum');
1177 SELECT 'SELECT SETVAL(' ||
1178 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1179 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1185 WHERE S.relkind = 'S'
1187 AND D.refobjid = T.oid
1188 AND D.refobjid = C.attrelid
1189 AND D.refobjsubid = C.attnum
1190 AND NS.oid = T.relnamespace
1194 while ($cs->fetch()) {
1197 foreach($cmds as $cmd) {
1198 $cs = DB_DataObject::factory('core_enum');
1205 var $extensions = array(
1210 function runExtensions()
1213 $ff = HTML_Flexyframework::get();
1215 $dburl = parse_url($ff->database);
1217 $dbtype = $dburl['scheme'];
1218 $dbtype = ($dbtype == 'mysqli') ? 'mysql' : $dbtype;
1220 foreach($this->extensions as $ext) {
1222 $scls = ucfirst($dbtype). $ext;
1223 $cls = __CLASS__ . '_'. $scls;
1224 $fn = implode('/',explode('_', $cls)).'.php';
1226 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1237 function checkSystem($req = false, $pref = false)
1239 // most of these are from File_Convert...
1241 // these are required - and have simple dependancies.
1242 require_once 'System.php';
1243 $req = $req !== false ? $req : array(
1248 'rsvg-convert', //librsvg2-bin
1251 'gifsicle', // used for gif conversions
1256 // these are prefered - but may have complicated depenacies
1257 $pref = $pref !== false ? $pref : array(
1261 'html2text', // not availabe in debian squeeze
1262 'pdftocairo', //poppler-utils - not available in debian squeeze.
1272 foreach($req as $r) {
1273 if (!System::which($r)) {
1279 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1281 foreach($pref as $r) {
1282 if (!System::which($r)) {
1288 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1295 function clearApacheDataobjectsCache()
1298 // this needs to clear it's own cache along with remote one..
1300 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1302 echo "Clearing Database Cache : http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache\n";
1304 $response = $this->curl($url);
1306 $json = json_decode($response, true);
1308 if(empty($json['data']) || $json['data'] != 'DONE'){
1309 echo "fetching $url\n";
1310 echo "GOT:" . $response. "\n";
1311 echo "Clear DataObjects Cache failed\n";
1318 function clearApacheAssetCache()
1320 echo "Clearing Asset Cache : http://localhost{$this->local_base_url}/Core/Asset\n";
1321 $response = $this->curl(
1322 "http://localhost{$this->local_base_url}/Core/Asset",
1323 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1326 $json = json_decode($response, true);
1328 if(empty($json['success']) || !$json['success']) {
1329 echo $response. "\n";
1330 echo "CURL Clear Asset cache failed\n";
1337 function curl($url, $request = array(), $method = 'GET')
1339 if($method == 'GET'){
1340 $request = http_build_query($request);
1341 $url = $url . "?" . $request;
1344 $ch = curl_init($url);
1346 if ($method == 'POST') {
1348 curl_setopt($ch, CURLOPT_POST, 1);
1349 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1352 curl_setopt($ch, CURLOPT_HTTPHEADER,
1353 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1357 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1359 curl_setopt($ch, CURLOPT_HEADER, false);
1360 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1361 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1362 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1364 $response = curl_exec($ch);
1371 static function verifyExtensions($extensions)
1375 foreach ($extensions as $e){
1377 if(empty($e) || extension_loaded($e)) {
1381 $error[] = "Error: Please install php extension: {$e}";
1387 $ff = HTML_FLexyFramework::get();
1389 $ff->page->jerr(implode('\n', $error));