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',
94 static function cli_opts()
97 $ret = self::$cli_opts;
98 $ff = HTML_FlexyFramework::get();
100 $mods = $a->modulesList();
101 foreach($mods as $m) {
103 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
104 if (!file_exists($fd)) {
110 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
111 $ar = $cls->getStaticProperties();
112 if (isset($ar['cli_opts'])) {
114 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
122 var $disabled = array();
127 var $local_base_url = false;
129 var $emailTemplates = array(
130 'EVENT_ERRORS_REPORT' => array(
131 'bcc_group' => 'Empty Group',
132 'test_class' => 'Pman/Admin/Report/SendEventErrors',
133 'to_group' => 'Administrators',
135 'description' => '9.2 System Error Messages',
136 'template_dir' => '/Pman/Admin/templates/mail/'
138 'ADMIN_PASSWORD_RESET' => array(
139 'bcc_group' => 'Administrators',
140 'test_class' => 'Pman/Core/DataObjects/Core_person',
143 'description' => '9.1 Management System Password Reset',
144 'template_dir' => '/Pman/Core/templates/mail/'
150 var $required_extensions = array(
158 $ff = HTML_FlexyFramework::get();
159 if (!empty($ff->cli)) {
164 parent::getAuth(); // load company!
165 $au = $this->getAuthUser();
166 if (!$au || $au->company()->comptype != 'OWNER') {
167 $this->jerr("Not authenticated", array('authFailure' => true));
169 $this->authUser = $au;
173 function get($args, $opts=array())
175 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
177 $this->checkSystem();
179 $this->verifyExtensions($this->required_extensions);
181 if (class_exists('PDO_DataObjects_Introspection')) {
182 PDO_DataObject_Introspection::$cache = array();
184 echo "Generate DB cache\n";
185 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
186 echo "Generated DB cache\n";
187 $ff = HTML_FlexyFramework::get();
189 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
190 die("Please setup Pman[local_base_url]\n");
193 $this->local_base_url = $ff->Pman['local_base_url'];
195 if(!empty($ff->Core_Notify)){
196 // require_once 'Pman/Core/NotifySmtpCheck.php';
197 // $x = new Pman_Core_NotifySmtpCheck();
201 $this->disabled = explode(',', $ff->disable);
203 //$this->fixSequencesPgsql();exit;
206 if (!empty($opts['debug'])) {
207 DB_DataObject::DebugLevel($opts['debug']);
210 // ask all the modules to verify the opts
211 echo "Checking options\n";
212 $this->checkOpts($opts);
214 $response = $this->curl("http://localhost{$this->local_base_url}/Core/UpdateDatabase/VerifyExtensions");
215 $json = json_decode($response, true);
217 if(empty($json['data']) || $json['data'] != 'DONE'){
218 echo "\nError: Missing php extensions:\n";
220 echo "Please install the above extensions and restart the apache.\n";
226 echo "Checking Setup Requirements\n";
227 require_once 'Pman/Core/UpdateDatabase/VerifyConfig.php';
228 $sq = new Pman_Core_UpdateDatabase_VerifyConfig();
229 $ret = $sq->get($args, $opts);
232 echo implode("\n", $ret) . "\n";
236 // do this first, so the innodb change + utf8 fixes column max sizes
238 // this will trigger errors about freetext indexes - we will have to remove them manually.?
239 // 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..)
241 $this->runExtensions();
244 if (empty($opts['data-only'])) {
247 if (!empty($opts['only-module-sql'])) {
253 $this->runUpdateModulesData();
255 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
256 // make sure we have a good cache...?
258 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
261 $this->runExtensions();
263 $this->clearApacheDataobjectsCache();
265 $this->clearApacheAssetCache();
275 echo "\nUpdate Completed SUCCESS\n";
279 * imports SQL files from all DataObjects directories....
281 * except any matching /migrate/
286 // loop through all the modules, and see if they have a importSQL method?
289 $ff = HTML_Flexyframework::get();
291 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
293 //$this->{'import' . $url['scheme']}($url);
295 $dbtype = $dburl['scheme'];
298 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
303 $ar = $this->modulesList();
308 if(in_array($m, $this->disabled)){
309 echo "module $m is disabled \n";
313 echo "Importing SQL from module $m\n";
314 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
319 // check to see if the class has
323 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
324 if($m != 'Core' && file_exists($file)){
327 $class = "Pman_{$m}_UpdateDatabase";
329 if(method_exists($x, 'importModuleSQL')){
330 echo "Importing SQL from module $m using Module::importModuleSQL\n";
331 $x->opts = $this->opts;
332 $x->rootDir = $this->rootDir;
333 $x->importModuleSQL($dburl);
338 echo "Importing SQL from module $m\n";
341 // if init has been called
343 if (!empty($this->opts['init'])) {
344 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
350 $fd = $this->rootDir. "/Pman/$m/DataObjects";
352 $this->{$dirmethod}($dburl, $fd);
355 // new -- sql directory..
356 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
357 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
358 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
360 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
361 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
365 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
366 if (class_exists('PDO_DataObjects_Introspection')) {
367 PDO_DataObject_Introspection::$cache = array();
369 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
371 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
372 $this->{'fixSequences'. $dbtype}();
385 /** -------------- code to handle importing a whole directory of files into the database ------- **/
388 function importpgsqldir($url, $dir, $disable_triggers = false)
390 $ff = HTML_FlexyFramework::get();
392 require_once 'System.php';
393 $cat = System::which('cat');
394 $psql = System::which('psql');
397 if (!empty($url['pass'])) {
398 putenv("PGPASSWORD=". $url['pass']);
402 ' -h ' . $url['host'] .
403 ' -U' . escapeshellarg($url['user']) .
404 ' ' . basename($url['path']);
407 echo $psql_cmd . "\n" ;
408 echo "scan : $dir\n";
411 $files = array($dir);
416 $files = glob($dir.'/*.sql');
417 uksort($files, 'strcasecmp');
419 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
420 //usort($files, $lsort);
423 foreach($files as $bfn) {
426 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
429 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
430 && !preg_match('#\.pg\.sql#i', basename($bfn))
431 ) { // skip migration scripts at present..
436 if (!preg_match('/pgsql/', basename($dir) )) {
437 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
438 $fn = $this->convertToPG($bfn);
442 // files ending in .pg.sql are native postgres files.. ## depricated
445 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
447 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
463 * mysql - does not support conversions.
467 function importmysqlidir($dburl, $dir) {
468 return $this->importmysqldir($dburl, $dir);
471 function importmysqldir($dburl, $dir)
474 $this->fixMysqlInnodb(); /// run once
476 echo "Import MYSQL :: $dir\n";
479 require_once 'System.php';
480 $cat = System::which('cat');
481 $mysql = System::which('mysql');
485 $mysql_cmd = $mysql .
486 ' -h ' . $dburl['host'] .
487 ' -u' . escapeshellarg($dburl['user']) .
488 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
489 ' ' . basename($dburl['path']);
490 //echo $mysql_cmd . "\n" ;
492 $files = glob($dir.'/*.sql');
493 uksort($files, 'strcasecmp');
496 foreach($files as $fn) {
499 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
502 // .my.sql but not .pg.sql
503 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
504 && !preg_match('#\.my\.sql#i', basename($fn))
505 ) { // skip migration scripts at present..
508 if (!strlen(trim($fn))) {
512 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
514 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
517 $fp = popen($cmd, "r");
520 // send the current file part to the browser
521 $line = trim(fgets($fp, 1024));
526 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
527 echo " ---- {$line}\n"; flush();
531 switch($matches[1]) {
532 case 1017: // cause by renaming table -- old one does not exist..
533 case 1050: // create tables triggers this..
534 case 1060: // Duplicate column name
535 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
536 case 1091: // drop index -- name does not exist.. might hide errors..
538 case 1146: // drop a index on an unknown table.. - happens rarely...
539 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
545 echo " ---- {$line}\n"; flush();
549 // 1051: // Unknown table -- normally drop = add iff exists..
550 echo "File: $fn\n$line\n";
566 * simple regex based convert mysql to pgsql...
568 function convertToPG($src)
570 //echo "Convert $src\n";
572 $fn = $this->tempName('sql');
574 $ret = array( ); // pad it a bit.
575 $extra = array("", "" );
578 foreach(file($src) as $l) {
581 if (!strlen($l) || $l[0] == '#') {
585 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
588 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
589 $tbl = 'shop_' . strtolower($m[1]);
590 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
592 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
593 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
596 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
597 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
598 $extra[] = "create sequence {$tbl}_seq;";
602 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
603 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
606 // enum value -- use the text instead..
608 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
609 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
611 // ignore the alter enum
612 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
616 // UNIQUE KEY .. ignore
617 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
618 $last = array_pop($ret);
619 $ret[] = trim($last, ",");
623 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
627 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
631 // INDEX lookup ..ignore
632 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
633 $last = array_pop($ret);
634 $ret[] = trim($last, ",");
639 // CREATE INDEX ..ignore
640 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
641 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
646 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
648 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
649 $l = preg_replace('# blob#i', ' TEXT', $l);
650 $l = preg_replace('# longtext#i', ' TEXT', $l);
651 $l = preg_replace('# tinyint#i', ' INT', $l);
657 $ret = array_merge($extra,$ret);
658 // echo implode("\n", $ret); exit;
660 file_put_contents($fn, implode("\n", $ret));
666 function checkOpts($opts)
670 foreach($opts as $o=>$v) {
671 if (!preg_match('/^json-/', $o) || empty($v)) {
674 if (!file_exists($v)) {
675 die("File does not exist : OPTION --{$o} = {$v} \n");
679 $modules = array_reverse($this->modulesList());
681 // move 'project' one to the end...
683 foreach ($modules as $module){
684 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
685 if($module == 'Core' || !file_exists($file)){
689 $class = "Pman_{$module}_UpdateDatabase";
691 if(!method_exists($x, 'checkOpts')){
694 $x->checkOpts($opts);
698 static function jsonImportFromArray($opts)
700 foreach($opts as $o=>$v) {
701 if (!preg_match('/^json-/', $o) || empty($v)) {
704 $type = str_replace('_', '-', substr($o,5));
706 $data= json_decode(file_get_contents($v),true);
707 $pg = HTML_FlexyFramework::get()->page;
708 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
718 function runUpdateModulesData()
720 if (class_exists('PDO_DataObjects_Introspection')) {
721 PDO_DataObject_Introspection::$cache = array();
723 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
725 if(!in_array('Core', $this->disabled)){
726 echo "Running jsonImportFromArray\n";
727 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
730 echo "Running updateData on modules\n";
736 $modules = array_reverse($this->modulesList());
738 // move 'project' one to the end...
740 foreach ($modules as $module){
741 if(in_array($module, $this->disabled)){
744 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
745 if($module == 'Core' || !file_exists($file)){
750 $class = "Pman_{$module}_UpdateDatabase";
752 if(!method_exists($x, 'updateData')){
762 function updateDataEnums()
764 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
766 $enum = DB_DataObject::Factory('core_enum');
767 //DB_DAtaObject::debugLevel(1);
772 'name' => 'COMPTYPE',
773 'display_name' => 'Company Types',
774 'is_system_enum' => 1,
778 'display_name' => 'Owner',
779 'seqid' => 999, // last...
780 'is_system_enum' => 1,
787 'name' => 'HtmlEditor.font-family',
788 'display_name' => 'HTML Editor font families',
789 'is_system_enum' => 1,
792 'name' => 'Helvetica,Arial,sans-serif',
793 'display_name' => 'Helvetica',
798 'name' => 'Courier New',
799 'display_name' => 'Courier',
804 'display_name' => 'Tahoma',
808 'name' => 'Times New Roman,serif',
809 'display_name' => 'Times',
814 'display_name' => 'Verdana',
827 function updateDataGroups()
830 $groups = DB_DataObject::factory('core_group');
831 $groups->initGroups();
833 $groups->initDatabase($this,array(
835 'name' => 'bcc-email', // group who are bcc'ed on all requests.
836 'type' => 0, // system
837 'display_name' => 'Standard BCC Group'
840 'name' => 'system-email-from',
841 'type' => 0, // system
842 'display_name' => 'Standard System Email From Group'
845 'name' => 'core-person-signup-bcc',
846 'type' => 0, // system
847 'display_name' => 'Standard Person Signup BCC Group'
850 'name' => 'Empty Group', // use for no bcc emails.
852 'display_name' => 'Standard Empty Group'
859 function updateDataCompanies()
862 // fix comptypes enums..
863 $c = DB_DataObject::Factory('core_company');
865 $c->selectAdd('distinct(comptype) as comptype');
869 comptype != 'undefined'
871 comptype != 'undefine'
875 foreach($c->fetchAll('comptype') as $cts) {
877 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
880 $c = DB_DataObject::Factory('core_enum');
883 //DB_DataObject::debugLevel(1);
885 $c = DB_DataObject::Factory('core_company');
887 UPDATE {$c->tableName()}
889 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
902 function updateDataEmails()
904 foreach ($this->emailTemplates as $k => $mail) {
906 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
916 function initEmails($templateDir, $emails, $mapping = false)
918 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
920 $pg = HTML_FlexyFramework::get()->page;
921 foreach($emails as $name=>$data) {
922 $cm = DB_DataObject::factory('core_email');
923 $update = $cm->get('name', $name);
926 if (empty($cm->bcc_group_id)) {
927 if (empty($data['bcc_group'])) {
928 $this->jerr("missing bcc_group for template $name");
931 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
934 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
937 if (!$g->members('email') && $g->name != 'Empty Group') {
938 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
941 $cm->bcc_group_id = $g->id;
943 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
944 //if (empty($cm->test_class)) {
945 if (empty($data['test_class'])) {
946 $this->jerr("missing test_class for template $name");
949 $cm->test_class = $data['test_class'];
951 if(isset($cm->to_group_id)) {
956 !empty($data['to_group']) &&
957 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
959 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
961 if (empty($gp->id)) {
962 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
965 $cm->to_group_id = $gp->id;
969 isset($data['active']) && !isset($cm->active)
971 $cm->active = $data['active'];
975 * Set description to email.
976 * However we do not update if it is been set.
978 if(empty($cm->description) && !empty($data['description'])){
979 $cm->description = $cm->escape($data['description']);
982 require_once $cm->test_class . '.php';
984 $clsname = str_replace('/','_', $cm->test_class);
986 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
987 $got_it = $method->isStatic();
988 } catch(Exception $e) {
993 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
997 echo "email: {$name} - checked\n";
998 continue; /// we do not import the body content of templates that exist...
1005 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1009 'file' => $templateDir. $name .'.html'
1012 if (!empty($data['master'])) {
1013 $opts['master'] = $templateDir . $master .'.html';
1015 require_once 'Pman/Core/Import/Core_email.php';
1016 $x = new Pman_Core_Import_Core_email();
1018 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1020 echo "email: {$name} - CREATED\n";
1025 function updateData()
1028 if (class_exists('PDO_DataObjects_Introspection')) {
1029 PDO_DataObject_Introspection::$cache = array();
1031 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1033 $this->updateDataEnums();
1034 $this->updateDataGroups();
1035 $this->updateDataCompanies();
1037 $this->updateDataEmails();
1039 $c = DB_DataObject::Factory('I18n');
1043 function fixMysqlInnodb()
1046 static $done_check = false;
1052 if (!empty($this->opts['skip-mysql-checks'])) {
1055 // innodb in single files is far more efficient that MYD or one big innodb file.
1056 // first check if database is using this format.
1057 $db = DB_DataObject::factory('core_enum');
1058 $db->query("show variables like 'innodb_file_per_table'");
1060 if ($db->Value == 'OFF') {
1061 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1064 $db = DB_DataObject::factory('core_enum');
1065 $db->query("select version() as version");
1068 if (version_compare($db->version, '5.7', '>=' )) {
1070 $db = DB_DataObject::factory('core_enum');
1071 $db->query("show variables like 'sql_mode'");
1074 $modes = explode(",", $db->Value);
1076 // these are 'new' problems with mysql.
1078 in_array('NO_ZERO_IN_DATE', $modes) ||
1079 in_array('NO_ZERO_DATE', $modes) ||
1080 in_array('STRICT_TRANS_TABLES', $modes) ||
1081 !in_array('ALLOW_INVALID_DATES', $modes)
1083 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".
1084 "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1089 $done_check = true;;
1100 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1102 function fixSequencesMysql()
1107 function fixSequencesPgsql()
1111 //DB_DataObject::debugLevel(1);
1112 $cs = DB_DataObject::factory('core_enum');
1116 CASE WHEN strpos(seq_name, '.') > 0 THEN
1119 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1122 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1123 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1127 n.nspname AS schema_name,
1128 c.relname AS table_name,
1129 a.attname AS column_name,
1130 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1132 JOIN pg_attribute a ON (c.oid=a.attrelid)
1133 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1134 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1135 WHERE has_schema_privilege(n.oid,'USAGE')
1136 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1137 AND has_table_privilege(c.oid,'SELECT')
1138 AND (NOT a.attisdropped)
1139 AND d.adsrc ~ '^nextval'
1143 CASE WHEN strpos(seq_name, '.') > 0 THEN
1144 substring(seq_name, 1,strpos(seq_name,'.')-1)
1149 GROUP BY seq_name HAVING count(*)=1
1152 while ($cs->fetch()) {
1155 foreach($cmds as $cmd) {
1156 $cs = DB_DataObject::factory('core_enum');
1160 $cs = DB_DataObject::factory('core_enum');
1162 SELECT 'SELECT SETVAL(' ||
1163 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1164 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1170 WHERE S.relkind = 'S'
1172 AND D.refobjid = T.oid
1173 AND D.refobjid = C.attrelid
1174 AND D.refobjsubid = C.attnum
1175 AND NS.oid = T.relnamespace
1179 while ($cs->fetch()) {
1182 foreach($cmds as $cmd) {
1183 $cs = DB_DataObject::factory('core_enum');
1190 var $extensions = array(
1195 function runExtensions()
1198 $ff = HTML_Flexyframework::get();
1200 $dburl = parse_url($ff->database);
1202 $dbtype = $dburl['scheme'];
1203 $dbtype = ($dbtype == 'mysqli') ? 'mysql' : $dbtype;
1205 foreach($this->extensions as $ext) {
1207 $scls = ucfirst($dbtype). $ext;
1208 $cls = __CLASS__ . '_'. $scls;
1209 $fn = implode('/',explode('_', $cls)).'.php';
1211 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1222 function checkSystem($req = false, $pref = false)
1224 // most of these are from File_Convert...
1226 // these are required - and have simple dependancies.
1227 require_once 'System.php';
1228 $req = $req !== false ? $req : array(
1233 'rsvg-convert', //librsvg2-bin
1236 'gifsicle', // used for gif conversions
1241 // these are prefered - but may have complicated depenacies
1242 $pref = $pref !== false ? $pref : array(
1246 'html2text', // not availabe in debian squeeze
1247 'pdftocairo', //poppler-utils - not available in debian squeeze.
1257 foreach($req as $r) {
1258 if (!System::which($r)) {
1264 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1266 foreach($pref as $r) {
1267 if (!System::which($r)) {
1273 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1280 function clearApacheDataobjectsCache()
1283 // this needs to clear it's own cache along with remote one..
1285 $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1287 echo "Clearing Database Cache : http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache\n";
1289 $response = $this->curl($url);
1291 $json = json_decode($response, true);
1293 if(empty($json['data']) || $json['data'] != 'DONE'){
1294 echo "fetching $url\n";
1295 echo "GOT:" . $response. "\n";
1296 echo "Clear DataObjects Cache failed\n";
1303 function clearApacheAssetCache()
1305 echo "Clearing Asset Cache : http://localhost{$this->local_base_url}/Core/Asset\n";
1306 $response = $this->curl(
1307 "http://localhost{$this->local_base_url}/Core/Asset",
1308 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1311 $json = json_decode($response, true);
1313 if(empty($json['success']) || !$json['success']) {
1314 echo $response. "\n";
1315 echo "CURL Clear Asset cache failed\n";
1322 function curl($url, $request = array(), $method = 'GET')
1324 if($method == 'GET'){
1325 $request = http_build_query($request);
1326 $url = $url . "?" . $request;
1329 $ch = curl_init($url);
1331 if ($method == 'POST') {
1333 curl_setopt($ch, CURLOPT_POST, 1);
1334 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1337 curl_setopt($ch, CURLOPT_HTTPHEADER,
1338 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1342 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1344 curl_setopt($ch, CURLOPT_HEADER, false);
1345 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1346 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1347 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1349 $response = curl_exec($ch);
1356 static function verifyExtensions($extensions)
1360 foreach ($extensions as $e){
1362 if(empty($e) || extension_loaded($e)) {
1366 $error[] = "Error: Please install php extension: {$e}";
1372 $ff = HTML_FLexyFramework::get();
1374 $ff->page->jerr(implode('\n', $error));