function fix_amputees()
 {
     if ($this->mode == 'test') {
         echo '<p>Would attempt to fix amputees</p>';
     } else {
         $fixer = new AmputeeFixer();
         $fixer->fix_amputees();
         $fixer->generate_report();
     }
 }
 protected function _add_table($table_name)
 {
     $es = new entity_selector();
     $es->add_type(id_of('content_table'));
     $es->add_relation('entity.name = "' . reason_sql_string_escape($table_name) . '"');
     $es->set_num(1);
     $results = $es->run_one();
     if (empty($results)) {
         create_reason_table($table_name, $this->_type_unique_name(), $this->user_id());
         $ret = '<p>Created the ' . $table_name . ' table.</p>';
     } else {
         $table_entity = current($results);
         create_relationship($this->_type_id(), $table_entity->id(), relationship_id_of('type_to_table'));
         $ret = '<p>Added the ' . $table_name . ' table to the ' . $this->_type_unique_name() . ' type.</p>' . "\n";
     }
     reason_include_once('classes/amputee_fixer.php');
     $fixer = new AmputeeFixer();
     $fixer->fix_amputees($this->_type_id());
     return $ret;
 }
if (!reason_user_has_privs(get_user_id($current_user), 'db_maintenance')) {
    die('<html><head><title>Reason: Fix Amputees</title></head><body><h1>Sorry.</h1><p>You do not have permission to fix amputees.</p><p>Only Reason users who have database maintenance privileges may do that.</p></body></html>');
}
?>
	<html>
	<head>
	<title>Reason: Fix Amputees</title>
	</head>
	<body>
	<h1>Fix Amputees</h1>
	<?php 
if (empty($_POST['do_it'])) {
    ?>
	<form method="post">
	<p>Amputees are entities that do not have records in all of their tables. Amputees are generally invisible to Reason, since entities are grabbed all-at-once.</p>
	<p>When this script is run, it will find all of the amputees in Reason and fix them by creating records in the appropriate tables.</p>
	<p>This script must be run after a table is added to a type.  We should probably make this script a cron job and/or have this code be run when finishing a type.</p>
	<input type="submit" name="do_it" value="Run the script" />
	</form>
	<?php 
} else {
    connectDB(REASON_DB);
    reason_include_once('classes/amputee_fixer.php');
    $fixer = new AmputeeFixer();
    $fixer->fix_amputees();
    $fixer->generate_report();
}
?>
	</body>
	</html>
	/**
	 * Create a new table in Reason as part of a type
	 *
	 * @param string $table_name
	 * @param string $type_unique_name
	 * @param mixed $username string or integer user id
	 * @return mixed integer table id if successful or false if unsuccessful
	 */
	function create_reason_table($table_name, $type_unique_name, $username)
	{
		if(str_replace(' ','_',addslashes($table_name)) != $table_name)
		{
			trigger_error( 'The table name ' . $table_name . ' does not exist.');
			return false;
		}
		if(is_numeric($type_unique_name))
			$type_id = $type_unique_name;
		else
			$type_id = id_of($type_unique_name, false); // lets not use cache in case type was just created
		if(empty($type_id))
		{
			trigger_error( 'The type ' . $type_unique_name . ' does not exist.');
			return false;
		}
		else
		{
			$es = new entity_selector();
			$es->add_type(id_of('content_table'));
			$es->add_relation('entity.name = "'.$table_name.'"');
			$results = $es->run_one();
			if(!empty($results))
			{
				trigger_error( 'Unable to create table ' . $table_name . ', which already exists.');
				return false;
			}
			else
			{
				$q = "CREATE TABLE ".$table_name." (id int unsigned primary key)" ;
				if(db_query( $q, 'Unable to create new table' ))
				{
					if(is_numeric($username))
						$user_id = $username;
					else
						$user_id = get_user_id($username);
					$id = reason_create_entity(id_of('master_admin'), id_of('content_table'), $user_id, $table_name, array('new' => 0));
					create_relationship( $type_id, $id, relationship_id_of('type_to_table'));
					reason_include_once('classes/amputee_fixer.php');
					$fixer = new AmputeeFixer();
					$fixer->fix_amputees($type_id);
					// Trigger error on normal behavior? No thanks.
					//trigger_error( 'The table ' . $table_name . ' was created and added to the type ' . $type_unique_name);
					return $id;
				}
			}
		}
	}
 //echo 'the script cannot continue to run and this database has ';
 //echo 'probably already been upgraded.</p>';
 //die;
 //check if entity table date_format exists
 if ($blog_type_exists && create_entity_table("date_format", "blog_type", get_user_id($user_netID))) {
     echo '<p>created entity table date_format and added to blog type</p>';
     $fixer = new AmputeeFixer();
     $fixer->fix_amputees(id_of('blog_type'));
     $fixer->generate_report();
 } else {
     echo '<p>date_format entity table already exists - not created</p>';
 }
 //check if entity table news_section exists
 if (create_entity_table("news_section", "news_section_type", get_user_id($user_netID))) {
     echo '<p>created entity table news_section and added to news section type</p>';
     $fixer = new AmputeeFixer();
     $fixer->fix_amputees(id_of('news_section_type'));
     $fixer->generate_report();
 } else {
     echo '<p>news_section entity table already exists - not created</p>';
 }
 //$entity_table_name = 'commenting_settings';
 //$fields = array('enable_comment_notification' => array('db_type' => "enum('yes','no')"));
 //$updater = new FieldToEntityTable($entity_table_name, $fields);
 //$updater->update_entity_table();
 //$updater->report();
 $entity_table_name = 'date_format';
 $fields = array('date_format' => array('db_type' => 'tinytext'));
 $updater2 = new FieldToEntityTable($entity_table_name, $fields);
 $updater2->update_entity_table();
 $updater2->report();
$es = new entity_selector();
$es->add_relation('entity.name = "external_css"');
$es->set_num(1);
$tables = $es->run_one(id_of('content_table'));
if (empty($tables)) {
    echo 'no "external_css" content table entity exists<br />';
    $table_id = create_reason_table('external_css', 'css', $current_user);
    if (!empty($table_id)) {
        echo 'Created external_css table for the css type<br />';
        reason_include_once('classes/field_to_entity_table_class.php');
        reason_include_once('classes/amputee_fixer.php');
        $fields = array('css_relative_to_reason_http_base' => array('db_type' => "enum('true','false')"));
        $updater = new FieldToEntityTable('external_css', $fields);
        $updater->update_entity_table();
        $updater->report();
        $fixer = new AmputeeFixer();
        $fixer->fix_amputees(id_of('css'));
        $fixer->generate_report();
    }
}
$es = new entity_selector();
$es->add_relation('url = "/global_stock/css/tableless_layouts/three_column_1.css"');
$es->set_num(1);
$css_entities = $es->run_one(id_of('css'));
if (!empty($css_entities)) {
    $css_entity = current($css_entities);
    echo 'Updating ' . $css_entity->get_value('name') . '<br />';
    reason_update_entity($css_entity->id(), $user_id, array('url' => 'css/tableless_layouts/three_column_1.css', 'css_relative_to_reason_http_base' => 'true'));
}
$es = new entity_selector();
$es->add_relation('url = "/global_stock/css/opensource_reason/reason.css"');
 $es = new entity_selector();
 $es->add_relation('entity.name = "audience_integration"');
 $es->set_num(1);
 $tables = $es->run_one(id_of('content_table'));
 if (empty($tables)) {
     $out[] = "no content table entity exists";
     $table_id = create_reason_table('audience_integration', $audience_type_id, 'root');
     if (!empty($table_id)) {
         $out[] = 'The table audience_integration was created and added to the type audience_type';
         reason_include_once('classes/field_to_entity_table_class.php');
         reason_include_once('classes/amputee_fixer.php');
         $fields = array('directory_service_value' => array('db_type' => 'tinytext'), 'directory_service' => array('db_type' => 'tinytext'), 'audience_filter' => array('db_type' => 'tinytext'));
         $updater = new FieldToEntityTable('audience_integration', $fields);
         $updater->update_entity_table();
         $updater->report();
         $fixer = new AmputeeFixer();
         $fixer->fix_amputees($audience_type_id);
         $fixer->generate_report();
     }
 }
 $audience_ids = array();
 foreach ($audiences as $audience => $audience_data) {
     $out[] = 'Looking at audience: ' . $audience;
     if (!id_of($audience . '_audience')) {
         $out[] = $audience . ' entity does not exist yet';
         $audience_ids[$audience] = reason_create_entity(id_of('master_admin'), $audience_type_id, get_user_id('root'), $audience_data['name'], $audience_data);
         $out[] = 'Created ' . $audience . ' entity';
     } else {
         $out[] = $audience . ' exists';
         reason_update_entity(id_of($audience . '_audience'), get_user_id('root'), $audience_data);
         $audience_ids[$audience] = id_of($audience . '_audience');
	protected function _add_table($table_name)
	{
		$es = new entity_selector();
		$es->add_type(id_of('content_table'));
		$es->add_relation('entity.name = "'.addslashes($table_name).'"');
		$es->set_num(1);
		$results = $es->run_one();
		
		if(empty($results))
		{
			create_reason_table($table_name, $this->type_unique_name(), $this->user_id());
			$ret = '<p>Created the '.htmlspecialchars($table_name).' table.</p>';
		}
		else
		{
			$table_entity = current($results);
			create_relationship( $this->type_id(), $table_entity->id(), relationship_id_of('type_to_table'));
			
			$ret = '<p>Added the '.htmlspecialchars($table_name).' table to the '.htmlspecialchars($this->type_unique_name()).' type.</p>'."\n";
		}
		$fixer = new AmputeeFixer();
		$fixer->fix_amputees($this->type_id());
		
		return $ret;
	}
function add_entity_table_to_type($et, $type)
{
    $pub_type_id = id_of($type);
    $es = new entity_selector(id_of('master_admin'));
    $es->add_type(id_of('content_table'));
    $es->add_right_relationship($pub_type_id, relationship_id_of('type_to_table'));
    $es->add_relation('entity.name = "' . $et . '"');
    $entities = $es->run_one();
    if (empty($entities)) {
        $es2 = new entity_selector();
        $es2->add_type(id_of('content_table'));
        $es2->add_relation('entity.name = "' . $et . '"');
        $es2->set_num(1);
        $tables = $es2->run_one();
        if (!empty($tables)) {
            $table = current($tables);
            create_relationship($pub_type_id, $table->id(), relationship_id_of('type_to_table'));
            $fixer = new AmputeeFixer();
            $fixer->fix_amputees($pub_type_id);
            $fixer->generate_report();
            return true;
        }
    }
    return false;
}
 /**
  * fix the amputees
  */
 function run()
 {
     $fixer = new AmputeeFixer();
     $fixer->fix_amputees($this->vars['id']);
 }
function create_external_url_type($type_id, $type_name, $type_unique_name, $type_plural_name, $entity_table_fields)
{
    $user_id = get_user_id(reason_require_authentication());
    if ($type_id == 0) {
        $type_id = reason_create_entity(id_of('master_admin'), id_of('type'), $user_id, $type_name, array('unique_name' => $type_unique_name, 'plural_name' => $type_plural_name, 'new' => 0));
        if ($type_id != 0) {
            report($type_name . ' type created');
            if (@create_default_rels_for_new_type($type_id, $type_unique_name)) {
                report($type_name . ' default rels created');
            }
        } else {
            warn($type_name . ' not created - this is unexpected');
            return false;
        }
    }
    if (!empty($entity_table_fields)) {
        foreach ($entity_table_fields as $table_name => $table_fields) {
            $table_id = @create_reason_table($table_name, $type_id, $user_id);
            if ($table_id) {
                report('created entity table ' . $table_name . ' with id ' . $table_id);
            } else {
                report('did not create entity table ' . $table_name . ' - probably already exists - will try to add to type');
                add_entity_table_to_type($table_name, $type_id);
            }
            $updater = new FieldToEntityTable($table_name, $table_fields);
            $updater->update_entity_table();
            if ($updater->fields > 0) {
                ob_start();
                $updater->report();
                $updater_report = '<h3>Amputee Report - entity table ' . $table_name . '</h3><hr />' . ob_get_contents() . '<hr />';
                ob_end_clean();
                report($updater_report);
            }
        }
        $fixer = new AmputeeFixer();
        $fixer->fix_amputees($type_id);
        report('fixed amputees for type ' . $type_name);
    } else {
        report($type_name . ' requires no entity table(s) because it has no fields other than what is in the entity table');
    }
    return $type_id;
}