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',
77 'json-person' => array(
78 'desc' => 'Person JSON file',
85 'desc' => 'Debug the database',
93 var $emailTemplates = array(
94 'ADMIN_PASSWORD_RESET' => array(
95 'bcc_group' => 'Administrators',
96 'test_class' => 'Pman/Core/DataObjects/Core_person',
97 'to_group' => 'Review Submission Group',
99 'description' => '3. Application submitted - email to admin with deposit slip'
101 static function cli_opts()
104 $ret = self::$cli_opts;
105 $ff = HTML_FlexyFramework::get();
107 $mods = $a->modulesList();
108 foreach($mods as $m) {
110 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
111 if (!file_exists($fd)) {
117 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
118 $ar = $cls->getStaticProperties();
119 if (isset($ar['cli_opts'])) {
121 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
129 var $disabled = array();
134 var $local_base_url = false;
136 var $emailTemplates = array(
137 'EVENT_ERRORS_REPORT' => array(
138 'bcc_group' => 'Empty Group',
139 'test_class' => 'Pman/Admin/Report/SendEventErrors',
140 'to_group' => 'Administrators',
142 'description' => '9. System Error Messages',
143 'template_dir' => '/Pman/Admin/templates/mail/'
147 var $required_extensions = array(
155 $ff = HTML_FlexyFramework::get();
156 if (!empty($ff->cli)) {
161 parent::getAuth(); // load company!
162 $au = $this->getAuthUser();
163 if (!$au || $au->company()->comptype != 'OWNER') {
164 $this->jerr("Not authenticated", array('authFailure' => true));
166 $this->authUser = $au;
170 function get($args, $opts=array())
172 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
174 $this->checkSystem();
176 $this->verifyExtensions($this->required_extensions);
178 if (class_exists('PDO_DataObjects_Introspection')) {
179 PDO_DataObject_Introspection::$cache = array();
181 echo "Generate DB cache\n";
182 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
183 echo "Generated DB cache\n";
184 $ff = HTML_FlexyFramework::get();
186 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
187 die("Please setup Pman[local_base_url]\n");
190 $this->local_base_url = $ff->Pman['local_base_url'];
192 if(!empty($ff->Core_Notify)){
193 // require_once 'Pman/Core/NotifySmtpCheck.php';
194 // $x = new Pman_Core_NotifySmtpCheck();
198 $this->disabled = explode(',', $ff->disable);
200 //$this->fixSequencesPgsql();exit;
203 if (!empty($opts['debug'])) {
204 DB_DataObject::DebugLevel($opts['debug']);
207 // ask all the modules to verify the opts
208 echo "Checking options\n";
209 $this->checkOpts($opts);
211 $response = $this->curl("http://localhost{$this->local_base_url}/Core/UpdateDatabase/VerifyExtensions");
212 $json = json_decode($response, true);
214 if(empty($json['data']) || $json['data'] != 'DONE'){
215 echo "\nError: Missing php extensions:\n";
217 echo "Please install the above extensions and restart the apache.\n";
223 echo "Checking Setup Requirements\n";
224 require_once 'Pman/Core/UpdateDatabase/VerifyConfig.php';
225 $sq = new Pman_Core_UpdateDatabase_VerifyConfig();
226 $ret = $sq->get($args, $opts);
229 echo implode("\n", $ret) . "\n";
233 // do this first, so the innodb change + utf8 fixes column max sizes
235 // this will trigger errors about freetext indexes - we will have to remove them manually.?
236 // 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..)
238 $this->runExtensions();
241 if (empty($opts['data-only'])) {
244 if (!empty($opts['only-module-sql'])) {
250 $this->runUpdateModulesData();
252 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
253 // make sure we have a good cache...?
255 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
258 $this->runExtensions();
260 $this->clearApacheDataobjectsCache();
262 $this->clearApacheAssetCache();
266 echo "\nUpdate Completed SUCCESS\n";
270 * imports SQL files from all DataObjects directories....
272 * except any matching /migrate/
277 // loop through all the modules, and see if they have a importSQL method?
280 $ff = HTML_Flexyframework::get();
282 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
284 //$this->{'import' . $url['scheme']}($url);
286 $dbtype = $dburl['scheme'];
289 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
294 $ar = $this->modulesList();
299 if(in_array($m, $this->disabled)){
300 echo "module $m is disabled \n";
304 echo "Importing SQL from module $m\n";
305 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
310 // check to see if the class has
314 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
315 if($m != 'Core' && file_exists($file)){
318 $class = "Pman_{$m}_UpdateDatabase";
320 if(method_exists($x, 'importModuleSQL')){
321 echo "Importing SQL from module $m using Module::importModuleSQL\n";
322 $x->opts = $this->opts;
323 $x->rootDir = $this->rootDir;
324 $x->importModuleSQL($dburl);
329 echo "Importing SQL from module $m\n";
332 // if init has been called
334 if (!empty($this->opts['init'])) {
335 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
341 $fd = $this->rootDir. "/Pman/$m/DataObjects";
343 $this->{$dirmethod}($dburl, $fd);
346 // new -- sql directory..
347 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
348 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
349 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
351 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
352 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
356 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
357 if (class_exists('PDO_DataObjects_Introspection')) {
358 PDO_DataObject_Introspection::$cache = array();
360 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
362 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
363 $this->{'fixSequences'. $dbtype}();
376 /** -------------- code to handle importing a whole directory of files into the database ------- **/
379 function importpgsqldir($url, $dir, $disable_triggers = false)
381 $ff = HTML_FlexyFramework::get();
383 require_once 'System.php';
384 $cat = System::which('cat');
385 $psql = System::which('psql');
388 if (!empty($url['pass'])) {
389 putenv("PGPASSWORD=". $url['pass']);
393 ' -h ' . $url['host'] .
394 ' -U' . escapeshellarg($url['user']) .
395 ' ' . basename($url['path']);
398 echo $psql_cmd . "\n" ;
399 echo "scan : $dir\n";
402 $files = array($dir);
407 $files = glob($dir.'/*.sql');
408 uksort($files, 'strcasecmp');
410 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
411 //usort($files, $lsort);
414 foreach($files as $bfn) {
417 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
420 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
421 && !preg_match('#\.pg\.sql#i', basename($bfn))
422 ) { // skip migration scripts at present..
427 if (!preg_match('/pgsql/', basename($dir) )) {
428 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
429 $fn = $this->convertToPG($bfn);
433 // files ending in .pg.sql are native postgres files.. ## depricated
436 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
438 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
454 * mysql - does not support conversions.
458 function importmysqlidir($dburl, $dir) {
459 return $this->importmysqldir($dburl, $dir);
462 function importmysqldir($dburl, $dir)
465 $this->fixMysqlInnodb(); /// run once
467 echo "Import MYSQL :: $dir\n";
470 require_once 'System.php';
471 $cat = System::which('cat');
472 $mysql = System::which('mysql');
476 $mysql_cmd = $mysql .
477 ' -h ' . $dburl['host'] .
478 ' -u' . escapeshellarg($dburl['user']) .
479 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
480 ' ' . basename($dburl['path']);
481 //echo $mysql_cmd . "\n" ;
483 $files = glob($dir.'/*.sql');
484 uksort($files, 'strcasecmp');
487 foreach($files as $fn) {
490 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
493 // .my.sql but not .pg.sql
494 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
495 && !preg_match('#\.my\.sql#i', basename($fn))
496 ) { // skip migration scripts at present..
499 if (!strlen(trim($fn))) {
503 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
505 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
508 $fp = popen($cmd, "r");
511 // send the current file part to the browser
512 $line = trim(fgets($fp, 1024));
517 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
518 echo " ---- {$line}\n"; flush();
522 switch($matches[1]) {
523 case 1017: // cause by renaming table -- old one does not exist..
524 case 1050: // create tables triggers this..
525 case 1060: // Duplicate column name
526 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
527 case 1091: // drop index -- name does not exist.. might hide errors..
529 case 1146: // drop a index on an unknown table.. - happens rarely...
530 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
536 echo " ---- {$line}\n"; flush();
540 // 1051: // Unknown table -- normally drop = add iff exists..
541 echo "File: $fn\n$line\n";
557 * simple regex based convert mysql to pgsql...
559 function convertToPG($src)
561 //echo "Convert $src\n";
563 $fn = $this->tempName('sql');
565 $ret = array( ); // pad it a bit.
566 $extra = array("", "" );
569 foreach(file($src) as $l) {
572 if (!strlen($l) || $l[0] == '#') {
576 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
579 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
580 $tbl = 'shop_' . strtolower($m[1]);
581 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
583 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
584 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
587 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
588 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
589 $extra[] = "create sequence {$tbl}_seq;";
593 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
594 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
597 // enum value -- use the text instead..
599 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
600 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
602 // ignore the alter enum
603 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
607 // UNIQUE KEY .. ignore
608 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
609 $last = array_pop($ret);
610 $ret[] = trim($last, ",");
614 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
618 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
622 // INDEX lookup ..ignore
623 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
624 $last = array_pop($ret);
625 $ret[] = trim($last, ",");
630 // CREATE INDEX ..ignore
631 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
632 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
637 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
639 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
640 $l = preg_replace('# blob#i', ' TEXT', $l);
641 $l = preg_replace('# longtext#i', ' TEXT', $l);
642 $l = preg_replace('# tinyint#i', ' INT', $l);
648 $ret = array_merge($extra,$ret);
649 // echo implode("\n", $ret); exit;
651 file_put_contents($fn, implode("\n", $ret));
657 function checkOpts($opts)
661 foreach($opts as $o=>$v) {
662 if (!preg_match('/^json-/', $o) || empty($v)) {
665 if (!file_exists($v)) {
666 die("File does not exist : OPTION --{$o} = {$v} \n");
670 $modules = array_reverse($this->modulesList());
672 // move 'project' one to the end...
674 foreach ($modules as $module){
675 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
676 if($module == 'Core' || !file_exists($file)){
680 $class = "Pman_{$module}_UpdateDatabase";
682 if(!method_exists($x, 'checkOpts')){
685 $x->checkOpts($opts);
689 static function jsonImportFromArray($opts)
691 foreach($opts as $o=>$v) {
692 if (!preg_match('/^json-/', $o) || empty($v)) {
695 $type = str_replace('_', '-', substr($o,5));
697 $data= json_decode(file_get_contents($v),true);
698 $pg = HTML_FlexyFramework::get()->page;
699 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
709 function runUpdateModulesData()
711 if (class_exists('PDO_DataObjects_Introspection')) {
712 PDO_DataObject_Introspection::$cache = array();
714 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
716 if(!in_array('Core', $this->disabled)){
717 echo "Running jsonImportFromArray\n";
718 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
721 echo "Running updateData on modules\n";
727 $modules = array_reverse($this->modulesList());
729 // move 'project' one to the end...
731 foreach ($modules as $module){
732 if(in_array($module, $this->disabled)){
735 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
736 if($module == 'Core' || !file_exists($file)){
741 $class = "Pman_{$module}_UpdateDatabase";
743 if(!method_exists($x, 'updateData')){
753 function updateDataEnums()
755 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
757 $enum = DB_DataObject::Factory('core_enum');
758 //DB_DAtaObject::debugLevel(1);
763 'name' => 'COMPTYPE',
764 'display_name' => 'Company Types',
765 'is_system_enum' => 1,
769 'display_name' => 'Owner',
770 'seqid' => 999, // last...
771 'is_system_enum' => 1,
778 'name' => 'HtmlEditor.font-family',
779 'display_name' => 'HTML Editor font families',
780 'is_system_enum' => 1,
783 'name' => 'Helvetica,Arial,sans-serif',
784 'display_name' => 'Helvetica',
789 'name' => 'Courier New',
790 'display_name' => 'Courier',
795 'display_name' => 'Tahoma',
799 'name' => 'Times New Roman,serif',
800 'display_name' => 'Times',
805 'display_name' => 'Verdana',
818 function updateDataGroups()
821 $groups = DB_DataObject::factory('core_group');
822 $groups->initGroups();
824 $groups->initDatabase($this,array(
826 'name' => 'bcc-email', // group who are bcc'ed on all requests.
827 'type' => 0, // system
828 'display_name' => 'Standard BCC Group'
831 'name' => 'system-email-from',
832 'type' => 0, // system
833 'display_name' => 'Standard System Email From Group'
836 'name' => 'core-person-signup-bcc',
837 'type' => 0, // system
838 'display_name' => 'Standard Person Signup BCC Group'
841 'name' => 'Empty Group', // use for no bcc emails.
843 'display_name' => 'Standard Empty Group'
850 function updateDataCompanies()
853 // fix comptypes enums..
854 $c = DB_DataObject::Factory('core_company');
856 $c->selectAdd('distinct(comptype) as comptype');
860 comptype != 'undefined'
862 comptype != 'undefine'
866 foreach($c->fetchAll('comptype') as $cts) {
868 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
871 $c = DB_DataObject::Factory('core_enum');
874 //DB_DataObject::debugLevel(1);
876 $c = DB_DataObject::Factory('core_company');
878 UPDATE {$c->tableName()}
880 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
893 function updateDataEmails()
895 foreach ($this->emailTemplates as $k => $mail) {
897 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
907 function initEmails($templateDir, $emails, $mapping = false)
909 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
911 $pg = HTML_FlexyFramework::get()->page;
912 foreach($emails as $name=>$data) {
913 $cm = DB_DataObject::factory('core_email');
914 $update = $cm->get('name', $name);
917 if (empty($cm->bcc_group_id)) {
918 if (empty($data['bcc_group'])) {
919 $this->jerr("missing bcc_group for template $name");
922 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
925 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
928 if (!$g->members('email') && $g->name != 'Empty Group') {
929 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
932 $cm->bcc_group_id = $g->id;
934 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
935 //if (empty($cm->test_class)) {
936 if (empty($data['test_class'])) {
937 $this->jerr("missing test_class for template $name");
940 $cm->test_class = $data['test_class'];
942 if(isset($cm->to_group_id)) {
947 !empty($data['to_group']) &&
948 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
950 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
952 if (empty($gp->id)) {
953 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
956 $cm->to_group_id = $gp->id;
960 isset($data['active']) && !isset($cm->active)
962 $cm->active = $data['active'];
966 * Set description to email.
967 * However we do not update if it is been set.
969 if(empty($cm->description) && !empty($data['description'])){
970 $cm->description = $cm->escape($data['description']);
973 require_once $cm->test_class . '.php';
975 $clsname = str_replace('/','_', $cm->test_class);
977 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
978 $got_it = $method->isStatic();
979 } catch(Exception $e) {
984 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
988 echo "email: {$name} - checked\n";
989 continue; /// we do not import the body content of templates that exist...
996 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1000 'file' => $templateDir. $name .'.html'
1003 if (!empty($data['master'])) {
1004 $opts['master'] = $templateDir . $master .'.html';
1006 require_once 'Pman/Core/Import/Core_email.php';
1007 $x = new Pman_Core_Import_Core_email();
1009 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1011 echo "email: {$name} - CREATED\n";
1016 function updateData()
1019 if (class_exists('PDO_DataObjects_Introspection')) {
1020 PDO_DataObject_Introspection::$cache = array();
1022 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1024 $this->updateDataEnums();
1025 $this->updateDataGroups();
1026 $this->updateDataCompanies();
1028 $this->updateDataEmails();
1030 $c = DB_DataObject::Factory('I18n');
1034 function fixMysqlInnodb()
1037 static $done_check = false;
1043 if (!empty($this->opts['skip-mysql-checks'])) {
1046 // innodb in single files is far more efficient that MYD or one big innodb file.
1047 // first check if database is using this format.
1048 $db = DB_DataObject::factory('core_enum');
1049 $db->query("show variables like 'innodb_file_per_table'");
1051 if ($db->Value == 'OFF') {
1052 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1055 $db = DB_DataObject::factory('core_enum');
1056 $db->query("select version() as version");
1059 if (version_compare($db->version, '5.7', '>=' )) {
1061 $db = DB_DataObject::factory('core_enum');
1062 $db->query("show variables like 'sql_mode'");
1065 $modes = explode(",", $db->Value);
1067 // these are 'new' problems with mysql.
1069 in_array('NO_ZERO_IN_DATE', $modes) ||
1070 in_array('NO_ZERO_DATE', $modes) ||
1071 in_array('STRICT_TRANS_TABLES', $modes) ||
1072 !in_array('ALLOW_INVALID_DATES', $modes)
1074 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".
1075 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1080 $done_check = true;;
1091 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1093 function fixSequencesMysql()
1098 function fixSequencesPgsql()
1102 //DB_DataObject::debugLevel(1);
1103 $cs = DB_DataObject::factory('core_enum');
1107 CASE WHEN strpos(seq_name, '.') > 0 THEN
1110 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1113 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1114 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1118 n.nspname AS schema_name,
1119 c.relname AS table_name,
1120 a.attname AS column_name,
1121 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1123 JOIN pg_attribute a ON (c.oid=a.attrelid)
1124 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1125 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1126 WHERE has_schema_privilege(n.oid,'USAGE')
1127 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1128 AND has_table_privilege(c.oid,'SELECT')
1129 AND (NOT a.attisdropped)
1130 AND d.adsrc ~ '^nextval'
1134 CASE WHEN strpos(seq_name, '.') > 0 THEN
1135 substring(seq_name, 1,strpos(seq_name,'.')-1)
1140 GROUP BY seq_name HAVING count(*)=1
1143 while ($cs->fetch()) {
1146 foreach($cmds as $cmd) {
1147 $cs = DB_DataObject::factory('core_enum');
1151 $cs = DB_DataObject::factory('core_enum');
1153 SELECT 'SELECT SETVAL(' ||
1154 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1155 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1161 WHERE S.relkind = 'S'
1163 AND D.refobjid = T.oid
1164 AND D.refobjid = C.attrelid
1165 AND D.refobjsubid = C.attnum
1166 AND NS.oid = T.relnamespace
1170 while ($cs->fetch()) {
1173 foreach($cmds as $cmd) {
1174 $cs = DB_DataObject::factory('core_enum');
1181 var $extensions = array(
1186 function runExtensions()
1189 $ff = HTML_Flexyframework::get();
1191 $dburl = parse_url($ff->database);
1193 $dbtype = $dburl['scheme'];
1195 foreach($this->extensions as $ext) {
1197 $scls = ucfirst($dbtype). $ext;
1198 $cls = __CLASS__ . '_'. $scls;
1199 $fn = implode('/',explode('_', $cls)).'.php';
1200 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1211 function checkSystem($req = false, $pref = false)
1213 // most of these are from File_Convert...
1215 // these are required - and have simple dependancies.
1216 require_once 'System.php';
1217 $req = $req !== false ? $req : array(
1222 'rsvg-convert', //librsvg2-bin
1225 'gifsicle', // used for gif conversions
1230 // these are prefered - but may have complicated depenacies
1231 $pref = $pref !== false ? $pref : array(
1235 'html2text', // not availabe in debian squeeze
1236 'pdftocairo', //poppler-utils - not available in debian squeeze.
1246 foreach($req as $r) {
1247 if (!System::which($r)) {
1253 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1255 foreach($pref as $r) {
1256 if (!System::which($r)) {
1262 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1269 function clearApacheDataobjectsCache()
1271 echo "Clearing Database Cache\n";
1272 // this needs to clear it's own cache along with remote one..
1274 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1275 $response = $this->curl($url);
1277 $json = json_decode($response, true);
1279 if(empty($json['data']) || $json['data'] != 'DONE'){
1280 echo "fetching $url\n";
1281 echo "GOT:" . $response. "\n";
1282 echo "Clear DataObjects Cache failed\n";
1289 function clearApacheAssetCache()
1291 echo "Clearing Asset Cache\n";
1292 $response = $this->curl(
1293 "http://localhost{$this->local_base_url}/Core/Asset",
1294 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1297 $json = json_decode($response, true);
1299 if(empty($json['success']) || !$json['success']) {
1300 echo $response. "\n";
1301 echo "CURL Clear Asset cache failed\n";
1308 function curl($url, $request = array(), $method = 'GET')
1310 if($method == 'GET'){
1311 $request = http_build_query($request);
1312 $url = $url . "?" . $request;
1315 $ch = curl_init($url);
1317 if ($method == 'POST') {
1319 curl_setopt($ch, CURLOPT_POST, 1);
1320 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1323 curl_setopt($ch, CURLOPT_HTTPHEADER,
1324 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1328 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1330 curl_setopt($ch, CURLOPT_HEADER, false);
1331 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1332 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1333 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1335 $response = curl_exec($ch);
1342 static function verifyExtensions($extensions)
1346 foreach ($extensions as $e){
1348 if(empty($e) || extension_loaded($e)) {
1352 $error[] = "Error: Please install php extension: {$e}";
1358 $ff = HTML_FLexyFramework::get();
1360 $ff->page->jerr(implode('\n', $error));