2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 require_once("include/EditView/EditView2.php");
39 require_once("include/upload_file.php");
41 class ViewConvertLead extends SugarView
43 protected $fileName = "modules/Leads/metadata/convertdefs.php";
44 protected $new_contact = false;
46 public function __construct(
48 $view_object_map = array()
51 parent::SugarView($bean, $view_object_map);
52 $this->medataDataFile = $this->fileName;
53 if (file_exists("custom/$this->fileName"))
55 $this->medataDataFile = "custom/$this->fileName";
59 public function preDisplay()
61 if (!$this->bean->ACLAccess('edit')) {
62 ACLController::displayNoAccess();
68 * @see SugarView::display()
70 public function display()
72 if (!empty($_REQUEST['handle']) && $_REQUEST['handle'] == 'save')
74 return $this->handleSave();
79 // get the EditView defs to check if opportunity_name exists, for a check below for populating data
80 $opportunityNameInLayout = false;
81 $editviewFile = 'modules/Leads/metadata/editviewdefs.php';
82 $this->medataDataFile = $editviewFile;
83 if (file_exists("custom/{$editviewFile}"))
85 $this->medataDataFile = "custom/{$editviewFile}";
87 include($this->medataDataFile);
88 foreach($viewdefs['Leads']['EditView']['panels'] as $panel_index => $section){
89 foreach($section as $row_array){
90 foreach($row_array as $cell){
91 if(isset($cell['name']) && $cell['name'] == 'opportunity_name'){
92 $opportunityNameInLayout = true;
98 $this->medataDataFile = $this->fileName;
99 if (file_exists("custom/$this->fileName"))
101 $this->medataDataFile = "custom/$this->fileName";
105 $this->checkForDuplicates($this->focus);
106 $smarty = new Sugar_Smarty();
107 $ev = new EditView();
109 $ev->view = "ConvertLead";
110 echo $this->getModuleTitle();
112 require_once("include/QuickSearchDefaults.php");
113 $qsd = QuickSearchDefaults::getQuickSearchDefaults();
114 $qsd->setFormName("ConvertLead");
116 $this->contact = new Contact();
119 * Setup filter for Account/Contact popup picker
122 // Check if Lead has an account set
123 if (!empty($this->focus->account_name))
125 $filter .= '&name_advanced=' . urlencode($this->focus->account_name);
127 // Check if Lead First name is available
128 if (!empty($this->focus->first_name))
130 $filter .= '&first_name_advanced=' . urlencode($this->focus->first_name);
132 // Lead Last Name is always available
133 $filter .= '&last_name_advanced=' . urlencode($this->focus->last_name);
135 $smarty->assign('initialFilter', $filter);
136 $smarty->assign('displayParams', array('initial_filter' => '{$initialFilter}'));
138 $relatedFields = $this->contact->get_related_fields();
139 $selectFields = array();
140 foreach ($this->defs as $moduleName => $mDefs)
142 if (!empty($mDefs[$ev->view]['select']) && !empty($relatedFields[$mDefs[$ev->view]['select']]))
144 $selectFields[$moduleName] = $mDefs[$ev->view]['select'];
147 foreach ($relatedFields as $fDef)
149 if (!empty($fDef['link']) && !empty($fDef['module']) && $fDef['module'] == $moduleName)
151 $selectFields[$moduleName] = $fDef['name'];
157 $smarty->assign('selectFields', $selectFields);
159 $smarty->assign("contact_def", $this->contact->field_defs);
160 $smarty->assign("form_name", "ConvertLead");
161 $smarty->assign("form_id", "ConvertLead");
162 $smarty->assign("module", "Leads");
163 $smarty->assign("view", "convertlead");
164 $smarty->assign("bean", $this->focus);
165 $smarty->assign("record_id", $this->focus->id);
167 $smarty->assign('MOD', $mod_strings);
168 $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
170 echo "<div class='edit view' style='width:auto;'>";
172 global $sugar_config, $app_list_strings, $app_strings;
173 $smarty->assign('lead_conv_activity_opt', $sugar_config['lead_conv_activity_opt']);
175 //Switch up list depending on copy or move
176 if($sugar_config['lead_conv_activity_opt'] == 'move')
178 $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('None'=>$app_strings['LBL_NONE'], 'Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
180 else if($sugar_config['lead_conv_activity_opt'] == 'copy')
182 $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
187 foreach($this->defs as $module => $vdef)
189 if(!isset($beanList[$module]))
195 $bean = $beanList[$module];
196 $focus = new $bean();
198 // skip if we aren't allowed to save this bean
199 if (!$focus->ACLAccess('save'))
204 $focus->fill_in_additional_detail_fields();
205 foreach($focus->field_defs as $field => $def)
207 if(isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData'])
209 if ($module == "Accounts" && $field == 'name')
211 $focus->name = $this->focus->account_name;
213 else if ($module == "Opportunities" && $field == 'amount')
215 $focus->amount = unformat_number($this->focus->opportunity_amount);
217 else if ($module == "Opportunities" && $field == 'name') {
218 if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)){
219 $focus->name = $this->focus->opportunity_name;
222 else if ($field == "id")
224 //If it is not a contact, don't copy the ID from the lead
225 if ($module == "Contacts") {
226 $focus->$field = $this->focus->$field;
228 } else if (is_a($focus, "Company") && $field == 'phone_office')
230 //Special case where company and person have the same field with a different name
231 $focus->phone_office = $this->focus->phone_work;
233 else if (strpos($field, "billing_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */
235 $tmp_field = str_replace("billing_", "primary_", $field);
236 $focus->field_defs[$field]["type"] = "text";
237 if (isset($this->focus->$tmp_field)) {
238 $focus->$field = $this->focus->$tmp_field;
242 else if (strpos($field, "shipping_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */
244 $tmp_field = str_replace("shipping_", "primary_", $field);
245 if (isset($this->focus->$tmp_field)) {
246 $focus->$field = $this->focus->$tmp_field;
248 $focus->field_defs[$field]["type"] = "text";
250 else if (isset($this->focus->$field))
252 $focus->$field = $this->focus->$field;
257 //Copy over email data
258 $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
260 echo($ev->display(false));
261 echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
264 echo ($qsd->getQSScriptsJSONAlreadyDefined());
265 // need to re-assign bean as it gets overridden by $ev->display
266 $smarty->assign("bean", $this->focus);
267 $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
270 protected function getRecord()
272 $this->focus = new Lead();
273 if (isset($_REQUEST['record']))
275 $this->focus->retrieve($_REQUEST['record']);
279 protected function loadDefs()
282 include($this->medataDataFile);
283 $this->defs = $viewdefs;
287 * Returns the javascript to enable/disable validation of each module's sub-form
288 * //TODO: This should probably be on the smarty template
289 * @param $module String the target module name.
290 * @param $focus SugarBean instance of the target module.
291 * @param $focus EditView def for the module.
292 * @return String, javascript to echo to page.
294 protected function getValidationJS(
300 $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
302 <script type='text/javascript'>
303 if (!SUGAR.convert) SUGAR.convert = {requiredFields: {}};
304 SUGAR.convert.toggle$module = function(){
306 inputsWithErrors = [];
307 if(!SUGAR.convert.{$module}Enabled)
309 for(var i in SUGAR.convert.requiredFields.$module)
311 addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
314 if ($validateSelect) {
316 removeFromValidate('ConvertLead', '{$viewdef['select']}');";
320 SUGAR.convert.{$module}Enabled = true;
322 for(var i in SUGAR.convert.requiredFields.$module)
324 removeFromValidate('ConvertLead', '$module' + i);
326 if ($validateSelect) {
328 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
329 . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
332 SUGAR.convert.{$module}Enabled = false;
334 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
337 if (isset($viewdef['required']) && $viewdef['required'])
339 if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
342 SUGAR.convert.{$module}Enabled = true;";
345 YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
346 } else if (isset($viewdef['default_action']) && $viewdef['default_action'] == "create")
348 $jsOut .= "\n SUGAR.convert.{$module}Enabled = true;";
351 YAHOO.util.Event.addListener('new$module', 'click', SUGAR.convert.toggle$module);
352 SUGAR.convert.requiredFields.$module = {};";
353 foreach($focus->field_defs as $field => $def)
355 if (isset($def['required']) && $def['required'])
358 SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
369 * Saves a new Contact as well as any related items passed in.
373 protected function handleSave()
375 require_once('modules/Campaigns/utils.php');
376 require_once("include/formbase.php");
378 if (!empty($_REQUEST['record']))
381 $lead->retrieve($_REQUEST['record']);
387 $selectedBeans = array();
390 // Make sure the contact object is availible for relationships.
391 $beans['Contacts'] = new Contact();
394 if (!empty($_REQUEST['selectedContact']))
396 $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
397 if (!empty($beans['Contacts']->id))
399 $beans['Contacts']->new_with_id = false;
400 unset($_REQUEST["convert_create_Contacts"]);
401 unset($_POST["convert_create_Contacts"]);
404 elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact']))
406 require_once('modules/Contacts/ContactFormBase.php');
407 $contactForm = new ContactFormBase();
408 $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
410 if (isset($duplicateContacts))
412 echo $contactForm->buildTableForm($duplicateContacts, 'Contacts');
415 $this->new_contact = true;
416 } elseif (isset($_POST['ContinueContact'])) {
417 $this->new_contact = true;
420 if (!empty($_REQUEST['selectedAccount']))
422 $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
423 unset($_REQUEST["convert_create_Accounts"]);
424 unset($_POST["convert_create_Accounts"]);
426 elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount']))
428 require_once('modules/Accounts/AccountFormBase.php');
429 $accountForm = new AccountFormBase();
430 $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
431 if (isset($duplicateAccounts))
433 echo $accountForm->buildTableForm($duplicateAccounts);
438 foreach ($this->defs as $module => $vdef)
440 //Create a new record if "create" was selected
441 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
443 //Save the new record
444 $bean = $beanList[$module];
445 if (empty($beans[$module]))
446 $beans[$module] = new $bean();
448 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
449 // when creating a new contact, create the id for linking with other modules
450 // and do not populate it with lead's old account_id
451 if ($module == 'Contacts')
453 $beans[$module]->id = create_guid();
454 $beans[$module]->new_with_id = true;
455 $beans[$module]->account_id = '';
458 //If an existing bean was selected, relate it to the contact
459 else if (!empty($vdef['ConvertLead']['select']))
461 //Save the new record
462 $select = $vdef['ConvertLead']['select'];
463 $fieldDef = $beans['Contacts']->field_defs[$select];
464 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
466 $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
467 $selects[$module] = $_REQUEST[$fieldDef['id_name']];
468 if (!empty($_REQUEST[$select]))
470 $beans['Contacts']->$select = $_REQUEST[$select];
472 // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
473 $bean = loadBean($module);
474 $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
475 $selectedBeans[$module] = $bean;
476 // If we selected the Contact, just overwrite the $beans['Contacts']
477 if ($module == 'Contacts')
479 $beans[$module] = $bean;
485 $this->handleActivities($lead, $beans);
486 // Bug 39268 - Add the lead's activities to the selected beans
487 $this->handleActivities($lead, $selectedBeans);
489 //link selected account to lead if it exists
490 if (!empty($selectedBeans['Accounts']))
492 $lead->account_id = $selectedBeans['Accounts']->id;
495 // link account to contact, if we picked an existing contact and created a new account
496 if (!empty($beans['Accounts']->id) && !empty($beans['Contacts']->account_id)
497 && $beans['Accounts']->id != $beans['Contacts']->account_id)
499 $beans['Contacts']->account_id = $beans['Accounts']->id;
502 // Saving beans with priorities.
503 // Contacts and Accounts should be saved before lead activities to create correct relations
504 $saveBeanPriority = array('Contacts', 'Accounts');
505 $tempBeans = array();
507 foreach ($saveBeanPriority as $name)
509 if (isset($beans[$name]))
511 $tempBeans[$name] = $beans[$name];
515 $beans = array_merge($tempBeans, $beans);
518 //Handle non-contacts relationships
519 foreach ($beans as $bean)
523 if (empty($bean->assigned_user_id))
525 $bean->assigned_user_id = $lead->assigned_user_id;
527 $leadsRel = $this->findRelationship($bean, $lead);
528 if (!empty($leadsRel))
530 $bean->load_relationship($leadsRel);
531 $relObject = $bean->$leadsRel->getRelationshipObject();
532 if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
534 $id_field = $relObject->rhs_key;
535 $lead->$id_field = $bean->id;
539 $bean->$leadsRel->add($lead->id);
543 //Special case code for opportunities->Accounts
544 if ($bean->object_name == "Opportunity" && empty($bean->account_id))
546 if (isset($beans['Accounts']))
548 $bean->account_id = $beans['Accounts']->id;
549 $bean->account_name = $beans['Accounts']->name;
551 else if (!empty($selects['Accounts']))
553 $bean->account_id = $selects['Accounts'];
557 //create meetings-users relationship
558 if ($bean->object_name == "Meeting")
560 $bean = $this->setMeetingsUsersRelationship($bean);
562 $this->copyAddressFields($bean, $beans['Contacts']);
565 //if campaign id exists then there should be an entry in campaign_log table for the newly created contact: bug 44522
566 if (isset($lead->campaign_id) && $lead->campaign_id != null && $bean->object_name == "Contact")
568 campaign_log_lead_or_contact_entry($lead->campaign_id, $lead, $beans['Contacts'], 'contact');
572 { //Mark the original Lead converted
573 $lead->status = "Converted";
574 $lead->converted = '1';
575 $lead->in_workflow = true;
579 $this->displaySaveResults($beans);
582 public function setMeetingsUsersRelationship($bean)
584 global $current_user;
585 $meetingsRel = $this->findRelationshipByName($bean, $this->defs['Meetings']['ConvertLead']['relationship']);
586 if (!empty($meetingsRel))
588 $bean->load_relationship($meetingsRel);
589 $bean->$meetingsRel->add($current_user->id);
597 protected function displaySaveResults(
603 foreach($beans as $bean)
605 $beanName = $bean->object_name;
606 if ( $beanName == 'Contact' && !$this->new_contact ) {
607 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
608 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
609 {$bean->get_summary_text()}
613 global $app_list_strings;
614 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
615 $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
617 $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
619 if(empty($module_name)) {
620 $module_name = translate($beanName);
622 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
623 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
624 {$bean->get_summary_text()}
632 protected function handleActivities(
637 global $app_list_strings;
638 global $sugar_config;
640 $parent_types = $app_list_strings['record_type_display'];
642 $activities = $this->getActivitiesFromLead($lead);
644 //if account is being created, we will specify the account as the parent bean
645 $accountParentInfo = array();
647 //determine the account id info ahead of time if it is being created as part of this conversion
648 if(!empty($beans['Accounts'])){
649 $account_id = create_guid();
650 if(!empty($beans['Accounts']->id)){
651 $account_id = $beans['Accounts']->id;
653 $beans['Accounts']->id = $account_id;
655 $accountParentInfo = array('id'=>$account_id,'type'=>'Accounts');
658 foreach($beans as $module => $bean)
660 if (isset($parent_types[$module]))
662 if (empty($bean->id))
664 $bean->id = create_guid();
665 $bean->new_with_id = true;
667 if( isset($_POST['lead_conv_ac_op_sel']) && $_POST['lead_conv_ac_op_sel'] != 'None')
669 foreach($activities as $activity)
671 if (!isset($sugar_config['lead_conv_activity_opt']) || $sugar_config['lead_conv_activity_opt'] == 'copy') {
672 if (isset($_POST['lead_conv_ac_op_sel'])) {
673 //if the copy to module(s) are defined, copy only to those module(s)
674 if (is_array($_POST['lead_conv_ac_op_sel'])) {
675 foreach ($_POST['lead_conv_ac_op_sel'] as $mod) {
676 if ($mod == $module) {
677 $this->copyActivityAndRelateToBean($activity, $bean, $accountParentInfo);
684 else if ($sugar_config['lead_conv_activity_opt'] == 'move') {
685 // if to move activities, should be only one module selected
686 if ($_POST['lead_conv_ac_op_sel'] == $module) {
687 $this->moveActivity($activity, $bean);
697 * Change the parent id and parent type of an activity
698 * @param $activity Activity to be modified
699 * @param $bean New parent bean of the activity
701 protected function moveActivity($activity, $bean) {
705 if (!empty($_REQUEST['record']))
708 $lead->retrieve($_REQUEST['record']);
711 // delete the old relationship to the old parent (lead)
712 if ($rel = $this->findRelationship($activity, $lead)) {
713 $activity->load_relationship ($rel) ;
715 if ($activity->parent_id && $activity->id) {
716 $activity->$rel->delete($activity->id, $activity->parent_id);
720 // add the new relationship to the new parent (contact, account, etc)
721 if ($rel = $this->findRelationship($activity, $bean)) {
722 $activity->load_relationship ($rel) ;
724 $relObj = $activity->$rel->getRelationshipObject();
725 if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
727 $key = $relObj->rhs_key;
728 $activity->$key = $bean->id;
730 $activity->$rel->add($bean);
733 // set the new parent id and type
734 $activity->parent_id = $bean->id;
735 $activity->parent_type = $bean->module_dir;
741 * Gets the list of activities related to the lead
742 * @param Lead $lead Lead to get activities from
743 * @return Array of Activity SugarBeans .
745 protected function getActivitiesFromLead(
751 global $beanList, $db;
753 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
754 $activities = array();
756 foreach($activitesList as $module)
758 $beanName = $beanList[$module];
759 $activity = new $beanName();
760 $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
761 $result = $db->query($query,true);
762 while($row = $db->fetchByAssoc($result))
764 $activity = new $beanName();
765 $activity->retrieve($row['id']);
766 $activity->fixUpFormatting();
767 $activities[] = $activity;
774 protected function copyActivityAndRelateToBean(
782 $newActivity = clone $activity;
783 $newActivity->id = create_guid();
784 $newActivity->new_with_id = true;
786 //set the parent id and type if it was passed in, otherwise use blank to wipe it out
789 if(!empty($parentArr)){
790 if(!empty($parentArr['id'])){
791 $parentID = $parentArr['id'];
794 if(!empty($parentArr['type'])){
795 $parentType = $parentArr['type'];
800 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
801 if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
803 $newActivity->contact_id = $newActivity->contact_name = "";
806 if ($rel = $this->findRelationship($newActivity, $bean))
808 if (isset($newActivity->$rel))
810 // this comes form $activity, get rid of it and load our own
811 $newActivity->$rel = '';
814 $newActivity->load_relationship ($rel) ;
815 $relObj = $newActivity->$rel->getRelationshipObject();
816 if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
818 $key = $relObj->rhs_key;
819 $newActivity->$key = $bean->id;
822 //parent (related to field) should be blank unless it is explicitly sent in
823 //it is not sent in unless the account is being created as well during lead conversion
824 $newActivity->parent_id = $parentID;
825 $newActivity->parent_type = $parentType;
827 $newActivity->update_date_modified = false; //bug 41747
828 $newActivity->save();
829 $newActivity->$rel->add($bean);
830 if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
831 UploadFile::duplicate_file($activity->id, $newActivity->id, $newActivity->filename);
837 * Populates the passed in Bean fron the contact and the $_REQUEST
838 * @param String $module Module of new bean
839 * @param SugarBean $bean SugarBean to be populated.
840 * @param Contact $contact Contact to relate the bean to.
842 protected function populateNewBean(
849 //Copy data from the contact to new bean
850 foreach($bean->field_defs as $field => $def)
852 if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
854 $bean->$field = $lead->$field;
855 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
858 populateFromPost($module, $bean, true);
859 //Try to link to the new contact
861 if (!empty($vdef['ConvertLead']['select']))
863 $select = $vdef['ConvertLead']['select'];
864 $fieldDef = $contact->field_defs[$select];
865 if (!empty($fieldDef['id_name']))
867 $bean->id = create_guid();
868 $bean->new_with_id = true;
869 $contact->$fieldDef['id_name'] = $bean->id ;
870 if ($fieldDef['id_name'] != $select) {
871 $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
872 if (!empty($rname) && isset($bean->$rname))
873 $contact->$select = $bean->$rname;
875 $contact->$select = $bean->name;
878 } else if ($module != "Contacts"){
879 $contactRel = $this->findRelationship($contact, $bean);
880 if (!empty($contactRel))
882 $bean->id = create_guid();
883 $bean->new_with_id = true;
884 $contact->load_relationship ($contactRel) ;
885 $relObject = $contact->$contactRel->getRelationshipObject();
886 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
888 $id_field = $relObject->rhs_key;
889 $bean->$id_field = $contact->id;
891 $contact->$contactRel->add($bean);
893 //Set the parent of activites to the new Contact
894 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
896 $bean->parent_id = $contact->id;
897 $bean->parent_type = "Contacts";
903 protected function copyAddressFields($bean, $contact)
905 //Copy over address info from the contact to any beans with address not set
906 foreach($bean->field_defs as $field => $def)
908 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
911 if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
915 if(strpos($field, "_address_street_2") !== false)
916 $type = "_address_street_2";
917 else if(strpos($field, "_address_street_3") !== false)
918 $type = "_address_street_3";
919 else if(strpos($field, "_address_street_4") !== false)
921 else if(strpos($field, "_address_street") !== false)
922 $type = "_address_street";
923 else if(strpos($field, "_address_city") !== false)
924 $type = "_address_city";
925 else if(strpos($field, "_address_state") !== false)
926 $type = "_address_state";
927 else if(strpos($field, "_address_postalcode") !== false)
928 $type = "_address_postalcode";
929 else if(strpos($field, "_address_country") !== false)
930 $type = "_address_country";
933 if (isset($contact->$var))
934 $bean->$field = $contact->$var;
940 protected function findRelationship(
946 require_once("modules/TableDictionary.php");
947 foreach ($from->field_defs as $field=>$def)
949 if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship']))
951 $rel_name = $def['relationship'];
953 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
955 $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
957 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
959 $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
961 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
962 && isset($dictionary[$rel_name]['relationships'][$rel_name]))
964 $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
966 if (!empty($rel_def)) {
967 if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
971 else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
981 protected function findRelationshipByName($from, $rel_name)
984 require_once("modules/TableDictionary.php");
985 foreach ($from->field_defs as $field => $def)
987 if (isset($def['relationship']) && $def['relationship'] == $rel_name)
995 * @see SugarView::_getModuleTitleParams()
997 protected function _getModuleTitleParams($browserTitle = false)
1000 $params = parent::_getModuleTitleParams($browserTitle);
1001 $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
1002 $params[] = $mod_strings['LBL_CONVERTLEAD'];
1007 protected function checkForDuplicates(
1011 if ($lead->status == "Converted")
1013 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
1015 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
1016 $result = $lead->db->query($q);
1017 while($row = $lead->db->fetchByAssoc($result)) {
1018 $contact = new Contact();
1019 $contact->retrieve($row['id']);
1020 $dupes[$row['id']] = $contact->name;
1024 foreach($dupes as $id => $name)
1026 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");