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