/**
  * Create a duplicate. 
  *
  * @param integer $customWriteModuleId
  * @param string $duplicate_name the name of the duplicate, if false,
  *           the name "[MODULE NAME] copy [x] will be given to the duplicate. 
  */
 function Create($customWriteModuleId, $duplicate_name = false)
 {
     global $wpdb;
     // Get module name
     $customModule = RCCWP_CustomWriteModule::Get($customWriteModuleId);
     if (!$duplicate_name) {
         // go ahead and rename, then duplicate
         $duplicate_name = $customModule->name;
         if ($other_blocks = $wpdb->get_results("SELECT duplicate_name FROM " . FLUTTER_TABLE_MODULES_DUPLICATES . " WHERE duplicate_name LIKE '" . preg_replace('/\\scopy\\s[0-9]*/', '', $duplicate_name) . " %' ORDER BY duplicate_id DESC")) {
             $duplicate_name = $other_blocks[0]->duplicate_name;
             $testcase = substr($duplicate_name, -1, 1);
             $duplicate_name[strlen($duplicate_name) - 1] = intval($testcase) + 1;
         } else {
             $duplicate_name .= ' copy 2';
         }
     }
     $wpdb->query("INSERT INTO " . FLUTTER_TABLE_MODULES_DUPLICATES . " (module_id, duplicate_name) VALUES ({$customWriteModuleId}, '{$duplicate_name}')");
     FlutterLayoutBlock::UpdateAllModulesSettings();
     return $wpdb->insert_id;
 }
 $moduleTmpPath = "{$tmpPath}{$module->name}";
 chmod_R($moduleTmpPath, 0777);
 // Export write panels
 //check if arrary the write modules is empty
 if ($_POST["write_panels"] != NULL) {
     $write_panels = split(",", $_POST["write_panels"]);
     foreach ($write_panels as $panelID) {
         $writePanel = RCCWP_CustomWritePanel::Get($panelID);
         $exportedFilename = $moduleTmpPath . DIRECTORY_SEPARATOR . '_' . $writePanel->name . '.pnl';
         RCCWP_CustomWritePanel::Export($panelID, $exportedFilename);
     }
 }
 // Export duplicates and description
 $moduleInfoFilename = $moduleTmpPath . DIRECTORY_SEPARATOR . 'module_info.exp';
 $moduleInfo_exported_data['duplicates'] = RCCWP_ModuleDuplicate::GetCustomModulesDuplicates($moduleID);
 $moduleInfo_exported_data['moduleinfo'] = RCCWP_CustomWriteModule::Get($moduleID);
 $handle = fopen($moduleInfoFilename, "w");
 $result = @fwrite($handle, serialize($moduleInfo_exported_data));
 @fclose($handle);
 // -- Create zip file
 $zipFile = "{$tmpPath}{$module->name}.zip";
 chdir($moduleTmpPath . DIRECTORY_SEPARATOR);
 if (RCCWP_Application::CheckCompressionProgramZip()) {
     $command = "zip -r {$zipFile}  ./*";
 } else {
     _e('Cannot find zip program', $flutter_domain);
     return;
 }
 exec($command, $out, $err);
 // send file in header
 header('Content-type: binary');
 /**
  * Import a module given the zip file path. Importing a module means inserting it in
  * the database and copying its folder to modules folder. If a module with the same
  * name already exists, the function will append a number to the module name. You must 
  * have either php ZipArchive extension or unzip program installed.
  *
  * @param string $zipFilePath the full path of the zip file
  * @param string $moduleName the module name, if this value if false, the function will
  * 							use the zip filename as the module name. The default value is false
  * @return the module id, or false in case of error.
  */
 function Import($zipFilePath, $moduleName = false)
 {
     include_once 'RCCWP_CustomGroup.php';
     include_once 'RCCWP_CustomField.php';
     include_once 'RCCWP_CustomWritePanel.php';
     include_once 'RCCWP_Application.php';
     include_once 'RCCWP_CustomWritePanel.php';
     global $flutter_domain;
     if (!strpos($zipFilePath, ".zip")) {
         return false;
     }
     if (!$moduleName) {
         //use zip filename
         $moduleName = basename($zipFilePath, ".zip");
     }
     if ($moduleName == '') {
         return false;
     }
     // Append a number if the module already exists,
     $i = 1;
     $newModuleName = $moduleName;
     while (file_exists(FLUTTER_MODULES_DIR . $newModuleName)) {
         $newModuleName = $moduleName . "_" . $i++;
     }
     $moduleName = $newModuleName;
     mkdir(FLUTTER_MODULES_DIR . $moduleName);
     chmod(FLUTTER_MODULES_DIR . $moduleName, 0777);
     $destPath = FLUTTER_MODULES_DIR . $moduleName . DIRECTORY_SEPARATOR;
     if (class_exists('ZipArchive')) {
         $zip = new ZipArchive();
         // open archive
         if ($zip->open($zipFilePath) !== TRUE) {
             die(__('Could not open archive', $flutter_domain));
         }
         // extract contents to destination directory
         $zip->extractTo($destPath);
         // close archive
         $zip->close();
     } else {
         if (RCCWP_Application::CheckDecompressionProgramUnzip()) {
             $command = "unzip {$zipFilePath} -d " . $destPath;
         } else {
             die(__('Cannot find unzip program!', $flutter_domain));
         }
         exec($command, $out, $err);
     }
     $moduleInfo_imported_data = unserialize(file_get_contents($destPath . 'module_info.exp'));
     //Import module
     $moduleID = RCCWP_CustomWriteModule::Create($moduleName, $moduleInfo_imported_data['moduleinfo']->description, false);
     //Import any panels
     if ($handle = @opendir($destPath)) {
         while (false !== ($file = readdir($handle))) {
             if (substr($file, 0, 1) == "_") {
                 $panelName = basename(substr($file, 1), ".pnl");
                 RCCWP_CustomWritePanel::Import($destPath . $file, $panelName);
             }
         }
     }
     //Create Duplicates
     foreach ($moduleInfo_imported_data['duplicates'] as $moduleDuplicate) {
         RCCWP_ModuleDuplicate::Create($moduleID, $moduleDuplicate->duplicate_name);
     }
     return $moduleID;
 }
 function Import()
 {
     global $flutter_domain;
     include_once 'RCCWP_CustomWriteModule.php';
     if (isset($_FILES['import-module-file']) && !empty($_FILES['import-module-file']['tmp_name'])) {
         $zipFilePath = $_FILES['import-module-file']['tmp_name'];
     } else {
         die(_e('Error uploading file!', $flutter_domain));
     }
     $moduleName = basename($_FILES['import-module-file']['name'], ".zip");
     $moduleID = RCCWP_CustomWriteModule::Import($zipFilePath, $moduleName);
     unlink($zipFilePath);
     echo "<h3>" . __('The module was imported successfuly.', $flutter_domain) . "</h3>";
     echo '<p><a href="' . RCCWP_ManagementPage::GetCustomWriteModuleEditUrl($moduleID) . '"> ' . __('Click here', $flutter_domain) . ' </a>' . __(' to edit the module.', $flutter_domain) . ' </p>';
 }
 /**
  * Import default modules/panels in the theme if it is the first time to 
  * activate the theme and add the theme settings to the database.
  *
  */
 function ImportNewTheme($themeName)
 {
     // -- Add/update theme settings to the database
     FlutterLayoutBlock::UpdateModuleSettings(get_template_directory() . '/configure.xml', -1, '-', get_option('template'));
     FlutterLayoutBlock::UpdateAllModulesSettings();
     // -- Import modules and panels
     if (RCCWP_Application::IsWordpressMu()) {
         if (get_site_option('Flutter_theme_ft_' . $themeName) == '1') {
             return;
         }
         update_site_option('Flutter_theme_ft_' . $themeName, '1');
     } else {
         if (get_option('Flutter_theme_ft_' . $themeName) == '1') {
             return;
         }
         update_option('Flutter_theme_ft_' . $themeName, '1');
     }
     $modulesFolder = get_template_directory() . '/Flutter_modules/';
     $panelsFolder = get_template_directory() . '/Flutter_panels/';
     // Import modules
     if ($handle = @opendir($modulesFolder)) {
         while (false !== ($file = readdir($handle))) {
             $filePath = $modulesFolder . $file;
             RCCWP_CustomWriteModule::Import($filePath);
         }
     }
     // Import panels
     if ($handle = @opendir($panelsFolder)) {
         while (false !== ($file = readdir($handle))) {
             $filePath = $panelsFolder . $file;
             RCCWP_CustomWritePanel::Import($filePath);
         }
     }
 }
 function Main()
 {
     require_once 'RC_Format.php';
     global $CUSTOM_WRITE_PANEL;
     wp_enqueue_script('jquery-ui-sortable');
     if (isset($_POST['edit-with-no-custom-write-panel'])) {
         wp_redirect('post.php?action=edit&post=' . $_POST['post-id'] . '&no-custom-write-panel=' . $_POST['custom-write-panel-id']);
     } else {
         if (isset($_POST['edit-with-custom-write-panel'])) {
             wp_redirect('post.php?action=edit&post=' . $_POST['post-id'] . '&custom-write-panel-id=' . $_POST['custom-write-panel-id']);
         }
     }
     if (empty($_REQUEST['flutter_action'])) {
         $currentAction = "";
     } else {
         $currentAction = $_REQUEST['flutter_action'];
     }
     switch ($currentAction) {
         // ------------ Write Panels
         case 'finish-create-custom-write-panel':
             include_once 'RCCWP_CustomWritePanel.php';
             $default_theme_page = NULL;
             if ($_POST['radPostPage'] == 'page') {
                 $default_theme_page = $_POST['page_template'];
             }
             $customWritePanelId = RCCWP_CustomWritePanel::Create($_POST['custom-write-panel-name'], $_POST['custom-write-panel-description'], $_POST['custom-write-panel-standard-fields'], $_POST['custom-write-panel-categories'], $_POST['custom-write-panel-order'], FALSE, true, $_POST['single'], $default_theme_page);
             wp_redirect(RCCWP_ManagementPage::GetCustomWritePanelGenericUrl('view-custom-write-panel', $customWritePanelId));
             break;
         case 'submit-edit-custom-write-panel':
             include_once 'RCCWP_CustomWritePanel.php';
             $default_theme_page = NULL;
             if ($_POST['radPostPage'] == 'page') {
                 $default_theme_page = $_POST['page_template'];
             }
             RCCWP_CustomWritePanel::Update($_POST['custom-write-panel-id'], $_POST['custom-write-panel-name'], $_POST['custom-write-panel-description'], $_POST['custom-write-panel-standard-fields'], $_POST['custom-write-panel-categories'], $_POST['custom-write-panel-order'], FALSE, true, $_POST['single'], $default_theme_page);
             RCCWP_CustomWritePanel::AssignToRole($_POST['custom-write-panel-id'], 'administrator');
             break;
         case 'export-custom-write-panel':
             require_once 'RCCWP_CustomWritePanel.php';
             $panelID = $_REQUEST['custom-write-panel-id'];
             $writePanel = RCCWP_CustomWritePanel::Get($panelID);
             $exportedFilename = $tmpPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $writePanel->name . '.pnl';
             RCCWP_CustomWritePanel::Export($panelID, $exportedFilename);
             // send file in header
             header('Content-type: binary');
             header('Content-Disposition: attachment; filename="' . $writePanel->name . '.pnl"');
             readfile($exportedFilename);
             unlink($exportedFilename);
             exit;
             break;
         case 'delete-custom-write-panel':
             include_once 'RCCWP_CustomWritePanel.php';
             RCCWP_CustomWritePanel::Delete($_GET['custom-write-panel-id']);
             //wp_redirect('?page=' . urlencode(FLUTTER_PLUGIN_DIR . DIRECTORY_SEPARATOR . 'RCCWP_Menu.php'));
             break;
             // ------------ Modules
             // ------------ Groups
         // ------------ Modules
         // ------------ Groups
         case 'finish-create-custom-group':
             include_once 'RCCWP_CustomGroup.php';
             $customGroupId = RCCWP_CustomGroup::Create($_POST['custom-write-panel-id'], $_POST['custom-group-name'], $_POST['custom-group-duplicate'], $_POST['custom-group-at_right']);
             break;
         case 'delete-custom-group':
             include_once 'RCCWP_CustomGroup.php';
             $customGroup = RCCWP_CustomGroup::Get((int) $_REQUEST['custom-group-id']);
             RCCWP_CustomGroup::Delete($_GET['custom-group-id']);
             break;
         case 'submit-edit-custom-group':
             include_once 'RCCWP_CustomGroup.php';
             RCCWP_CustomGroup::Update($_REQUEST['custom-group-id'], $_POST['custom-group-name'], $_POST['custom-group-duplicate'], $_POST['custom-group-at_right']);
             break;
             // ------------ Fields
         // ------------ Fields
         case 'copy-custom-field':
             include_once 'RCCWP_CustomField.php';
             $fieldToCopy = RCCWP_CustomField::Get($_REQUEST['custom-field-id']);
             if (RCCWP_Processor::CheckFieldName($fieldToCopy->name, $_REQUEST['custom-write-panel-id'])) {
                 $newURL = RCCWP_ManagementPage::GetCustomWritePanelGenericUrl('create-custom-field') . '&custom-group-id=' . $_REQUEST['custom-group-id'] . '&err_msg=-1';
                 wp_redirect($newURL);
                 exit;
             }
             RCCWP_CustomField::Create($_REQUEST['custom-group-id'], $fieldToCopy->name, $fieldToCopy->description, $fieldToCopy->display_order, $fieldToCopy->required_field, $fieldToCopy->type_id, $fieldToCopy->options, $fieldToCopy->default_value, $fieldToCopy->properties, $fieldToCopy->duplicate);
         case 'continue-create-custom-field':
             if (RCCWP_Processor::CheckFieldName($_POST['custom-field-name'], $_REQUEST['custom-write-panel-id'])) {
                 $newURL = RCCWP_ManagementPage::GetCustomWritePanelGenericUrl('create-custom-field') . '&custom-group-id=' . $_REQUEST['custom-group-id'] . '&err_msg=-1';
                 wp_redirect($newURL);
                 exit;
             }
             break;
         case 'finish-create-custom-field':
             include_once 'RCCWP_CustomField.php';
             if (RCCWP_Processor::CheckFieldName($_POST['custom-field-name'], $_REQUEST['custom-write-panel-id'])) {
                 $newURL = RCCWP_ManagementPage::GetCustomWritePanelGenericUrl('create-custom-field') . '&custom-group-id=' . $_REQUEST['custom-group-id'] . '&err_msg=-1';
                 wp_redirect($newURL);
                 exit;
             }
             $current_field = RCCWP_CustomField::GetCustomFieldTypes((int) $_REQUEST['custom-field-type']);
             if ($current_field->has_properties) {
                 $custom_field_properties = array();
                 if (in_array($current_field->name, array('Textbox', 'Listbox'))) {
                     $custom_field_properties['size'] = $_POST['custom-field-size'];
                 } else {
                     if (in_array($current_field->name, array('Multiline Textbox'))) {
                         $custom_field_properties['height'] = $_POST['custom-field-height'];
                         $custom_field_properties['width'] = $_POST['custom-field-width'];
                     } else {
                         if (in_array($current_field->name, array('Date'))) {
                             $custom_field_properties['format'] = $_POST['custom-field-date-format'];
                         } else {
                             if (in_array($current_field->name, array('Image'))) {
                                 $params = '';
                                 if ($_POST['custom-field-photo-height'] != '' && is_numeric($_POST['custom-field-photo-height'])) {
                                     $params .= '&h=' . $_POST['custom-field-photo-height'];
                                 }
                                 if ($_POST['custom-field-photo-width'] != '' && is_numeric($_POST['custom-field-photo-width'])) {
                                     $params .= '&w=' . $_POST['custom-field-photo-width'];
                                 }
                                 if ($_POST['custom-field-custom-params'] != '') {
                                     $params .= '&' . $_POST['custom-field-custom-params'];
                                 }
                                 if ($params) {
                                     $custom_field_properties['params'] = $params;
                                 }
                             } else {
                                 if (in_array($current_field->name, array('Date'))) {
                                     $custom_field_properties['format'] = $_POST['custom-field-date-format'];
                                 } else {
                                     if (in_array($current_field->name, array('Slider'))) {
                                         $custom_field_properties['max'] = $_POST['custom-field-slider-max'];
                                         $custom_field_properties['min'] = $_POST['custom-field-slider-min'];
                                         $custom_field_properties['step'] = $_POST['custom-field-slider-step'];
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             RCCWP_CustomField::Create($_POST['custom-group-id'], $_POST['custom-field-name'], $_POST['custom-field-description'], $_POST['custom-field-order'], $_POST['custom-field-required'], $_POST['custom-field-type'], $_POST['custom-field-options'], $_POST['custom-field-default-value'], $custom_field_properties, $_POST['custom-field-duplicate']);
             break;
         case 'submit-edit-custom-field':
             include_once 'RCCWP_CustomField.php';
             $current_field_obj = RCCWP_CustomField::Get($_POST['custom-field-id']);
             if ($_POST['custom-field-name'] != $current_field_obj->name && RCCWP_Processor::CheckFieldName($_POST['custom-field-name'], $_REQUEST['custom-write-panel-id'])) {
                 $newURL = RCCWP_ManagementPage::GetCustomWritePanelGenericUrl('edit-custom-field') . '&custom-field-id=' . $_POST['custom-field-id'] . '&err_msg=-1';
                 wp_redirect($newURL);
                 exit;
             }
             $current_field = RCCWP_CustomField::GetCustomFieldTypes((int) $_POST['custom-field-type']);
             if ($current_field->has_properties) {
                 $custom_field_properties = array();
                 if (in_array($current_field->name, array('Textbox', 'Listbox'))) {
                     $custom_field_properties['size'] = $_POST['custom-field-size'];
                 } else {
                     if (in_array($current_field->name, array('Multiline Textbox'))) {
                         $custom_field_properties['height'] = $_POST['custom-field-height'];
                         $custom_field_properties['width'] = $_POST['custom-field-width'];
                     } else {
                         if (in_array($current_field->name, array('Image'))) {
                             $params = '';
                             if ($_POST['custom-field-photo-height'] != '' && is_numeric($_POST['custom-field-photo-height'])) {
                                 $params = '&h=' . $_POST['custom-field-photo-height'];
                             }
                             if ($_POST['custom-field-photo-width'] != '' && is_numeric($_POST['custom-field-photo-width'])) {
                                 $params .= '&w=' . $_POST['custom-field-photo-width'];
                             }
                             if ($_POST['custom-field-custom-params'] != '') {
                                 $params .= '&' . $_POST['custom-field-custom-params'];
                             }
                             if ($params) {
                                 $custom_field_properties['params'] = $params;
                             }
                         } else {
                             if (in_array($current_field->name, array('Date'))) {
                                 $custom_field_properties['format'] = $_POST['custom-field-date-format'];
                             } else {
                                 if (in_array($current_field->name, array('Slider'))) {
                                     $custom_field_properties['max'] = $_POST['custom-field-slider-max'];
                                     $custom_field_properties['min'] = $_POST['custom-field-slider-min'];
                                     $custom_field_properties['step'] = $_POST['custom-field-slider-step'];
                                 }
                             }
                         }
                     }
                 }
             }
             RCCWP_CustomField::Update($_POST['custom-field-id'], $_POST['custom-field-name'], $_POST['custom-field-description'], $_POST['custom-field-order'], $_POST['custom-field-required'], $_POST['custom-field-type'], $_POST['custom-field-options'], $_POST['custom-field-default-value'], $custom_field_properties, $_POST['custom-field-duplicate']);
             break;
         case 'delete-custom-field':
             include_once 'RCCWP_CustomField.php';
             if (isset($_REQUEST['custom-group-id']) && !empty($_REQUEST['custom-group-id'])) {
                 $customGroupId = (int) $_REQUEST['custom-group-id'];
             }
             $customGroup = RCCWP_CustomGroup::Get($customGroupId);
             RCCWP_CustomField::Delete($_REQUEST['custom-field-id']);
             break;
         case 'delete-theme-settings':
             include_once 'RCCWP_ThemeSettingsPage.php';
             $settings = new RCCWP_ThemeSettingsPage();
             $settings->remove_layout_setting();
             break;
         case 'create-layout-setting':
             include_once 'RCCWP_ThemeSettingsPage.php';
             if (!empty($_POST['variable_name'])) {
                 RCCWP_ThemeSettingsPage::finish_create_layout_element();
                 break;
             }
         default:
             if (RCCWP_Application::InWritePostPanel()) {
                 include_once 'RCCWP_Menu.php';
                 include_once 'RCCWP_WritePostPage.php';
                 $CUSTOM_WRITE_PANEL = RCCWP_Post::GetCustomWritePanel();
                 if (isset($CUSTOM_WRITE_PANEL) && $CUSTOM_WRITE_PANEL > 0) {
                     ob_start(array('RCCWP_WritePostPage', 'ApplyCustomWritePanelAssignedCategories'));
                     add_action('admin_head', array('RCCWP_WritePostPage', 'ApplyCustomWritePanelHeader'));
                     // Allows fields to be added to right
                     //	commented to test		add_action('submitpost_box', array('RCCWP_WritePostPage', 'CustomFieldCollectionInterfaceRight'), 5);
                     //						add_action('submitpage_box', array('RCCWP_WritePostPage', 'CustomFieldCollectionInterfaceRight'), 5);
                     // commented to test
                     add_action('add_meta_box', 'post', 'side', array('RCCWP_WritePostPage', 'CustomFieldCollectionInterfaceRight'));
                     // Allows fields to be added to the post edit body
                     add_action('simple_edit_form', array('RCCWP_WritePostPage', 'CustomFieldCollectionInterface'), 5);
                     add_action('edit_form_advanced', array('RCCWP_WritePostPage', 'CustomFieldCollectionInterface'), 5);
                     add_action('edit_page_form', array('RCCWP_WritePostPage', 'CustomFieldCollectionInterface'), 5);
                 } else {
                     if (!isset($_REQUEST['no-custom-write-panel']) && isset($_REQUEST['post'])) {
                         include_once 'RCCWP_Options.php';
                         $promptEditingPost = RCCWP_Options::Get('prompt-editing-post');
                         if ($promptEditingPost == 1) {
                             wp_redirect('?page=' . urlencode(FLUTTER_PLUGIN_DIR . DIRECTORY_SEPARATOR . 'RCCWP_Menu.php') . '&assign-custom-write-panel=' . (int) $_GET['post']);
                         }
                     }
                 }
             } else {
                 if (isset($_POST['finish-create-custom-write-module'])) {
                     include_once 'RCCWP_CustomWriteModule.php';
                     $customWriteModuleId = RCCWP_CustomWriteModule::Create($_POST['custom-write-module-name'], $_POST['custom-write-module-description']);
                     //RCCWP_CustomWritePanel::AssignToRole($customWritePanelId, 'administrator');
                     if ($customWriteModuleId == -1) {
                         //$_POST['create-custom-write-module'] = 1;
                         $modulesURL = '?page=' . 'FlutterManageModules' . '&view-modules=1&create-custom-write-module=1&err_msg=-1';
                         wp_redirect($modulesURL);
                     } else {
                         wp_redirect(RCCWP_ManagementPage::GetCustomWriteModuleEditUrl($customWriteModuleId));
                     }
                 } else {
                     if (isset($_POST['submit-edit-custom-write-module'])) {
                         include_once 'RCCWP_CustomWriteModule.php';
                         $customWriteModuleId = RCCWP_CustomWriteModule::Update($_REQUEST['custom-write-module-id'], $_REQUEST['custom-write-module-name'], $_REQUEST['custom-write-module-description']);
                         if ($customWriteModuleId == -1) {
                             $customWriteModuleId = $_REQUEST['custom-write-module-id'];
                             $modulesURL = '?page=' . 'FlutterManageModules' . "&edit-custom-write-module=1&view-custom-write-module={$customWriteModuleId}&custom-write-module-id={$customWriteModuleId}&err_msg=-1";
                             wp_redirect($modulesURL);
                         }
                         //RCCWP_CustomWritePanel::AssignToRole($_POST['custom-write-panel-id'], 'administrator');
                     } else {
                         if (isset($_POST['update-custom-write-panel-options'])) {
                             if ($_POST['uninstall-custom-write-panel'] == 'uninstall') {
                                 RCCWP_Application::Uninstall();
                                 wp_redirect('options-general.php');
                             } else {
                                 include_once 'RCCWP_Options.php';
                                 $options['hide-write-post'] = $_POST['hide-write-post'];
                                 $options['hide-write-page'] = $_POST['hide-write-page'];
                                 $options['hide-visual-editor'] = $_POST['hide-visual-editor'];
                                 $options['prompt-editing-post'] = $_POST['prompt-editing-post'];
                                 $options['assign-to-role'] = $_POST['assign-to-role'];
                                 $options['use-snipshot'] = $_POST['use-snipshot'];
                                 $options['enable-editnplace'] = $_POST['enable-editnplace'];
                                 $options['eip-highlight-color'] = $_POST['eip-highlight-color'];
                                 $options['enable-swfupload'] = $_POST['enable-swfupload'];
                                 $options['enable-browserupload'] = $_POST['enable-browserupload'];
                                 $options['default-custom-write-panel'] = $_POST['default-custom-write-panel'];
                                 $options['enable-HTMLPurifier'] = $_POST['enable-HTMLPurifier'];
                                 $options['tidy-level'] = $_POST['tidy-level'];
                                 $options['canvas_show_instructions'] = $_POST['canvas_show_instructions'];
                                 $options['canvas_show_zone_name'] = $_POST['canvas_show_zone_name'];
                                 $options['canvas_show'] = $_POST['canvas_show'];
                                 $options['ink_show'] = $_POST['ink_show'];
                                 RCCWP_Options::Update($options);
                             }
                         } else {
                             if (isset($_REQUEST['create-module-duplicate'])) {
                                 include_once 'RCCWP_ModuleDuplicate.php';
                                 $moduleID = $_REQUEST['custom-write-module-id'];
                                 RCCWP_ModuleDuplicate::Create($moduleID);
                                 wp_redirect(RCCWP_ManagementPage::GetCustomWriteModuleEditUrl($moduleID));
                             } else {
                                 if (isset($_POST['submit-edit-module-duplicate'])) {
                                     include_once 'RCCWP_ModuleDuplicate.php';
                                     $moduleID = $_REQUEST['custom-write-module-id'];
                                     RCCWP_ModuleDuplicate::Update($_REQUEST['module-duplicate-id'], $_REQUEST['module-duplicate-name']);
                                     wp_redirect('?page=' . urlencode(FLUTTER_PLUGIN_DIR . DIRECTORY_SEPARATOR . 'RCCWP_Menu.php') . '&view-custom-write-module=' . $moduleID . '&custom-write-module-id=' . $moduleID);
                                 } else {
                                     if (isset($_REQUEST['delete-module-duplicate'])) {
                                         include_once 'RCCWP_ModuleDuplicate.php';
                                         $moduleID = $_REQUEST['custom-write-module-id'];
                                         RCCWP_ModuleDuplicate::Delete($_REQUEST['module-duplicate-id']);
                                         wp_redirect(RCCWP_ManagementPage::GetCustomWriteModuleEditUrl($moduleID));
                                     } else {
                                         if (isset($_POST['delete-custom-write-module'])) {
                                             include_once 'RCCWP_CustomWriteModule.php';
                                             $moduleID = $_REQUEST['custom-write-module-id'];
                                             RCCWP_CustomWriteModule::Delete($moduleID);
                                             wp_redirect('?page=' . urlencode(FLUTTER_PLUGIN_DIR . DIRECTORY_SEPARATOR . 'RCCWP_Menu.php') . '&view-modules=1');
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
     }
 }
            } else {
                $templatesNamesStr = $templatesNamesStr . "<option value='" . $file . "'>" . $file . "</option>";
            }
        }
    }
    closedir($handle);
}
?>
<div class="lbContent">
<?php 
global $wpdb, $canvas;
$variables = $wpdb->get_results("SELECT * FROM " . $canvas->variables . " WHERE parent = '{$block_id}' ORDER BY variable_id");
$title = $wpdb->get_results("SELECT * FROM " . $canvas->main . " WHERE block_id = '{$block_id}'");
// Get module name
include_once 'RCCWP_CustomWriteModule.php';
$customWriteModule = RCCWP_CustomWriteModule::Get($title[0]->module_id);
if ($title[0]->duplicate_id == 0) {
    $title[0]->module_title = $customWriteModule->name;
} else {
    $title[0]->module_title = $wpdb->get_var("SELECT duplicate_name FROM " . $canvas->duplicates . " WHERE duplicate_id = " . $title[0]->duplicate_id);
}
$content = '<h3>' . $title[0]->module_title . '';
if ($title[0]->author != '' && $title[0]->uri != '') {
    $content .= '<span>by <a target="new" href="' . $title[0]->uri . '">' . $title[0]->author . '</a></span>';
}
if ($title[0]->description != '') {
    $content .= '<p>' . $title[0]->description . '</p>';
}
$F = "\$F";
$module_template_name_id = 'canvas_' . $zone . '_' . $position . '_' . $block_id . '_module_template_name';
$ListboxAJAX = FLUTTER_URI . "ajax/canvas-populate-listbox.php?mod_name=" . $module_name . "&template_name=";
 function UpdateAllModulesSettings()
 {
     global $wpdb;
     $customModules = RCCWP_CustomWriteModule::GetCustomModules();
     $currDuplicates = $wpdb->get_results("SELECT * FROM " . FLUTTER_TABLE_MODULES_DUPLICATES);
     $currModules = $wpdb->get_results("SELECT * FROM " . FLUTTER_TABLE_LAYOUT_MODULES);
     foreach ($currModules as $currModule) {
         // -- Delete obselete modules
         if ($currModule->module_id > -1) {
             $found = false;
             foreach ($customModules as $customModule) {
                 if ($customModule->id == $currModule->module_id) {
                     $found = true;
                 }
             }
             if (!$found) {
                 FlutterLayoutBlock::DeleteModule($currModule->module_id);
             }
         }
         // -- Delete obselete duplicates
         $found = false;
         foreach ($currDuplicates as $currDuplicate) {
             if ($currDuplicate->duplicate_id == $currModule->duplicate_id) {
                 $found = true;
             }
         }
         if (!$found && $currModule->duplicate_id != 0) {
             FlutterLayoutBlock::DeleteDuplicate($currModule->duplicate_id);
         }
     }
     // -- Insert/Update modules in the Layout table
     foreach ($customModules as $customModule) {
         $filename = FLUTTER_MODULES_DIR . $customModule->name . "/configure.xml";
         FlutterLayoutBlock::UpdateModuleSettings($filename, $customModule->id);
         //Insert duplicates
         $currDuplicates = $wpdb->get_results("SELECT * FROM " . FLUTTER_TABLE_MODULES_DUPLICATES . " WHERE module_id = '{$customModule->id}'");
         foreach ($currDuplicates as $currDuplicate) {
             FlutterLayoutBlock::UpdateModuleSettings($filename, $customModule->id, false, false, $currDuplicate->duplicate_id);
         }
     }
 }
    function Main()
    {
        global $flutter_domain;
        $modules = RCCWP_CustomWriteModule::GetCustomModules();
        if (isset($_GET['custom-write-panel-id']) && !empty($_GET['custom-write-panel-id'])) {
            $customWritePanelId = (int) $_GET['custom-write-panel-id'];
        }
        if (isset($_POST['custom-write-panel-id']) && !empty($_POST['custom-write-panel-id'])) {
            $customWritePanelId = (int) $_POST['custom-write-panel-id'];
        }
        ?>

		<div class="wrap">

		<h2><?php 
        _e('Add Module', $flutter_domain);
        ?>
</h2>
		
		<form action="" method="post" id="add-new-module-form">
		
		<table class="form-table" width="100%" border="0" cellspacing="0" cellpadding="6">
		<tbody>

		<tr valign="top">
			<th scope="row"  align="right"><?php 
        _e('Name', $flutter_domain);
        ?>
:</th>
			<td>
		
				<input type="hidden" name="custom-write-panel-id" value="<?php 
        echo $customWritePanelId;
        ?>
" />
				<select tabindex="3" name="custom-write-module-id"  id="custom-write-module-id">
					<?php 
        foreach ($modules as $module) {
            ?>
					
						<option value="<?php 
            echo $module->id;
            ?>
"><?php 
            echo $module->name;
            ?>
</option>
					
					<?php 
        }
        ?>
				</select>
			</td>
		</tr>
		</tbody>
		</table>
		
		<p class="submit" >
			<input name="cancel-add-module" type="submit" id="cancel-add-module" value="<?php 
        _e('Cancel', $flutter_domain);
        ?>
" /> 
			<input name="finish-add-module" type="submit" id="finish-add-module" value="<?php 
        _e('Finish', $flutter_domain);
        ?>
" />
		</p>
		
		</form>

		</div>

		<?php 
    }
    function ViewModules()
    {
        global $flutter_domain;
        $customWriteModules = RCCWP_CustomWriteModule::GetCustomModules();
        ?>
<script type='text/javascript' src='../../wp-includes/js/thickbox/thickbox.js'></script>
<link rel='stylesheet' href='../../wp-includes/js/thickbox/thickbox.css' type='text/css' media='all' />



		<div class="wrap">
		
		<form action="<?php 
        echo RCCWP_ManagementPage::GetCustomWriteModuleGenericUrl('import-module');
        ?>
" method="post"  id="posts-filter" name="ImportModuleForm" enctype="multipart/form-data">
			<h2><?php 
        _e('Modules');
        ?>
</h2>
			<p id="post-search">					
				<input id="import-module-file" name="import-module-file" type="file" /> 
				<a href="#none" class="button-secondary" style="display:inline" onclick="document.ImportModuleForm.submit();"><?php 
        _e('Import a Module', $flutter_domain);
        ?>
</a>
				<a href="<?php 
        echo RCCWP_ManagementPage::GetCustomWriteModuleGenericUrl('create-custom-write-module');
        ?>
" class="button-secondary" style="display:inline">+ <?php 
        _e('Create a Module', $flutter_domain);
        ?>
</a>
			</p>	
		</form>

		<br class="clear"/>
		<table cellpadding="3" cellspacing="3" width="100%" class="widefat">
		<thead>
		<tr>
			<th scope="col" width="70%"><?php 
        _e('Name');
        ?>
</th>
			<th scope="col" colspan="2" ><?php 
        _e('Actions');
        ?>
</th>
		</tr>
		</thead>
		<tbody>
		<?php 
        foreach ($customWriteModules as $module) {
            $class = $class == '' ? 'alternate' : '';
            ?>
		<tr class="<?php 
            echo $class;
            ?>
">
			<td><?php 
            echo $module->name;
            ?>
</td>
			<td><a href="<?php 
            echo RCCWP_ManagementPage::GetCustomWriteModuleEditUrl($module->id);
            ?>
" class="edit"><?php 
            _e('Edit');
            ?>
</a></td>
			<td><a href="<?php 
            echo FLUTTER_URI . "RCCWP_ExportModule.php?custom-write-module-id={$module->id}";
            ?>
&amp;TB_iframe=true&amp;height=500&amp;width=700" class="thickbox" title='Export Module'><?php 
            _e('Export', $flutter_domain);
            ?>
</a></td>
		</tr>
		<?php 
        }
        ?>
		</tbody>
		</table>

		<form style="display:none" id="do_export" name="do_export" action="<?php 
        echo FLUTTER_URI . "RCCWP_ExportModule.php";
        ?>
" method="post" >
			<input type="text" name="write_panels"/>
			<input type="text" name="custom-write-module-id"/>
		</form>	
		
		</div>
		<?php 
    }