1<?php
2/*
3	FusionPBX
4	Version: MPL 1.1
5
6	The contents of this file are subject to the Mozilla Public License Version
7	1.1 (the "License"); you may not use this file except in compliance with
8	the License. You may obtain a copy of the License at
9	http://www.mozilla.org/MPL/
10
11	Software distributed under the License is distributed on an "AS IS" basis,
12	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13	for the specific language governing rights and limitations under the
14	License.
15
16	The Original Code is FusionPBX
17
18	The Initial Developer of the Original Code is
19	Mark J Crane <markjcrane@fusionpbx.com>
20	Portions created by the Initial Developer are Copyright (C) 2008-2017
21	the Initial Developer. All Rights Reserved.
22
23	Contributor(s):
24	Mark J Crane <markjcrane@fusionpbx.com>
25*/
26
27//includes
28	include "root.php";
29	require_once "resources/require.php";
30	require_once "resources/check_auth.php";
31
32//check permissions
33	if (permission_exists('contact_add')) {
34		//access granted
35	}
36	else {
37		echo "access denied";
38		exit;
39	}
40
41//add multi-lingual support
42	$language = new text;
43	$text = $language->get();
44
45//built in str_getcsv requires PHP 5.3 or higher, this function can be used to reproduct the functionality but requirs PHP 5.1.0 or higher
46	if(!function_exists('str_getcsv')) {
47		function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
48			$fp = fopen("php://memory", 'r+');
49			fputs($fp, $input);
50			rewind($fp);
51			$data = fgetcsv($fp, null, $delimiter, $enclosure); // $escape only got added in 5.3.0
52			fclose($fp);
53			return $data;
54		}
55	}
56
57//set the max php execution time
58	ini_set(max_execution_time,7200);
59
60//get the http get values and set them as php variables
61	$action = check_str($_POST["action"]);
62	$order_by = check_str($_POST["order_by"]);
63	$order = check_str($_POST["order"]);
64	$delimiter = check_str($_POST["data_delimiter"]);
65	$enclosure = check_str($_POST["data_enclosure"]);
66
67//save the data to the csv file
68	if (isset($_POST['data'])) {
69		$file = $_SESSION['server']['temp']['dir']."/contacts-".$_SESSION['domain_name'].".csv";
70		file_put_contents($file, $_POST['data']);
71		$_SESSION['file'] = $file;
72	}
73
74//copy the csv file
75	//$_POST['submit'] == "Upload" &&
76	if ( is_uploaded_file($_FILES['ulfile']['tmp_name']) && permission_exists('contact_upload')) {
77		if (check_str($_POST['type']) == 'csv') {
78			move_uploaded_file($_FILES['ulfile']['tmp_name'], $_SESSION['server']['temp']['dir'].'/'.$_FILES['ulfile']['name']);
79			$save_msg = "Uploaded file to ".$_SESSION['server']['temp']['dir']."/". htmlentities($_FILES['ulfile']['name']);
80			//system('chmod -R 744 '.$_SESSION['server']['temp']['dir'].'*');
81			unset($_POST['txtCommand']);
82			$file = $_SESSION['server']['temp']['dir'].'/'.$_FILES['ulfile']['name'];
83			$_SESSION['file'] = $file;
84		}
85	}
86
87//get the schema
88	if (strlen($delimiter) > 0) {
89		//get the first line
90			$line = fgets(fopen($_SESSION['file'], 'r'));
91			$line_fields = explode($delimiter, $line);
92
93		//get the schema
94			$x = 0;
95			include ("app/contacts/app_config.php");
96			$i = 0;
97			foreach($apps[0]['db'] as $table) {
98				//get the table name and parent name
99				$table_name = $table["table"]['name'];
100				$parent_name = $table["table"]['parent'];
101
102				//remove the v_ table prefix
103				if (substr($table_name, 0, 2) == 'v_') {
104						$table_name = substr($table_name, 2);
105				}
106				if (substr($parent_name, 0, 2) == 'v_') {
107						$parent_name = substr($parent_name, 2);
108				}
109
110				//filter for specific tables and build the schema array
111				if ($table_name == "contacts" || $table_name == "contact_addresses" ||
112					$table_name == "contact_phones" || $table_name == "contact_emails" ||
113					$table_name == "contact_urls") {
114
115					$schema[$i]['table'] = $table_name;
116					$schema[$i]['parent'] = $parent_name;
117					foreach($table['fields'] as $row) {
118						if ($row['deprecated'] !== 'true') {
119							if (is_array($row['name'])) {
120								$field_name = $row['name']['text'];
121							}
122							else {
123								$field_name = $row['name'];
124							}
125							$schema[$i]['fields'][] = $field_name;
126						}
127					}
128					$i++;
129				}
130			}
131	}
132
133//match the column names to the field names
134	if (strlen($delimiter) > 0 && file_exists($_SESSION['file']) && $action != 'import') {
135
136		//form to match the fields to the column names
137			require_once "resources/header.php";
138
139			echo "<form action='contact_import.php' method='POST' enctype='multipart/form-data' name='frmUpload' onSubmit=''>\n";
140			echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
141
142			echo "	<tr>\n";
143			echo "	<td valign='top' align='left' nowrap='nowrap'>\n";
144			echo "		<b>".$text['header-contacts_import']."</b><br />\n";
145			echo "	</td>\n";
146			echo "	<td valign='top' align='right'>\n";
147			echo "		<input type='button' class='btn' name='' alt='".$text['button-back']."' onclick=\"window.location='contact_import.php'\" value='".$text['button-back']."'>\n";
148			echo "		<input name='submit' type='submit' class='btn' id='import' value=\"".$text['button-import']."\">\n";
149			echo "	</td>\n";
150			echo "	</tr>\n";
151			echo "	<tr>\n";
152			echo "	<td colspan='2' align='left'>\n";
153			echo "		".$text['description-contacts_import']."\n";
154			echo "	</td>\n";
155			echo "	</tr>\n";
156
157			//echo "<tr>\n";
158			//echo "<td align='left' width='30%' nowrap='nowrap'><b>".$text['header-contacts_import']."</b></td>\n";
159			//echo "<td width='70%' align='right'>\n";
160			//echo "	<input type='button' class='btn' name='' alt='".$text['button-back']."' onclick=\"window.location='contact_import.php'\" value='".$text['button-back']."'>\n";
161			//echo "</td>\n";
162			//echo "</tr>\n";
163
164			//loop through user columns
165			$x = 0;
166			foreach ($line_fields as $line_field) {
167				$line_field = trim(trim($line_field), $enclosure);
168				echo "<tr>\n";
169				echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
170				//echo "    ".$text['label-zzz']."\n";
171				echo $line_field;
172				echo "</td>\n";
173				echo "<td class='vtable' align='left'>\n";
174				echo "    			<select class='formfld' style='' name='fields[$x]'>\n";
175				echo "    			<option value=''></option>\n";
176				foreach($schema as $row) {
177					echo "			<optgroup label='".$row['table']."'>\n";
178					foreach($row['fields'] as $field) {
179						if (substr($field, -5) != '_uuid') {
180							echo "    			<option value='".$row['table'].".$field'>$field</option>\n";
181						}
182					}
183					echo "			</optgroup>\n";
184				}
185				echo "    			</select>\n";
186				//echo "<br />\n";
187				//echo $text['description-zzz']."\n";
188				echo "			</td>\n";
189				echo "		</tr>\n";
190				$x++;
191			}
192
193			echo "		<tr>\n";
194			echo "			<td colspan='2' valign='top' align='right' nowrap='nowrap'>\n";
195			echo "				<input name='action' type='hidden' value='import'>\n";
196			echo "				<input name='data_delimiter' type='hidden' value='$delimiter'>\n";
197			echo "				<input name='data_enclosure' type='hidden' value='$enclosure'>\n";
198			echo "				<input type='submit' class='btn' id='import' value=\"".$text['button-import']."\">\n";
199			echo "			</td>\n";
200			echo "		</tr>\n";
201
202			echo "	</table>\n";
203			echo "</form>\n";
204			require_once "resources/footer.php";
205
206		//normalize the column names
207			//$line = strtolower($line);
208			//$line = str_replace("-", "_", $line);
209			//$line = str_replace($delimiter."title".$delimiter, $delimiter."contact_title".$delimiter, $line);
210			//$line = str_replace("firstname", "name_given", $line);
211			//$line = str_replace("lastname", "name_family", $line);
212			//$line = str_replace("company", "organization", $line);
213			//$line = str_replace("company", "contact_email", $line);
214
215		//end the script
216			exit;
217	}
218
219//get the parent table
220	function get_parent($schema,$table_name) {
221		foreach ($schema as $row) {
222			if ($row['table'] == $table_name) {
223				return $row['parent'];
224			}
225		}
226	}
227
228//upload the contact csv
229	if (file_exists($_SESSION['file']) && $action == 'import') {
230
231		//form to match the fields to the column names
232			//require_once "resources/header.php";
233
234		//user selected fields
235			$fields = $_POST['fields'];
236
237		//set the domain_uuid
238			$domain_uuid = $_SESSION['domain_uuid'];
239
240		//get the contents of the csv file and convert them into an array
241			$handle = @fopen($_SESSION['file'], "r");
242			if ($handle) {
243				//set the row id
244					$row_id = 0;
245
246				//loop through the array
247					while (($line = fgets($handle, 4096)) !== false) {
248
249						//format the data
250							$y = 0;
251							foreach ($fields as $key => $value) {
252								//get the line
253								$result = str_getcsv($line, $delimiter, $enclosure);
254
255								//get the table and field name
256								$field_array = explode(".",$value);
257								$table_name = $field_array[0];
258								$field_name = $field_array[1];
259								//echo "value: $value<br />\n";
260								//echo "table_name: $table_name<br />\n";
261								//echo "field_name: $field_name<br />\n";
262
263								//get the parent table name
264								$parent = get_parent($schema, $table_name);
265
266								//remove formatting from the phone number
267								if ($field_name == "phone_number") {
268									$result[$key] = preg_replace('{\D}', '', $result[$key]);
269								}
270
271								//build the data array
272								if (strlen($table_name) > 0) {
273									if (strlen($parent) == 0) {
274										$array[$table_name][$row_id]['domain_uuid'] = $domain_uuid;
275										$array[$table_name][$row_id][$field_name] = $result[$key];
276									}
277									else {
278										$array[$parent][$row_id][$table_name][$y]['domain_uuid'] = $domain_uuid;
279										$array[$parent][$row_id][$table_name][$y][$field_name] = $result[$key];
280									}
281								}
282							}
283
284						//process a chunk of the array
285							if ($row_id === 1000) {
286
287								//save to the data
288									$database = new database;
289									$database->app_name = 'contacts';
290									$database->app_uuid = '04481e0e-a478-c559-adad-52bd4174574c';
291									$database->save($array);
292									//$message = $database->message;
293
294								//clear the array
295									unset($array);
296
297								//set the row id back to 0
298									$row_id = 0;
299							}
300
301						//increment row id
302							$row_id++;
303					}
304					fclose($handle);
305
306				//debug info
307					//echo "<pre>\n";
308					//print_r($array);
309					//echo "</pre>\n";
310					//exit;
311
312				//save to the data
313					if (is_array($array)) {
314						$database = new database;
315						$database->app_name = 'contacts';
316						$database->app_uuid = '04481e0e-a478-c559-adad-52bd4174574c';
317						$database->save($array);
318						//$message = $database->message;
319					}
320
321				//send the redirect header
322					header("Location: contacts.php");
323					return;
324			}
325
326		//show the header
327			require_once "resources/header.php";
328			echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
329			echo "<tr>\n";
330			echo "<td align='left' width='30%' nowrap='nowrap'><b>".$text['header-contacts_import']."</b></td>\n";
331			echo "<td width='70%' align='right'>\n";
332			echo "	<input type='button' class='btn' name='' alt='".$text['button-back']."' onclick=\"window.location='contacts.php?".$_GET["query_string"]."'\" value='".$text['button-back']."'>\n";
333			echo "</td>\n";
334			echo "</tr>\n";
335			echo "<tr>\n";
336			echo "<td align='left' colspan='2'>\n";
337			echo "	".$text['message-results']."<br /><br />\n";
338			echo "</td>\n";
339			echo "</tr>\n";
340			echo "</table>\n";
341
342		//show the results
343			echo "<table width='100%'  border='0' cellpadding='0' cellspacing='0' width='100%'>\n";
344			echo "<tr>\n";
345			echo "	<th>".$text['label-contact_name']."</th>\n";
346			echo "	<th>".$text['label-contact_organization']."</th>\n";
347			//echo "	<th>".$text['label-contact_email']."</th>\n";
348			echo "	<th>".$text['label-contact_url']."</th>\n";
349			echo "</tr>\n";
350			if ($results) {
351				foreach($results as $row) {
352					echo "<tr>\n";
353					echo "	<td class='vncell' valign='top' align='left'>\n";
354					echo 		$row['FirstName'] ." ".$row['LastName'];
355					echo "	</td>\n";
356					echo "	<td class='vncell' valign='top' align='left'>\n";
357					echo 	$row['Company']."&nbsp;\n";
358					echo "	</td>\n";
359					echo "	<td class='vncell' valign='top' align='left'>\n";
360					echo 		$row['EmailAddress']."&nbsp;\n";
361					echo "	</td>\n";
362					echo "	<td class='vncell' valign='top' align='left'>\n";
363					echo 		$row['Web Page']."&nbsp;\n";
364					echo "	</td>\n";
365					echo "</tr>\n";
366				}
367			}
368			echo "</table>\n";
369
370		//include the footer
371			require_once "resources/footer.php";
372
373		//end the script
374			exit;
375	}
376
377//include the header
378	require_once "resources/header.php";
379
380//begin the content
381	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
382	echo "	<tr>\n";
383	echo "	<td valign='top' align='left' width='30%' nowrap='nowrap'>\n";
384	echo "		<b>".$text['header-contacts_import']."</b><br />\n";
385	echo "		".$text['description-contacts_import']."\n";
386	echo "	</td>\n";
387	echo "	<td valign='top' width='70%' align='right'>\n";
388	echo "		<input type='button' class='btn' name='' alt='".$text['button-back']."' onclick=\"window.location='contacts.php?".$_GET["query_string"]."'\" value='".$text['button-back']."'>\n";
389	//echo "		<input name='submit' type='submit' class='btn' id='import' value=\"".$text['button-import']."\">\n";
390	echo "	</td>\n";
391	echo "	</tr>\n";
392	echo "</table>";
393
394	echo "<br />\n";
395
396	echo "<form action='' method='POST' enctype='multipart/form-data' name='frmUpload' onSubmit=''>\n";
397	echo "	<table border='0' cellpadding='0' cellspacing='0' width='100%'>\n";
398
399	echo "<tr>\n";
400	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
401	echo "    ".$text['label-import_data']."\n";
402	echo "</td>\n";
403	echo "<td class='vtable' align='left'>\n";
404	echo "    <textarea name='data' id='data' rows='7' class='formfld' style='width: 100%;' wrap='off'>$data</textarea>\n";
405	echo "<br />\n";
406	echo $text['description-import_data']."\n";
407	echo "</td>\n";
408	echo "</tr>\n";
409
410	echo "<tr>\n";
411	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
412	echo "    ".$text['label-import_delimiter']."\n";
413	echo "</td>\n";
414	echo "<td class='vtable' align='left'>\n";
415	echo "    <select class='formfld' style='width:40px;' name='data_delimiter'>\n";
416	echo "    <option value=','>,</option>\n";
417	echo "    <option value='|'>|</option>\n";
418	echo "    </select>\n";
419	echo "<br />\n";
420	echo $text['description-import_delimiter']."\n";
421	echo "</td>\n";
422	echo "</tr>\n";
423
424	echo "<tr>\n";
425	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
426	echo "    ".$text['label-import_enclosure']."\n";
427	echo "</td>\n";
428	echo "<td class='vtable' align='left'>\n";
429	echo "    <select class='formfld' style='width:40px;' name='data_enclosure'>\n";
430	echo "    <option value='\"'>\"</option>\n";
431	echo "    <option value=''></option>\n";
432	echo "    </select>\n";
433	echo "<br />\n";
434	echo $text['description-import_enclosure']."\n";
435	echo "</td>\n";
436	echo "</tr>\n";
437
438	echo "<tr>\n";
439	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
440	echo "			".$text['label-import_file_upload']."\n";
441	echo "</td>\n";
442	echo "<td class='vtable' align='left'>\n";
443	echo "			<input name='ulfile' type='file' class='formfld fileinput' id='ulfile'>\n";
444	echo "<br />\n";
445	echo "</td>\n";
446	echo "</tr>\n";
447
448	echo "	<tr>\n";
449	echo "		<td valign='bottom'>\n";
450	if (function_exists('curl_version') && $_SESSION['contact']['google_oauth_client_id']['text'] != '' && $_SESSION['contact']['google_oauth_client_secret']['text'] != '') {
451		echo "		<a href='contact_import_google.php'><img src='resources/images/icon_gcontacts.png' style='width: 21px; height: 21px; border: none; text-decoration: none; margin-right: 5px;' align='absmiddle'>".$text['header-contacts_import_google']."</a>\n";
452	}
453	echo "		</td>\n";
454	echo "		<td valign='bottom' align='right' nowrap>\n";
455	echo "			<input name='type' type='hidden' value='csv'>\n";
456	echo "			<br />\n";
457	echo "			<input name='submit' type='submit' class='btn' id='import' value=\"".$text['button-import']."\">\n";
458	echo "		</td>\n";
459	echo "	</tr>\n";
460	echo "	</table>\n";
461	echo "<br><br>";
462	echo "</form>";
463
464//include the footer
465	require_once "resources/footer.php";
466
467?>
468