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