<?php
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/
require_once ('modules/ModuleBuilder/MB/ModuleBuilder.php');
require_once ('modules/ModuleBuilder/parsers/ParserFactory.php');

class ModuleBuilderController extends SugarController
{
    var $action_remap = array();

    function fromModuleBuilder()
    {
        return (isset($_REQUEST['MB']) && ($_REQUEST['MB'] == '1'));
    }

    function action_editLayout ()
    {
        switch ( strtolower($_REQUEST ['view']))
        {
            case 'editview' :
            case 'detailview' :
            case 'quickcreate' :
                $this->view = 'layoutView';
                break;
            case 'listview' :
                $this->view = 'listView';
                break;
            case 'searchview' :
                $this->view = 'searchView';
                break;
            default :
                $GLOBALS ['log']->fatal('Action = editLayout with unknown view=' . $_REQUEST ['view']);
        }
    }

    function action_ViewTree ()
    {
        require_once ('modules/ModuleBuilder/MB/AjaxCompose.php');
        switch ( $_REQUEST ['tree'])
        {
            case 'ModuleBuilder' :
                require_once ('modules/ModuleBuilder/MB/MBPackageTree.php');
                $mbt = new MBPackageTree();
                break;
            case 'Studio' :
                require_once ('modules/ModuleBuilder/Module/StudioTree.php');
                $mbt = new StudioTree();
        }
        $ajax = new AjaxCompose();
        $ajax->addSection('west', $mbt->getName(), $mbt->fetchNodes());
        echo $ajax->getJavascript();

        sugar_cleanup(true);

    }
    function action_SavePackage ()
    {
        $mb = new ModuleBuilder ( ) ;
        $load = (! empty ( $_REQUEST [ 'original_name' ] )) ? $_REQUEST [ 'original_name' ] : $_REQUEST [ 'name' ] ;
        if (! empty ( $load ))
        {
            $mb->getPackage ( $load ) ;
            
            if (! empty ( $_REQUEST [ 'duplicate' ] ))
            {
                $result = $mb->packages [ $load ]->copy ( $_REQUEST [ 'name' ] ) ;
                $load = $mb->packages [ $load ]->name ;
                $mb->getPackage ( $load ) ;
            }
            $mb->packages [ $load ]->populateFromPost () ;
            $mb->packages [ $load ]->loadModules () ;
            $mb->save () ;
            if (! empty ( $_REQUEST [ 'original_name' ] ) && $_REQUEST [ 'original_name' ] != $_REQUEST [ 'name' ])
            {
                if (! $mb->packages [ $load ]->rename ( $_REQUEST [ 'name' ] ))
                {
                    $mb->packages [ $load ]->name = $_REQUEST [ 'original_name' ] ;
                    $_REQUEST [ 'name' ] = $_REQUEST [ 'original_name' ] ;
                }
            }
            $_REQUEST [ 'package' ] = $load ;
            $this->view = 'package' ;
        }
    }

    function action_BuildPackage ()
    {
        $mb = new ModuleBuilder();
        $load = $_REQUEST ['name'];
        if (! empty($load))
        {
            $mb->getPackage($load);
            $mb->packages [$load]->build();
        }
    }
    function action_DeployPackage(){
        $mb =  new ModuleBuilder();
        $load = $_REQUEST['package'];
        $message = $GLOBALS['mod_strings']['LBL_MODULE_DEPLOYED'];
        if(!empty($load)){
            $zip = $mb->getPackage($load);
            require_once('ModuleInstall/PackageManager/PackageManager.php');
            $pm = new PackageManager();
            $info = $mb->packages[$load]->build(false);
            mkdir_recursive($GLOBALS['sugar_config']['cache_dir'] . '/'. 'upload/upgrades/module/');
            rename($info['zip'], $GLOBALS['sugar_config']['cache_dir'] . '/'. 'upload/upgrades/module/'. $info['name']. '.zip');
            copy($info['manifest'], $GLOBALS['sugar_config']['cache_dir'] . '/'. 'upload/upgrades/module/'. $info['name']. '-manifest.php');
            $_REQUEST['install_file'] = $GLOBALS['sugar_config']['cache_dir'] . '/'. 'upload/upgrades/module/'. $info['name']. '.zip';
            $GLOBALS['mi_remove_tables'] = false;
            $pm->performUninstall($load);
            $pm->performInstall($_REQUEST['install_file']);
        }
		echo 'complete';

    }

    function action_ExportPackage()
    {
        $mb = new ModuleBuilder();
        $load = $_REQUEST ['name'];
        $author = $_REQUEST ['author'];
        $description = $_REQUEST ['description'];
        $readme=$_REQUEST['readme'];
        if (! empty($load))
        {
            $mb->getPackage($load);
            $mb->packages [$load]->author=$author;
            $mb->packages [$load]->description=$description;
            $mb->packages [$load]->exportProject();
            $mb->packages [$load]->readme=$readme;
        }
    }

    function action_DeletePackage ()
    {
        $mb = new ModuleBuilder();
        $mb->getPackage($_REQUEST ['package']);
        $mb->packages [$_REQUEST ['package']]->delete();
        $this->view = 'deletepackage';
    }

    function action_SaveModule ()
    {
        $mb = new ModuleBuilder();
        $load = (! empty($_REQUEST ['original_name'])) ? $_REQUEST ['original_name'] : $_REQUEST ['name'];
        if (! empty($load))
        {
            $mb->getPackage($_REQUEST ['package']);
            $mb->packages [$_REQUEST ['package']]->getModule($load);
            $module = & $mb->packages [$_REQUEST ['package']]->modules [$load];
            $module->populateFromPost();
            $mb->save();
            if (! empty($_REQUEST ['duplicate']))
            {
                $module->copy($_REQUEST ['name']);
            } else if (! empty($_REQUEST ['original_name']) && $_REQUEST ['original_name'] != $_REQUEST ['name'])
            {
                if (! $module->rename($_REQUEST ['name']))
                {
                    $module->name = $_REQUEST ['original_name'];
                    $_REQUEST ['name'] = $_REQUEST ['original_name'];
                }
            }

            $_REQUEST ['view_package'] = $_REQUEST ['package'];
            $_REQUEST ['view_module'] = $module->name;
            $this->view = 'module';
        }
    }
    function action_DeleteModule ()
    {
        $mb = new ModuleBuilder();
        $module = & $mb->getPackageModule($_REQUEST ['package'], $_REQUEST ['view_module']);
        $module->delete();
        $this->view = 'package';
    }

    // TO DO: unifying MB and Studio2 resulted in two saveLabels actions - this needs to be tidied or rethought
    function action_saveLabels ()
    {
        $parser = ParserFactory::getParser('label');
        if (isset($_REQUEST ['view_module'])) //MODULE BUILDER
        {
            $parser->handleSave($_REQUEST, $_REQUEST ['view_module'], $_REQUEST ['selected_lang']);
            $this->view = 'modulelabels';
        } else //STUDIO
        {
            $parser->handleSave($_REQUEST, $_REQUEST ['editModule'], $_REQUEST ['selected_lang']);
            $this->view = isset($_REQUEST ['editLayout']) ? 'edit' : 'labels'; // detect if we are being called by the LayoutEditor rather than the LabelEditor (set in view.layoutlabel.php)
        }
    }

    function action_SaveLabel ()
    {
        if (! empty($_REQUEST ['view_module']))
        {
            $module = $_REQUEST ['view_module'];
            //$label_array = array("label_" . $_REQUEST['label']=>$_REQUEST['label_value']);
            $params = $_REQUEST;
            $params ["label_" . $_REQUEST ['label']] = $_REQUEST ['label_value'];
            $parser = ParserFactory::getParser('label');
            $parser->handleSave($params, $module, $GLOBALS [ 'current_language' ]);
        }
        $this->view = 'modulefields';
    }

    function action_ExportCustom ()
    {
        $modules  = $_REQUEST['modules'];
        $name  = $_REQUEST['name'];
        $author  = $_REQUEST['author'];
        $description  = $_REQUEST['description'];
        ob_clean();
        if(!empty($modules) && !empty($name)){
            require_once('modules/ModuleBuilder/MB/ModuleBuilder.php');
            $mb = new MBPackage($name);
            $mb->author = $author;
            $mb->description = $description;
            $mb->exportCustom($modules,true,true);
        }
    }

    function action_SaveField ()
    {
        require_once ('modules/DynamicFields/FieldCases.php');
        $field = get_widget($_POST ['type']);
        $_POST ['name'] = trim(strtolower($_POST ['name']));
        $field->populateFromPost(); 

        $type = $_REQUEST ['view_package'];
        if ($type == 'studio')
        {
            require_once ('modules/DynamicFields/DynamicField.php');
            if (! empty($_REQUEST ['view_module']))
            {
                $module = $_REQUEST ['view_module'];
                $df = new DynamicField($module);
                $class_name = $GLOBALS ['beanList'] [$module];
                require_once ($GLOBALS ['beanFiles'] [$class_name]);
                $mod = new $class_name();
                $df->setup($mod);

                $field->save($df);
                $this->action_SaveLabel();
            }
        } else
        {
            $vardef = $field->get_field_def();
            unset($vardef ['source']);
            $mb = new ModuleBuilder();
            $module = & $mb->getPackageModule($_REQUEST ['view_package'], $_REQUEST ['view_module']);
            $field->save($module);
            if (isset($_REQUEST ['label']) && isset($_REQUEST ['label_value']))
                $module->setLabel($GLOBALS [ 'current_language' ], $_REQUEST ['label'], $_REQUEST ['label_value']);
//              if (! empty($_REQUEST ['view_module']))
//        {
//            $module = $_REQUEST ['view_module'];
//            //$label_array = array("label_" . $_REQUEST['label']=>$_REQUEST['label_value']);
//            $params = $_REQUEST;
//            $params ["label_" . $_REQUEST ['label']] = $_REQUEST ['label_value'];
//            $parser = ParserFactory::getParser('label');
//            $parser->handleSave($params, $module, $GLOBALS [ 'current_language' ]);
//        }
            $mb->save();
        }
        $this->view = 'modulefields';
    }
    function action_RefreshField ()
    {
        require_once ('modules/DynamicFields/FieldCases.php');
        $field = get_widget($_POST ['type']);
        $field->populateFromPost();
        $this->view = 'modulefield';
    }

    function action_SaveRelationship ()
    {
        $mb = new ModuleBuilder();
        $module = & $mb->getPackageModule($_REQUEST ['view_package'], $_REQUEST ['view_module']);
        $rel = $module->mbrelationship->relationshipFromPost();
        $module->mbrelationship->add($rel);
        $module->setLabel($GLOBALS [ 'current_language' ], 'lbl_' . $rel ['name'], $rel ['label']);
        $mb->save();
        $this->view = 'relationships';
    }
    function action_DeleteRelationship ()
    {
        $mb = new ModuleBuilder();
        $module = & $mb->getPackageModule($_REQUEST ['view_package'], $_REQUEST ['view_module']);
        $rel = $module->mbrelationship->relationshipFromPost();
        $module->mbrelationship->delete($rel ['name']);
        $mb->save();
        $this->view = 'relationships';
    }

    function action_SaveDropDown ()
    {
        $parser = ParserFactory::getParser('dropdown');
        $parser->saveDropDown($_REQUEST);
        $this->view = 'dropdowns';
    }

    function action_DeleteField ()
    {
        $type = $_REQUEST ['view_package'];
        $field = get_widget($_POST['type']);
        $field->name = $_REQUEST['name'];
        if ($type == 'studio')
        {
            if (! empty($_REQUEST ['name']) && ! empty($_REQUEST ['view_module']))
            {
                require_once ('modules/DynamicFields/DynamicField.php');
                $module = $_REQUEST ['view_module'];
                $class_name = $GLOBALS ['beanList'] [$module];
                require_once ($GLOBALS ['beanFiles'] [$class_name]);
                $seed = new $class_name();
//                $temp = $GLOBALS['external_cache_object']->get("VardefManager".$module.$class_name);
//                $GLOBALS['log']->debug("cache for ".$module.$class_name." initially = ".$temp);
                $df = new DynamicField($module);
                $df->setup($seed);
                $field->delete($df);
//                $temp = $GLOBALS['external_cache_object']->get("VardefManager".$module.$class_name);
//                $GLOBALS['log']->debug("cache now = ".$temp);
            }
        } else
        {
            $mb = new ModuleBuilder();
            $module = & $mb->getPackageModule($_REQUEST ['view_package'], $_REQUEST ['view_module']);
            $field->delete($module);
            $mb->save();
        }
        $this->view = 'modulefields';
    }

    function action_CloneField ()
    {
        $this->view_object_map ['field_name'] = $_REQUEST ['name'];
        $this->view_object_map ['is_clone'] = true;
        $this->view = 'modulefield';
    }

    function action_SaveAssistantPref ()
    {
		global $current_user;
		if (isset($_REQUEST ['pref_value'])){
			if($_REQUEST['pref_value'] == 'ignore'){
				$current_user->setPreference('mb_assist', 'DISABLED', 0, 'Assistant') ;
			} else{
				$current_user->setPreference('mb_assist', 'ENABLED', 0, 'Assistant');
			}
			$current_pref=$current_user->getPreference('mb_assist', 'Assistant');
			echo "Assistant.processUserPref('$current_pref')";
			sugar_cleanup(true); //push preferences to DB.
                }
            }
    // Studio2 Actions


    function action_EditProperty ()
    {
        $this->view = 'property';
    }

    function action_saveProperty()
    {
        $parser = ParserFactory::getParser('label');
        $parser->init($_REQUEST['editModule']);
        $language = (isset($_REQUEST [ 'selected_lang' ])) ? $_REQUEST [ 'selected_lang' ] : $GLOBALS['current_language'] ;
        $parser->handleSave($_REQUEST, ($_REQUEST['subpanel'] != "") ? $_REQUEST['subpanel'] : $_REQUEST['editModule'], $language);
        $this->view = 'closeeast';
    }

    function action_editModule ()
    {
        $this->view = 'module';
    }

    function action_wizard ()
    {
        $this->view = 'wizard';
    }

    /**
     * Receive a layout through $_REQUEST and save it out to the working files directory
     * Expects a series of $_REQUEST parameters all in the format $_REQUEST['slot-panel#-slot#-property']=value
     */

    function action_saveLayout ()
    {









            $parser = ParserFactory::getParser('layoutview', $this->fromModuleBuilder());
            $this->view = 'layoutview';



        $parser->init($_REQUEST ['editModule'], $_REQUEST ['view'], true);
        $parser->writeWorkingFile();
    }

    function action_saveAndPublishLayout ()
    {









            $parser = ParserFactory::getParser('layoutview', $this->fromModuleBuilder());
            $this->view = 'layoutview';



        $parser->init($_REQUEST ['editModule'], $_REQUEST ['view'], true);
        $parser->writeWorkingFile();
        $parser->handleSave();
    }

    function action_manageBackups ()
    {

    }


    function action_listViewSave ()
    {










            $this->view = 'listview';
            if (! empty($_REQUEST ['subpanel']))
            {
                $parserName = (! empty($_REQUEST ['local'])) ? 'localsubpanel' : 'subpanel';
                $lv = ParserFactory::getParser($parserName, ! empty($_REQUEST ['MB']));
                $lv->init($_REQUEST ['editModule'], $_REQUEST ['subpanel']);
                $GLOBALS['log']->debug("in action_listviewsave - parser = $parserName");
            }
            else
            {
                $lv = ParserFactory::getParser('listview', $this->fromModuleBuilder());
                $lv->init($_REQUEST ['editModule']);
                $GLOBALS['log']->debug("in action_listviewsave - parser = listview");
            }



        $lv->handleSave();
    }

    function action_searchViewSave ()
    {
        $lv = ParserFactory::getParser('searchview', $this->fromModuleBuilder());
        $lv->init($_REQUEST ['editModule'],$_REQUEST['searchlayout']);
        $lv->handleSave();
        $this->view = 'searchView';
    }

    function action_editLabels ()
    {
        $this->view = 'labels';
    }
	
    function action_get_app_list_string ()
    {
    	require_once('include/JSON.php');
        $json = new JSON();
        if (isset($_REQUEST['key']) && !empty($_REQUEST['key'])) {
        	$key = $_REQUEST['key'];
        	$value = array();
        	if (!empty($GLOBALS['app_list_strings'][$key])) {
        		$value = $GLOBALS['app_list_strings'][$key];
        	} else {
	        	$package_strings = array();
				if(!empty($_REQUEST['view_package']) && $_REQUEST['view_package'] != 'studio' && !empty($_REQUEST['view_module'])){
					require_once('modules/ModuleBuilder/MB/ModuleBuilder.php');
					$mb = new ModuleBuilder();
					$module =& $mb->getPackageModule($_REQUEST['view_package'], $_REQUEST['view_module']);
					$lang = $GLOBALS['current_language'];
					$module->mblanguage->generateAppStrings(false);
					$package_strings = $module->mblanguage->appListStrings[$lang.'.lang.php'];
					if (isset($package_strings[$key]) && is_array($package_strings[$key])) {
						$value = $package_strings[$key];
					}
				}
        	}
        	echo $json->encode($value);
        }
    }
















































}
?>
