]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Leads/views/view.convertlead.php
Release 6.5.16
[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                 // 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')
452                 {
453                     $beans[$module]->id = create_guid();
454                     $beans[$module]->new_with_id = true;
455                     $beans[$module]->account_id = '';
456                 }
457             }
458             //If an existing bean was selected, relate it to the contact
459             else if (!empty($vdef['ConvertLead']['select'])) 
460             {
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']]))
465                 {
466                     $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
467                     $selects[$module] = $_REQUEST[$fieldDef['id_name']];
468                     if (!empty($_REQUEST[$select]))
469                     {
470                         $beans['Contacts']->$select = $_REQUEST[$select];
471                     }
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')
478                     {
479                         $beans[$module] = $bean;
480                     }
481                 }
482             }
483         }
484
485         $this->handleActivities($lead, $beans);
486         // Bug 39268 - Add the lead's activities to the selected beans
487         $this->handleActivities($lead, $selectedBeans);
488
489         //link selected account to lead if it exists
490         if (!empty($selectedBeans['Accounts']))
491         {
492             $lead->account_id = $selectedBeans['Accounts']->id;
493         }
494         
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)
498         {
499             $beans['Contacts']->account_id = $beans['Accounts']->id;
500         }
501         
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();
506
507         foreach ($saveBeanPriority as $name)
508         {
509             if (isset($beans[$name]))
510             {
511                 $tempBeans[$name] = $beans[$name];
512             }
513         }
514
515         $beans = array_merge($tempBeans, $beans);
516         unset($tempBeans);
517
518         //Handle non-contacts relationships
519         foreach ($beans as $bean)
520         {
521             if (!empty($lead))
522             {
523                 if (empty($bean->assigned_user_id))
524                 {
525                     $bean->assigned_user_id = $lead->assigned_user_id;
526                 }
527                 $leadsRel = $this->findRelationship($bean, $lead);
528                 if (!empty($leadsRel))
529                 {
530                     $bean->load_relationship($leadsRel);
531                     $relObject = $bean->$leadsRel->getRelationshipObject();
532                     if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
533                     {
534                         $id_field = $relObject->rhs_key;
535                         $lead->$id_field = $bean->id;
536                     }
537                     else 
538                     {
539                         $bean->$leadsRel->add($lead->id);
540                     }
541                 }
542             }
543             //Special case code for opportunities->Accounts
544             if ($bean->object_name == "Opportunity" && empty($bean->account_id))
545             {
546                 if (isset($beans['Accounts']))
547                 {
548                     $bean->account_id = $beans['Accounts']->id;
549                     $bean->account_name = $beans['Accounts']->name;
550                 }
551                 else if (!empty($selects['Accounts']))
552                 {
553                     $bean->account_id = $selects['Accounts'];
554                 }
555             }
556
557             //create meetings-users relationship
558             if ($bean->object_name == "Meeting")
559             {
560                 $bean = $this->setMeetingsUsersRelationship($bean);
561             }
562             $this->copyAddressFields($bean, $beans['Contacts']);
563
564             $bean->save();
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")
567             {
568                 campaign_log_lead_or_contact_entry($lead->campaign_id, $lead, $beans['Contacts'], 'contact');
569             }
570         }
571         if (!empty($lead))
572         {       //Mark the original Lead converted
573             $lead->status = "Converted";
574             $lead->converted = '1';
575             $lead->in_workflow = true;
576             $lead->save();
577         }
578
579         $this->displaySaveResults($beans);
580     }
581
582     public function setMeetingsUsersRelationship($bean)
583     {
584         global $current_user;
585         $meetingsRel = $this->findRelationshipByName($bean, $this->defs['Meetings']['ConvertLead']['relationship']);
586         if (!empty($meetingsRel))
587         {
588             $bean->load_relationship($meetingsRel);
589             $bean->$meetingsRel->add($current_user->id);
590             return $bean;
591         }
592         else
593         {
594             return false;
595         }
596     }
597     protected function displaySaveResults(
598         $beans
599         )
600     {
601         global $beanList;
602         echo "<div><ul>";
603         foreach($beans as $bean)
604         {
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()}
610                     </a></li>";
611             }
612             else {
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];
616                 } else {
617                     $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
618                 }
619                 if(empty($module_name)) {
620                     $module_name = translate($beanName);
621                 }
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()}
625                     </a></li>";
626             }
627         }
628
629         echo "</ul></div>";
630     }
631
632     protected function handleActivities(
633         $lead,
634         $beans
635         )
636     {
637         global $app_list_strings;
638         global $sugar_config;
639         global $app_strings;
640         $parent_types = $app_list_strings['record_type_display'];
641
642         $activities = $this->getActivitiesFromLead($lead);
643
644         //if account is being created, we will specify the account as the parent bean
645         $accountParentInfo = array();
646
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;
652             }else{
653                 $beans['Accounts']->id = $account_id;
654             }
655             $accountParentInfo = array('id'=>$account_id,'type'=>'Accounts');
656         }
657
658         foreach($beans as $module => $bean)
659         {
660                 if (isset($parent_types[$module]))
661                 {
662                 if (empty($bean->id))
663                 {
664                     $bean->id = create_guid();
665                             $bean->new_with_id = true;
666                 }
667                 if( isset($_POST['lead_conv_ac_op_sel']) && $_POST['lead_conv_ac_op_sel'] != 'None')
668                 {
669                         foreach($activities as $activity)
670                                 {
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);
678                                                         break;
679                                                     }
680                                                 }
681                                             }
682                                         }
683                                     }
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);
688                                         }
689                                     }
690                                 }
691                 }
692                 }
693         }
694     }
695
696     /**
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
700      */
701     protected function moveActivity($activity, $bean) {
702         global $beanList;
703
704         $lead = null;
705         if (!empty($_REQUEST['record']))
706         {
707             $lead = new Lead();
708             $lead->retrieve($_REQUEST['record']);
709         }
710
711         // delete the old relationship to the old parent (lead)
712         if ($rel = $this->findRelationship($activity, $lead)) {
713             $activity->load_relationship ($rel) ;
714
715             if ($activity->parent_id && $activity->id) {
716                 $activity->$rel->delete($activity->id, $activity->parent_id);
717             }
718         }
719
720         // add the new relationship to the new parent (contact, account, etc)
721         if ($rel = $this->findRelationship($activity, $bean)) {
722             $activity->load_relationship ($rel) ;
723
724             $relObj = $activity->$rel->getRelationshipObject();
725             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
726             {
727                 $key = $relObj->rhs_key;
728                 $activity->$key = $bean->id;
729             }
730             $activity->$rel->add($bean);
731         }
732
733         // set the new parent id and type
734         $activity->parent_id = $bean->id;
735         $activity->parent_type = $bean->module_dir;
736
737         $activity->save();
738     }
739
740     /**
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 .
744      */
745         protected function getActivitiesFromLead(
746             $lead
747             )
748         {
749                 if (!$lead) return;
750
751                 global $beanList, $db;
752
753                 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
754                 $activities = array();
755
756                 foreach($activitesList as $module)
757                 {
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))
763             {
764                 $activity = new $beanName();
765                                 $activity->retrieve($row['id']);
766                                 $activity->fixUpFormatting();
767                                 $activities[] = $activity;
768             }
769                 }
770
771                 return $activities;
772         }
773
774         protected function copyActivityAndRelateToBean(
775             $activity,
776             $bean,
777         $parentArr = array()
778             )
779         {
780                 global $beanList;
781
782                 $newActivity = clone $activity;
783                 $newActivity->id = create_guid();
784                 $newActivity->new_with_id = true;
785
786         //set the parent id and type if it was passed in, otherwise use blank to wipe it out
787         $parentID = '';
788         $parentType = '';
789         if(!empty($parentArr)){
790             if(!empty($parentArr['id'])){
791                 $parentID = $parentArr['id'];
792             }
793
794             if(!empty($parentArr['type'])){
795                 $parentType = $parentArr['type'];
796             }
797
798         }
799
800                 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
801         if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
802         {
803             $newActivity->contact_id = $newActivity->contact_name = "";
804         }
805
806                 if ($rel = $this->findRelationship($newActivity, $bean))
807         {
808             if (isset($newActivity->$rel))
809             {
810                 // this comes form $activity, get rid of it and load our own
811                 $newActivity->$rel = '';
812             }
813
814             $newActivity->load_relationship ($rel) ;
815             $relObj = $newActivity->$rel->getRelationshipObject();
816             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
817             {
818                 $key = $relObj->rhs_key;
819                 $newActivity->$key = $bean->id;
820             }
821
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;
826
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);
832                 }
833          }
834         }
835
836     /**
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.
841      */
842         protected function populateNewBean(
843             $module,
844             $bean,
845             $contact,
846             $lead
847             )
848         {
849                 //Copy data from the contact to new bean
850                 foreach($bean->field_defs as $field => $def)
851                 {
852                         if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
853                         {
854                                 $bean->$field = $lead->$field;
855                                 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
856                         }
857                 }
858         populateFromPost($module, $bean, true);
859                 //Try to link to the new contact
860                 $contactRel = "";
861                 if (!empty($vdef['ConvertLead']['select']))
862                 {
863                         $select = $vdef['ConvertLead']['select'];
864                         $fieldDef = $contact->field_defs[$select];
865                         if (!empty($fieldDef['id_name']))
866                         {
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;
874                                         else
875                                                 $contact->$select = $bean->name;
876                                 }
877                         }
878                 } else if ($module != "Contacts"){
879                         $contactRel = $this->findRelationship($contact, $bean);
880                         if (!empty($contactRel))
881                         {
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())
887                                 {
888                                         $id_field = $relObject->rhs_key;
889                                         $bean->$id_field = $contact->id;
890                                 } else {
891                                         $contact->$contactRel->add($bean);
892                                 }
893                                 //Set the parent of activites to the new Contact
894                                 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
895                                 {
896                                         $bean->parent_id = $contact->id;
897                                         $bean->parent_type = "Contacts";
898                                 }
899                         }
900                 }
901         }
902
903         protected function copyAddressFields($bean, $contact)
904         {
905         //Copy over address info from the contact to any beans with address not set
906                 foreach($bean->field_defs as $field => $def)
907                         {
908                                 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
909                                 {
910                                         $set = "primary";
911                                         if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
912                                                 $set = "alt";
913                                         $type = "";
914
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)
920                                                 $type = "";
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";
931
932                                                 $var = $set.$type;
933                                         if (isset($contact->$var))
934                                                 $bean->$field = $contact->$var;
935                                 }
936                         }
937         }
938
939
940     protected function findRelationship(
941         $from,
942         $to
943         )
944     {
945         global $dictionary;
946         require_once("modules/TableDictionary.php");
947         foreach ($from->field_defs as $field=>$def)
948         {
949             if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) 
950                         {
951                 $rel_name = $def['relationship'];
952                 $rel_def = "";
953                 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
954                 {
955                     $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
956                 }
957                 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
958                 {
959                     $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
960                 }
961                 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
962                         && isset($dictionary[$rel_name]['relationships'][$rel_name]))
963                 {
964                         $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
965                 }
966                 if (!empty($rel_def)) {
967                     if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
968                     {
969                         return $field;
970                     }
971                     else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
972                     {
973                         return $field;
974                     }
975                 }
976             }
977         }
978         return false;
979     }
980
981     protected function findRelationshipByName($from, $rel_name)
982     {
983         global $dictionary;
984         require_once("modules/TableDictionary.php");
985         foreach ($from->field_defs as $field => $def)
986         {
987             if (isset($def['relationship']) && $def['relationship'] == $rel_name) 
988             {
989                 return $field;
990             }
991         }
992         return false;
993     }
994         /**
995          * @see SugarView::_getModuleTitleParams()
996          */
997         protected function _getModuleTitleParams($browserTitle = false)
998         {
999             global $mod_strings;
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'];
1003         return $params;
1004     }
1005
1006
1007     protected function checkForDuplicates(
1008         $lead
1009         )
1010     {
1011         if ($lead->status == "Converted")
1012         {
1013                 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
1014                 $dupes = array();
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;
1021                 }
1022                 if (!empty($dupes))
1023                 {
1024                         foreach($dupes as $id => $name)
1025                         {
1026                                 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");
1027                                 break;
1028                         }
1029                 }
1030                 echo "</span>";
1031         }
1032         return false;
1033     }
1034 }