]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Leads/views/view.convertlead.php
Release 6.2.3
[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 (isset($this->focus->$field))
165                     {
166                         $focus->$field = $this->focus->$field;
167                     }
168                 }
169             }
170
171             //Copy over email data
172             $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
173             $ev->process();
174             echo($ev->display(false));
175             echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
176         }
177         echo "</div>";
178         echo ($qsd->getQSScriptsJSONAlreadyDefined());
179         $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
180     }
181
182     protected function getRecord()
183     {
184         $this->focus = new Lead();
185         if (isset($_REQUEST['record']))
186         {
187                 $this->focus->retrieve($_REQUEST['record']);
188         }
189     }
190
191     protected function loadDefs()
192     {
193         $viewdefs = array();
194         include($this->medataDataFile);
195         $this->defs = $viewdefs;
196     }
197
198     /**
199      * Returns the javascript to enable/disable validation of each module's sub-form
200      * //TODO: This should probably be on the smarty template
201      * @param $module String the target module name.
202      * @param $focus SugarBean instance of the target module.
203      * @param $focus EditView def for the module.
204      * @return String, javascript to echo to page.
205      */
206     protected function getValidationJS(
207         $module,
208         $focus,
209         $viewdef
210         )
211     {
212         $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
213         $jsOut  = "
214         <script type='text/javascript'>
215             if (!SUGAR.convert)  SUGAR.convert = {requiredFields: {}};
216             SUGAR.convert.toggle$module = function(){
217                 clear_all_errors();
218                 inputsWithErrors = [];
219                 if(!SUGAR.convert.{$module}Enabled)
220                 {
221                     for(var i in SUGAR.convert.requiredFields.$module)
222                     {
223                         addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
224                     }
225                     ";
226         if ($validateSelect) {
227                 $jsOut  .= "
228                     removeFromValidate('ConvertLead', '{$viewdef['select']}');";
229         }
230
231         $jsOut .= "
232                     SUGAR.convert.{$module}Enabled = true;
233                 } else {
234                     for(var i in SUGAR.convert.requiredFields.$module)
235                     {
236                         removeFromValidate('ConvertLead', '$module' + i);
237                     }";
238         if ($validateSelect) {
239             $jsOut  .= "
240                 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
241             . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
242         }
243         $jsOut .= "
244                     SUGAR.convert.{$module}Enabled = false;
245                 }
246                 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
247             };\n";
248
249         if (isset($viewdef['required']) && $viewdef['required'])
250         {
251             if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
252             {
253                 $jsOut .= "
254             SUGAR.convert.{$module}Enabled = true;";
255             }
256             $jsOut .= "
257             YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
258         } else if (isset($viewdef['default_action'])  && $viewdef['default_action'] == "create")
259         {
260              $jsOut .= "\n            SUGAR.convert.{$module}Enabled = true;";
261         }
262         $jsOut .= "
263             YAHOO.util.Event.addListener('new$module', 'click', SUGAR.convert.toggle$module);
264             SUGAR.convert.requiredFields.$module = {};";
265         foreach($focus->field_defs as $field => $def)
266         {
267             if (isset($def['required']) && $def['required'])
268             {
269                 $jsOut .= "
270             SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
271             }
272         }
273
274         $jsOut .= "
275         </script>";
276
277         return $jsOut;
278     }
279
280     /**
281      * Saves a new Contact as well as any related items passed in.
282      *
283      * @return null
284      */
285     protected function handleSave()
286     {
287         require_once('modules/Campaigns/utils.php');
288         require_once("include/formbase.php");
289         $lead = false;
290                 if (!empty($_REQUEST['record']))
291                 {
292                         $lead = new Lead();
293                         $lead->retrieve($_REQUEST['record']);
294                 }
295
296         global $beanList;
297         $this->loadDefs();
298         $beans = array();
299         $selectedBeans = array();
300         $selects = array();
301         //Make sure the contact object is availible for relationships.
302         $beans['Contacts'] = new Contact();
303         $beans['Contacts']->id = create_guid();
304         $beans['Contacts']->new_with_id = true;
305
306         // Bug 39287 - Check for Duplicates on selected modules before save
307         if ( !empty($_REQUEST['selectedContact']) ) {
308             $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
309             if ( !empty($beans['Contacts']->id) ) {
310                 $beans['Contacts']->new_with_id = false;
311                 unset($_REQUEST["convert_create_Contacts"]);
312                 unset($_POST["convert_create_Contacts"]);
313             }
314         }
315         elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact'])) {
316             require_once('modules/Contacts/ContactFormBase.php');
317             $contactForm = new ContactFormBase();
318             $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
319             if(isset($duplicateContacts)){
320                 echo $contactForm->buildTableForm($duplicateContacts,  'Contacts');
321                 return;
322             }
323         }
324         if ( !empty($_REQUEST['selectedAccount']) ) {
325             $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
326                 unset($_REQUEST["convert_create_Accounts"]);
327                 unset($_POST["convert_create_Accounts"]);
328         }
329         elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount'])){
330             require_once('modules/Accounts/AccountFormBase.php');
331             $accountForm = new AccountFormBase();
332             $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
333             if(isset($duplicateAccounts)){
334                 echo $accountForm->buildTableForm($duplicateAccounts);
335                 return;
336             }
337         }
338
339         foreach($this->defs as $module => $vdef)
340         {
341             //Create a new record if "create" was selected
342                 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
343             {
344                 //Save the new record
345                 $bean = $beanList[$module];
346                     if (empty($beans[$module]))
347                         $beans[$module] = new $bean();
348
349                 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
350
351             }
352             //If an existing bean was selected, relate it to the contact
353             else if (!empty($vdef['ConvertLead']['select'])) {
354                 //Save the new record
355                 $select = $vdef['ConvertLead']['select'];
356                 $fieldDef = $beans['Contacts']->field_defs[$select];
357                 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
358                 {
359                         $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
360                         $selects[$module] = $_REQUEST[$fieldDef['id_name']];
361                         if (!empty($_REQUEST[$select]))
362                         {
363                             $beans['Contacts']->$select = $_REQUEST[$select];
364                         }
365                         // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
366                         $bean = loadBean($module);
367                     $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
368                     $selectedBeans[$module] = $bean;
369                 }
370             }
371         }
372
373                 $this->handleActivities($lead, $beans);
374                 // Bug 39268 - Add the lead's activities to the selected beans
375                 $this->handleActivities($lead, $selectedBeans);
376
377                 //link selected account to lead if it exists
378         if(!empty($selectedBeans['Accounts'])){
379             $lead->account_id = $selectedBeans['Accounts']->id;
380         }
381
382         //Handle non-contacts relationships
383             foreach($beans as $bean)
384         {
385                 if (!empty($lead))
386                         {
387                         if (empty($bean->assigned_user_id))
388                                 {
389                                         $bean->assigned_user_id = $lead->assigned_user_id;
390                                 }
391                                 $leadsRel = $this->findRelationship($bean, $lead);
392                                 if (!empty($leadsRel))
393                                 {
394
395                                         $bean->load_relationship ($leadsRel) ;
396                                         $relObject = $bean->$leadsRel->getRelationshipObject();
397                                         if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
398                                         {
399                                                 $id_field = $relObject->rhs_key;
400                                                 $lead->$id_field = $bean->id;
401                                         } else {
402                                                 $bean->$leadsRel->add($lead->id);
403                                         }
404                                 }
405                         }
406                         //Special case code for opportunities->Accounts
407                         if ($bean->object_name == "Opportunity" && empty($bean->account_id))
408                         {
409                                 if( isset($beans['Accounts'])) {
410                                         $bean->account_id = $beans['Accounts']->id;
411                                         $bean->account_name = $beans['Accounts']->name;
412                                 }
413                                 else if (!empty($selects['Accounts'])){
414                                          $bean->account_id = $selects['Accounts'];
415                                 }
416                         }
417
418                 $this->copyAddressFields($bean, $beans['Contacts']);
419
420                         $bean->save();
421                 //if campaign id exists then there should be an entry in campaign_log table for the newly created contact: bug 44522    
422         if(isset($lead->campaign_id) && $lead->campaign_id != null && $bean->object_name == "Contact"){
423                 campaign_log_lead_or_contact_entry($lead->campaign_id,$lead, $beans['Contacts'],'contact');
424             }
425         }
426         if (!empty($lead))
427                 {       //Mark the original Lead converted
428                   $lead->status = "Converted";
429                   $lead->converted = '1';
430                   $lead->in_workflow = true;
431                   $lead->save();
432                 }
433
434         $this->displaySaveResults($beans);
435     }
436
437     protected function displaySaveResults(
438         $beans
439         )
440     {
441         global $beanList;
442         echo "<div><ul>";
443         foreach($beans as $bean)
444         {
445             $beanName = $bean->object_name;
446             if ( $beanName == 'Contact' && !$bean->new_with_id ) {
447                 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
448                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
449                        {$bean->get_summary_text()}
450                     </a></li>";
451             }
452             else {
453                 global $app_list_strings;
454                 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
455                     $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
456                 } else {
457                     $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
458                 }
459                 if(empty($module_name)) {
460                     $module_name = translate($beanName);
461                 }
462                 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
463                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
464                        {$bean->get_summary_text()}
465                     </a></li>";
466             }
467         }
468
469         echo "</ul></div>";
470     }
471
472     protected function handleActivities(
473         $lead,
474         $beans
475         )
476     {
477         global $app_list_strings;
478         $parent_types = $app_list_strings['record_type_display'];
479
480         $activities = $this->getActivitiesFromLead($lead);
481
482         foreach($beans as $module => $bean)
483         {
484                 if (isset($parent_types[$module]))
485                 {
486                 foreach($activities as $activity)
487                         {
488                                 $this->copyActivityAndRelateToBean($activity, $bean);
489                         }
490                 }
491         }
492     }
493
494     /**
495      * Gets the list of activities related to the lead
496      * @param Lead $lead Lead to get activities from
497      * @return Array of Activity SugarBeans .
498      */
499         protected function getActivitiesFromLead(
500             $lead
501             )
502         {
503                 if (!$lead) return;
504
505                 global $beanList, $db;
506
507                 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
508                 $activities = array();
509
510                 foreach($activitesList as $module)
511                 {
512                         $beanName = $beanList[$module];
513                         $activity = new $beanName();
514                         $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
515                         $result = $db->query($query,true);
516             while($row = $db->fetchByAssoc($result))
517             {
518                 $activity = new $beanName();
519                                 $activity->retrieve($row['id']);
520                                 $activity->fixUpFormatting();
521                                 $activities[] = $activity;
522             }
523                 }
524
525                 return $activities;
526         }
527
528         protected function copyActivityAndRelateToBean(
529             $activity,
530             $bean
531             )
532         {
533                 global $beanList;
534
535                 $newActivity = clone $activity;
536                 $newActivity->id = create_guid();
537                 $newActivity->new_with_id = true;
538
539                 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
540         if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
541         {
542                 $newActivity->contact_id = $activity->contact_name = "";
543         }
544
545                 if ($rel = $this->findRelationship($newActivity, $bean))
546         {
547             $newActivity->load_relationship ($rel) ;
548             $relObj = $newActivity->$rel->getRelationshipObject();
549             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
550             {
551                 $key = $relObj->rhs_key;
552                 $newActivity->$key = $bean->id;
553             }
554             $newActivity->$rel->add($bean->id);
555             $newActivity->parent_id = $bean->id;
556                 $newActivity->parent_type = $bean->module_dir;
557                 $newActivity->update_date_modified = false; //bug 41747 
558                 $newActivity->save();
559                 if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
560                         UploadFile::duplicate_file($activity->id, $newActivity->id,  $newActivity->filename);
561                 }
562          }
563         }
564
565     /**
566      * Populates the passed in Bean fron the contact and the $_REQUEST
567      * @param String $module Module of new bean
568      * @param SugarBean $bean SugarBean to be populated.
569      * @param Contact $contact Contact to relate the bean to.
570      */
571         protected function populateNewBean(
572             $module,
573             $bean,
574             $contact,
575             $lead
576             )
577         {
578                 populateFromPost($module, $bean, true);
579
580                 //Copy data from the contact to new bean
581                 foreach($bean->field_defs as $field => $def)
582                 {
583                         if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
584                         {
585                                 $bean->$field = $lead->$field;
586                                 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
587                         }
588                 }
589                 //Try to link to the new contact
590                 $contactRel = "";
591                 if (!empty($vdef['ConvertLead']['select']))
592                 {
593                         $select = $vdef['ConvertLead']['select'];
594                         $fieldDef = $contact->field_defs[$select];
595                         if (!empty($fieldDef['id_name']))
596                         {
597                                 $bean->id = create_guid();
598                                 $bean->new_with_id = true;
599                                 $contact->$fieldDef['id_name'] = $bean->id ;
600                                 if ($fieldDef['id_name'] != $select) {
601                                         $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
602                                         if (!empty($rname) && isset($bean->$rname))
603                                                 $contact->$select = $bean->$rname;
604                                         else
605                                                 $contact->$select = $bean->name;
606                                 }
607                         }
608                 } else if ($module != "Contacts"){
609                         $contactRel = $this->findRelationship($contact, $bean);
610                         if (!empty($contactRel))
611                         {
612                                 $bean->id = create_guid();
613                                 $bean->new_with_id = true;
614                                 $contact->load_relationship ($contactRel) ;
615                                 $relObject = $contact->$contactRel->getRelationshipObject();
616                                 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
617                                 {
618                                         $id_field = $relObject->rhs_key;
619                                         $bean->$id_field = $contact->id;
620                                 } else {
621                                         $contact->$contactRel->add($bean->id);
622                                 }
623                                 //Set the parent of activites to the new Contact
624                                 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
625                                 {
626                                         $bean->parent_id = $contact->id;
627                                         $bean->parent_type = "Contacts";
628                                 }
629                         }
630                 }
631         }
632
633         protected function copyAddressFields($bean, $contact)
634         {
635         //Copy over address info from the contact to any beans with address not set
636                 foreach($bean->field_defs as $field => $def)
637                         {
638                                 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
639                                 {
640                                         $set = "primary";
641                                         if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
642                                                 $set = "alt";
643                                         $type = "";
644
645                                         if(strpos($field, "_address_street_2") !== false)
646                                                 $type = "_address_street_2";
647                                         else if(strpos($field, "_address_street_3") !== false)
648                                                 $type = "_address_street_3";
649                                         else if(strpos($field, "_address_street_4") !== false)
650                                                 $type = "";
651                                         else if(strpos($field, "_address_street") !== false)
652                                                 $type = "_address_street";
653                                         else if(strpos($field, "_address_city") !== false)
654                                                 $type = "_address_city";
655                                         else if(strpos($field, "_address_state") !== false)
656                                                 $type = "_address_state";
657                                         else if(strpos($field, "_address_postalcode") !== false)
658                                                 $type = "_address_postalcode";
659                                         else if(strpos($field, "_address_country") !== false)
660                                                 $type = "_address_country";
661
662                                                 $var = $set.$type;
663                                         if (isset($contact->$var))
664                                                 $bean->$field = $contact->$var;
665                                 }
666                         }
667         }
668
669
670     protected function findRelationship(
671         $from,
672         $to
673         )
674     {
675         global $dictionary;
676         require_once("modules/TableDictionary.php");
677         foreach ($from->field_defs as $field=>$def)
678         {
679             if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) {
680                 $rel_name = $def['relationship'];
681                 $rel_def = "";
682                 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
683                 {
684                     $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
685                 }
686                 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
687                 {
688                     $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
689                 }
690                 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
691                         && isset($dictionary[$rel_name]['relationships'][$rel_name]))
692                 {
693                         $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
694                 }
695                 if (!empty($rel_def)) {
696                     if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
697                     {
698                         return $field;
699                     }
700                     else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
701                     {
702                         return $field;
703                     }
704                 }
705             }
706         }
707         return false;
708     }
709
710         /**
711          * @see SugarView::_getModuleTitleParams()
712          */
713         protected function _getModuleTitleParams($browserTitle = false)
714         {
715             global $mod_strings;
716             $params = parent::_getModuleTitleParams($browserTitle);
717             $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
718             $params[] = $mod_strings['LBL_CONVERTLEAD'];
719         return $params;
720     }
721
722
723     protected function checkForDuplicates(
724         $lead
725         )
726     {
727         if ($lead->status == "Converted")
728         {
729                 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
730                 $dupes = array();
731                 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
732                 $result = $lead->db->query($q);
733                 while($row = $lead->db->fetchByAssoc($result)) {
734                         $contact = new Contact();
735                         $contact->retrieve($row['id']);
736                         $dupes[$row['id']] = $contact->name;
737                 }
738                 if (!empty($dupes))
739                 {
740                         foreach($dupes as $id => $name)
741                         {
742                                 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");
743                                 break;
744                         }
745                 }
746                 echo "</span>";
747         }
748         return false;
749     }
750 }