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