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