]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Leads/views/view.convertlead.php
Release 6.3.0
[Github/sugarcrm.git] / modules / Leads / views / view.convertlead.php
1 <?php
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-2011 SugarCRM Inc.
6  * 
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.
13  * 
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
17  * details.
18  * 
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
22  * 02110-1301 USA.
23  * 
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.
26  * 
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.
30  * 
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  ********************************************************************************/
37
38 require_once("include/EditView/EditView2.php");
39 require_once("include/upload_file.php");
40
41 class ViewConvertLead extends SugarView
42 {
43     protected $fileName = "modules/Leads/metadata/convertdefs.php";
44     protected $new_contact = false;
45
46     public function __construct(
47         $bean = null,
48         $view_object_map = array()
49         )
50     {
51         parent::SugarView($bean, $view_object_map);
52         $this->medataDataFile = $this->fileName;
53         if (file_exists("custom/$this->fileName"))
54         {
55             $this->medataDataFile = "custom/$this->fileName";
56         }
57     }
58
59     public function preDisplay()
60     {
61         if (!$this->bean->ACLAccess('edit')) {
62             ACLController::displayNoAccess();
63             sugar_die('');
64         }
65     }
66
67     /**
68          * @see SugarView::display()
69          */
70         public function display()
71     {
72         if (!empty($_REQUEST['handle']) && $_REQUEST['handle'] == 'save')
73         {
74                 return $this->handleSave();
75         }
76
77         global $beanList;
78
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}"))
84         {
85             $this->medataDataFile = "custom/{$editviewFile}";
86         }
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;
93                         }
94                 }
95             }
96         }
97
98         $this->medataDataFile = $this->fileName;
99         if (file_exists("custom/$this->fileName"))
100         {
101             $this->medataDataFile = "custom/$this->fileName";
102         }
103         $this->loadDefs();
104         $this->getRecord();
105         $this->checkForDuplicates($this->focus);
106         $smarty = new Sugar_Smarty();
107         $ev = new EditView();
108         $ev->ss = $smarty;
109         $ev->view = "ConvertLead";
110         echo $this->getModuleTitle();
111
112         require_once("include/QuickSearchDefaults.php");
113         $qsd = new QuickSearchDefaults();
114         $qsd->setFormName("ConvertLead");
115
116         $this->contact = new Contact();
117         $smarty->assign("contact_def", $this->contact->field_defs);
118         $smarty->assign("form_name", "ConvertLead");
119         $smarty->assign("form_id", "ConvertLead");
120         $smarty->assign("module", "Leads");
121         $smarty->assign("view", "convertlead");
122         $smarty->assign("bean", $this->focus);
123                 $smarty->assign("record_id", $this->focus->id);
124         global $mod_strings;
125         $smarty->assign('MOD', $mod_strings);
126         $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
127
128         echo "<div class='edit view' style='width:auto;'>";
129
130         global $sugar_config, $app_list_strings;
131         $smarty->assign('lead_conv_activity_opt', $sugar_config['lead_conv_activity_opt']);
132         $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
133
134         foreach($this->defs as $module => $vdef)
135         {
136             if(!isset($beanList[$module]))
137             {
138                 continue;
139             }
140             $bean = $beanList[$module];
141             $focus = new $bean();
142             $focus->fill_in_additional_detail_fields();
143             foreach($focus->field_defs as $field => $def)
144             {
145                 if(isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData'])
146                 {
147                         if ($module == "Accounts" && $field == 'name')
148                         {
149                             $focus->name = $this->focus->account_name;
150                         }
151                         else if ($module == "Opportunities" && $field == 'amount')
152                         {
153                             $focus->amount = unformat_number($this->focus->opportunity_amount);
154                         } 
155                         else if ($module == "Opportunities" && $field == 'name') {
156                                 if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)){
157                            $focus->name = $this->focus->opportunity_name;
158                                 }
159                         }
160                         else if ($field == "id")
161                     {
162                                                 //If it is not a contact, don't copy the ID from the lead
163                         if ($module == "Contacts") {
164                            $focus->$field = $this->focus->$field;
165                         }
166                     } else if (is_a($focus, "Company") && $field == 'phone_office')
167                         {
168                                 //Special case where company and person have the same field with a different name
169                                 $focus->phone_office = $this->focus->phone_work;
170                         }
171                                         else if (strpos($field, "billing_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */         
172                                         {
173                                                 $tmp_field = str_replace("billing_", "primary_", $field);
174                                                 $focus->field_defs[$field]["type"] = "text";
175                         if (isset($this->focus->$tmp_field)) {
176                                                     $focus->$field = $this->focus->$tmp_field;
177                         }
178                                          }
179
180                                         else if (strpos($field, "shipping_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */
181                                         {
182                                                 $tmp_field = str_replace("shipping_", "primary_", $field);
183                                                 if (isset($this->focus->$tmp_field)) {
184                             $focus->$field = $this->focus->$tmp_field;
185                         }
186                                                 $focus->field_defs[$field]["type"] = "text";
187                                         }                                       
188                     else if (isset($this->focus->$field))
189                     {
190                         $focus->$field = $this->focus->$field;
191                     }
192                 }
193             }
194
195             //Copy over email data
196             $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
197             $ev->process();
198             echo($ev->display(false));
199             echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
200         }
201         echo "</div>";
202         echo ($qsd->getQSScriptsJSONAlreadyDefined());
203         $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
204     }
205
206     protected function getRecord()
207     {
208         $this->focus = new Lead();
209         if (isset($_REQUEST['record']))
210         {
211                 $this->focus->retrieve($_REQUEST['record']);
212         }
213     }
214
215     protected function loadDefs()
216     {
217         $viewdefs = array();
218         include($this->medataDataFile);
219         $this->defs = $viewdefs;
220     }
221
222     /**
223      * Returns the javascript to enable/disable validation of each module's sub-form
224      * //TODO: This should probably be on the smarty template
225      * @param $module String the target module name.
226      * @param $focus SugarBean instance of the target module.
227      * @param $focus EditView def for the module.
228      * @return String, javascript to echo to page.
229      */
230     protected function getValidationJS(
231         $module,
232         $focus,
233         $viewdef
234         )
235     {
236         $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
237         $jsOut  = "
238         <script type='text/javascript'>
239             if (!SUGAR.convert)  SUGAR.convert = {requiredFields: {}};
240             SUGAR.convert.toggle$module = function(){
241                 clear_all_errors();
242                 inputsWithErrors = [];
243                 if(!SUGAR.convert.{$module}Enabled)
244                 {
245                     for(var i in SUGAR.convert.requiredFields.$module)
246                     {
247                         addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
248                     }
249                     ";
250         if ($validateSelect) {
251                 $jsOut  .= "
252                     removeFromValidate('ConvertLead', '{$viewdef['select']}');";
253         }
254
255         $jsOut .= "
256                     SUGAR.convert.{$module}Enabled = true;
257                 } else {
258                     for(var i in SUGAR.convert.requiredFields.$module)
259                     {
260                         removeFromValidate('ConvertLead', '$module' + i);
261                     }";
262         if ($validateSelect) {
263             $jsOut  .= "
264                 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
265             . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
266         }
267         $jsOut .= "
268                     SUGAR.convert.{$module}Enabled = false;
269                 }
270                 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
271             };\n";
272
273         if (isset($viewdef['required']) && $viewdef['required'])
274         {
275             if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
276             {
277                 $jsOut .= "
278             SUGAR.convert.{$module}Enabled = true;";
279             }
280             $jsOut .= "
281             YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
282         } else if (isset($viewdef['default_action'])  && $viewdef['default_action'] == "create")
283         {
284              $jsOut .= "\n            SUGAR.convert.{$module}Enabled = true;";
285         }
286         $jsOut .= "
287             YAHOO.util.Event.addListener('new$module', 'click', SUGAR.convert.toggle$module);
288             SUGAR.convert.requiredFields.$module = {};";
289         foreach($focus->field_defs as $field => $def)
290         {
291             if (isset($def['required']) && $def['required'])
292             {
293                 $jsOut .= "
294             SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
295             }
296         }
297
298         $jsOut .= "
299         </script>";
300
301         return $jsOut;
302     }
303
304     /**
305      * Saves a new Contact as well as any related items passed in.
306      *
307      * @return null
308      */
309     protected function handleSave()
310     {
311         require_once('modules/Campaigns/utils.php');
312         require_once("include/formbase.php");
313         $lead = false;
314         if (!empty($_REQUEST['record']))
315         {
316             $lead = new Lead();
317             $lead->retrieve($_REQUEST['record']);
318         }
319
320         global $beanList;
321         $this->loadDefs();
322         $beans = array();
323         $selectedBeans = array();
324         $selects = array();
325         //Make sure the contact object is availible for relationships.
326         $beans['Contacts'] = new Contact();
327         $beans['Contacts']->id = create_guid();
328         $beans['Contacts']->new_with_id = true;
329
330         // Bug 39287 - Check for Duplicates on selected modules before save
331         if (!empty($_REQUEST['selectedContact']))
332         {
333             $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
334             if (!empty($beans['Contacts']->id))
335             {
336                 $beans['Contacts']->new_with_id = false;
337                 unset($_REQUEST["convert_create_Contacts"]);
338                 unset($_POST["convert_create_Contacts"]);
339             }
340         }
341         elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact'])) 
342         {
343             require_once('modules/Contacts/ContactFormBase.php');
344             $contactForm = new ContactFormBase();
345             $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
346             if (isset($duplicateContacts))
347             {
348                 echo $contactForm->buildTableForm($duplicateContacts,  'Contacts');
349                 return;
350             }
351             $this->new_contact = true;
352         }
353         if (!empty($_REQUEST['selectedAccount']))
354         {
355             $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
356             unset($_REQUEST["convert_create_Accounts"]);
357             unset($_POST["convert_create_Accounts"]);
358         }
359         elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount']))
360         {
361             require_once('modules/Accounts/AccountFormBase.php');
362             $accountForm = new AccountFormBase();
363             $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
364             if (isset($duplicateAccounts))
365             {
366                 echo $accountForm->buildTableForm($duplicateAccounts);
367                 return;
368             }
369         }
370
371         foreach ($this->defs as $module => $vdef)
372         {
373             //Create a new record if "create" was selected
374                 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
375             {
376                 //Save the new record
377                 $bean = $beanList[$module];
378                     if (empty($beans[$module]))
379                         $beans[$module] = new $bean();
380
381                 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
382
383             }
384             //If an existing bean was selected, relate it to the contact
385             else if (!empty($vdef['ConvertLead']['select'])) 
386             {
387                 //Save the new record
388                 $select = $vdef['ConvertLead']['select'];
389                 $fieldDef = $beans['Contacts']->field_defs[$select];
390                 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
391                 {
392                     $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
393                     $selects[$module] = $_REQUEST[$fieldDef['id_name']];
394                     if (!empty($_REQUEST[$select]))
395                     {
396                         $beans['Contacts']->$select = $_REQUEST[$select];
397                     }
398                     // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
399                     $bean = loadBean($module);
400                     $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
401                     $selectedBeans[$module] = $bean;
402                 }
403             }
404         }
405
406         $this->handleActivities($lead, $beans);
407         // Bug 39268 - Add the lead's activities to the selected beans
408         $this->handleActivities($lead, $selectedBeans);
409
410         //link selected account to lead if it exists
411         if (!empty($selectedBeans['Accounts']))
412         {
413             $lead->account_id = $selectedBeans['Accounts']->id;
414         }
415
416         //Handle non-contacts relationships
417         foreach ($beans as $bean)
418         {
419
420             if (!empty($lead))
421             {
422                 if (empty($bean->assigned_user_id))
423                 {
424                     $bean->assigned_user_id = $lead->assigned_user_id;
425                 }
426                 $leadsRel = $this->findRelationship($bean, $lead);
427                 if (!empty($leadsRel))
428                 {
429                     $bean->load_relationship($leadsRel);
430                     $relObject = $bean->$leadsRel->getRelationshipObject();
431                     if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
432                     {
433                         $id_field = $relObject->rhs_key;
434                         $lead->$id_field = $bean->id;
435                     }
436                     else 
437                     {
438                         $bean->$leadsRel->add($lead->id);
439                     }
440                 }
441             }
442             //Special case code for opportunities->Accounts
443             if ($bean->object_name == "Opportunity" && empty($bean->account_id))
444             {
445                 if (isset($beans['Accounts']))
446                 {
447                     $bean->account_id = $beans['Accounts']->id;
448                     $bean->account_name = $beans['Accounts']->name;
449                 }
450                 else if (!empty($selects['Accounts']))
451                 {
452                     $bean->account_id = $selects['Accounts'];
453                 }
454             }
455
456             //create meetings-users relationship
457             if ($bean->object_name == "Meeting")
458             {
459                 $bean = $this->setMeetingsUsersRelationship($bean);
460             }
461             $this->copyAddressFields($bean, $beans['Contacts']);
462
463             $bean->save();
464             //if campaign id exists then there should be an entry in campaign_log table for the newly created contact: bug 44522        
465             if (isset($lead->campaign_id) && $lead->campaign_id != null && $bean->object_name == "Contact")
466             {
467                 campaign_log_lead_or_contact_entry($lead->campaign_id, $lead, $beans['Contacts'], 'contact');
468             }
469         }
470         if (!empty($lead))
471         {       //Mark the original Lead converted
472             $lead->status = "Converted";
473             $lead->converted = '1';
474             $lead->in_workflow = true;
475             $lead->save();
476         }
477
478         $this->displaySaveResults($beans);
479     }
480
481     public function setMeetingsUsersRelationship($bean)
482     {
483         global $current_user;
484         $meetingsRel = $this->findRelationshipByName($bean, $this->defs['Meetings']['ConvertLead']['relationship']);
485         if (!empty($meetingsRel))
486         {
487             $bean->load_relationship($meetingsRel);
488             $bean->$meetingsRel->add($current_user->id);
489             return $bean;
490         }
491         else
492         {
493             return false;
494         }
495     }
496     protected function displaySaveResults(
497         $beans
498         )
499     {
500         global $beanList;
501         echo "<div><ul>";
502         foreach($beans as $bean)
503         {
504             $beanName = $bean->object_name;
505             if ( $beanName == 'Contact' && !$this->new_contact ) {
506                 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
507                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
508                        {$bean->get_summary_text()}
509                     </a></li>";
510             }
511             else {
512                 global $app_list_strings;
513                 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
514                     $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
515                 } else {
516                     $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
517                 }
518                 if(empty($module_name)) {
519                     $module_name = translate($beanName);
520                 }
521                 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
522                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
523                        {$bean->get_summary_text()}
524                     </a></li>";
525             }
526         }
527
528         echo "</ul></div>";
529     }
530
531     protected function handleActivities(
532         $lead,
533         $beans
534         )
535     {
536         global $app_list_strings;
537         global $sugar_config;
538         $parent_types = $app_list_strings['record_type_display'];
539
540         $activities = $this->getActivitiesFromLead($lead);
541
542         foreach($beans as $module => $bean)
543         {
544                 if (isset($parent_types[$module]))
545                 {
546                 if (empty($bean->id))
547                 {
548                     $bean->id = create_guid();
549                             $bean->new_with_id = true;
550                 }
551                 foreach($activities as $activity)
552                         {
553                             if (!isset($sugar_config['lead_conv_activity_opt']) || $sugar_config['lead_conv_activity_opt'] == 'copy') {
554                                 if (isset($_POST['lead_conv_ac_op_sel'])) {
555                                     //if the copy to module(s) are defined, copy only to those module(s)
556                                     if (is_array($_POST['lead_conv_ac_op_sel'])) {
557                                         foreach ($_POST['lead_conv_ac_op_sel'] as $mod) {
558                                             if ($mod == $module) {
559                                                 $this->copyActivityAndRelateToBean($activity, $bean);
560                                                 break;
561                                             }
562                                         }
563                                     }
564                                 }
565                             }
566                             else if ($sugar_config['lead_conv_activity_opt'] == 'move') {
567                                 // if to move activities, should be only one module selected
568                                 if ($_POST['lead_conv_ac_op_sel'] == $module) {
569                                     $this->moveActivity($activity, $bean);
570                                 }
571                             }
572                         }
573                 }
574         }
575     }
576
577     /**
578      * Change the parent id and parent type of an activity
579      * @param $activity Activity to be modified
580      * @param $bean New parent bean of the activity
581      */
582     protected function moveActivity($activity, $bean) {
583         global $beanList;
584
585         $lead = null;
586         if (!empty($_REQUEST['record']))
587         {
588             $lead = new Lead();
589             $lead->retrieve($_REQUEST['record']);
590         }
591
592         // delete the old relationship to the old parent (lead)
593         if ($rel = $this->findRelationship($activity, $lead)) {
594             $activity->load_relationship ($rel) ;
595
596             if ($activity->parent_id && $activity->id) {
597                 $activity->$rel->delete($activity->id, $activity->parent_id);
598             }
599         }
600
601         // add the new relationship to the new parent (contact, account, etc)
602         if ($rel = $this->findRelationship($activity, $bean)) {
603             $activity->load_relationship ($rel) ;
604
605             $relObj = $activity->$rel->getRelationshipObject();
606             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
607             {
608                 $key = $relObj->rhs_key;
609                 $activity->$key = $bean->id;
610             }
611             $activity->$rel->add($bean);
612         }
613
614         // set the new parent id and type
615         $activity->parent_id = $bean->id;
616         $activity->parent_type = $bean->module_dir;
617
618         $activity->save();
619     }
620
621     /**
622      * Gets the list of activities related to the lead
623      * @param Lead $lead Lead to get activities from
624      * @return Array of Activity SugarBeans .
625      */
626         protected function getActivitiesFromLead(
627             $lead
628             )
629         {
630                 if (!$lead) return;
631
632                 global $beanList, $db;
633
634                 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
635                 $activities = array();
636
637                 foreach($activitesList as $module)
638                 {
639                         $beanName = $beanList[$module];
640                         $activity = new $beanName();
641                         $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
642                         $result = $db->query($query,true);
643             while($row = $db->fetchByAssoc($result))
644             {
645                 $activity = new $beanName();
646                                 $activity->retrieve($row['id']);
647                                 $activity->fixUpFormatting();
648                                 $activities[] = $activity;
649             }
650                 }
651
652                 return $activities;
653         }
654
655         protected function copyActivityAndRelateToBean(
656             $activity,
657             $bean
658             )
659         {
660                 global $beanList;
661
662                 $newActivity = clone $activity;
663                 $newActivity->id = create_guid();
664                 $newActivity->new_with_id = true;
665
666                 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
667         if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
668         {
669                 $newActivity->contact_id = $activity->contact_name = "";
670         }
671
672                 if ($rel = $this->findRelationship($newActivity, $bean))
673         {
674             $newActivity->load_relationship ($rel) ;
675             $relObj = $newActivity->$rel->getRelationshipObject();
676             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
677             {
678                 $key = $relObj->rhs_key;
679                 $newActivity->$key = $bean->id;
680             }
681             $newActivity->parent_id = $bean->id;
682                 $newActivity->parent_type = $bean->module_dir;
683                 $newActivity->update_date_modified = false; //bug 41747 
684                 $newActivity->save();
685             $newActivity->$rel->add($bean);
686             if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
687                         UploadFile::duplicate_file($activity->id, $newActivity->id,  $newActivity->filename);
688                 }
689          }
690         }
691
692     /**
693      * Populates the passed in Bean fron the contact and the $_REQUEST
694      * @param String $module Module of new bean
695      * @param SugarBean $bean SugarBean to be populated.
696      * @param Contact $contact Contact to relate the bean to.
697      */
698         protected function populateNewBean(
699             $module,
700             $bean,
701             $contact,
702             $lead
703             )
704         {
705                 populateFromPost($module, $bean, true);
706
707                 //Copy data from the contact to new bean
708                 foreach($bean->field_defs as $field => $def)
709                 {
710                         if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
711                         {
712                                 $bean->$field = $lead->$field;
713                                 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
714                         }
715                 }
716                 //Try to link to the new contact
717                 $contactRel = "";
718                 if (!empty($vdef['ConvertLead']['select']))
719                 {
720                         $select = $vdef['ConvertLead']['select'];
721                         $fieldDef = $contact->field_defs[$select];
722                         if (!empty($fieldDef['id_name']))
723                         {
724                                 $bean->id = create_guid();
725                                 $bean->new_with_id = true;
726                                 $contact->$fieldDef['id_name'] = $bean->id ;
727                                 if ($fieldDef['id_name'] != $select) {
728                                         $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
729                                         if (!empty($rname) && isset($bean->$rname))
730                                                 $contact->$select = $bean->$rname;
731                                         else
732                                                 $contact->$select = $bean->name;
733                                 }
734                         }
735                 } else if ($module != "Contacts"){
736                         $contactRel = $this->findRelationship($contact, $bean);
737                         if (!empty($contactRel))
738                         {
739                                 $bean->id = create_guid();
740                                 $bean->new_with_id = true;
741                                 $contact->load_relationship ($contactRel) ;
742                                 $relObject = $contact->$contactRel->getRelationshipObject();
743                                 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
744                                 {
745                                         $id_field = $relObject->rhs_key;
746                                         $bean->$id_field = $contact->id;
747                                 } else {
748                                         $contact->$contactRel->add($bean);
749                                 }
750                                 //Set the parent of activites to the new Contact
751                                 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
752                                 {
753                                         $bean->parent_id = $contact->id;
754                                         $bean->parent_type = "Contacts";
755                                 }
756                         }
757                 }
758         }
759
760         protected function copyAddressFields($bean, $contact)
761         {
762         //Copy over address info from the contact to any beans with address not set
763                 foreach($bean->field_defs as $field => $def)
764                         {
765                                 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
766                                 {
767                                         $set = "primary";
768                                         if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
769                                                 $set = "alt";
770                                         $type = "";
771
772                                         if(strpos($field, "_address_street_2") !== false)
773                                                 $type = "_address_street_2";
774                                         else if(strpos($field, "_address_street_3") !== false)
775                                                 $type = "_address_street_3";
776                                         else if(strpos($field, "_address_street_4") !== false)
777                                                 $type = "";
778                                         else if(strpos($field, "_address_street") !== false)
779                                                 $type = "_address_street";
780                                         else if(strpos($field, "_address_city") !== false)
781                                                 $type = "_address_city";
782                                         else if(strpos($field, "_address_state") !== false)
783                                                 $type = "_address_state";
784                                         else if(strpos($field, "_address_postalcode") !== false)
785                                                 $type = "_address_postalcode";
786                                         else if(strpos($field, "_address_country") !== false)
787                                                 $type = "_address_country";
788
789                                                 $var = $set.$type;
790                                         if (isset($contact->$var))
791                                                 $bean->$field = $contact->$var;
792                                 }
793                         }
794         }
795
796
797     protected function findRelationship(
798         $from,
799         $to
800         )
801     {
802         global $dictionary;
803         require_once("modules/TableDictionary.php");
804         foreach ($from->field_defs as $field=>$def)
805         {
806             if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) 
807                         {
808                 $rel_name = $def['relationship'];
809                 $rel_def = "";
810                 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
811                 {
812                     $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
813                 }
814                 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
815                 {
816                     $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
817                 }
818                 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
819                         && isset($dictionary[$rel_name]['relationships'][$rel_name]))
820                 {
821                         $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
822                 }
823                 if (!empty($rel_def)) {
824                     if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
825                     {
826                         return $field;
827                     }
828                     else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
829                     {
830                         return $field;
831                     }
832                 }
833             }
834         }
835         return false;
836     }
837
838     protected function findRelationshipByName($from, $rel_name)
839     {
840         global $dictionary;
841         require_once("modules/TableDictionary.php");
842         foreach ($from->field_defs as $field => $def)
843         {
844             if (isset($def['relationship']) && $def['relationship'] == $rel_name) 
845             {
846                 return $field;
847             }
848         }
849         return false;
850     }
851         /**
852          * @see SugarView::_getModuleTitleParams()
853          */
854         protected function _getModuleTitleParams($browserTitle = false)
855         {
856             global $mod_strings;
857             $params = parent::_getModuleTitleParams($browserTitle);
858             $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
859             $params[] = $mod_strings['LBL_CONVERTLEAD'];
860         return $params;
861     }
862
863
864     protected function checkForDuplicates(
865         $lead
866         )
867     {
868         if ($lead->status == "Converted")
869         {
870                 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
871                 $dupes = array();
872                 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
873                 $result = $lead->db->query($q);
874                 while($row = $lead->db->fetchByAssoc($result)) {
875                         $contact = new Contact();
876                         $contact->retrieve($row['id']);
877                         $dupes[$row['id']] = $contact->name;
878                 }
879                 if (!empty($dupes))
880                 {
881                         foreach($dupes as $id => $name)
882                         {
883                                 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");
884                                 break;
885                         }
886                 }
887                 echo "</span>";
888         }
889         return false;
890     }
891 }