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