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(
171 $ff = HTML_FlexyFramework::get();
172 if (!empty($ff->cli)) {
177 parent::getAuth(); // load company!
178 $au = $this->getAuthUser();
179 if (!$au || $au->company()->comptype != 'OWNER') {
180 $this->jerror("LOGIN-NOAUTH", "Not authenticated", array('authFailure' => true));
182 $this->authUser = $au;
186 function get($args, $opts=array())
188 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
190 $this->checkSystem();
192 $this->verifyExtensions($this->required_extensions);
194 if (class_exists('PDO_DataObjects_Introspection')) {
195 PDO_DataObject_Introspection::$cache = array();
197 echo "Generate DB cache\n";
198 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
199 echo "Generated DB cache\n";
200 $ff = HTML_FlexyFramework::get();
202 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
203 die("Please setup Pman[local_base_url]\n");
206 $this->local_base_url = $ff->Pman['local_base_url'];
208 if(!empty($ff->Core_Notify)){
209 // require_once 'Pman/Core/NotifySmtpCheck.php';
210 // $x = new Pman_Core_NotifySmtpCheck();
214 $this->disabled = explode(',', $ff->disable);
216 //$this->fixSequencesPgsql();exit;
219 if (!empty($opts['debug'])) {
220 DB_DataObject::DebugLevel($opts['debug']);
223 // ask all the modules to verify the opts
224 echo "Checking options\n";
225 $this->checkOpts($opts);
227 $response = $this->curl("http://localhost{$this->local_base_url}/Core/UpdateDatabase/VerifyExtensions");
228 $json = json_decode($response, true);
230 if(empty($json['data']) || $json['data'] != 'DONE'){
231 echo "\nError: Missing php extensions:\n";
233 echo "Please install the above extensions and restart the apache.\n";
239 echo "Checking Setup Requirements\n";
240 require_once 'Pman/Core/UpdateDatabase/VerifyConfig.php';
241 $sq = new Pman_Core_UpdateDatabase_VerifyConfig();
242 $ret = $sq->get($args, $opts);
245 echo implode("\n", $ret) . "\n";
249 // do this first, so the innodb change + utf8 fixes column max sizes
251 // this will trigger errors about freetext indexes - we will have to remove them manually.?
252 // 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 echo "Run extensions\n";
255 $this->runExtensions();
258 if (empty($opts['data-only'])) {
262 if (!empty($opts['only-module-sql'])) {
266 echo "run Update Modules Data\n";
268 $this->runUpdateModulesData();
270 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
271 // make sure we have a good cache...?
273 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
276 $this->runExtensions();
278 $this->clearApacheDataobjectsCache();
280 $this->clearApacheAssetCache();
290 echo "\nUpdate Completed SUCCESS\n";
294 * imports SQL files from all DataObjects directories....
296 * except any matching /migrate/
301 // loop through all the modules, and see if they have a importSQL method?
304 $ff = HTML_Flexyframework::get();
306 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
308 //$this->{'import' . $url['scheme']}($url);
310 $dbtype = $dburl['scheme'];
313 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
318 $ar = $this->modulesList();
323 if(in_array($m, $this->disabled)){
324 echo "module $m is disabled \n";
328 echo "Importing SQL from module $m\n";
329 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
334 // check to see if the class has
338 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
339 if($m != 'Core' && file_exists($file)){
342 $class = "Pman_{$m}_UpdateDatabase";
344 if(method_exists($x, 'importModuleSQL')){
345 echo "Importing SQL from module $m using Module::importModuleSQL\n";
346 $x->opts = $this->opts;
347 $x->rootDir = $this->rootDir;
348 $x->importModuleSQL($dburl);
353 echo "Importing SQL from module $m\n";
356 // if init has been called
358 if (!empty($this->opts['init'])) {
359 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
365 $fd = $this->rootDir. "/Pman/$m/DataObjects";
367 $this->{$dirmethod}($dburl, $fd);
370 // new -- sql directory..
371 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
372 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
373 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
375 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
376 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
380 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
381 if (class_exists('PDO_DataObjects_Introspection')) {
382 PDO_DataObject_Introspection::$cache = array();
384 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
386 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
387 $this->{'fixSequences'. $dbtype}();
400 /** -------------- code to handle importing a whole directory of files into the database ------- **/
403 function importpgsqldir($url, $dir, $disable_triggers = false)
405 $ff = HTML_FlexyFramework::get();
407 require_once 'System.php';
408 $cat = System::which('cat');
409 $psql = System::which('psql');
412 if (!empty($url['pass'])) {
413 putenv("PGPASSWORD=". $url['pass']);
417 ' -h ' . $url['host'] .
418 ' -U' . escapeshellarg($url['user']) .
419 ' ' . basename($url['path']);
422 echo $psql_cmd . "\n" ;
423 echo "scan : $dir\n";
426 $files = array($dir);
431 $files = glob($dir.'/*.sql');
432 uksort($files, 'strcasecmp');
434 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
435 //usort($files, $lsort);
438 foreach($files as $bfn) {
441 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
444 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
445 && !preg_match('#\.pg\.sql#i', basename($bfn))
446 ) { // skip migration scripts at present..
451 if (!preg_match('/pgsql/', basename($dir) )) {
452 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
453 $fn = $this->convertToPG($bfn);
457 // files ending in .pg.sql are native postgres files.. ## depricated
460 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
462 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
478 * mysql - does not support conversions.
482 function importmysqlidir($dburl, $dir) {
483 return $this->importmysqldir($dburl, $dir);
486 function importmysqldir($dburl, $dir)
489 $this->fixMysqlInnodb(); /// run once
491 echo "Import MYSQL :: $dir\n";
494 require_once 'System.php';
495 $cat = System::which('cat');
496 $mysql = System::which('mysql');
500 $mysql_cmd = $mysql .
501 ' -h ' . $dburl['host'] .
502 (empty($dburl['port']) ? '' : " -P{$dburl['port']} ") .
503 ' -u' . escapeshellarg($dburl['user']) .
504 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
505 ' ' . basename($dburl['path']);
506 //echo $mysql_cmd . "\n" ;
508 $files = glob($dir.'/*.sql');
509 uksort($files, 'strcasecmp');
512 foreach($files as $fn) {
515 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
518 // .my.sql but not .pg.sql
519 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
520 && !preg_match('#\.my\.sql#i', basename($fn))
521 ) { // skip migration scripts at present..
524 if (!strlen(trim($fn))) {
528 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
530 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
533 $fp = popen($cmd, "r");
536 // send the current file part to the browser
537 $line = trim(fgets($fp, 1024));
542 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
543 echo " ---- {$line}\n"; flush();
547 switch($matches[1]) {
548 case 1017: // cause by renaming table -- old one does not exist..
549 case 1050: // create tables triggers this..
550 case 1060: // Duplicate column name
551 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
552 case 1091: // drop index -- name does not exist.. might hide errors..
554 case 1146: // drop a index on an unknown table.. - happens rarely...
555 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
561 echo " ---- {$line}\n"; flush();
565 // 1051: // Unknown table -- normally drop = add iff exists..
566 echo "File: $fn\n$line\n";
582 * simple regex based convert mysql to pgsql...
584 function convertToPG($src)
586 //echo "Convert $src\n";
588 $fn = $this->tempName('sql');
590 $ret = array( ); // pad it a bit.
591 $extra = array("", "" );
594 foreach(file($src) as $l) {
597 if (!strlen($l) || $l[0] == '#') {
601 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
604 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
605 $tbl = 'shop_' . strtolower($m[1]);
606 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
608 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
609 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
612 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
613 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
614 $extra[] = "create sequence {$tbl}_seq;";
617 if ($tbl && preg_match('#engine=\S+#i', $l, $m)) {
618 $l = preg_replace('#engine=\S+#i', '', $l);
621 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
622 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
625 // enum value -- use the text instead..
627 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
628 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
630 // ignore the alter enum
631 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
635 // UNIQUE KEY .. ignore
636 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
637 $last = array_pop($ret);
638 $ret[] = trim($last, ",");
642 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
646 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
650 // INDEX lookup ..ignore
651 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
652 $last = array_pop($ret);
653 $ret[] = trim($last, ",");
658 // CREATE INDEX ..ignore
659 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
660 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
665 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
667 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
668 $l = preg_replace('# blob#i', ' TEXT', $l);
669 $l = preg_replace('# longtext#i', ' TEXT', $l);
670 $l = preg_replace('# tinyint#i', ' INT', $l);
676 $ret = array_merge($extra,$ret);
677 // echo implode("\n", $ret); exit;
679 file_put_contents($fn, implode("\n", $ret));
685 function checkOpts($opts)
689 foreach($opts as $o=>$v) {
690 if (!preg_match('/^json-/', $o) || empty($v)) {
693 if (!file_exists($v)) {
694 die("File does not exist : OPTION --{$o} = {$v} \n");
698 $modules = array_reverse($this->modulesList());
700 // move 'project' one to the end...
702 foreach ($modules as $module){
703 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
704 if($module == 'Core' || !file_exists($file)){
708 $class = "Pman_{$module}_UpdateDatabase";
710 if(!method_exists($x, 'checkOpts')){
713 $x->checkOpts($opts);
717 static function jsonImportFromArray($opts)
719 foreach($opts as $o=>$v) {
720 if (!preg_match('/^json-/', $o) || empty($v)) {
723 $type = str_replace('_', '-', substr($o,5));
725 $data= json_decode(file_get_contents($v),true);
726 $pg = HTML_FlexyFramework::get()->page;
727 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
737 function runUpdateModulesData()
739 if (class_exists('PDO_DataObjects_Introspection')) {
740 PDO_DataObject_Introspection::$cache = array();
742 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
744 if(!in_array('Core', $this->disabled)){
745 echo "Running jsonImportFromArray\n";
746 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
749 echo "Running updateData on modules\n";
755 $modules = array_reverse($this->modulesList());
757 // move 'project' one to the end...
759 foreach ($modules as $module){
760 if(in_array($module, $this->disabled)){
763 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
764 if($module == 'Core' || !file_exists($file)){
769 $class = "Pman_{$module}_UpdateDatabase";
771 if(!method_exists($x, 'updateData')){
774 $x->rootDir = $this->rootDir;
782 function updateDataEnums()
784 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
786 $enum = DB_DataObject::Factory('core_enum');
787 //DB_DAtaObject::debugLevel(1);
792 'name' => 'COMPTYPE',
793 'display_name' => 'Company Types',
794 'is_system_enum' => 1,
798 'display_name' => 'Owner',
799 'seqid' => 999, // last...
800 'is_system_enum' => 1,
807 'name' => 'HtmlEditor.font-family',
808 'display_name' => 'HTML Editor font families',
809 'is_system_enum' => 1,
812 'name' => 'Helvetica,Arial,sans-serif',
813 'display_name' => 'Helvetica',
818 'name' => 'Courier New',
819 'display_name' => 'Courier',
824 'display_name' => 'Tahoma',
828 'name' => 'Times New Roman,serif',
829 'display_name' => 'Times',
834 'display_name' => 'Verdana',
847 function updateDataGroups()
850 $groups = DB_DataObject::factory('core_group');
851 $groups->initGroups();
853 $groups->initDatabase($this,array(
855 'name' => 'bcc-email', // group who are bcc'ed on all requests.
856 'type' => 0, // system
858 'display_name' => 'Standard BCC Group'
861 'name' => 'system-email-from',
862 'type' => 0, // system
864 'display_name' => 'Standard System Email From Group'
867 'name' => 'core-person-signup-bcc',
868 'type' => 0, // system
870 'display_name' => 'Standard Person Signup BCC Group'
873 'name' => 'Empty Group', // use for no bcc emails.
876 'display_name' => 'Standard Empty Group'
883 function updateDataCompanies()
886 // fix comptypes enums..
887 $c = DB_DataObject::Factory('core_company');
889 $c->selectAdd('distinct(comptype) as comptype');
893 comptype != 'undefined'
895 comptype != 'undefine'
899 foreach($c->fetchAll('comptype') as $cts) {
901 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
904 $c = DB_DataObject::Factory('core_enum');
907 //DB_DataObject::debugLevel(1);
909 $c = DB_DataObject::Factory('core_company');
911 UPDATE {$c->tableName()}
913 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
926 function updateDataEmails()
928 if (!empty($this->opts['skip-email-import'])) {
931 foreach ($this->emailTemplates as $k => $mail) {
934 !empty($mail['template_dir']) ? "{$this->rootDir}{$mail['template_dir']}" : '',
941 function initEmails($templateDir, $emails, $mapping = false)
943 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
945 $pg = HTML_FlexyFramework::get()->page;
946 foreach($emails as $name=>$data) {
947 $cm = DB_DataObject::factory('core_email');
948 $update = $cm->get('name', $name);
951 if (empty($cm->bcc_group_id)) {
952 if (empty($data['bcc_group'])) {
953 $this->jerr("missing bcc_group for template $name");
956 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
958 if (empty($g->id)) { // Admin group as bcc will not have any member at initialization.
959 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
962 if (!$g->members('email') && $g->name != 'Empty Group' && $g->name != 'Administrators') {
963 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
966 $cm->bcc_group_id = $g->id;
968 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
969 //if (empty($cm->test_class)) {
970 if (empty($data['test_class'])) {
971 $this->jerr("missing test_class for template $name");
974 $cm->test_class = $data['test_class'];
976 if(isset($cm->to_group_id)) {
981 !empty($data['to_group']) &&
982 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
984 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
986 if (empty($gp->id)) {
987 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
990 $cm->to_group_id = $gp->id;
994 isset($data['active']) && !isset($cm->active)
996 $cm->active = $data['active'];
1000 * Set description to email.
1001 * However we do not update if it is been set.
1003 if(empty($cm->description) && !empty($data['description'])){
1004 $cm->description = $cm->escape($data['description']);
1007 require_once $cm->test_class . '.php';
1009 $clsname = str_replace('/','_', $cm->test_class);
1011 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
1012 $got_it = $method->isStatic();
1013 } catch(Exception $e) {
1018 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
1022 echo "email: {$name} - checked\n";
1023 continue; /// we do not import the body content of templates that exist...
1030 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1035 if (!empty($templateDir)) {
1036 $opts['file'] = $templateDir. $name .'.html';
1038 if (!empty($data['raw_content'])) {
1039 $opts['raw_content'] = $data['raw_content'];
1040 $opts['name'] = $name;
1042 if (!empty($data['master'])) {
1043 $opts['master'] = $templateDir . $master .'.html';
1045 require_once 'Pman/Core/Import/Core_email.php';
1046 $x = new Pman_Core_Import_Core_email();
1048 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1050 echo "email: {$name} - CREATED\n";
1055 function updateData()
1058 if (class_exists('PDO_DataObjects_Introspection')) {
1059 PDO_DataObject_Introspection::$cache = array();
1061 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1063 $this->updateDataEnums();
1064 $this->updateDataGroups();
1065 $this->updateDataCompanies();
1067 $this->updateDataEmails();
1069 $c = DB_DataObject::Factory('I18n');
1073 function fixMysqlInnodb()
1076 static $done_check = false;
1082 if (!empty($this->opts['skip-mysql-checks'])) {
1085 // innodb in single files is far more efficient that MYD or one big innodb file.
1086 // first check if database is using this format.
1087 $db = DB_DataObject::factory('core_enum');
1088 $db->query("show variables like 'innodb_file_per_table'");
1090 if ($db->Value == 'OFF') {
1091 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1094 $db = DB_DataObject::factory('core_enum');
1095 $db->query("select version() as version");
1098 if (version_compare($db->version, '5.7', '>=' )) {
1100 $db = DB_DataObject::factory('core_enum');
1101 $db->query("show variables like 'sql_mode'");
1104 $modes = explode(",", $db->Value);
1106 // these are 'new' problems with mysql.
1108 in_array('NO_ZERO_IN_DATE', $modes) ||
1109 in_array('NO_ZERO_DATE', $modes) ||
1110 in_array('STRICT_TRANS_TABLES', $modes) ||
1111 !in_array('ALLOW_INVALID_DATES', $modes)
1113 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".
1114 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1119 $done_check = true;;
1130 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1132 function fixSequencesMysql()
1137 function fixSequencesPgsql()
1141 //DB_DataObject::debugLevel(1);
1142 $cs = DB_DataObject::factory('core_enum');
1146 CASE WHEN strpos(seq_name, '.') > 0 THEN
1149 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1152 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1153 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1157 n.nspname AS schema_name,
1158 c.relname AS table_name,
1159 a.attname AS column_name,
1160 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1162 JOIN pg_attribute a ON (c.oid=a.attrelid)
1163 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1164 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1165 WHERE has_schema_privilege(n.oid,'USAGE')
1166 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1167 AND has_table_privilege(c.oid,'SELECT')
1168 AND (NOT a.attisdropped)
1169 AND d.adsrc ~ '^nextval'
1173 CASE WHEN strpos(seq_name, '.') > 0 THEN
1174 substring(seq_name, 1,strpos(seq_name,'.')-1)
1179 GROUP BY seq_name HAVING count(*)=1
1182 while ($cs->fetch()) {
1185 foreach($cmds as $cmd) {
1186 $cs = DB_DataObject::factory('core_enum');
1190 $cs = DB_DataObject::factory('core_enum');
1192 SELECT 'SELECT SETVAL(' ||
1193 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1194 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1200 WHERE S.relkind = 'S'
1202 AND D.refobjid = T.oid
1203 AND D.refobjid = C.attrelid
1204 AND D.refobjsubid = C.attnum
1205 AND NS.oid = T.relnamespace
1209 while ($cs->fetch()) {
1212 foreach($cmds as $cmd) {
1213 $cs = DB_DataObject::factory('core_enum');
1220 var $extensions = array(
1225 function runExtensions()
1228 $ff = HTML_Flexyframework::get();
1230 $dburl = parse_url($ff->database);
1232 $dbtype = $dburl['scheme'];
1233 $dbtype = ($dbtype == 'mysqli') ? 'mysql' : $dbtype;
1235 foreach($this->extensions as $ext) {
1237 $scls = ucfirst($dbtype). $ext;
1238 $cls = __CLASS__ . '_'. $scls;
1239 $fn = implode('/',explode('_', $cls)).'.php';
1241 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1244 echo "Running : {$fn}\n";
1253 function checkSystem($req = false, $pref = false)
1255 // most of these are from File_Convert...
1257 // these are required - and have simple dependancies.
1258 require_once 'System.php';
1259 $req = $req !== false ? $req : array(
1264 'rsvg-convert', //librsvg2-bin
1267 'gifsicle', // used for gif conversions
1271 // these are prefered - but may have complicated depenacies
1272 $pref = $pref !== false ? $pref : array(
1276 'html2text', // not availabe in debian squeeze
1277 'pdftocairo', //poppler-utils - not available in debian squeeze.
1287 foreach($req as $r) {
1288 if (!System::which($r)) {
1294 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1296 foreach($pref as $r) {
1297 if (!System::which($r)) {
1303 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1310 function clearApacheDataobjectsCache()
1313 // this needs to clear it's own cache along with remote one..
1315 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1317 echo "Clearing Database Cache : http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache\n";
1319 $response = $this->curl($url);
1321 $json = json_decode($response, true);
1323 if(empty($json['data']) || $json['data'] != 'DONE'){
1324 echo "fetching $url\n";
1325 echo "GOT:" . $response. "\n";
1326 echo "Clear DataObjects Cache failed\n";
1333 function clearApacheAssetCache()
1335 echo "Clearing Asset Cache : http://localhost{$this->local_base_url}/Core/Asset\n";
1336 $response = $this->curl(
1337 "http://localhost{$this->local_base_url}/Core/Asset",
1338 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1341 $json = json_decode($response, true);
1343 if(empty($json['success']) || !$json['success']) {
1344 echo $response. "\n";
1345 echo "CURL Clear Asset cache failed\n";
1352 function curl($url, $request = array(), $method = 'GET')
1354 if($method == 'GET'){
1355 $request = http_build_query($request);
1356 $url = $url . "?" . $request;
1359 $ch = curl_init($url);
1361 if ($method == 'POST') {
1363 curl_setopt($ch, CURLOPT_POST, 1);
1364 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1367 curl_setopt($ch, CURLOPT_HTTPHEADER,
1368 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1372 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1374 curl_setopt($ch, CURLOPT_HEADER, false);
1375 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1376 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1377 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1379 $response = curl_exec($ch);
1386 static function verifyExtensions($extensions)
1390 foreach ($extensions as $e){
1392 if(empty($e) || extension_loaded($e)) {
1396 $error[] = "Error: Please install php extension: {$e}";
1402 $ff = HTML_FLexyFramework::get();
1404 $ff->page->jerr(implode('\n', $error));