]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Leads/views/view.convertlead.php
Release 6.2.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
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("include/formbase.php");
288         $lead = false;
289                 if (!empty($_REQUEST['record']))
290                 {
291                         $lead = new Lead();
292                         $lead->retrieve($_REQUEST['record']);
293                 }
294
295         global $beanList;
296         $this->loadDefs();
297         $beans = array();
298         $selectedBeans = array();
299         $selects = array();
300         //Make sure the contact object is availible for relationships.
301         $beans['Contacts'] = new Contact();
302         $beans['Contacts']->id = create_guid();
303         $beans['Contacts']->new_with_id = true;
304
305         // Bug 39287 - Check for Duplicates on selected modules before save
306         if ( !empty($_REQUEST['selectedContact']) ) {
307             $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
308             if ( !empty($beans['Contacts']->id) ) {
309                 $beans['Contacts']->new_with_id = false;
310                 unset($_REQUEST["convert_create_Contacts"]);
311                 unset($_POST["convert_create_Contacts"]);
312             }
313         }
314         elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact'])) {
315             require_once('modules/Contacts/ContactFormBase.php');
316             $contactForm = new ContactFormBase();
317             $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
318             if(isset($duplicateContacts)){
319                 echo $contactForm->buildTableForm($duplicateContacts,  'Contacts');
320                 return;
321             }
322         }
323         if ( !empty($_REQUEST['selectedAccount']) ) {
324             $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
325                 unset($_REQUEST["convert_create_Accounts"]);
326                 unset($_POST["convert_create_Accounts"]);
327         }
328         elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount'])){
329             require_once('modules/Accounts/AccountFormBase.php');
330             $accountForm = new AccountFormBase();
331             $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
332             if(isset($duplicateAccounts)){
333                 echo $accountForm->buildTableForm($duplicateAccounts);
334                 return;
335             }
336         }
337
338         foreach($this->defs as $module => $vdef)
339         {
340             //Create a new record if "create" was selected
341                 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
342             {
343                 //Save the new record
344                 $bean = $beanList[$module];
345                     if (empty($beans[$module]))
346                         $beans[$module] = new $bean();
347
348                 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
349
350             }
351             //If an existing bean was selected, relate it to the contact
352             else if (!empty($vdef['ConvertLead']['select'])) {
353                 //Save the new record
354                 $select = $vdef['ConvertLead']['select'];
355                 $fieldDef = $beans['Contacts']->field_defs[$select];
356                 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
357                 {
358                         $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
359                         $selects[$module] = $_REQUEST[$fieldDef['id_name']];
360                         if (!empty($_REQUEST[$select]))
361                         {
362                             $beans['Contacts']->$select = $_REQUEST[$select];
363                         }
364                         // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
365                         $bean = loadBean($module);
366                     $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
367                     $selectedBeans[$module] = $bean;
368                 }
369             }
370         }
371
372                 $this->handleActivities($lead, $beans);
373                 // Bug 39268 - Add the lead's activities to the selected beans
374                 $this->handleActivities($lead, $selectedBeans);
375
376                 //link selected account to lead if it exists
377         if(!empty($selectedBeans['Accounts'])){
378             $lead->account_id = $selectedBeans['Accounts']->id;
379         }
380
381         //Handle non-contacts relationships
382             foreach($beans as $bean)
383         {
384                 if (!empty($lead))
385                         {
386                         if (empty($bean->assigned_user_id))
387                                 {
388                                         $bean->assigned_user_id = $lead->assigned_user_id;
389                                 }
390                                 $leadsRel = $this->findRelationship($bean, $lead);
391                                 if (!empty($leadsRel))
392                                 {
393
394                                         $bean->load_relationship ($leadsRel) ;
395                                         $relObject = $bean->$leadsRel->getRelationshipObject();
396                                         if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
397                                         {
398                                                 $id_field = $relObject->rhs_key;
399                                                 $lead->$id_field = $bean->id;
400                                         } else {
401                                                 $bean->$leadsRel->add($lead->id);
402                                         }
403                                 }
404                         }
405                         //Special case code for opportunities->Accounts
406                         if ($bean->object_name == "Opportunity" && empty($bean->account_id))
407                         {
408                                 if( isset($beans['Accounts'])) {
409                                         $bean->account_id = $beans['Accounts']->id;
410                                         $bean->account_name = $beans['Accounts']->name;
411                                 }
412                                 else if (!empty($selects['Accounts'])){
413                                          $bean->account_id = $selects['Accounts'];
414                                 }
415                         }
416
417                 $this->copyAddressFields($bean, $beans['Contacts']);
418
419                         $bean->save();
420         }
421         if (!empty($lead))
422                 {       //Mark the original Lead converted
423                   $lead->status = "Converted";
424                   $lead->converted = '1';
425                   $lead->in_workflow = true;
426                   $lead->save();
427                 }
428
429         $this->displaySaveResults($beans);
430     }
431
432     protected function displaySaveResults(
433         $beans
434         )
435     {
436         global $beanList;
437         echo "<div><ul>";
438         foreach($beans as $bean)
439         {
440             $beanName = $bean->object_name;
441             if ( $beanName == 'Contact' && !$bean->new_with_id ) {
442                 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
443                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
444                        {$bean->get_summary_text()}
445                     </a></li>";
446             }
447             else {
448                 global $app_list_strings;
449                 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
450                     $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
451                 } else {
452                     $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
453                 }
454                 if(empty($module_name)) {
455                     $module_name = translate($beanName);
456                 }
457                 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
458                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
459                        {$bean->get_summary_text()}
460                     </a></li>";
461             }
462         }
463
464         echo "</ul></div>";
465     }
466
467     protected function handleActivities(
468         $lead,
469         $beans
470         )
471     {
472         global $app_list_strings;
473         $parent_types = $app_list_strings['record_type_display'];
474
475         $activities = $this->getActivitiesFromLead($lead);
476
477         foreach($beans as $module => $bean)
478         {
479                 if (isset($parent_types[$module]))
480                 {
481                 foreach($activities as $activity)
482                         {
483                                 $this->copyActivityAndRelateToBean($activity, $bean);
484                         }
485                 }
486         }
487     }
488
489     /**
490      * Gets the list of activities related to the lead
491      * @param Lead $lead Lead to get activities from
492      * @return Array of Activity SugarBeans .
493      */
494         protected function getActivitiesFromLead(
495             $lead
496             )
497         {
498                 if (!$lead) return;
499
500                 global $beanList, $db;
501
502                 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
503                 $activities = array();
504
505                 foreach($activitesList as $module)
506                 {
507                         $beanName = $beanList[$module];
508                         $activity = new $beanName();
509                         $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
510                         $result = $db->query($query,true);
511             while($row = $db->fetchByAssoc($result))
512             {
513                 $activity = new $beanName();
514                                 $activity->retrieve($row['id']);
515                                 $activity->fixUpFormatting();
516                                 $activities[] = $activity;
517             }
518                 }
519
520                 return $activities;
521         }
522
523         protected function copyActivityAndRelateToBean(
524             $activity,
525             $bean
526             )
527         {
528                 global $beanList;
529
530                 $newActivity = clone $activity;
531                 $newActivity->id = create_guid();
532                 $newActivity->new_with_id = true;
533
534                 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
535         if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
536         {
537                 $newActivity->contact_id = $activity->contact_name = "";
538         }
539
540                 if ($rel = $this->findRelationship($newActivity, $bean))
541         {
542             $newActivity->load_relationship ($rel) ;
543             $relObj = $newActivity->$rel->getRelationshipObject();
544             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
545             {
546                 $key = $relObj->rhs_key;
547                 $newActivity->$key = $bean->id;
548             }
549             $newActivity->$rel->add($bean->id);
550             $newActivity->parent_id = $bean->id;
551                 $newActivity->parent_type = $bean->module_dir;
552                 $newActivity->update_date_modified = false; //bug 41747 
553                 $newActivity->save();
554                 if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
555                         UploadFile::duplicate_file($activity->id, $newActivity->id,  $newActivity->filename);
556                 }
557          }
558         }
559
560     /**
561      * Populates the passed in Bean fron the contact and the $_REQUEST
562      * @param String $module Module of new bean
563      * @param SugarBean $bean SugarBean to be populated.
564      * @param Contact $contact Contact to relate the bean to.
565      */
566         protected function populateNewBean(
567             $module,
568             $bean,
569             $contact,
570             $lead
571             )
572         {
573                 populateFromPost($module, $bean, true);
574
575                 //Copy data from the contact to new bean
576                 foreach($bean->field_defs as $field => $def)
577                 {
578                         if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
579                         {
580                                 $bean->$field = $lead->$field;
581                                 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
582                         }
583                 }
584                 //Try to link to the new contact
585                 $contactRel = "";
586                 if (!empty($vdef['ConvertLead']['select']))
587                 {
588                         $select = $vdef['ConvertLead']['select'];
589                         $fieldDef = $contact->field_defs[$select];
590                         if (!empty($fieldDef['id_name']))
591                         {
592                                 $bean->id = create_guid();
593                                 $bean->new_with_id = true;
594                                 $contact->$fieldDef['id_name'] = $bean->id ;
595                                 if ($fieldDef['id_name'] != $select) {
596                                         $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
597                                         if (!empty($rname) && isset($bean->$rname))
598                                                 $contact->$select = $bean->$rname;
599                                         else
600                                                 $contact->$select = $bean->name;
601                                 }
602                         }
603                 } else if ($module != "Contacts"){
604                         $contactRel = $this->findRelationship($contact, $bean);
605                         if (!empty($contactRel))
606                         {
607                                 $bean->id = create_guid();
608                                 $bean->new_with_id = true;
609                                 $contact->load_relationship ($contactRel) ;
610                                 $relObject = $contact->$contactRel->getRelationshipObject();
611                                 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
612                                 {
613                                         $id_field = $relObject->rhs_key;
614                                         $bean->$id_field = $contact->id;
615                                 } else {
616                                         $contact->$contactRel->add($bean->id);
617                                 }
618                                 //Set the parent of activites to the new Contact
619                                 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
620                                 {
621                                         $bean->parent_id = $contact->id;
622                                         $bean->parent_type = "Contacts";
623                                 }
624                         }
625                 }
626         }
627
628         protected function copyAddressFields($bean, $contact)
629         {
630         //Copy over address info from the contact to any beans with address not set
631                 foreach($bean->field_defs as $field => $def)
632                         {
633                                 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
634                                 {
635                                         $set = "primary";
636                                         if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
637                                                 $set = "alt";
638                                         $type = "";
639
640                                         if(strpos($field, "_address_street_2") !== false)
641                                                 $type = "_address_street_2";
642                                         else if(strpos($field, "_address_street_3") !== false)
643                                                 $type = "_address_street_3";
644                                         else if(strpos($field, "_address_street_4") !== false)
645                                                 $type = "";
646                                         else if(strpos($field, "_address_street") !== false)
647                                                 $type = "_address_street";
648                                         else if(strpos($field, "_address_city") !== false)
649                                                 $type = "_address_city";
650                                         else if(strpos($field, "_address_state") !== false)
651                                                 $type = "_address_state";
652                                         else if(strpos($field, "_address_postalcode") !== false)
653                                                 $type = "_address_postalcode";
654                                         else if(strpos($field, "_address_country") !== false)
655                                                 $type = "_address_country";
656
657                                                 $var = $set.$type;
658                                         if (isset($contact->$var))
659                                                 $bean->$field = $contact->$var;
660                                 }
661                         }
662         }
663
664
665     protected function findRelationship(
666         $from,
667         $to
668         )
669     {
670         global $dictionary;
671         require_once("modules/TableDictionary.php");
672         foreach ($from->field_defs as $field=>$def)
673         {
674             if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) {
675                 $rel_name = $def['relationship'];
676                 $rel_def = "";
677                 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
678                 {
679                     $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
680                 }
681                 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
682                 {
683                     $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
684                 }
685                 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
686                         && isset($dictionary[$rel_name]['relationships'][$rel_name]))
687                 {
688                         $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
689                 }
690                 if (!empty($rel_def)) {
691                     if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
692                     {
693                         return $field;
694                     }
695                     else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
696                     {
697                         return $field;
698                     }
699                 }
700             }
701         }
702         return false;
703     }
704
705         /**
706          * @see SugarView::_getModuleTitleParams()
707          */
708         protected function _getModuleTitleParams($browserTitle = false)
709         {
710             global $mod_strings;
711             $params = parent::_getModuleTitleParams($browserTitle);
712             $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
713             $params[] = $mod_strings['LBL_CONVERTLEAD'];
714         return $params;
715     }
716
717
718     protected function checkForDuplicates(
719         $lead
720         )
721     {
722         if ($lead->status == "Converted")
723         {
724                 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
725                 $dupes = array();
726                 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
727                 $result = $lead->db->query($q);
728                 while($row = $lead->db->fetchByAssoc($result)) {
729                         $contact = new Contact();
730                         $contact->retrieve($row['id']);
731                         $dupes[$row['id']] = $contact->name;
732                 }
733                 if (!empty($dupes))
734                 {
735                         foreach($dupes as $id => $name)
736                         {
737                                 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");
738                                 break;
739                         }
740                 }
741                 echo "</span>";
742         }
743         return false;
744     }
745 }