Adding tests for securing private variable inclussion on templates.
[akelos.git] / lib / AkInstaller.php
blob80802d4a811a8c3782e88d8a3202fdd52fffdec2
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4 // +----------------------------------------------------------------------+
5 // | Akelos Framework - http://www.akelos.org |
6 // +----------------------------------------------------------------------+
7 // | Copyright (c) 2002-2006, Akelos Media, S.L. & Bermi Ferrer Martinez |
8 // | Released under the GNU Lesser General Public License, see LICENSE.txt|
9 // +----------------------------------------------------------------------+
11 /**
12 * @package ActiveSupport
13 * @subpackage Installer
14 * @author Bermi Ferrer <bermi a.t akelos c.om>
15 * @copyright Copyright (c) 2002-2006, Akelos Media, S.L. http://www.akelos.org
16 * @license GNU Lesser General Public License <http://www.gnu.org/copyleft/lesser.html>
19 require_once(AK_LIB_DIR.DS.'Ak.php');
20 require_once(AK_LIB_DIR.DS.'AkActiveRecord.php');
21 file_exists(AK_APP_DIR.DS.'shared_model.php') ? require_once(AK_APP_DIR.DS.'shared_model.php') : null;
22 defined('AK_APP_INSTALLERS_DIR') ? null : define('AK_APP_INSTALLERS_DIR', AK_APP_DIR.DS.'installers');
24 // Install scripts might use more RAM than normal requests.
25 @ini_set('memory_limit', -1);
27 /**
29 * == Column Types ==
31 * Akelos natively supports the following column data types.
33 * integer|int, float, decimal,
34 * string, text,
35 * datetime|timestamp, date,
36 * binary,
37 * boolean
39 * Caution: Because boolean is virtual tinyint on mysql, you can't use tinyint for other things!
42 * == Default settings for columns ==
44 * AkInstaller suggests some default values for the column-details.
46 * So
47 * <code>
48 * $this->createTable('Post','title,body,created_at,is_draft');
49 * </code>
51 * will actually create something like this:
53 * title => string(255), body => text, created_at => datetime, is_draft => boolean not null default 0 index
56 * column_name | default setting
57 * -------------------------------+--------------------------------------------
58 * id | integer not null auto_increment primary_key
59 * *_id,*_by | integer index
60 * description,content,body | text
61 * position | integer index
62 * *_count | integer default 0
63 * lock_version | integer default 1
64 * *_at | datetime
65 * *_on | date
66 * is_*,has_*,do_*,does_*,are_* | boolean not null default 0 index
67 * *somename | multilingual column => en_somename, es_somename
68 * default | string
71 class AkInstaller
73 var $db;
74 var $data_dictionary;
75 var $available_tables = array();
76 var $vervose = true;
77 var $module;
78 var $warn_if_same_version = true;
80 function AkInstaller($db_connection = null)
82 if(empty($db_connection)){
83 $this->db =& AkDbAdapter::getInstance();
84 }else {
85 $this->db =& $db_connection;
88 $this->data_dictionary =& $this->db->getDictionary();
89 $this->available_tables = $this->getAvailableTables();
92 function install($version = null, $options = array())
94 $version = (is_null($version)) ? max($this->getAvailableVersions()) : $version;
95 return $this->_upgradeOrDowngrade('up', $version , $options);
98 function up($version = null, $options = array())
100 return $this->_upgradeOrDowngrade('up', $version, $options);
103 function uninstall($version = null, $options = array())
105 $version = (is_null($version)) ? 0 : $version;
106 return $this->_upgradeOrDowngrade('down', $version, $options);
109 function down($version = null, $options = array())
111 return $this->_upgradeOrDowngrade('down', $version, $options);
114 function _upgradeOrDowngrade($action, $version = null, $options = array())
116 if(in_array('quiet',$options) && AK_ENVIRONMENT == 'development'){
117 $this->vervose = false;
118 }elseif(!empty($this->vervose) && AK_ENVIRONMENT == 'development'){
119 $this->debug(true);
122 $current_version = $this->getInstalledVersion($options);
123 $available_versions = $this->getAvailableVersions();
125 $action = stristr($action,'down') ? 'down' : 'up';
127 if($action == 'up'){
128 $newest_version = max($available_versions);
129 $version = isset($version[0]) && is_numeric($version[0]) ? $version[0] : $newest_version;
130 $versions = range($current_version+1,$version);
132 if($current_version > $version){
133 echo Ak::t("You can't upgrade to version %version, when you are currently on version %current_version", array('%version'=>$version,'%current_version'=>$current_version));
134 return false;
136 }else{
137 $version = !empty($version[0]) && is_numeric($version[0]) ? $version[0] : 0;
138 $versions = range($current_version, empty($version) ? 1 : $version+1);
140 if($current_version == 0){
141 return true;
142 }elseif($current_version < $version){
143 echo Ak::t("You can't downgrade to version %version, when you just have installed version %current_version", array('%version'=>$version,'%current_version'=>$current_version));
144 return false;
148 if($this->warn_if_same_version && $current_version == $version){
149 echo Ak::t("Can't go $action to version %version, you're already on version %version", array('%version'=>$version));
150 return false;
153 if(AK_CLI && !empty($this->vervose) && AK_ENVIRONMENT == 'development'){
154 echo Ak::t(ucfirst($action).'grading');
157 if(!empty($versions) && is_array($versions)){
158 foreach ($versions as $version){
159 if(!$this->_runInstallerMethod($action, $version, $options)){
160 return false;
163 }else{
164 return false;
167 return true;
170 function installVersion($version, $options = array())
172 return $this->_runInstallerMethod('up', $version, $options);
175 function uninstallVersion($version, $options = array())
177 return $this->_runInstallerMethod('down', $version, $options);
181 * Runs a a dow_1, up_3 method and wraps it into a transaction.
183 function _runInstallerMethod($method_prefix, $version, $options = array(), $version_number = null)
185 $method_name = $method_prefix.'_'.$version;
186 if(!method_exists($this, $method_name)){
187 return false;
190 $version_number = empty($version_number) ? ($method_prefix=='down' ? $version-1 : $version) : $version_number;
192 $this->transactionStart();
193 if($this->$method_name($options) === false){
194 $this->transactionFail();
196 $success = !$this->transactionHasFailed();
197 $this->transactionComplete();
198 if($success){
199 $this->setInstalledVersion($version_number, $options);
201 return $success;
204 function getInstallerName()
206 return str_replace('installer','',strtolower(get_class($this)));
209 function _versionPath($options = array())
211 $mode = empty($options['mode']) ? AK_ENVIRONMENT : $options['mode'];
212 return AK_APP_INSTALLERS_DIR.DS.(empty($this->module)?'':$this->module.DS).'versions'.DS.$mode.'_'.$this->getInstallerName().'_version.txt';
216 function getInstalledVersion($options = array())
218 $version_file = $this->_versionPath($options);
220 if(!is_file($version_file)){
221 $this->setInstalledVersion(0, $options);
223 return Ak::file_get_contents($this->_versionPath($options));
227 function setInstalledVersion($version, $options = array())
229 return Ak::file_put_contents($this->_versionPath($options), $version);
233 function getAvailableVersions()
235 $versions = array();
236 foreach(get_class_methods($this) as $method_name){
237 if(preg_match('/^up_([0-9]*)$/',$method_name, $match)){
238 $versions[] = $match[1];
241 sort($versions);
242 return $versions;
246 function modifyTable($table_name, $column_options = null, $table_options = array())
248 return $this->_createOrModifyTable($table_name, $column_options, $table_options);
252 * Adds a new column to the table called $table_name
254 function addColumn($table_name, $column_details)
256 $column_details = $this->_getColumnsAsAdodbDataDictionaryString($column_details);
257 return $this->data_dictionary->ExecuteSQLArray($this->data_dictionary->AddColumnSQL($table_name, $column_details));
260 function changeColumn($table_name, $column_details)
262 $column_details = $this->_getColumnsAsAdodbDataDictionaryString($column_details);
263 return $this->data_dictionary->ExecuteSQLArray($this->data_dictionary->AlterColumnSQL($table_name, $column_details));
266 function removeColumn($table_name, $column_name)
268 return $this->data_dictionary->ExecuteSQLArray($this->data_dictionary->DropColumnSQL($table_name, $column_name));
271 function renameColumn($table_name, $old_column_name, $new_column_name)
273 return $this->db->renameColumn($table_name,$old_column_name,$new_column_name);
277 function createTable($table_name, $column_options = null, $table_options = array())
279 if($this->tableExists($table_name)){
280 trigger_error(Ak::t('Table %table_name already exists on the database', array('%table_name'=>$table_name)), E_USER_NOTICE);
281 return false;
283 $this->timestamps = (!isset($table_options['timestamp']) || (isset($table_options['timestamp']) && $table_options['timestamp'])) &&
284 (!strstr($column_options, 'created') && !strstr($column_options, 'updated'));
285 return $this->_createOrModifyTable($table_name, $column_options, $table_options);
288 function _createOrModifyTable($table_name, $column_options = null, $table_options = array())
290 if(empty($column_options) && $this->_loadDbDesignerDbSchema()){
291 $column_options = $this->db_designer_schema[$table_name];
292 }elseif(empty($column_options)){
293 trigger_error(Ak::t('You must supply details for the table you are creating.'), E_USER_ERROR);
294 return false;
297 $column_options = is_string($column_options) ? array('columns'=>$column_options) : $column_options;
299 $default_column_options = array(
300 'sequence_table' => false
302 $column_options = array_merge($default_column_options, $column_options);
304 $default_table_options = array(
305 'mysql' => 'TYPE=InnoDB',
306 //'REPLACE'
308 $table_options = array_merge($default_table_options, $table_options);
310 $column_string = $this->_getColumnsAsAdodbDataDictionaryString($column_options['columns']);
312 $create_or_alter_table_sql = $this->data_dictionary->ChangeTableSQL($table_name, str_replace(array(' UNIQUE', ' INDEX', ' FULLTEXT', ' HASH'), '', $column_string), $table_options);
313 $result = $this->data_dictionary->ExecuteSQLArray($create_or_alter_table_sql, false);
315 if($result){
316 $this->available_tables[] = $table_name;
317 }else{
318 trigger_error(Ak::t("Could not create or alter table %name using the SQL \n--------\n%sql\n--------\n", array('%name'=>$table_name, '%sql'=>$create_or_alter_table_sql[0])), E_USER_ERROR);
321 $columns_to_index = $this->_getColumnsToIndex($column_string);
323 foreach ($columns_to_index as $column_to_index => $index_type){
324 $this->addIndex($table_name, $column_to_index.($index_type != 'INDEX' ? ' '.$index_type : ''));
327 if(isset($column_options['index_columns'])){
328 $this->addIndex($table_name, $column_options['index_columns']);
331 if($column_options['sequence_table'] || $this->_requiresSequenceTable($column_string)){
332 $this->createSequence($table_name);
335 return $result;
338 function dropTable($table_name, $options = array())
340 $result = $this->tableExists($table_name) ? $this->db->execute('DROP TABLE '.$table_name) : true;
341 if($result){
342 unset($this->available_tables[array_search($table_name, $this->available_tables)]);
343 if(!empty($options['sequence'])){
344 $this->dropSequence($table_name);
349 function dropTables()
351 $args = func_get_args();
352 if(!empty($args)){
353 $num_args = count($args);
354 $options = $num_args > 1 && is_array($args[$num_args-1]) ? array_shift($args) : array();
355 $tables = count($args) > 1 ? $args : (is_array($args[0]) ? $args[0] : Ak::toArray($args[0]));
356 foreach ($tables as $table){
357 $this->dropTable($table, $options);
362 function addIndex($table_name, $columns, $index_name = '')
364 $index_name = ($index_name == '') ? 'idx_'.$table_name.'_'.$columns : $index_name;
365 $index_options = array();
366 if(preg_match('/(UNIQUE|FULLTEXT|HASH)/',$columns,$match)){
367 $columns = trim(str_replace($match[1],'',$columns),' ');
368 $index_options[] = $match[1];
370 return $this->tableExists($table_name) ? $this->data_dictionary->ExecuteSQLArray($this->data_dictionary->CreateIndexSQL($index_name, $table_name, $columns, $index_options)) : false;
373 function removeIndex($table_name, $columns_or_index_name)
375 if(!$this->tableExists($table_name)){
376 return false;
378 $available_indexes = $this->db->getIndexes($table_name);
379 $index_name = isset($available_indexes[$columns_or_index_name]) ? $columns_or_index_name : 'idx_'.$table_name.'_'.$columns_or_index_name;
380 if(!isset($available_indexes[$index_name])){
381 trigger_error(Ak::t('Index %index_name does not exist.', array('%index_name'=>$index_name)), E_USER_NOTICE);
382 return false;
384 return $this->data_dictionary->ExecuteSQLArray($this->data_dictionary->DropIndexSQL($index_name, $table_name));
387 function dropIndex($table_name, $columns_or_index_name)
389 return $this->removeIndex($table_name,$columns_or_index_name);
392 function createSequence($table_name)
394 $result = $this->tableExists('seq_'.$table_name) ? false : $this->db->connection->CreateSequence('seq_'.$table_name);
395 $this->available_tables[] = 'seq_'.$table_name;
396 return $result;
399 function dropSequence($table_name)
401 $result = $this->tableExists('seq_'.$table_name) ? $this->db->connection->DropSequence('seq_'.$table_name) : true;
402 if($result){
403 unset($this->available_tables[array_search('seq_'.$table_name, $this->available_tables)]);
406 return $result;
409 function getAvailableTables()
411 if(empty($this->available_tables)){
412 $this->available_tables = $this->db->availableTables();
414 return $this->available_tables;
417 function tableExists($table_name)
419 return in_array($table_name,$this->getAvailableTables());
422 function _getColumnsAsAdodbDataDictionaryString($columns)
424 $columns = $this->_setColumnDefaults($columns);
425 $this->_ensureColumnNameCompatibility($columns);
427 $equivalences = array(
428 '/ ((limit|max|length) ?= ?)([0-9]+)([ \n\r,]+)/'=> ' (\3) ',
429 '/([ \n\r,]+)default([ =]+)([^\'^,^\n]+)/i'=> ' DEFAULT \'\3\'',
430 '/([ \n\r,]+)(integer|int)([( \n\r,]+)/'=> '\1 I \3',
431 '/([ \n\r,]+)float([( \n\r,]+)/'=> '\1 F \2',
432 '/([ \n\r,]+)decimal([( \n\r,]+)/'=> '\1 N \2',
433 '/([ \n\r,]+)datetime([( \n\r,]+)/'=> '\1 T \2',
434 '/([ \n\r,]+)date([( \n\r,]+)/'=> '\1 D \2',
435 '/([ \n\r,]+)timestamp([( \n\r,]+)/'=> '\1 T \2',
436 '/([ \n\r,]+)time([( \n\r,]+)/'=> '\1 T \2',
437 '/([ \n\r,]+)text([( \n\r,]+)/'=> '\1 XL \2',
438 '/([ \n\r,]+)string([( \n\r,]+)/'=> '\1 C \2',
439 '/([ \n\r,]+)binary([( \n\r,]+)/'=> '\1 B \2',
440 '/([ \n\r,]+)boolean([( \n\r,]+)/'=> '\1 L'.($this->db->type()=='mysql'?'(1)':'').' \2',
441 '/ NOT( |_)?NULL/i'=> ' NOTNULL',
442 '/ AUTO( |_)?INCREMENT/i'=> ' AUTO ',
443 '/ +/'=> ' ',
444 '/ ([\(,]+)/'=> '\1',
445 '/ INDEX| IDX/i'=> ' INDEX ',
446 '/ UNIQUE/i'=> ' UNIQUE ',
447 '/ HASH/i'=> ' HASH ',
448 '/ FULL_?TEXT/i'=> ' FULLTEXT ',
449 '/ ((PRIMARY( |_)?)?KEY|pk)/i'=> ' KEY',
452 return trim(preg_replace(array_keys($equivalences),array_values($equivalences), ' '.$columns.' '), ' ');
455 function _setColumnDefaults($columns)
457 $columns = Ak::toArray($columns);
458 foreach ((array)$columns as $column){
459 $column = trim($column, "\n\t\r, ");
460 if(!empty($column)){
461 $single_columns[$column] = $this->_setColumnDefault($column);
464 if(!empty($this->timestamps) && !isset($single_columns['created_at']) && !isset($single_columns['updated_at'])){
465 $single_columns['updated_at'] = $this->_setColumnDefault('updated_at');
466 $single_columns['created_at'] = $this->_setColumnDefault('created_at');
468 return join(",\n", $single_columns);
471 function _setColumnDefault($column)
473 return $this->_needsDefaultAttributes($column) ? $this->_setDefaultAttributes($column) : $column;
476 function _needsDefaultAttributes($column)
478 return preg_match('/^(([A-Z0-9_\(\)]+)|(.+ string[^\(.]*)|(\*.*))$/i',$column);
481 function _setDefaultAttributes($column)
483 $rules = $this->getDefaultColumnAttributesRules();
484 foreach ($rules as $regex=>$replacement){
485 if(is_string($replacement)){
486 $column = preg_replace($regex,$replacement,$column);
487 }elseif(preg_match($regex,$column,$match)){
488 $column = call_user_func_array($replacement,$match);
491 return $column;
495 * Returns a key => value pair of regular expressions that will trigger methods
496 * to cast database columns to their respective default values or a replacement expression.
498 function getDefaultColumnAttributesRules()
500 return array(
501 '/^\*(.*)$/i' => array(&$this,'_castToMultilingualColumn'),
502 '/^(description|content|body)$/i' => '\1 text',
503 '/^(lock_version)$/i' => '\1 integer default \'1\'',
504 '/^(.+_count)$/i' => '\1 integer default \'0\'',
505 '/^(id)$/i' => 'id integer not null auto_increment primary_key',
506 '/^(.+)_(id|by)$/i' => '\1_\2 integer index',
507 '/^(position)$/i' => '\1 integer index',
508 '/^(.+_at)$/i' => '\1 datetime',
509 '/^(.+_on)$/i' => '\1 date',
510 '/^(is_|has_|do_|does_|are_)([A-Z0-9_]+)$/i' => '\1\2 boolean not null default \'0\' index', //
511 '/^([A-Z0-9_]+) *(\([0-9]+\))?$/i' => '\1 string\2', // Everything else will default to string
512 '/^((.+ )string([^\(.]*))$/i' => '\2string(255)\3', // If we don't set the string lenght it will fail, so if not present will set it to 255
516 function _castToMultilingualColumn($found, $column)
518 $columns = array();
519 foreach (Ak::langs() as $lang){
520 $columns[] = $lang.'_'.ltrim($column);
522 return $this->_setColumnDefaults($columns);
525 function _getColumnsToIndex($column_string)
527 $columns_to_index = array();
528 foreach (explode(',',$column_string.',') as $column){
529 if(preg_match('/([A-Za-z0-9_]+) (.*) (INDEX|UNIQUE|FULLTEXT|HASH) ?(.*)$/i',$column,$match)){
530 $columns_to_index[$match[1]] = $match[3];
533 return $columns_to_index;
536 function _getUniqueValueColumns($column_string)
538 $unique_columns = array();
539 foreach (explode(',',$column_string.',') as $column){
540 if(preg_match('/([A-Za-z0-9_]+) (.*) UNIQUE ?(.*)$/',$column,$match)){
541 $unique_columns[] = $match[1];
544 return $unique_columns;
547 function _requiresSequenceTable($column_string)
549 if(in_array($this->db->type(),array('mysql','postgre'))){
550 return false;
552 foreach (explode(',',$column_string.',') as $column){
553 if(preg_match('/([A-Za-z0-9_]+) (.*) AUTO (.*)$/',$column)){
554 return true;
556 if(preg_match('/^id /',$column)){
557 return true;
560 return false;
565 * Transaction support for database operations
567 * Transactions are enabled automatically for Intaller objects, But you can nest transactions within models.
568 * This transactions are nested, and only the othermost will be executed
570 * $UserInstalller->transactionStart();
571 * $UserInstalller->addTable('id, name');
573 * if(!isCompatible()){
574 * $User->transactionFail();
577 * $User->transactionComplete();
579 function transactionStart()
581 return $this->db->startTransaction();
584 function transactionComplete()
586 return $this->db->stopTransaction();
589 function transactionFail()
591 return $this->db->failTransaction();
594 function transactionHasFailed()
596 return $this->db->hasTransactionFailed();
600 function _loadDbDesignerDbSchema()
602 if($path = $this->_getDbDesignerFilePath()){
603 $this->db_designer_schema = Ak::convert('DBDesigner','AkelosDatabaseDesign', Ak::file_get_contents($path));
604 return !empty($this->db_designer_schema);
606 return false;
609 function _getDbDesignerFilePath()
611 $path = AK_APP_INSTALLERS_DIR.DS.$this->getInstallerName().'.xml';
612 return file_exists($path) ? $path : false;
615 function _ensureColumnNameCompatibility($columns)
617 $columns = explode(',',$columns.',');
618 foreach ($columns as $column){
619 $column = trim($column);
620 $column = substr($column, 0, strpos($column.' ',' '));
621 $this->_canUseColumn($column);
625 function _canUseColumn($column_name)
627 $invalid_columns = $this->_getInvalidColumnNames();
628 if(in_array($column_name, $invalid_columns)){
630 $method_name_part = AkInflector::camelize($column_name);
631 require_once(AK_LIB_DIR.DS.'AkActiveRecord.php');
632 $method_name = (method_exists(new AkActiveRecord(), 'set'.$method_name_part)?'set':'get').$method_name_part;
634 trigger_error(Ak::t('A method named %method_name exists in the AkActiveRecord class'.
635 ' which will cause a recusion problem if you use the column %column_name in your database. '.
636 'You can disable automatic %type by setting the constant %constant to false '.
637 'in your configuration file.', array(
638 '%method_name'=> $method_name,
639 '%column_name' => $column_name,
640 '%type' => Ak::t($method_name[0] == 's' ? 'setters' : 'getters'),
641 '%constant' => Ak::t($method_name[0] == 's' ? 'AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS' : 'AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS'),
643 )), E_USER_ERROR);
647 function _getInvalidColumnNames()
649 return defined('AK_INVALID_ACTIVE_RECORD_COLUMNS') ? explode(',',AK_INVALID_ACTIVE_RECORD_COLUMNS) : array('sanitized_conditions_array','conditions','inheritance_column','inheritance_column',
650 'subclasses','attribute','attributes','attribute','attributes','accessible_attributes','protected_attributes',
651 'serialized_attributes','available_attributes','attribute_caption','primary_key','column_names','content_columns',
652 'attribute_names','combined_subattributes','available_combined_attributes','connection','connection','primary_key',
653 'table_name','table_name','only_available_atrributes','columns_for_atrributes','columns_with_regex_boundaries','columns',
654 'column_settings','column_settings','akelos_data_type','class_for_database_table_mapping','display_field','display_field',
655 'internationalized_columns','available_locales','current_locale','attribute_by_locale','attribute_locales',
656 'attribute_by_locale','attribute_locales','attributes_before_type_cast','attribute_before_type_cast','serialize_attribute',
657 'available_attributes_quoted','attributes_quoted','column_type','value_for_date_column','observable_state',
658 'observable_state','observers','errors','base_errors','errors_on','full_error_messages','array_from_ak_string',
659 'attribute_condition','association_handler','associated','associated_finder_sql_options','association_option',
660 'association_option','association_id','associated_ids','associated_handler_name','associated_type','association_type',
661 'collection_handler_name','model_name','model_name','parent_model_name','parent_model_name');
664 function execute($sql)
666 return $this->db->execute($sql);
669 function debug($toggle = null)
671 $this->db->connection->debug = $toggle === null ? !$this->db->connection->debug : $toggle;
674 function usage()
676 echo Ak::t("Description:
677 Database migrations is a sort of SCM like subversion, but for database settings.
679 The migration command takes the name of an installer located on your
680 /app/installers folder and runs one of the following commands:
682 - \"install\" + (options version number): Will update to the provided version
683 number or to the latest one in no version is given.
685 - \"uninstall\" + (options version number): Will downgrade to the provided
686 version number or to the lowest one in no version is given.
688 Current version number will be sorted at app/installers/installer_name_version.txt.
690 Example:
691 >> migrate framework install
693 Will run the default database schema for the framework.
694 This generates the tables for handling database driven sessions and cache.