1<?php
2/* Copyright (C) 2001-2002  Rodolphe Quiedeville    <rodolphe@quiedeville.org>
3 * Copyright (C) 2001-2002  Jean-Louis Bergamo      <jlb@j1b.org>
4 * Copyright (C) 2006-2013  Laurent Destailleur     <eldy@users.sourceforge.net>
5 * Copyright (C) 2012       Regis Houssin           <regis.houssin@inodbox.com>
6 * Copyright (C) 2012       J. Fernando Lagrange    <fernando@demo-tic.org>
7 * Copyright (C) 2018-2021  Frédéric France         <frederic.france@netlogic.fr>
8 * Copyright (C) 2018       Alexandre Spangaro      <aspangaro@open-dsi.fr>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
24/**
25 *	\file       htdocs/public/project/new.php
26 *	\ingroup    project
27 *	\brief      Example of form to add a new lead
28 */
29
30if (!defined('NOLOGIN')) {
31	define("NOLOGIN", 1); // This means this output page does not require to be logged.
32}
33if (!defined('NOCSRFCHECK')) {
34	define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
35}
36if (!defined('NOIPCHECK')) {
37	define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
38}
39if (!defined('NOBROWSERNOTIF')) {
40	define('NOBROWSERNOTIF', '1');
41}
42if (!defined('NOIPCHECK')) {
43	define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
44}
45
46// For MultiCompany module.
47// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
48// TODO This should be useless. Because entity must be retrieve from object ref and not from url.
49$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
50if (is_numeric($entity)) {
51	define("DOLENTITY", $entity);
52}
53
54require '../../main.inc.php';
55require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
56require_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
57require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
58require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
59require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
60
61// Init vars
62$errmsg = '';
63$error = 0;
64$backtopage = GETPOST('backtopage', 'alpha');
65$action = GETPOST('action', 'aZ09');
66
67// Load translation files
68$langs->loadLangs(array("members", "companies", "install", "other"));
69
70if (empty($conf->global->PROJECT_ENABLE_PUBLIC)) {
71	print $langs->trans("Form for public lead registration has not been enabled");
72	exit;
73}
74
75// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
76$hookmanager->initHooks(array('publicnewleadcard', 'globalcard'));
77
78$extrafields = new ExtraFields($db);
79
80$object = new Project($db);
81
82$user->loadDefaultValues();
83
84// Security check
85if (empty($conf->projet->enabled)) {
86	accessforbidden('', 0, 0, 1);
87}
88
89
90/**
91 * Show header for new member
92 *
93 * @param 	string		$title				Title
94 * @param 	string		$head				Head array
95 * @param 	int    		$disablejs			More content into html header
96 * @param 	int    		$disablehead		More content into html header
97 * @param 	array  		$arrayofjs			Array of complementary js files
98 * @param 	array  		$arrayofcss			Array of complementary css files
99 * @return	void
100 */
101function llxHeaderVierge($title, $head = "", $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '')
102{
103	global $user, $conf, $langs, $mysoc;
104
105	top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss); // Show html headers
106
107	print '<body id="mainbody" class="publicnewmemberform">';
108
109	// Define urllogo
110	$urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png';
111
112	if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) {
113		$urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small);
114	} elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) {
115		$urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo);
116	} elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) {
117		$urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg';
118	}
119
120	print '<div class="center">';
121
122	// Output html code for logo
123	if ($urllogo) {
124		print '<div class="backgreypublicpayment">';
125		print '<div class="logopublicpayment">';
126		print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
127		print '>';
128		print '</div>';
129		if (empty($conf->global->MAIN_HIDE_POWERED_BY)) {
130			print '<div class="poweredbypublicpayment opacitymedium right"><a class="poweredbyhref" href="https://www.dolibarr.org?utm_medium=website&utm_source=poweredby" target="dolibarr" rel="noopener">'.$langs->trans("PoweredBy").'<br><img class="poweredbyimg" src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.svg" width="80px"></a></div>';
131		}
132		print '</div>';
133	}
134
135	if (!empty($conf->global->PROJECT_IMAGE_PUBLIC_ORGANIZEDEVENT)) {
136		print '<div class="backimagepublicorganizedevent">';
137		print '<img id="idPROJECT_IMAGE_PUBLIC_ORGANIZEDEVENT" src="'.$conf->global->PROJECT_IMAGE_PUBLIC_ORGANIZEDEVENT.'">';
138		print '</div>';
139	}
140
141	print '</div>';
142
143	print '<div class="divmainbodylarge">';
144}
145
146/**
147 * Show footer for new member
148 *
149 * @return	void
150 */
151function llxFooterVierge()
152{
153	print '</div>';
154
155	printCommonFooter('public');
156
157	print "</body>\n";
158	print "</html>\n";
159}
160
161
162$arrayofdata = array();
163if (GETPOST('action') == 'addlead') {
164	// When a json request is sent
165	$entityBody = file_get_contents('php://input');
166
167	if ($entityBody) {
168		$arrayofdata = json_decode($entityBody, true);
169	}
170
171	print 'Date received and lead created';
172
173	$db->close();
174	exit;
175}
176
177
178
179/*
180 * Actions
181 */
182
183$parameters = array();
184// Note that $action and $object may have been modified by some hooks
185$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
186if ($reshook < 0) {
187	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
188}
189
190// Action called when page is submitted
191if (empty($reshook) && $action == 'add') {
192	$error = 0;
193	$urlback = '';
194
195	$db->begin();
196
197	// test if lead already exists
198	/*
199	if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) {
200		if (!GETPOST('login')) {
201			$error++;
202			$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Login"))."<br>\n";
203		}
204		$sql = "SELECT login FROM ".MAIN_DB_PREFIX."adherent WHERE login='".$db->escape(GETPOST('login'))."'";
205		$result = $db->query($sql);
206		if ($result) {
207			$num = $db->num_rows($result);
208		}
209		if ($num != 0) {
210			$error++;
211			$langs->load("errors");
212			$errmsg .= $langs->trans("ErrorLoginAlreadyExists")."<br>\n";
213		}
214		if (!GETPOSTISSET("pass1") || !GETPOSTISSET("pass2") || GETPOST("pass1", 'none') == '' || GETPOST("pass2", 'none') == '' || GETPOST("pass1", 'none') != GETPOST("pass2", 'none')) {
215			$error++;
216			$langs->load("errors");
217			$errmsg .= $langs->trans("ErrorPasswordsMustMatch")."<br>\n";
218		}
219		if (!GETPOST("email")) {
220			$error++;
221			$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("EMail"))."<br>\n";
222		}
223	}
224	*/
225	if (GETPOST('type') <= 0) {
226		$error++;
227		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type"))."<br>\n";
228	}
229	if (!in_array(GETPOST('morphy'), array('mor', 'phy'))) {
230		$error++;
231		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('Nature'))."<br>\n";
232	}
233	if (!GETPOST("lastname")) {
234		$error++;
235		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Lastname"))."<br>\n";
236	}
237	if (!GETPOST("firstname")) {
238		$error++;
239		$errmsg .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Firstname"))."<br>\n";
240	}
241	if (GETPOST("email") && !isValidEmail(GETPOST("email"))) {
242		$error++;
243		$langs->load("errors");
244		$errmsg .= $langs->trans("ErrorBadEMail", GETPOST("email"))."<br>\n";
245	}
246
247	if (!$error) {
248		// email a peu pres correct et le login n'existe pas
249		$proj = new Project($db);
250		$proj->statut      = -1;
251		$proj->email       = GETPOST("email");
252		$proj->note_private = GETPOST("note_private");
253
254
255		// Fill array 'array_options' with data from add form
256		$extrafields->fetch_name_optionals_label($proj->table_element);
257		$ret = $extrafields->setOptionalsFromPost(null, $proj);
258		if ($ret < 0) {
259			$error++;
260		}
261
262		$result = $proj->create($user);
263		if ($result > 0) {
264			require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
265			$object = $proj;
266
267			if ($object->email) {
268				$subject = '';
269				$msg = '';
270
271				// Send subscription email
272				include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
273				$formmail = new FormMail($db);
274				// Set output language
275				$outputlangs = new Translate('', $conf);
276				$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
277				// Load traductions files required by page
278				$outputlangs->loadLangs(array("main", "members"));
279				// Get email content from template
280				$arraydefaultmessage = null;
281				$labeltouse = $conf->global->PROJECT_EMAIL_TEMPLATE_AUTOLEAD;
282
283				if (!empty($labeltouse)) {
284					$arraydefaultmessage = $formmail->getEMailTemplate($db, 'project', $user, $outputlangs, 0, 1, $labeltouse);
285				}
286
287				if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
288					$subject = $arraydefaultmessage->topic;
289					$msg     = $arraydefaultmessage->content;
290				}
291
292				$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
293				complete_substitutions_array($substitutionarray, $outputlangs, $object);
294				$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
295				$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnValid()), $substitutionarray, $outputlangs);
296
297				if ($subjecttosend && $texttosend) {
298					$moreinheader = 'X-Dolibarr-Info: send_an_email by public/lead/new.php'."\r\n";
299
300					$result = $object->send_an_email($texttosend, $subjecttosend, array(), array(), array(), "", "", 0, -1, '', $moreinheader);
301				}
302				/*if ($result < 0) {
303					$error++;
304					setEventMessages($object->error, $object->errors, 'errors');
305				}*/
306			}
307
308			if (!empty($backtopage)) {
309				$urlback = $backtopage;
310			} elseif (!empty($conf->global->PROJECT_URL_REDIRECT_LEAD)) {
311				$urlback = $conf->global->PROJECT_URL_REDIRECT_LEAD;
312				// TODO Make replacement of __AMOUNT__, etc...
313			} else {
314				$urlback = $_SERVER["PHP_SELF"]."?action=added";
315			}
316
317			if (!empty($entity)) {
318				$urlback .= '&entity='.$entity;
319			}
320			dol_syslog("project lead ".$proj->ref." was created, we redirect to ".$urlback);
321		} else {
322			$error++;
323			$errmsg .= join('<br>', $proj->errors);
324		}
325	}
326
327	if (!$error) {
328		$db->commit();
329
330		Header("Location: ".$urlback);
331		exit;
332	} else {
333		$db->rollback();
334	}
335}
336
337// Create lead from $arrayofdata
338if (empty($reshook) && !empty($arrayofdata)) {
339	// TODO
340	dol_syslog(var_export($arrayofdata, true));
341	// ...
342}
343
344// Action called after a submitted was send and member created successfully
345// If MEMBER_URL_REDIRECT_SUBSCRIPTION is set to url we never go here because a redirect was done to this url.
346// backtopage parameter with an url was set on member submit page, we never go here because a redirect was done to this url.
347if (empty($reshook) && $action == 'added') {
348	llxHeaderVierge($langs->trans("NewMemberForm"));
349
350	// Si on a pas ete redirige
351	print '<br>';
352	print '<div class="center">';
353	print $langs->trans("NewMemberbyWeb");
354	print '</div>';
355
356	llxFooterVierge();
357	exit;
358}
359
360
361
362/*
363 * View
364 */
365
366$form = new Form($db);
367$formcompany = new FormCompany($db);
368$extrafields->fetch_name_optionals_label('project'); // fetch optionals attributes and labels
369
370
371llxHeaderVierge($langs->trans("NewContact"));
372
373
374print load_fiche_titre($langs->trans("NewContact"), '', '', 0, 0, 'center');
375
376
377print '<div align="center">';
378print '<div id="divsubscribe">';
379
380print '<div class="center subscriptionformhelptext justify">';
381if (!empty($conf->global->PROJECT_NEWFORM_TEXT)) {
382	print $langs->trans($conf->global->PROJECT_NEWFORM_TEXT)."<br>\n";
383} else {
384	print $langs->trans("NewLeadDesc", $conf->global->MAIN_INFO_SOCIETE_MAIL)."<br>\n";
385}
386print '</div>';
387
388dol_htmloutput_errors($errmsg);
389
390// Print form
391print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="newlead">'."\n";
392print '<input type="hidden" name="token" value="'.newToken().'" / >';
393print '<input type="hidden" name="entity" value="'.$entity.'" />';
394print '<input type="hidden" name="action" value="add" />';
395
396print '<br>';
397
398print '<br><span class="opacitymedium">'.$langs->trans("FieldsWithAreMandatory", '*').'</span><br>';
399//print $langs->trans("FieldsWithIsForPublic",'**').'<br>';
400
401print dol_get_fiche_head('');
402
403print '<script type="text/javascript">
404jQuery(document).ready(function () {
405    jQuery(document).ready(function () {
406        jQuery("#selectcountry_id").change(function() {
407           document.newlead.action.value="create";
408           document.newlead.submit();
409        });
410    });
411});
412</script>';
413
414
415print '<table class="border" summary="form to subscribe" id="tablesubscribe">'."\n";
416
417// Lastname
418print '<tr><td>'.$langs->trans("Lastname").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="lastname" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('lastname')).'"></td></tr>'."\n";
419// Firstname
420print '<tr><td>'.$langs->trans("Firstname").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="firstname" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('firstname')).'"></td></tr>'."\n";
421// Company
422print '<tr id="trcompany" class="trcompany"><td>'.$langs->trans("Company").'</td><td><input type="text" name="societe" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('societe')).'"></td></tr>'."\n";
423// Address
424print '<tr><td>'.$langs->trans("Address").'</td><td>'."\n";
425print '<textarea name="address" id="address" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.dol_escape_htmltag(GETPOST('address', 'restricthtml'), 0, 1).'</textarea></td></tr>'."\n";
426// Zip / Town
427print '<tr><td>'.$langs->trans('Zip').' / '.$langs->trans('Town').'</td><td>';
428print $formcompany->select_ziptown(GETPOST('zipcode'), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6, 1);
429print ' / ';
430print $formcompany->select_ziptown(GETPOST('town'), 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 1);
431print '</td></tr>';
432// Country
433print '<tr><td>'.$langs->trans('Country').'</td><td>';
434$country_id = GETPOST('country_id');
435if (!$country_id && !empty($conf->global->PROJECT_NEWFORM_FORCECOUNTRYCODE)) {
436	$country_id = getCountry($conf->global->PROJECT_NEWFORM_FORCECOUNTRYCODE, 2, $db, $langs);
437}
438if (!$country_id && !empty($conf->geoipmaxmind->enabled)) {
439	$country_code = dol_user_country();
440	//print $country_code;
441	if ($country_code) {
442		$new_country_id = getCountry($country_code, 3, $db, $langs);
443		//print 'xxx'.$country_code.' - '.$new_country_id;
444		if ($new_country_id) {
445			$country_id = $new_country_id;
446		}
447	}
448}
449$country_code = getCountry($country_id, 2, $db, $langs);
450print $form->select_country($country_id, 'country_id');
451print '</td></tr>';
452// State
453if (empty($conf->global->SOCIETE_DISABLE_STATE)) {
454	print '<tr><td>'.$langs->trans('State').'</td><td>';
455	if ($country_code) {
456		print $formcompany->select_state(GETPOST("state_id"), $country_code);
457	} else {
458		print '';
459	}
460	print '</td></tr>';
461}
462// EMail
463print '<tr><td>'.$langs->trans("Email").' <FONT COLOR="red">*</FONT></td><td><input type="text" name="email" maxlength="255" class="minwidth150" value="'.dol_escape_htmltag(GETPOST('email')).'"></td></tr>'."\n";
464// Other attributes
465$tpl_context = 'public'; // define template context to public
466include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
467// Comments
468print '<tr>';
469print '<td class="tdtop">'.$langs->trans("Comments").'</td>';
470print '<td class="tdtop"><textarea name="note_private" id="note_private" wrap="soft" class="quatrevingtpercent" rows="'.ROWS_3.'">'.dol_escape_htmltag(GETPOST('note_private', 'restricthtml'), 0, 1).'</textarea></td>';
471print '</tr>'."\n";
472
473print "</table>\n";
474
475print dol_get_fiche_end();
476
477// Save
478print '<div class="center">';
479print '<input type="submit" value="'.$langs->trans("Submit").'" id="submitsave" class="button">';
480if (!empty($backtopage)) {
481	print ' &nbsp; &nbsp; <input type="submit" value="'.$langs->trans("Cancel").'" id="submitcancel" class="button button-cancel">';
482}
483print '</div>';
484
485
486print "</form>\n";
487print "<br>";
488print '</div></div>';
489
490
491llxFooterVierge();
492
493$db->close();
494