contact_import.php 18 KB

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