]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Leads/views/view.convertlead.php
Release 6.5.10
[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-2013 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 = QuickSearchDefaults::getQuickSearchDefaults();
114         $qsd->setFormName("ConvertLead");
115
116         $this->contact = new Contact();
117         
118         /*
119          * Setup filter for Account/Contact popup picker
120          */ 
121         $filter = '';
122         // Check if Lead has an account set
123         if (!empty($this->focus->account_name))
124         {
125             $filter .= '&name_advanced=' . urlencode($this->focus->account_name);
126         }
127         // Check if Lead First name is available
128         if (!empty($this->focus->first_name))
129         {
130             $filter .= '&first_name_advanced=' . urlencode($this->focus->first_name);
131         }
132         // Lead Last Name is always available
133         $filter .= '&last_name_advanced=' . urlencode($this->focus->last_name);
134         
135         $smarty->assign('initialFilter', $filter);
136         $smarty->assign('displayParams', array('initial_filter' => '{$initialFilter}'));
137         
138         $relatedFields = $this->contact->get_related_fields();
139         $selectFields = array();
140         foreach ($this->defs as $moduleName => $mDefs)
141         {   
142             if (!empty($mDefs[$ev->view]['select']) && !empty($relatedFields[$mDefs[$ev->view]['select']]))
143             {
144                 $selectFields[$moduleName] = $mDefs[$ev->view]['select'];
145                 continue;
146             }
147             foreach ($relatedFields as $fDef)
148             {
149                 if (!empty($fDef['link']) && !empty($fDef['module']) && $fDef['module'] == $moduleName)
150                 {
151                     $selectFields[$moduleName] = $fDef['name'];
152                     break;
153                 }
154             }
155         }
156         
157         $smarty->assign('selectFields', $selectFields);
158
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);
166         global $mod_strings;
167         $smarty->assign('MOD', $mod_strings);
168         $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
169
170         echo "<div class='edit view' style='width:auto;'>";
171
172         global $sugar_config, $app_list_strings, $app_strings;
173         $smarty->assign('lead_conv_activity_opt', $sugar_config['lead_conv_activity_opt']);
174         
175         //Switch up list depending on copy or move
176         if($sugar_config['lead_conv_activity_opt'] == 'move')
177         {
178                 $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('None'=>$app_strings['LBL_NONE'], 'Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));        
179         }
180         else if($sugar_config['lead_conv_activity_opt'] == 'copy')
181         {
182                 $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
183         }
184         
185         
186
187         foreach($this->defs as $module => $vdef)
188         {
189             if(!isset($beanList[$module]))
190             {
191                 continue;
192             }
193
194
195             $bean = $beanList[$module];
196             $focus = new $bean();
197
198             // skip if we aren't allowed to save this bean
199             if (!$focus->ACLAccess('save'))
200             {
201                 continue;
202             }
203
204             $focus->fill_in_additional_detail_fields();
205             foreach($focus->field_defs as $field => $def)
206             {
207                 if(isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData'])
208                 {
209                         if ($module == "Accounts" && $field == 'name')
210                         {
211                             $focus->name = $this->focus->account_name;
212                         }
213                         else if ($module == "Opportunities" && $field == 'amount')
214                         {
215                             $focus->amount = unformat_number($this->focus->opportunity_amount);
216                         } 
217                         else if ($module == "Opportunities" && $field == 'name') {
218                                 if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)){
219                            $focus->name = $this->focus->opportunity_name;
220                                 }
221                         }
222                         else if ($field == "id")
223                     {
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;
227                         }
228                     } else if (is_a($focus, "Company") && $field == 'phone_office')
229                         {
230                                 //Special case where company and person have the same field with a different name
231                                 $focus->phone_office = $this->focus->phone_work;
232                         }
233                                         else if (strpos($field, "billing_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */         
234                                         {
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;
239                         }
240                                          }
241
242                                         else if (strpos($field, "shipping_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */
243                                         {
244                                                 $tmp_field = str_replace("shipping_", "primary_", $field);
245                                                 if (isset($this->focus->$tmp_field)) {
246                             $focus->$field = $this->focus->$tmp_field;
247                         }
248                                                 $focus->field_defs[$field]["type"] = "text";
249                                         }                                       
250                     else if (isset($this->focus->$field))
251                     {
252                         $focus->$field = $this->focus->$field;
253                     }
254                 }
255             }
256
257             //Copy over email data
258             $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
259             $ev->process();
260             echo($ev->display(false));
261             echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
262         }
263         echo "</div>";
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");
268     }
269
270     protected function getRecord()
271     {
272         $this->focus = new Lead();
273         if (isset($_REQUEST['record']))
274         {
275                 $this->focus->retrieve($_REQUEST['record']);
276         }
277     }
278
279     protected function loadDefs()
280     {
281         $viewdefs = array();
282         include($this->medataDataFile);
283         $this->defs = $viewdefs;
284     }
285
286     /**
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.
293      */
294     protected function getValidationJS(
295         $module,
296         $focus,
297         $viewdef
298         )
299     {
300         $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
301         $jsOut  = "
302         <script type='text/javascript'>
303             if (!SUGAR.convert)  SUGAR.convert = {requiredFields: {}};
304             SUGAR.convert.toggle$module = function(){
305                 clear_all_errors();
306                 inputsWithErrors = [];
307                 if(!SUGAR.convert.{$module}Enabled)
308                 {
309                     for(var i in SUGAR.convert.requiredFields.$module)
310                     {
311                         addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
312                     }
313                     ";
314         if ($validateSelect) {
315                 $jsOut  .= "
316                     removeFromValidate('ConvertLead', '{$viewdef['select']}');";
317         }
318
319         $jsOut .= "
320                     SUGAR.convert.{$module}Enabled = true;
321                 } else {
322                     for(var i in SUGAR.convert.requiredFields.$module)
323                     {
324                         removeFromValidate('ConvertLead', '$module' + i);
325                     }";
326         if ($validateSelect) {
327             $jsOut  .= "
328                 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
329             . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
330         }
331         $jsOut .= "
332                     SUGAR.convert.{$module}Enabled = false;
333                 }
334                 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
335             };\n";
336
337         if (isset($viewdef['required']) && $viewdef['required'])
338         {
339             if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
340             {
341                 $jsOut .= "
342             SUGAR.convert.{$module}Enabled = true;";
343             }
344             $jsOut .= "
345             YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
346         } else if (isset($viewdef['default_action'])  && $viewdef['default_action'] == "create")
347         {
348              $jsOut .= "\n            SUGAR.convert.{$module}Enabled = true;";
349         }
350         $jsOut .= "
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)
354         {
355             if (isset($def['required']) && $def['required'])
356             {
357                 $jsOut .= "
358             SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
359             }
360         }
361
362         $jsOut .= "
363         </script>";
364
365         return $jsOut;
366     }
367
368     /**
369      * Saves a new Contact as well as any related items passed in.
370      *
371      * @return null
372      */
373     protected function handleSave()
374     {
375         require_once('modules/Campaigns/utils.php');
376         require_once("include/formbase.php");
377         $lead = false;
378         if (!empty($_REQUEST['record']))
379         {
380             $lead = new Lead();
381             $lead->retrieve($_REQUEST['record']);
382         }
383
384         global $beanList;
385         $this->loadDefs();
386         $beans = array();
387         $selectedBeans = array();
388         $selects = array();
389         
390         // Make sure the contact object is availible for relationships.
391         $beans['Contacts'] = new Contact();
392         
393         // Contacts
394         if (!empty($_REQUEST['selectedContact']))
395         {
396             $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
397             if (!empty($beans['Contacts']->id))
398             {
399                 $beans['Contacts']->new_with_id = false;
400                 unset($_REQUEST["convert_create_Contacts"]);
401                 unset($_POST["convert_create_Contacts"]);
402             }
403         }
404         elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact'])) 
405         {
406             require_once('modules/Contacts/ContactFormBase.php');
407             $contactForm = new ContactFormBase();
408             $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
409
410             if (isset($duplicateContacts))
411             {
412                 echo $contactForm->buildTableForm($duplicateContacts,  'Contacts');
413                 return;
414             }
415             $this->new_contact = true;
416         } elseif (isset($_POST['ContinueContact'])) {
417             $this->new_contact = true;
418         }
419         // Accounts
420         if (!empty($_REQUEST['selectedAccount']))
421         {
422             $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
423             unset($_REQUEST["convert_create_Accounts"]);
424             unset($_POST["convert_create_Accounts"]);
425         }
426         elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount']))
427         {
428             require_once('modules/Accounts/AccountFormBase.php');
429             $accountForm = new AccountFormBase();
430             $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
431             if (isset($duplicateAccounts))
432             {
433                 echo $accountForm->buildTableForm($duplicateAccounts);
434                 return;
435             }
436         }
437
438         foreach ($this->defs as $module => $vdef)
439         {
440             //Create a new record if "create" was selected
441                 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
442             {
443                 //Save the new record
444                 $bean = $beanList[$module];
445                     if (empty($beans[$module]))
446                         $beans[$module] = new $bean();
447
448                 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
449
450                 // when creating a new contact, create the id for linking with other modules
451                 // and do not populate it with lead's old account_id
452                 if ($module == 'Contacts')
453                 {
454                     $beans[$module]->id = create_guid();
455                     $beans[$module]->new_with_id = true;
456                     $beans[$module]->account_id = '';
457                 }
458             }
459             //If an existing bean was selected, relate it to the contact
460             else if (!empty($vdef['ConvertLead']['select'])) 
461             {
462                 //Save the new record
463                 $select = $vdef['ConvertLead']['select'];
464                 $fieldDef = $beans['Contacts']->field_defs[$select];
465                 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
466                 {
467                     $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
468                     $selects[$module] = $_REQUEST[$fieldDef['id_name']];
469                     if (!empty($_REQUEST[$select]))
470                     {
471                         $beans['Contacts']->$select = $_REQUEST[$select];
472                     }
473                     // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
474                     $bean = loadBean($module);
475                     $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
476                     $selectedBeans[$module] = $bean;
477                     // If we selected the Contact, just overwrite the $beans['Contacts']
478                     if ($module == 'Contacts')
479                     {
480                         $beans[$module] = $bean;
481                     }
482                 }
483             }
484         }
485
486         $this->handleActivities($lead, $beans);
487         // Bug 39268 - Add the lead's activities to the selected beans
488         $this->handleActivities($lead, $selectedBeans);
489
490         //link selected account to lead if it exists
491         if (!empty($selectedBeans['Accounts']))
492         {
493             $lead->account_id = $selectedBeans['Accounts']->id;
494         }
495         
496         // link account to contact, if we picked an existing contact and created a new account
497         if (!empty($beans['Accounts']->id) && !empty($beans['Contacts']->account_id) 
498                 && $beans['Accounts']->id != $beans['Contacts']->account_id)
499         {
500             $beans['Contacts']->account_id = $beans['Accounts']->id;
501         }
502         
503         // Saving beans with priorities.
504         // Contacts and Accounts should be saved before lead activities to create correct relations
505         $saveBeanPriority = array('Contacts', 'Accounts');
506         $tempBeans = array();
507
508         foreach ($saveBeanPriority as $name)
509         {
510             if (isset($beans[$name]))
511             {
512                 $tempBeans[$name] = $beans[$name];
513             }
514         }
515
516         $beans = array_merge($tempBeans, $beans);
517         unset($tempBeans);
518
519         //Handle non-contacts relationships
520         foreach ($beans as $bean)
521         {
522             if (!empty($lead))
523             {
524                 if (empty($bean->assigned_user_id))
525                 {
526                     $bean->assigned_user_id = $lead->assigned_user_id;
527                 }
528                 $leadsRel = $this->findRelationship($bean, $lead);
529                 if (!empty($leadsRel))
530                 {
531                     $bean->load_relationship($leadsRel);
532                     $relObject = $bean->$leadsRel->getRelationshipObject();
533                     if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
534                     {
535                         $id_field = $relObject->rhs_key;
536                         $lead->$id_field = $bean->id;
537                     }
538                     else 
539                     {
540                         $bean->$leadsRel->add($lead->id);
541                     }
542                 }
543             }
544             //Special case code for opportunities->Accounts
545             if ($bean->object_name == "Opportunity" && empty($bean->account_id))
546             {
547                 if (isset($beans['Accounts']))
548                 {
549                     $bean->account_id = $beans['Accounts']->id;
550                     $bean->account_name = $beans['Accounts']->name;
551                 }
552                 else if (!empty($selects['Accounts']))
553                 {
554                     $bean->account_id = $selects['Accounts'];
555                 }
556             }
557
558             //create meetings-users relationship
559             if ($bean->object_name == "Meeting")
560             {
561                 $bean = $this->setMeetingsUsersRelationship($bean);
562             }
563             $this->copyAddressFields($bean, $beans['Contacts']);
564
565             $bean->save();
566             //if campaign id exists then there should be an entry in campaign_log table for the newly created contact: bug 44522        
567             if (isset($lead->campaign_id) && $lead->campaign_id != null && $bean->object_name == "Contact")
568             {
569                 campaign_log_lead_or_contact_entry($lead->campaign_id, $lead, $beans['Contacts'], 'contact');
570             }
571         }
572         if (!empty($lead))
573         {       //Mark the original Lead converted
574             $lead->status = "Converted";
575             $lead->converted = '1';
576             $lead->in_workflow = true;
577             $lead->save();
578         }
579
580         $this->displaySaveResults($beans);
581     }
582
583     public function setMeetingsUsersRelationship($bean)
584     {
585         global $current_user;
586         $meetingsRel = $this->findRelationshipByName($bean, $this->defs['Meetings']['ConvertLead']['relationship']);
587         if (!empty($meetingsRel))
588         {
589             $bean->load_relationship($meetingsRel);
590             $bean->$meetingsRel->add($current_user->id);
591             return $bean;
592         }
593         else
594         {
595             return false;
596         }
597     }
598     protected function displaySaveResults(
599         $beans
600         )
601     {
602         global $beanList;
603         echo "<div><ul>";
604         foreach($beans as $bean)
605         {
606             $beanName = $bean->object_name;
607             if ( $beanName == 'Contact' && !$this->new_contact ) {
608                 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
609                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
610                        {$bean->get_summary_text()}
611                     </a></li>";
612             }
613             else {
614                 global $app_list_strings;
615                 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
616                     $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
617                 } else {
618                     $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
619                 }
620                 if(empty($module_name)) {
621                     $module_name = translate($beanName);
622                 }
623                 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
624                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
625                        {$bean->get_summary_text()}
626                     </a></li>";
627             }
628         }
629
630         echo "</ul></div>";
631     }
632
633     protected function handleActivities(
634         $lead,
635         $beans
636         )
637     {
638         global $app_list_strings;
639         global $sugar_config;
640         global $app_strings;
641         $parent_types = $app_list_strings['record_type_display'];
642
643         $activities = $this->getActivitiesFromLead($lead);
644
645         //if account is being created, we will specify the account as the parent bean
646         $accountParentInfo = array();
647
648         //determine the account id info ahead of time if it is being created as part of this conversion
649         if(!empty($beans['Accounts'])){
650             $account_id = create_guid();
651             if(!empty($beans['Accounts']->id)){
652                 $account_id = $beans['Accounts']->id;
653             }else{
654                 $beans['Accounts']->id = $account_id;
655             }
656             $accountParentInfo = array('id'=>$account_id,'type'=>'Accounts');
657         }
658
659         foreach($beans as $module => $bean)
660         {
661                 if (isset($parent_types[$module]))
662                 {
663                 if (empty($bean->id))
664                 {
665                     $bean->id = create_guid();
666                             $bean->new_with_id = true;
667                 }
668                 if( isset($_POST['lead_conv_ac_op_sel']) && $_POST['lead_conv_ac_op_sel'] != 'None')
669                 {
670                         foreach($activities as $activity)
671                                 {
672                                     if (!isset($sugar_config['lead_conv_activity_opt']) || $sugar_config['lead_conv_activity_opt'] == 'copy') {
673                                         if (isset($_POST['lead_conv_ac_op_sel'])) {
674                                             //if the copy to module(s) are defined, copy only to those module(s)
675                                             if (is_array($_POST['lead_conv_ac_op_sel'])) {
676                                                 foreach ($_POST['lead_conv_ac_op_sel'] as $mod) {
677                                                     if ($mod == $module) {
678                                                         $this->copyActivityAndRelateToBean($activity, $bean, $accountParentInfo);
679                                                         break;
680                                                     }
681                                                 }
682                                             }
683                                         }
684                                     }
685                                     else if ($sugar_config['lead_conv_activity_opt'] == 'move') {
686                                         // if to move activities, should be only one module selected
687                                         if ($_POST['lead_conv_ac_op_sel'] == $module) {
688                                             $this->moveActivity($activity, $bean);
689                                         }
690                                     }
691                                 }
692                 }
693                 }
694         }
695     }
696
697     /**
698      * Change the parent id and parent type of an activity
699      * @param $activity Activity to be modified
700      * @param $bean New parent bean of the activity
701      */
702     protected function moveActivity($activity, $bean) {
703         global $beanList;
704
705         $lead = null;
706         if (!empty($_REQUEST['record']))
707         {
708             $lead = new Lead();
709             $lead->retrieve($_REQUEST['record']);
710         }
711
712         // delete the old relationship to the old parent (lead)
713         if ($rel = $this->findRelationship($activity, $lead)) {
714             $activity->load_relationship ($rel) ;
715
716             if ($activity->parent_id && $activity->id) {
717                 $activity->$rel->delete($activity->id, $activity->parent_id);
718             }
719         }
720
721         // add the new relationship to the new parent (contact, account, etc)
722         if ($rel = $this->findRelationship($activity, $bean)) {
723             $activity->load_relationship ($rel) ;
724
725             $relObj = $activity->$rel->getRelationshipObject();
726             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
727             {
728                 $key = $relObj->rhs_key;
729                 $activity->$key = $bean->id;
730             }
731             $activity->$rel->add($bean);
732         }
733
734         // set the new parent id and type
735         $activity->parent_id = $bean->id;
736         $activity->parent_type = $bean->module_dir;
737
738         $activity->save();
739     }
740
741     /**
742      * Gets the list of activities related to the lead
743      * @param Lead $lead Lead to get activities from
744      * @return Array of Activity SugarBeans .
745      */
746         protected function getActivitiesFromLead(
747             $lead
748             )
749         {
750                 if (!$lead) return;
751
752                 global $beanList, $db;
753
754                 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
755                 $activities = array();
756
757                 foreach($activitesList as $module)
758                 {
759                         $beanName = $beanList[$module];
760                         $activity = new $beanName();
761                         $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
762                         $result = $db->query($query,true);
763             while($row = $db->fetchByAssoc($result))
764             {
765                 $activity = new $beanName();
766                                 $activity->retrieve($row['id']);
767                                 $activity->fixUpFormatting();
768                                 $activities[] = $activity;
769             }
770                 }
771
772                 return $activities;
773         }
774
775         protected function copyActivityAndRelateToBean(
776             $activity,
777             $bean,
778         $parentArr = array()
779             )
780         {
781                 global $beanList;
782
783                 $newActivity = clone $activity;
784                 $newActivity->id = create_guid();
785                 $newActivity->new_with_id = true;
786
787         //set the parent id and type if it was passed in, otherwise use blank to wipe it out
788         $parentID = '';
789         $parentType = '';
790         if(!empty($parentArr)){
791             if(!empty($parentArr['id'])){
792                 $parentID = $parentArr['id'];
793             }
794
795             if(!empty($parentArr['type'])){
796                 $parentType = $parentArr['type'];
797             }
798
799         }
800
801                 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
802         if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
803         {
804             $newActivity->contact_id = $newActivity->contact_name = "";
805         }
806
807                 if ($rel = $this->findRelationship($newActivity, $bean))
808         {
809             if (isset($newActivity->$rel))
810             {
811                 // this comes form $activity, get rid of it and load our own
812                 $newActivity->$rel = '';
813             }
814
815             $newActivity->load_relationship ($rel) ;
816             $relObj = $newActivity->$rel->getRelationshipObject();
817             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
818             {
819                 $key = $relObj->rhs_key;
820                 $newActivity->$key = $bean->id;
821             }
822
823             //parent (related to field) should be blank unless it is explicitly sent in
824             //it is not sent in unless the account is being created as well during lead conversion
825             $newActivity->parent_id =  $parentID;
826             $newActivity->parent_type = $parentType;
827
828                 $newActivity->update_date_modified = false; //bug 41747
829                 $newActivity->save();
830             $newActivity->$rel->add($bean);
831             if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
832                         UploadFile::duplicate_file($activity->id, $newActivity->id,  $newActivity->filename);
833                 }
834          }
835         }
836
837     /**
838      * Populates the passed in Bean fron the contact and the $_REQUEST
839      * @param String $module Module of new bean
840      * @param SugarBean $bean SugarBean to be populated.
841      * @param Contact $contact Contact to relate the bean to.
842      */
843         protected function populateNewBean(
844             $module,
845             $bean,
846             $contact,
847             $lead
848             )
849         {
850                 populateFromPost($module, $bean, true);
851
852                 //Copy data from the contact to new bean
853                 foreach($bean->field_defs as $field => $def)
854                 {
855                         if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
856                         {
857                                 $bean->$field = $lead->$field;
858                                 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
859                         }
860                 }
861                 //Try to link to the new contact
862                 $contactRel = "";
863                 if (!empty($vdef['ConvertLead']['select']))
864                 {
865                         $select = $vdef['ConvertLead']['select'];
866                         $fieldDef = $contact->field_defs[$select];
867                         if (!empty($fieldDef['id_name']))
868                         {
869                                 $bean->id = create_guid();
870                                 $bean->new_with_id = true;
871                                 $contact->$fieldDef['id_name'] = $bean->id ;
872                                 if ($fieldDef['id_name'] != $select) {
873                                         $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
874                                         if (!empty($rname) && isset($bean->$rname))
875                                                 $contact->$select = $bean->$rname;
876                                         else
877                                                 $contact->$select = $bean->name;
878                                 }
879                         }
880                 } else if ($module != "Contacts"){
881                         $contactRel = $this->findRelationship($contact, $bean);
882                         if (!empty($contactRel))
883                         {
884                                 $bean->id = create_guid();
885                                 $bean->new_with_id = true;
886                                 $contact->load_relationship ($contactRel) ;
887                                 $relObject = $contact->$contactRel->getRelationshipObject();
888                                 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
889                                 {
890                                         $id_field = $relObject->rhs_key;
891                                         $bean->$id_field = $contact->id;
892                                 } else {
893                                         $contact->$contactRel->add($bean);
894                                 }
895                                 //Set the parent of activites to the new Contact
896                                 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
897                                 {
898                                         $bean->parent_id = $contact->id;
899                                         $bean->parent_type = "Contacts";
900                                 }
901                         }
902                 }
903         }
904
905         protected function copyAddressFields($bean, $contact)
906         {
907         //Copy over address info from the contact to any beans with address not set
908                 foreach($bean->field_defs as $field => $def)
909                         {
910                                 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
911                                 {
912                                         $set = "primary";
913                                         if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
914                                                 $set = "alt";
915                                         $type = "";
916
917                                         if(strpos($field, "_address_street_2") !== false)
918                                                 $type = "_address_street_2";
919                                         else if(strpos($field, "_address_street_3") !== false)
920                                                 $type = "_address_street_3";
921                                         else if(strpos($field, "_address_street_4") !== false)
922                                                 $type = "";
923                                         else if(strpos($field, "_address_street") !== false)
924                                                 $type = "_address_street";
925                                         else if(strpos($field, "_address_city") !== false)
926                                                 $type = "_address_city";
927                                         else if(strpos($field, "_address_state") !== false)
928                                                 $type = "_address_state";
929                                         else if(strpos($field, "_address_postalcode") !== false)
930                                                 $type = "_address_postalcode";
931                                         else if(strpos($field, "_address_country") !== false)
932                                                 $type = "_address_country";
933
934                                                 $var = $set.$type;
935                                         if (isset($contact->$var))
936                                                 $bean->$field = $contact->$var;
937                                 }
938                         }
939         }
940
941
942     protected function findRelationship(
943         $from,
944         $to
945         )
946     {
947         global $dictionary;
948         require_once("modules/TableDictionary.php");
949         foreach ($from->field_defs as $field=>$def)
950         {
951             if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) 
952                         {
953                 $rel_name = $def['relationship'];
954                 $rel_def = "";
955                 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
956                 {
957                     $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
958                 }
959                 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
960                 {
961                     $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
962                 }
963                 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
964                         && isset($dictionary[$rel_name]['relationships'][$rel_name]))
965                 {
966                         $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
967                 }
968                 if (!empty($rel_def)) {
969                     if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
970                     {
971                         return $field;
972                     }
973                     else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
974                     {
975                         return $field;
976                     }
977                 }
978             }
979         }
980         return false;
981     }
982
983     protected function findRelationshipByName($from, $rel_name)
984     {
985         global $dictionary;
986         require_once("modules/TableDictionary.php");
987         foreach ($from->field_defs as $field => $def)
988         {
989             if (isset($def['relationship']) && $def['relationship'] == $rel_name) 
990             {
991                 return $field;
992             }
993         }
994         return false;
995     }
996         /**
997          * @see SugarView::_getModuleTitleParams()
998          */
999         protected function _getModuleTitleParams($browserTitle = false)
1000         {
1001             global $mod_strings;
1002             $params = parent::_getModuleTitleParams($browserTitle);
1003             $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
1004             $params[] = $mod_strings['LBL_CONVERTLEAD'];
1005         return $params;
1006     }
1007
1008
1009     protected function checkForDuplicates(
1010         $lead
1011         )
1012     {
1013         if ($lead->status == "Converted")
1014         {
1015                 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
1016                 $dupes = array();
1017                 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
1018                 $result = $lead->db->query($q);
1019                 while($row = $lead->db->fetchByAssoc($result)) {
1020                         $contact = new Contact();
1021                         $contact->retrieve($row['id']);
1022                         $dupes[$row['id']] = $contact->name;
1023                 }
1024                 if (!empty($dupes))
1025                 {
1026                         foreach($dupes as $id => $name)
1027                         {
1028                                 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");
1029                                 break;
1030                         }
1031                 }
1032                 echo "</span>";
1033         }
1034         return false;
1035     }
1036 }