/**
* Save the preferences file
*
* @param array	$preferences	The preferences to save
* @param string	$prefs_file		The preferences file to save
*
* @return boolean
* @access public
*/
function _savePreferences($preferences, $prefs_file)
{
    if (empty($preferences)) {
        return FALSE;
    }
    $str = '<' . '?php $preferences = ' . var_export($preferences, TRUE) . '; ?' . '>';
    // Backup the existing preference file
    if (file_exists($prefs_file)) {
        $i = 0;
        do {
            $i++;
            $old_version = $prefs_file . '.' . $i;
        } while (file_exists($old_version));
        if (!copy($prefs_file, $old_version)) {
            return FALSE;
        }
    }
    // endif
    require_once SQ_FUDGE_PATH . '/general/file_system.inc';
    // make sure the directory exists
    if (!create_directory(dirname($prefs_file))) {
        return FALSE;
    }
    // and save the file
    if (!string_to_file($str, $prefs_file)) {
        return FALSE;
    }
    // Otherwise a OK!
    return TRUE;
}
function upgrade_import_tool_configs()
{
    $root_user =& $GLOBALS['SQ_SYSTEM']->am->getSystemAsset('root_user');
    $GLOBALS['SQ_SYSTEM']->setCurrentUser($root_user);
    $GLOBALS['SQ_SYSTEM']->setRunLevel(SQ_RUN_LEVEL_FORCED);
    // update cms export path
    $import_manager = $GLOBALS['SQ_SYSTEM']->am->getSystemAsset('import_tools_manager');
    $cms_export_dir = $import_manager->attr('cms_file_export_dir');
    if (!empty($cms_export_dir) && strpos($cms_export_dir, '/') === 0) {
        $cms_export_dir_new = str_replace(SQ_SYSTEM_ROOT . '/', '', $cms_export_dir);
        if ($cms_export_dir_new !== $cms_export_dir) {
            $import_manager->setAttrValue('cms_file_export_dir', $cms_export_dir_new);
            $import_manager->saveAttributes();
            echo "Updated Import Tools Manager CMS Export Path\n";
        } else {
            echo "Absolute path found in form Import Tools Manager CMS FIle Export Dir. It can not be automatically converted to relative path. Location: {$cms_export_dir}\n";
        }
    }
    // update STRUCTURED_FILE_IMPORT_DIR and BULK_FILE_IMPORT_DIR
    require_once SQ_FUDGE_PATH . '/general/file_system.inc';
    $config_file = file_to_string(SQ_DATA_PATH . '/private/conf/import_tools_manager.inc');
    if (strpos($config_file, SQ_SYSTEM_ROOT . '/') !== FALSE) {
        $config_file = str_replace(SQ_SYSTEM_ROOT . '/', '', $config_file);
        string_to_file($config_file, SQ_DATA_PATH . '/private/conf/import_tools_manager.inc');
        echo "Updated Import Tools Manager Structed FIle Import and Bulk FIle Import Path\n";
    }
    // update word import tool converter
    $converters = $GLOBALS['SQ_SYSTEM']->am->getChildren('1', 'import_tool_converter_word');
    $converter = $GLOBALS['SQ_SYSTEM']->am->getAsset(array_pop(array_keys($converters)));
    $upload_directory = $converter->attr('upload_directory');
    if (!empty($upload_directory) && strpos($upload_directory, '/') === 0) {
        $upload_directory_new = str_replace(SQ_SYSTEM_ROOT . '/', '', $upload_directory);
        if ($upload_directory_new !== $upload_directory) {
            $converter->setAttrValue('upload_directory', $upload_directory_new);
            $converter->saveAttributes();
            echo "Updated Import Tools Manager Word Converter Path\n";
        } else {
            echo "Absolute path found in form Import Tools Manager Word Converter. It can not be automatically converted to relative path. Location: {$upload_directory}\n";
        }
    }
    // update file bridge config
    $config_file = file_to_string(SQ_DATA_PATH . '/private/conf/file_bridge.inc');
    if (strpos($config_file, SQ_SYSTEM_ROOT . '/') !== FALSE) {
        $config_file = str_replace(SQ_SYSTEM_ROOT . '/', '', $config_file);
        string_to_file($config_file, SQ_DATA_PATH . '/private/conf/file_bridge.inc');
        echo "Updated File Bridge Path\n";
    }
    $GLOBALS['SQ_SYSTEM']->restoreRunLevel();
    $GLOBALS['SQ_SYSTEM']->restoreCurrentUser();
}
/**
 * _updateFile
 * Update the target file by removing it first and then replace with a new file, update file versioning of it
 *
 * @return Boolean
 */
function _updateFile($new_file, $file_name, $data_path, $data_path_suffix)
{
    require_once SQ_FUDGE_PATH . '/general/file_system.inc';
    $fv = $GLOBALS['SQ_SYSTEM']->getFileVersioning();
    $file_path = $data_path . '/' . $file_name;
    if (!unlink($file_path)) {
        trigger_error('failed to remove old file ' . $file_name);
        return FALSE;
    }
    if (string_to_file(file_get_contents($new_file), $file_path)) {
        // add a new version to the repository
        $file_status = $fv->upToDate($file_path);
        if (FUDGE_FV_MODIFIED & $file_status) {
            if (!$fv->commit($file_path, '')) {
                trigger_localised_error('CORE0160', translate('Failed committing file version'), E_USER_WARNING);
            }
        }
    } else {
        trigger_error('Can not overwrite old file ' . $file_name);
    }
    // make sure we have the latest version of our file
    if (!$fv->checkOut($data_path_suffix . '/' . $file_name, $data_path)) {
        trigger_localised_error('CORE0032', translate('Failed checking out latest version of file'), E_USER_WARNING);
        return FALSE;
    }
    //end if
    return TRUE;
}
                printStatus($count . '/' . $total_number);
            }
            // blank out old value and new value returned from set attribute action.
            // recording the attribute value content will flood our temp data file and memory
            $new_entry = array_slice($import_action_outputs, -1, 1, TRUE);
            $new_entry_key = key($new_entry);
            if (isset($new_entry[$new_entry_key]['old_value'])) {
                unset($new_entry[$new_entry_key]['old_value']);
            }
            if (isset($new_entry[$new_entry_key]['new_value'])) {
                unset($new_entry[$new_entry_key]['new_value']);
            }
            $import_action_outputs = array_merge($import_action_outputs, $new_entry);
            // save global temp data to file
            $temp_string = serialize($import_action_outputs);
            string_to_file($temp_string, TEMP_FILE);
            $GLOBALS['SQ_SYSTEM']->doTransaction('COMMIT');
            $GLOBALS['SQ_SYSTEM']->restoreRunLevel();
            // Disconnect from DB
            _disconnectFromMatrixDatabase();
            exit(0);
            break;
        default:
            $status = null;
            pcntl_waitpid(-1, $status);
            break;
    }
    //end switch
}
_connectToMatrixDatabase();
// restore import action outputs from file
/**
* @author David Schoen
* $ID$
*/
require_once dirname(dirname(dirname(__FILE__))) . '/init.inc';
require_once SQ_FUDGE_PATH . '/general/file_system.inc';
$package = 'PACKAGE NAME HERE';
$export_dir = 'exported_attributes';
mkdir($export_dir) || trigger_error($export_dir . ' dir exists!', E_USER_ERROR);
$asset_types = get_asset_types_for_package($package);
foreach ($asset_types as $type) {
    $ids = get_asset_ids_by_type($type);
    foreach ($ids as $id) {
        $attrs = get_asset_attributes($id);
        string_to_file(serialize($attrs), "{$export_dir}/{$id}");
    }
}
function get_asset_attributes($assetId)
{
    $asset = $GLOBALS['SQ_SYSTEM']->am->getAsset($assetId);
    $attrs = array();
    foreach ($asset->vars as $attrName => $attrInfo) {
        $attrVal = $asset->attr($attrName);
        $attrs[$attrName] = $attrVal;
    }
    return $attrs;
}
function get_asset_ids_by_type($type_code)
{
    $res = $GLOBALS['SQ_SYSTEM']->db->getAll("select assetid from sq_ast where type_code = '{$type_code}'");
/**
*
* @param string	$file	the file to run through
*
* @return boolean
* @access public
*/
function process_file($path, $file, $force)
{
    $file_contents = file_get_contents($file);
    preg_match('|<files locale="([^"]*)">.*</file>|s', $file_contents, $match);
    // get locale and replace delimiters between locale parts with slashes
    $locale = $match[1];
    $locale = str_replace('@', '/', $locale);
    $locale = str_replace('_', '/', $locale);
    $old_force = $force;
    preg_match_all('|<file source="([^"]*)" name="([^"]*)">(.*)</file>|Us', $file_contents, $matches, PREG_SET_ORDER);
    foreach ($matches as $match) {
        $file_name = $path . '/' . $match[1] . '/' . $locale . '/' . $match[2];
        $file_str = '<?xml version="1.0" ?>' . "\n" . $match[3];
        if (!file_exists($file_name)) {
            $force = true;
        } else {
            $force = $old_force;
        }
        if (!$force) {
            // ask for the root password for the system
            echo 'Overwrite file ' . hide_system_root($file_name) . '?';
            $overwrite_confirm = '';
            while (strlen($overwrite_confirm) == 0 || strtolower($overwrite_confirm[0]) != 'y' && strtolower($overwrite_confirm[0]) != 'n') {
                $overwrite_confirm = rtrim(fgets(STDIN, 4094));
            }
            if (strtolower($overwrite_confirm[0]) == 'y') {
                $force = true;
            }
        }
        if ($force) {
            // create directory and dump file
            create_directory($path . '/' . $match[1] . '/' . $locale);
            string_to_file($file_str, $file_name);
            echo 'Wrote ' . hide_system_root($file_name) . "\n";
        }
    }
    return true;
}
        $thumbnail_exists = FALSE;
        foreach ($content as $link) {
            if ($link['value'] == 'thumbnail') {
                $thumbnail_exists = TRUE;
                break;
            }
        }
        $content[] = $notice_link;
        if (!$thumbnail_exists && !string_to_file(serialize($content), $asset->data_path . '/.sq_system/.sq_notice_links')) {
            print_r('Still writing :(');
            $count++;
            $bad_assetids[] = $assetid;
        }
    } else {
        $content[] = $notice_link;
        if (!string_to_file(serialize($content), $asset->data_path . '/.sq_system/.sq_notice_links')) {
            $count++;
            $bad_assetids[] = $assetid;
        }
    }
    $done_asset++;
    unset($assetid);
}
// Warn the user if an error happened
if (!empty($count)) {
    echo "There were {$count} errors in creating .sq_notice_links files.\nThese assets may need to be reviewed manually.\n";
    echo "Assetids that need to be looked into (These are in error.log too):\n";
    print_r($bad_assetids);
    // put them in error.log too
    log_dump("There were " . $count . " errors in creating .sq_notice_links files.\nThese assets may need to be reviewed manually.");
    log_dump("Assetids that need to be looked into :");