#!/usr/bin/php
<?php

if (!@include_once(dirname(dirname(__FILE__)).'/application/bootstrap_cli.php')) {
	echo "Please create a 'application/bootstrap-cli.php' file  to setup the include path and error handling\n";
	exit(-1);
}
$to_file = true;
if (isset($argv[1])) {
	if (in_array($argv[1], array('to-file', 'to-lob'))) {
		$to_file = $argv[1]=='to-file';
	} else {
		print "\nPlease use ".basename(__FILE__)." [to-file|to-lob]\n";
		print " - to-file (default): Will store any lobdata as a file\n";
		print " - to-lob           : Will store any file lobdata as a lobdata only\n\n";
		die();
	}
}
print "Updating Lob Fields:\n";


$db = &Objlib::GET(Objlib::TYPE_DB);
if (!isset($db->lob_data_path)) {
	die("The databases lob_data_path must be set\n");
}
require_once 'PHPOF2/DBTable.php';
// Go through all tables
$res = $db->query('show tables');
while ($row=$res->fetchRow()) {
	$table = new PHPOF2_DBTable($db, $row[0]);
	echo "Processing Table: $table->name\n";
	$table_row = $table->createRowObject();
	
	//Process Lob fields
	foreach ($table->getFieldListLOB() as $lob_field) {
		$non_lob_fields = $table->getPrimaryKeys()+$table->getFieldListNormal();
		
		$sql = "SELECT " . implode(',', $non_lob_fields) . " FROM $table->name WHERE $lob_field IS NOT NULL AND SUBSTRING(CONVERT($lob_field  USING utf8), 1, ".strlen(PHPOF2_DBRow::LOB_FILE_MARKER).")".($to_file?'!=':'=').$db->quote(PHPOF2_DBRow::LOB_FILE_MARKER);
		$lob_rows = $db->query($sql);
		echo "- Lob Field: $lob_field, Rows to process(".$lob_rows->numRows() . ")\n";
		while ($lob_rows->fetchInToObject($table_row)) {
			$lob_data = $table_row->getLobData($lob_field);
			$table_row->storeLobData($lob_data, $lob_field, !$to_file);
		}
	}
}
