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',
76 'disable-create-triggers' => array(
77 'desc' => 'So not create the mysql triggers',
83 'json-person' => array(
84 'desc' => 'Person JSON file',
91 'desc' => 'Debug the database',
100 static function cli_opts()
103 $ret = self::$cli_opts;
104 $ff = HTML_FlexyFramework::get();
106 $mods = $a->modulesList();
107 foreach($mods as $m) {
109 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
110 if (!file_exists($fd)) {
116 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
117 $ar = $cls->getStaticProperties();
118 if (isset($ar['cli_opts'])) {
120 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
128 var $disabled = array();
133 var $local_base_url = false;
135 var $emailTemplates = array(
136 'EVENT_ERRORS_REPORT' => array(
137 'bcc_group' => 'Empty Group',
138 'test_class' => 'Pman/Admin/Report/SendEventErrors',
139 'to_group' => 'Administrators',
141 'description' => '9.2 System Error Messages',
142 'template_dir' => '/Pman/Admin/templates/mail/'
144 'ADMIN_PASSWORD_RESET' => array(
145 'bcc_group' => 'Administrators',
146 'test_class' => 'Pman/Core/DataObjects/Core_person',
149 'description' => '9.1 Management System Password Reset',
150 'template_dir' => '/Pman/Core/templates/mail/'
156 var $required_extensions = array(
164 $ff = HTML_FlexyFramework::get();
165 if (!empty($ff->cli)) {
170 parent::getAuth(); // load company!
171 $au = $this->getAuthUser();
172 if (!$au || $au->company()->comptype != 'OWNER') {
173 $this->jerr("Not authenticated", array('authFailure' => true));
175 $this->authUser = $au;
179 function get($args, $opts=array())
181 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
183 $this->checkSystem();
185 $this->verifyExtensions($this->required_extensions);
187 if (class_exists('PDO_DataObjects_Introspection')) {
188 PDO_DataObject_Introspection::$cache = array();
190 echo "Generate DB cache\n";
191 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
192 echo "Generated DB cache\n";
193 $ff = HTML_FlexyFramework::get();
195 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
196 die("Please setup Pman[local_base_url]\n");
199 $this->local_base_url = $ff->Pman['local_base_url'];
201 if(!empty($ff->Core_Notify)){
202 // require_once 'Pman/Core/NotifySmtpCheck.php';
203 // $x = new Pman_Core_NotifySmtpCheck();
207 $this->disabled = explode(',', $ff->disable);
209 //$this->fixSequencesPgsql();exit;
212 if (!empty($opts['debug'])) {
213 DB_DataObject::DebugLevel($opts['debug']);
216 // ask all the modules to verify the opts
217 echo "Checking options\n";
218 $this->checkOpts($opts);
220 $response = $this->curl("http://localhost{$this->local_base_url}/Core/UpdateDatabase/VerifyExtensions");
221 $json = json_decode($response, true);
223 if(empty($json['data']) || $json['data'] != 'DONE'){
224 echo "\nError: Missing php extensions:\n";
226 echo "Please install the above extensions and restart the apache.\n";
232 echo "Checking Setup Requirements\n";
233 require_once 'Pman/Core/UpdateDatabase/VerifyConfig.php';
234 $sq = new Pman_Core_UpdateDatabase_VerifyConfig();
235 $ret = $sq->get($args, $opts);
238 echo implode("\n", $ret) . "\n";
242 // do this first, so the innodb change + utf8 fixes column max sizes
244 // this will trigger errors about freetext indexes - we will have to remove them manually.?
245 // 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..)
247 $this->runExtensions();
250 if (empty($opts['data-only'])) {
253 if (!empty($opts['only-module-sql'])) {
259 $this->runUpdateModulesData();
261 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
262 // make sure we have a good cache...?
264 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
267 $this->runExtensions();
269 $this->clearApacheDataobjectsCache();
271 $this->clearApacheAssetCache();
281 echo "\nUpdate Completed SUCCESS\n";
285 * imports SQL files from all DataObjects directories....
287 * except any matching /migrate/
292 // loop through all the modules, and see if they have a importSQL method?
295 $ff = HTML_Flexyframework::get();
297 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
299 //$this->{'import' . $url['scheme']}($url);
301 $dbtype = $dburl['scheme'];
304 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
309 $ar = $this->modulesList();
314 if(in_array($m, $this->disabled)){
315 echo "module $m is disabled \n";
319 echo "Importing SQL from module $m\n";
320 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
325 // check to see if the class has
329 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
330 if($m != 'Core' && file_exists($file)){
333 $class = "Pman_{$m}_UpdateDatabase";
335 if(method_exists($x, 'importModuleSQL')){
336 echo "Importing SQL from module $m using Module::importModuleSQL\n";
337 $x->opts = $this->opts;
338 $x->rootDir = $this->rootDir;
339 $x->importModuleSQL($dburl);
344 echo "Importing SQL from module $m\n";
347 // if init has been called
349 if (!empty($this->opts['init'])) {
350 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
356 $fd = $this->rootDir. "/Pman/$m/DataObjects";
358 $this->{$dirmethod}($dburl, $fd);
361 // new -- sql directory..
362 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
363 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
364 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
366 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
367 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
371 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
372 if (class_exists('PDO_DataObjects_Introspection')) {
373 PDO_DataObject_Introspection::$cache = array();
375 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
377 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
378 $this->{'fixSequences'. $dbtype}();
391 /** -------------- code to handle importing a whole directory of files into the database ------- **/
394 function importpgsqldir($url, $dir, $disable_triggers = false)
396 $ff = HTML_FlexyFramework::get();
398 require_once 'System.php';
399 $cat = System::which('cat');
400 $psql = System::which('psql');
403 if (!empty($url['pass'])) {
404 putenv("PGPASSWORD=". $url['pass']);
408 ' -h ' . $url['host'] .
409 ' -U' . escapeshellarg($url['user']) .
410 ' ' . basename($url['path']);
413 echo $psql_cmd . "\n" ;
414 echo "scan : $dir\n";
417 $files = array($dir);
422 $files = glob($dir.'/*.sql');
423 uksort($files, 'strcasecmp');
425 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
426 //usort($files, $lsort);
429 foreach($files as $bfn) {
432 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
435 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
436 && !preg_match('#\.pg\.sql#i', basename($bfn))
437 ) { // skip migration scripts at present..
442 if (!preg_match('/pgsql/', basename($dir) )) {
443 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
444 $fn = $this->convertToPG($bfn);
448 // files ending in .pg.sql are native postgres files.. ## depricated
451 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
453 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
469 * mysql - does not support conversions.
473 function importmysqlidir($dburl, $dir) {
474 return $this->importmysqldir($dburl, $dir);
477 function importmysqldir($dburl, $dir)
480 $this->fixMysqlInnodb(); /// run once
482 echo "Import MYSQL :: $dir\n";
485 require_once 'System.php';
486 $cat = System::which('cat');
487 $mysql = System::which('mysql');
491 $mysql_cmd = $mysql .
492 ' -h ' . $dburl['host'] .
493 ' -u' . escapeshellarg($dburl['user']) .
494 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
495 ' ' . basename($dburl['path']);
496 //echo $mysql_cmd . "\n" ;
498 $files = glob($dir.'/*.sql');
499 uksort($files, 'strcasecmp');
502 foreach($files as $fn) {
505 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
508 // .my.sql but not .pg.sql
509 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
510 && !preg_match('#\.my\.sql#i', basename($fn))
511 ) { // skip migration scripts at present..
514 if (!strlen(trim($fn))) {
518 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
520 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
523 $fp = popen($cmd, "r");
526 // send the current file part to the browser
527 $line = trim(fgets($fp, 1024));
532 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
533 echo " ---- {$line}\n"; flush();
537 switch($matches[1]) {
538 case 1017: // cause by renaming table -- old one does not exist..
539 case 1050: // create tables triggers this..
540 case 1060: // Duplicate column name
541 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
542 case 1091: // drop index -- name does not exist.. might hide errors..
544 case 1146: // drop a index on an unknown table.. - happens rarely...
545 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
551 echo " ---- {$line}\n"; flush();
555 // 1051: // Unknown table -- normally drop = add iff exists..
556 echo "File: $fn\n$line\n";
572 * simple regex based convert mysql to pgsql...
574 function convertToPG($src)
576 //echo "Convert $src\n";
578 $fn = $this->tempName('sql');
580 $ret = array( ); // pad it a bit.
581 $extra = array("", "" );
584 foreach(file($src) as $l) {
587 if (!strlen($l) || $l[0] == '#') {
591 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
594 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
595 $tbl = 'shop_' . strtolower($m[1]);
596 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
598 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
599 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
602 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
603 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
604 $extra[] = "create sequence {$tbl}_seq;";
608 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
609 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
612 // enum value -- use the text instead..
614 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
615 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
617 // ignore the alter enum
618 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
622 // UNIQUE KEY .. ignore
623 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
624 $last = array_pop($ret);
625 $ret[] = trim($last, ",");
629 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
633 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
637 // INDEX lookup ..ignore
638 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
639 $last = array_pop($ret);
640 $ret[] = trim($last, ",");
645 // CREATE INDEX ..ignore
646 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
647 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
652 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
654 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
655 $l = preg_replace('# blob#i', ' TEXT', $l);
656 $l = preg_replace('# longtext#i', ' TEXT', $l);
657 $l = preg_replace('# tinyint#i', ' INT', $l);
663 $ret = array_merge($extra,$ret);
664 // echo implode("\n", $ret); exit;
666 file_put_contents($fn, implode("\n", $ret));
672 function checkOpts($opts)
676 foreach($opts as $o=>$v) {
677 if (!preg_match('/^json-/', $o) || empty($v)) {
680 if (!file_exists($v)) {
681 die("File does not exist : OPTION --{$o} = {$v} \n");
685 $modules = array_reverse($this->modulesList());
687 // move 'project' one to the end...
689 foreach ($modules as $module){
690 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
691 if($module == 'Core' || !file_exists($file)){
695 $class = "Pman_{$module}_UpdateDatabase";
697 if(!method_exists($x, 'checkOpts')){
700 $x->checkOpts($opts);
704 static function jsonImportFromArray($opts)
706 foreach($opts as $o=>$v) {
707 if (!preg_match('/^json-/', $o) || empty($v)) {
710 $type = str_replace('_', '-', substr($o,5));
712 $data= json_decode(file_get_contents($v),true);
713 $pg = HTML_FlexyFramework::get()->page;
714 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
724 function runUpdateModulesData()
726 if (class_exists('PDO_DataObjects_Introspection')) {
727 PDO_DataObject_Introspection::$cache = array();
729 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
731 if(!in_array('Core', $this->disabled)){
732 echo "Running jsonImportFromArray\n";
733 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
736 echo "Running updateData on modules\n";
742 $modules = array_reverse($this->modulesList());
744 // move 'project' one to the end...
746 foreach ($modules as $module){
747 if(in_array($module, $this->disabled)){
750 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
751 if($module == 'Core' || !file_exists($file)){
756 $class = "Pman_{$module}_UpdateDatabase";
758 if(!method_exists($x, 'updateData')){
768 function updateDataEnums()
770 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
772 $enum = DB_DataObject::Factory('core_enum');
773 //DB_DAtaObject::debugLevel(1);
778 'name' => 'COMPTYPE',
779 'display_name' => 'Company Types',
780 'is_system_enum' => 1,
784 'display_name' => 'Owner',
785 'seqid' => 999, // last...
786 'is_system_enum' => 1,
793 'name' => 'HtmlEditor.font-family',
794 'display_name' => 'HTML Editor font families',
795 'is_system_enum' => 1,
798 'name' => 'Helvetica,Arial,sans-serif',
799 'display_name' => 'Helvetica',
804 'name' => 'Courier New',
805 'display_name' => 'Courier',
810 'display_name' => 'Tahoma',
814 'name' => 'Times New Roman,serif',
815 'display_name' => 'Times',
820 'display_name' => 'Verdana',
833 function updateDataGroups()
836 $groups = DB_DataObject::factory('core_group');
837 $groups->initGroups();
839 $groups->initDatabase($this,array(
841 'name' => 'bcc-email', // group who are bcc'ed on all requests.
842 'type' => 0, // system
843 'display_name' => 'Standard BCC Group'
846 'name' => 'system-email-from',
847 'type' => 0, // system
848 'display_name' => 'Standard System Email From Group'
851 'name' => 'core-person-signup-bcc',
852 'type' => 0, // system
853 'display_name' => 'Standard Person Signup BCC Group'
856 'name' => 'Empty Group', // use for no bcc emails.
858 'display_name' => 'Standard Empty Group'
865 function updateDataCompanies()
868 // fix comptypes enums..
869 $c = DB_DataObject::Factory('core_company');
871 $c->selectAdd('distinct(comptype) as comptype');
875 comptype != 'undefined'
877 comptype != 'undefine'
881 foreach($c->fetchAll('comptype') as $cts) {
883 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
886 $c = DB_DataObject::Factory('core_enum');
889 //DB_DataObject::debugLevel(1);
891 $c = DB_DataObject::Factory('core_company');
893 UPDATE {$c->tableName()}
895 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
908 function updateDataEmails()
910 foreach ($this->emailTemplates as $k => $mail) {
912 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
922 function initEmails($templateDir, $emails, $mapping = false)
924 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
926 $pg = HTML_FlexyFramework::get()->page;
927 foreach($emails as $name=>$data) {
928 $cm = DB_DataObject::factory('core_email');
929 $update = $cm->get('name', $name);
932 if (empty($cm->bcc_group_id)) {
933 if (empty($data['bcc_group'])) {
934 $this->jerr("missing bcc_group for template $name");
937 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
940 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
943 if (!$g->members('email') && $g->name != 'Empty Group') {
944 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
947 $cm->bcc_group_id = $g->id;
949 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
950 //if (empty($cm->test_class)) {
951 if (empty($data['test_class'])) {
952 $this->jerr("missing test_class for template $name");
955 $cm->test_class = $data['test_class'];
957 if(isset($cm->to_group_id)) {
962 !empty($data['to_group']) &&
963 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
965 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
967 if (empty($gp->id)) {
968 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
971 $cm->to_group_id = $gp->id;
975 isset($data['active']) && !isset($cm->active)
977 $cm->active = $data['active'];
981 * Set description to email.
982 * However we do not update if it is been set.
984 if(empty($cm->description) && !empty($data['description'])){
985 $cm->description = $cm->escape($data['description']);
988 require_once $cm->test_class . '.php';
990 $clsname = str_replace('/','_', $cm->test_class);
992 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
993 $got_it = $method->isStatic();
994 } catch(Exception $e) {
999 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
1003 echo "email: {$name} - checked\n";
1004 continue; /// we do not import the body content of templates that exist...
1011 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1015 'file' => $templateDir. $name .'.html'
1018 if (!empty($data['master'])) {
1019 $opts['master'] = $templateDir . $master .'.html';
1021 require_once 'Pman/Core/Import/Core_email.php';
1022 $x = new Pman_Core_Import_Core_email();
1024 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1026 echo "email: {$name} - CREATED\n";
1031 function updateData()
1034 if (class_exists('PDO_DataObjects_Introspection')) {
1035 PDO_DataObject_Introspection::$cache = array();
1037 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1039 $this->updateDataEnums();
1040 $this->updateDataGroups();
1041 $this->updateDataCompanies();
1043 $this->updateDataEmails();
1045 $c = DB_DataObject::Factory('I18n');
1049 function fixMysqlInnodb()
1052 static $done_check = false;
1058 if (!empty($this->opts['skip-mysql-checks'])) {
1061 // innodb in single files is far more efficient that MYD or one big innodb file.
1062 // first check if database is using this format.
1063 $db = DB_DataObject::factory('core_enum');
1064 $db->query("show variables like 'innodb_file_per_table'");
1066 if ($db->Value == 'OFF') {
1067 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1070 $db = DB_DataObject::factory('core_enum');
1071 $db->query("select version() as version");
1074 if (version_compare($db->version, '5.7', '>=' )) {
1076 $db = DB_DataObject::factory('core_enum');
1077 $db->query("show variables like 'sql_mode'");
1080 $modes = explode(",", $db->Value);
1082 // these are 'new' problems with mysql.
1084 in_array('NO_ZERO_IN_DATE', $modes) ||
1085 in_array('NO_ZERO_DATE', $modes) ||
1086 in_array('STRICT_TRANS_TABLES', $modes) ||
1087 !in_array('ALLOW_INVALID_DATES', $modes)
1089 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".
1090 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1095 $done_check = true;;
1106 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1108 function fixSequencesMysql()
1113 function fixSequencesPgsql()
1117 //DB_DataObject::debugLevel(1);
1118 $cs = DB_DataObject::factory('core_enum');
1122 CASE WHEN strpos(seq_name, '.') > 0 THEN
1125 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1128 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1129 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1133 n.nspname AS schema_name,
1134 c.relname AS table_name,
1135 a.attname AS column_name,
1136 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1138 JOIN pg_attribute a ON (c.oid=a.attrelid)
1139 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1140 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1141 WHERE has_schema_privilege(n.oid,'USAGE')
1142 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1143 AND has_table_privilege(c.oid,'SELECT')
1144 AND (NOT a.attisdropped)
1145 AND d.adsrc ~ '^nextval'
1149 CASE WHEN strpos(seq_name, '.') > 0 THEN
1150 substring(seq_name, 1,strpos(seq_name,'.')-1)
1155 GROUP BY seq_name HAVING count(*)=1
1158 while ($cs->fetch()) {
1161 foreach($cmds as $cmd) {
1162 $cs = DB_DataObject::factory('core_enum');
1166 $cs = DB_DataObject::factory('core_enum');
1168 SELECT 'SELECT SETVAL(' ||
1169 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1170 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1176 WHERE S.relkind = 'S'
1178 AND D.refobjid = T.oid
1179 AND D.refobjid = C.attrelid
1180 AND D.refobjsubid = C.attnum
1181 AND NS.oid = T.relnamespace
1185 while ($cs->fetch()) {
1188 foreach($cmds as $cmd) {
1189 $cs = DB_DataObject::factory('core_enum');
1196 var $extensions = array(
1201 function runExtensions()
1204 $ff = HTML_Flexyframework::get();
1206 $dburl = parse_url($ff->database);
1208 $dbtype = $dburl['scheme'];
1209 $dbtype = ($dbtype == 'mysqli') ? 'mysql' : $dbtype;
1211 foreach($this->extensions as $ext) {
1213 $scls = ucfirst($dbtype). $ext;
1214 $cls = __CLASS__ . '_'. $scls;
1215 $fn = implode('/',explode('_', $cls)).'.php';
1217 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1228 function checkSystem($req = false, $pref = false)
1230 // most of these are from File_Convert...
1232 // these are required - and have simple dependancies.
1233 require_once 'System.php';
1234 $req = $req !== false ? $req : array(
1239 'rsvg-convert', //librsvg2-bin
1242 'gifsicle', // used for gif conversions
1247 // these are prefered - but may have complicated depenacies
1248 $pref = $pref !== false ? $pref : array(
1252 'html2text', // not availabe in debian squeeze
1253 'pdftocairo', //poppler-utils - not available in debian squeeze.
1263 foreach($req as $r) {
1264 if (!System::which($r)) {
1270 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1272 foreach($pref as $r) {
1273 if (!System::which($r)) {
1279 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1286 function clearApacheDataobjectsCache()
1289 // this needs to clear it's own cache along with remote one..
1291 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1293 echo "Clearing Database Cache : http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache\n";
1295 $response = $this->curl($url);
1297 $json = json_decode($response, true);
1299 if(empty($json['data']) || $json['data'] != 'DONE'){
1300 echo "fetching $url\n";
1301 echo "GOT:" . $response. "\n";
1302 echo "Clear DataObjects Cache failed\n";
1309 function clearApacheAssetCache()
1311 echo "Clearing Asset Cache : http://localhost{$this->local_base_url}/Core/Asset\n";
1312 $response = $this->curl(
1313 "http://localhost{$this->local_base_url}/Core/Asset",
1314 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1317 $json = json_decode($response, true);
1319 if(empty($json['success']) || !$json['success']) {
1320 echo $response. "\n";
1321 echo "CURL Clear Asset cache failed\n";
1328 function curl($url, $request = array(), $method = 'GET')
1330 if($method == 'GET'){
1331 $request = http_build_query($request);
1332 $url = $url . "?" . $request;
1335 $ch = curl_init($url);
1337 if ($method == 'POST') {
1339 curl_setopt($ch, CURLOPT_POST, 1);
1340 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1343 curl_setopt($ch, CURLOPT_HTTPHEADER,
1344 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1348 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1350 curl_setopt($ch, CURLOPT_HEADER, false);
1351 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1352 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1353 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1355 $response = curl_exec($ch);
1362 static function verifyExtensions($extensions)
1366 foreach ($extensions as $e){
1368 if(empty($e) || extension_loaded($e)) {
1372 $error[] = "Error: Please install php extension: {$e}";
1378 $ff = HTML_FLexyFramework::get();
1380 $ff->page->jerr(implode('\n', $error));