user_import.module 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. <?php
  2. /**
  3. * @file
  4. * Import or update users with data from a comma separated file (csv).
  5. */
  6. // Update options for existing users
  7. define('UPDATE_NONE', 0);
  8. define('UPDATE_REPLACE', 1);
  9. define('UPDATE_ADD', 2);
  10. /**
  11. * - - - - - - - - HOOKS - - - - - - - -
  12. */
  13. /**
  14. * Implementation of hook_theme().
  15. */
  16. function user_import_theme() {
  17. return array(
  18. 'user_import_list' => array(
  19. 'variables' => array(),
  20. ),
  21. 'user_import_edit' => array(
  22. 'render element' => 'form',
  23. ),
  24. 'user_import_errors_display' => array(
  25. 'variables' => array('settings' => NULL),
  26. ),
  27. 'user_import_username_errors' => array(
  28. 'variables' => array('errors' => NULL),
  29. ),
  30. );
  31. }
  32. /**
  33. * Implementation of hook_help().
  34. */
  35. // function user_import_help($path, $arg) {
  36. // switch ($path) {
  37. // case 'admin/people/user_import':
  38. // return t("Import or update users from a comma separated file (csv). Click 'Import' to start a new import.");
  39. // }
  40. // }
  41. /**
  42. * Implementation of hook_perm().
  43. */
  44. function user_import_permission() {
  45. return array(
  46. 'import users' => array(
  47. 'title' => t('Import users'),
  48. 'description' => t('Import users.'),
  49. ),
  50. 'limited user import' => array(
  51. 'title' => t('Import users Reports'),
  52. 'description' => t('View import error reports.'),
  53. ),
  54. );
  55. }
  56. /**
  57. * Implementation of hook_menu().
  58. */
  59. function user_import_menu() {
  60. $items['admin/people/user_import'] = array(
  61. 'title' => 'Import',
  62. 'description' => 'Import or update users from a comma separated file (csv).',
  63. 'page callback' => 'user_import_list',
  64. 'access arguments' => array('import users'),
  65. 'type' => MENU_LOCAL_TASK,
  66. 'file' => 'user_import.admin.inc',
  67. );
  68. $items['admin/people/user_import/list'] = array(
  69. 'title' => 'List Imports',
  70. 'access arguments' => array('import users'),
  71. 'weight' => -10,
  72. 'type' => MENU_DEFAULT_LOCAL_TASK,
  73. 'file' => 'user_import.admin.inc',
  74. );
  75. $items['admin/people/user_import/add'] = array(
  76. 'title' => 'New Import',
  77. 'page callback' => 'user_import_preferences',
  78. 'access arguments' => array('import users'),
  79. 'weight' => -5,
  80. 'type' => MENU_LOCAL_TASK,
  81. 'file' => 'user_import.admin.inc',
  82. );
  83. $items['admin/people/user_import/continue/%'] = array(
  84. 'title' => 'Continue',
  85. 'page callback' => 'drupal_get_form',
  86. 'page arguments' => array('user_import_confirm_continue', 4),
  87. 'access arguments' => array('import users'),
  88. 'type' => MENU_CALLBACK,
  89. 'file' => 'user_import.admin.inc',
  90. );
  91. $items['admin/people/user_import/import/%'] = array(
  92. 'title' => 'Import',
  93. 'page callback' => 'drupal_get_form',
  94. 'page arguments' => array('user_import_confirm_import', 4),
  95. 'access arguments' => array('import users'),
  96. 'type' => MENU_CALLBACK,
  97. 'file' => 'user_import.admin.inc',
  98. );
  99. $items['admin/people/user_import/delete/%'] = array(
  100. 'title' => 'Delete Import',
  101. 'page callback' => 'drupal_get_form',
  102. 'page arguments' => array('user_import_confirm_delete', 4),
  103. 'access arguments' => array('import users'),
  104. 'type' => MENU_CALLBACK,
  105. 'file' => 'user_import.admin.inc',
  106. );
  107. $items['admin/people/user_import/configure'] = array(
  108. 'title' => 'Configure',
  109. 'page callback' => 'drupal_get_form',
  110. 'page arguments' => array('user_import_configure_form'),
  111. 'access arguments' => array('import users'),
  112. 'type' => MENU_LOCAL_TASK,
  113. 'file' => 'user_import.admin.inc',
  114. );
  115. $items['admin/people/user_import/errors/%'] = array(
  116. 'title' => 'Import Errors',
  117. 'page callback' => 'user_import_limited_errors',
  118. 'page arguments' => array(4),
  119. 'type' => MENU_CALLBACK,
  120. 'access arguments' => array('limited user import'),
  121. );
  122. return $items;
  123. }
  124. /**
  125. * Implementation of hook_cron().
  126. */
  127. function user_import_cron() {
  128. module_load_include('inc', 'user_import', 'user_import.import');
  129. // Continue any on-going imports.
  130. user_import_continue_imports();
  131. // Check for new imports.
  132. user_import_trigger_imports();
  133. }
  134. /**
  135. * Continue any on-going imports, durring a cron run.
  136. *
  137. **/
  138. function user_import_continue_imports() {
  139. $imports = _user_import_settings_select();
  140. if ($imports) {
  141. foreach ($imports as $import) {
  142. if ($import['setting'] == 'test' || $import['setting'] == 'import') {
  143. _user_import_process($import);
  144. }
  145. }
  146. }
  147. }
  148. /**
  149. * Trigger imports if new files are found durring a cron run.
  150. */
  151. function user_import_trigger_imports() {
  152. $auto_imports_enabled = variable_get('user_import_auto_imports_enabled', FALSE);
  153. if (empty($auto_imports_enabled)) {
  154. return;
  155. }
  156. // Load import functions.
  157. module_load_include('inc', 'user_import', 'user_import.admin');
  158. // Get list of templates to check.
  159. $imports = db_query("SELECT * FROM {user_import} WHERE auto_import_directory != '' AND setting = 'template'");
  160. foreach ($imports as $import) {
  161. // Check for file in the uploads directory of this template.
  162. $directory = 'private://user_import/uploads/' . $import->auto_import_directory;
  163. $files = file_scan_directory($directory, '/.*$/');
  164. foreach ($files as $import_file) {
  165. // Move file to processing directory.
  166. $filename_new = $import_file->filename . '-' . rand(1000000, 2000000);
  167. $import_file_new = file_unmanaged_move($import_file->uri, 'private://user_import/processing/' . $filename_new);
  168. // Create import.
  169. // Get template.
  170. $settings = _user_import_settings_select($import->import_id);
  171. $import_id = '';
  172. $name = '';
  173. $pointer = 0;
  174. $processed = 0;
  175. $valid = 0;
  176. $field_match = isset($settings['field_match']) ? serialize($settings['field_match']) : '';
  177. $roles = isset($settings['roles']) ? serialize($settings['roles']) : '';
  178. $options = isset($settings['options']) ? serialize($settings['options']) : '';
  179. $setting = 'import';
  180. $file->filename = $filename_new;
  181. $file->oldfilename = $import_file->filename;
  182. $file->filepath = 'private://user_import/processing/' . $filename_new;
  183. $import_id = user_import_import_set($name, $file, $pointer, $processed, $valid, $field_match, $roles, $options, $setting, $import_id);
  184. $settings = _user_import_settings_select($import_id);
  185. _user_import_process($settings);
  186. }
  187. }
  188. return;
  189. // Get template.
  190. $settings = _user_import_settings_select(2);
  191. foreach ($files as $filename) {
  192. if ($filename == 'sample.txt') {
  193. // Check if it's used for an import already.
  194. $imported = db_query('SELECT import_id FROM {user_import} WHERE filename = :filename', array(':filename' => $filename))->fetchField();
  195. if (!$imported) {
  196. $import_id = '';
  197. $name = '';
  198. $pointer = 0;
  199. $processed = 0;
  200. $valid = 0;
  201. $field_match = isset($settings['field_match']) ? serialize($settings['field_match']) : '';
  202. $roles = isset($settings['roles']) ? serialize($settings['roles']) : '';
  203. $options = isset($settings['options']) ? serialize($settings['options']) : '';
  204. $setting = 'import';
  205. $file->filename = $filename;
  206. $file->oldfilename = $filename;
  207. $file->filepath = drupal_get_path('module', 'user_import') . '/' . $filename;
  208. $import_id = user_import_import_set($name, $file, $pointer, $processed, $valid, $field_match, $roles, $options, $setting, $import_id);
  209. $settings = _user_import_settings_select($import_id);
  210. _user_import_process($settings);
  211. }
  212. }
  213. }
  214. return;
  215. }
  216. // - - - - - - - - FORMS - - - - - - - -
  217. /**
  218. * Saves options on content type configuration form
  219. * @todo check if this is cruft
  220. * @todo check $form['type']
  221. */
  222. function user_import_content_type_submit($form, &$form_state) {
  223. // user import template for Organic Groups content type
  224. $templates = variable_get('user_import_og_template', array());
  225. $templates[$form['type']] = $form_state['values']['user_import_og'];
  226. variable_set('user_import_og_template', $templates);
  227. }
  228. // - - - - - - - - PAGES - - - - - - - -
  229. function user_import_limited_errors($import_id = NULL, $template_id = NULL) {
  230. if (empty($import_id) || !is_numeric($import_id)) {
  231. drupal_goto('admin/people/user_import/' . $template_id);
  232. }
  233. $pager_id = 1;
  234. $max = 25;
  235. $import = _user_import_settings_select($import_id);
  236. $output = '';
  237. $file_lines = array();
  238. $total = db_query('SELECT count(data) FROM {user_import_errors} WHERE import_id = :import_id', array(':import_id' => $import_id))->fetchField();
  239. if (empty($total)) {
  240. $output .= theme('There were no import errors');
  241. }
  242. else {
  243. $header = array(
  244. array('data' => t('ID'), 'field' => 'import_id', 'sort' => 'desc'),
  245. array('data' => t('Data'), 'field' => 'data'),
  246. array('data' => t('Errors'), 'field' => 'errors')
  247. );
  248. $query = db_select('user_import_errors', 'uie')
  249. ->fields('uie')
  250. ->extend('PagerDefault')
  251. ->extend('TableSort');
  252. $query
  253. ->condition('import_id', $import_id, '=')
  254. ->limit($max)
  255. ->orderByHeader($header);
  256. $result = $query->execute();
  257. foreach ($result as $line) {
  258. $file_lines[] = array(
  259. 'data' => unserialize($line->data),
  260. 'errors' => unserialize($line->errors)
  261. );
  262. }
  263. $output .= theme('user_import_errors_display', array(
  264. 'import' => $import,
  265. 'file_lines' => $file_lines,
  266. 'total' => $total
  267. ));
  268. }
  269. $output .= l(t('Return'), "admin/people/user_import");
  270. return $output;
  271. }
  272. /**
  273. * @param null $import_id
  274. * @param null $template_id
  275. */
  276. function user_import_limited_delete($import_id = NULL, $template_id = NULL) {
  277. module_load_include('inc', 'user_import', 'user_import.admin');
  278. user_import_delete($import_id, "admin/people/user_import");
  279. }
  280. // - - - - - - - - THEMES - - - - - - - -
  281. /**
  282. * @return string
  283. */
  284. function theme_user_import_list() {
  285. $output = '';
  286. $imports = _user_import_settings_select();
  287. if (!$imports) {
  288. return ' ';
  289. }
  290. foreach ($imports as $import) {
  291. // header labels
  292. $import_label = ($import['setting'] == 'tested' || $import['setting'] == 'test') ? t('importable') : t('imported');
  293. $header = array(
  294. t('file'),
  295. t('started'),
  296. t('processed'),
  297. $import_label,
  298. t('errors'),
  299. t('status')
  300. );
  301. // info row
  302. $errors = db_query('SELECT COUNT(import_id) FROM {user_import_errors} WHERE import_id = :import_id', array(':import_id' => $import['import_id']))->fetchField();
  303. $errors_link = ($errors == 0) ? '0' : l($errors, 'admin/people/user_import/errors/' . $import['import_id']);
  304. $rows[0] = array(
  305. check_plain($import['oldfilename']),
  306. format_date($import['started'], 'small'),
  307. array("data" => $import['processed'], "align" => 'center'),
  308. array("data" => $import['valid'], "align" => 'center'),
  309. array("data" => $errors_link, "align" => 'center'),
  310. $import['setting'],
  311. );
  312. $output .= theme('table', array('header' => $header, 'rows' => $rows));
  313. // action buttons
  314. $delete_link = l(t('Delete'), 'admin/people/user_import/delete/' . $import['import_id']);
  315. $continue_link = l(t('Continue Processing'), 'admin/people/user_import/continue/' . $import['import_id']);
  316. $import_link = l(t('Import'), 'admin/people/user_import/import/' . $import['import_id']);
  317. $output .= $delete_link;
  318. if ($import['setting'] == 'tested' || $import['setting'] == 'test') {
  319. $output .= ' | ' . $import_link;
  320. }
  321. if ($import['setting'] == 'test' || $import['setting'] == 'import') {
  322. $output .= ' | ' . $continue_link;
  323. }
  324. }
  325. return $output;
  326. }
  327. function theme_user_import_edit($variables) {
  328. $output = '';
  329. $rows = array();
  330. $form = $variables['form'];
  331. $header = array(
  332. t('CSV column'),
  333. t('Drupal fields'),
  334. t('Username'),
  335. t('Abbreviate')
  336. );
  337. foreach (element_children($form['field_match']) as $key) {
  338. $rows[] = array(
  339. drupal_render($form['field_match'][$key]['csv']),
  340. drupal_render($form['field_match'][$key]['field_match']),
  341. drupal_render($form['field_match'][$key]['username']),
  342. drupal_render($form['field_match'][$key]['abbreviate']),
  343. );
  344. }
  345. $form['field_match']['#value'] = theme('table', array(
  346. 'header' => $header,
  347. 'rows' => $rows
  348. ));
  349. if (isset($form['remove'])) {
  350. $output .= drupal_render($form['remove']);
  351. }
  352. if (isset($form['options'])) {
  353. $output .= drupal_render($form['options']);
  354. }
  355. if (isset($form['field_match'])) {
  356. $output .= drupal_render($form['field_match']);
  357. }
  358. $output .= drupal_render_children($form);
  359. return $output;
  360. }
  361. function theme_user_import_errors_display($settings) {
  362. $output = '';
  363. $header[0] = t('Email Address');
  364. $data = $settings['file_lines'];
  365. $total = $settings['total'];
  366. $oldfilename = $settings['import']['oldfilename'];
  367. $field_match = $settings['import']['field_match'];
  368. $error_count = 0;
  369. $field_match = _user_import_unconcatenate_field_match($field_match);
  370. foreach ($data as $data_row) {
  371. $row = array();
  372. foreach ($data_row['data'] as $type => $fields) {
  373. if (!empty($fields)) {
  374. foreach ($fields as $field_id => $field_data) {
  375. foreach ($field_match as $column_info) {
  376. if ($column_info['type'] == $type && $column_info['field_id'] == $field_id) {
  377. if (!empty($column_info['username'])) {
  378. $header[$column_info['username']] = t('Name %sort', array('%sort' => $column_info['username']));
  379. $row[$column_info['username']] = array(
  380. "data" => $field_data[0],
  381. "align" => "left"
  382. );
  383. }
  384. if ($column_info['field_id'] == 'email') {
  385. $row[0] = array("data" => $field_data[0], "align" => "left");
  386. }
  387. }
  388. }
  389. }
  390. }
  391. }
  392. ksort($row);
  393. $row[] = implode('<br />', $data_row['errors']);
  394. $rows[] = $row;
  395. }
  396. $output .= '<p>' . t('<strong>CSV File:</strong> %file', array('%file' => $oldfilename)) . '<br />';
  397. $output .= t('<strong>Errors:</strong> !total', array('!total' => $total)) . '</p>';
  398. $header['errors'] = t('Errors');
  399. // Output of table with the paging
  400. $output .= theme('table',
  401. array(
  402. "header" => $header,
  403. "rows" => $rows,
  404. "attributes" => array(),
  405. "sticky" => FALSE,
  406. // Table header will be sticky
  407. "caption" => '',
  408. "colgroups" => array(),
  409. "empty" => t("There are no errors.")
  410. // The message to be displayed if table is empty
  411. )
  412. ) . theme("pager");
  413. //$output .= theme('table', array('header' => $header, 'rows' => $rows));
  414. return $output;
  415. }
  416. function theme_user_import_username_errors($errors) {
  417. if (empty($errors)) {
  418. $output = '<p><strong>' . t('All usernames are OK.') . '</strong></p>';
  419. }
  420. else {
  421. $header = array(t('User ID'), t('Email'), t('Username'), t('Error'));
  422. $output = theme('table', array('header' => $header, 'errors' => $errors));
  423. }
  424. return $output;
  425. }
  426. // - - - - - - - - MISC - - - - - - - -
  427. function _user_import_settings_save($settings) {
  428. // Database field defaults.
  429. $database_fields = array(
  430. 'import_id' => NULL,
  431. 'name' => '',
  432. 'auto_import_directory' => '',
  433. 'filename' => '',
  434. 'oldfilename' => '',
  435. 'filepath' => '',
  436. 'started' => 0,
  437. 'pointer' => 0,
  438. 'processed' => 0,
  439. 'valid' => 0,
  440. 'field_match' => array(),
  441. 'roles' => '',
  442. 'options' => array(),
  443. 'setting' => '',
  444. );
  445. // Form elements we never want to save in the options column.
  446. $form_variables = array(
  447. 'form_id',
  448. 'form_token',
  449. 'form_build_id',
  450. 'cancel',
  451. 'import',
  452. 'submit',
  453. 'op',
  454. 0,
  455. 'return_path'
  456. );
  457. $form_variables = array_flip($form_variables);
  458. // Remove settings we don't need in the options column.
  459. $options = array_diff_key($settings, $database_fields);
  460. $options = array_diff_key($options, $form_variables);
  461. // Optimise Email Domain option if it's set.
  462. if (!empty($options['email_domain'])) {
  463. $options['email_domain'] = trim($options['email_domain']);
  464. if (substr($options['email_domain'], 0, 1) != '@') {
  465. $options['email_domain'] = '@' . $options['email_domain'];
  466. }
  467. }
  468. // Set defaults for options.
  469. foreach ($options as $key => $value) {
  470. $settings['options'][$key] = isset($settings[$key]) ? $settings[$key] : '';
  471. }
  472. // Optimise Email Domain option if it's set.
  473. if (!empty($settings['options']['email_domain'])) {
  474. $settings['options']['email_domain'] = trim($settings['options']['email_domain']);
  475. if (substr($settings['options']['email_domain'], 0, 1) != '@') {
  476. $settings['options']['email_domain'] = '@' . $settings['options']['email_domain'];
  477. }
  478. }
  479. // Set defaults for fields.
  480. foreach ($database_fields as $key => $value) {
  481. $settings[$key] = isset($settings[$key]) ? $settings[$key] : $value;
  482. }
  483. // Set default values.
  484. $import_id = isset($settings['import_id']) ? $settings['import_id'] : '';
  485. $name = isset($settings['name']) ? trim($settings['name']) : '';
  486. $pointer = isset($settings['pointer']) ? $settings['pointer'] : 0;
  487. $processed = isset($settings['processed']) ? $settings['processed'] : 0;
  488. $valid = isset($settings['valid']) ? $settings['valid'] : 0;
  489. $field_match = isset($settings['field_match']) ? serialize($settings['field_match']) : '';
  490. $roles = isset($settings['roles']) ? serialize($settings['roles']) : '';
  491. $options = isset($settings['options']) ? serialize($settings['options']) : '';
  492. $setting = isset($settings['setting']) ? $settings['setting'] : '';
  493. // Only set an auto import directory if saving a template.
  494. if (isset($settings['auto_import_directory']) && $settings['setting'] == 'template') {
  495. $auto_import_directory = $settings['auto_import_directory'];
  496. }
  497. else {
  498. $auto_import_directory = '';
  499. }
  500. $file = new ArrayObject();
  501. $file->filename = isset($settings['filename']) ? $settings['filename'] : '';
  502. $file->oldfilename = isset($settings['oldfilename']) ? $settings['oldfilename'] : '';
  503. $file->filepath = isset($settings['filepath']) ? $settings['filepath'] : '';
  504. $settings['import_id'] = user_import_import_set($name, $file, $pointer, $processed, $valid, $field_match, $roles, $options, $setting, $auto_import_directory, $import_id);
  505. return $settings;
  506. }
  507. function user_import_import_set($name = '', $file = '', $pointer = 0, $processed = 0, $valid = 0, $field_match = '', $roles = '', $options = '', $setting = '', $auto_import_directory = '', $import_id = '') {
  508. // Update settings for existing import.
  509. if (!empty($import_id)) {
  510. db_update('user_import')
  511. ->fields(array(
  512. 'name' => $name,
  513. 'auto_import_directory' => $auto_import_directory,
  514. 'filename' => $file->filename,
  515. 'oldfilename' => $file->oldfilename,
  516. 'filepath' => $file->filepath,
  517. 'pointer' => $pointer,
  518. 'processed' => $processed,
  519. 'valid' => $valid,
  520. 'field_match' => $field_match,
  521. 'roles' => $roles,
  522. 'options' => $options,
  523. 'setting' => $setting
  524. ))
  525. ->condition('import_id', $import_id)
  526. ->execute();
  527. }
  528. else {
  529. $import_id = db_insert('user_import')
  530. ->fields(array(
  531. 'name' => $name,
  532. 'auto_import_directory' => $auto_import_directory,
  533. 'filename' => $file->filename,
  534. 'oldfilename' => $file->oldfilename,
  535. 'filepath' => $file->filepath,
  536. 'started' => time(),
  537. 'pointer' => $pointer,
  538. 'processed' => $processed,
  539. 'valid' => $valid,
  540. 'field_match' => $field_match,
  541. 'roles' => $roles,
  542. 'options' => $options,
  543. 'setting' => $setting
  544. ))
  545. ->execute();
  546. }
  547. return $import_id;
  548. }
  549. /**
  550. * Return either a single import setting, or all template, or all non-template settings.
  551. */
  552. function _user_import_settings_select($import_id = NULL, $template = FALSE) {
  553. $import = array();
  554. if (!empty($import_id) && !is_numeric($import_id)) {
  555. return;
  556. }
  557. if (!empty($import_id)) {
  558. $sql = 'SELECT * FROM {user_import} WHERE import_id = :import_id';
  559. if ($template) {
  560. $sql .= " AND setting = 'template'";
  561. }
  562. $import = (array) db_query_range($sql, 0, 1, array(':import_id' => $import_id))->fetchObject();
  563. if (empty($import)) {
  564. return FALSE;
  565. }
  566. $import['field_match'] = unserialize($import['field_match']);
  567. $import['roles'] = unserialize($import['roles']);
  568. $import['options'] = unserialize($import['options']);
  569. if (is_array($import['options'])) {
  570. foreach ($import['options'] as $key => $value) {
  571. $import[$key] = $value;
  572. }
  573. }
  574. }
  575. else {
  576. $query = ($template) ? "SELECT * FROM {user_import} WHERE setting = 'template'" : "SELECT * FROM {user_import} WHERE setting <> 'template' ORDER BY started DESC";
  577. $result = db_query($query);
  578. foreach ($result as $row_data) {
  579. $row = (array) $row_data;
  580. $row['field_match'] = unserialize($row['field_match']);
  581. $row['roles'] = unserialize($row['roles']);
  582. $row['options'] = unserialize($row['options']);
  583. foreach ($row['options'] as $key => $value) {
  584. $row[$key] = $value;
  585. }
  586. $import[] = $row;
  587. }
  588. }
  589. return $import;
  590. }
  591. function _user_import_settings_deletion($import_id) {
  592. $sql = 'SELECT auto_import_directory FROM {user_import} WHERE import_id = :import_id';
  593. $auto_import_directory = db_query_range($sql, 0, 1, array(':import_id' => $import_id))->fetchField();
  594. if (!empty($auto_import_directory)) {
  595. $deleted = file_unmanaged_delete_recursive('private://user_import/uploads/' . $auto_import_directory);
  596. if ($deleted) {
  597. watchdog('Usr Import', t("Directory '%directory' has been deleted."), array('%directory' => $auto_import_directory));
  598. }
  599. }
  600. db_delete('user_import')
  601. ->condition('import_id', $import_id)
  602. ->execute();
  603. db_delete('user_import_errors')
  604. ->condition('import_id', $import_id)
  605. ->execute();
  606. return;
  607. }
  608. // Used by user_import_og.module
  609. function user_import_profile_load($user) {
  610. $result = db_query('SELECT f.name, f.type, f.fid, v.value FROM {profile_field} f INNER JOIN {profile_values} v ON f.fid = v.fid WHERE uid = %d', $user->uid);
  611. foreach ($result as $field) {
  612. if (empty($profile[$field->fid])) {
  613. $profile[$field->fid] = _profile_field_serialize($field->type) ? unserialize($field->value) : $field->value;
  614. }
  615. }
  616. return $profile;
  617. }
  618. function _user_import_unconcatenate_field_match($settings) {
  619. $settings_updated = array();
  620. foreach ($settings as $column_id => $values) {
  621. if (!empty($values['field_match']) || !empty($values['username'])) {
  622. // If we have a username but no field_match, set a special type.
  623. // This allows us to skip saving the field but still use it in
  624. // concatenating a username value.
  625. if (empty($values['field_match'])) {
  626. $values['type'] = 'username_part';
  627. $values['field_id'] = 'username_part_' . $column_id;
  628. }
  629. else {
  630. $key_parts = explode('-', $values['field_match']);
  631. $values['type'] = array_shift($key_parts);
  632. $values['field_id'] = implode('-', $key_parts);
  633. }
  634. unset($values['field_match']);
  635. $settings_updated[$column_id] = $values;
  636. }
  637. }
  638. return $settings_updated;
  639. }
  640. /**
  641. * Loads the hooks for the supported modules.
  642. */
  643. function user_import_load_supported() {
  644. static $loaded = FALSE;
  645. if (!$loaded) {
  646. $path = drupal_get_path('module', 'user_import') . '/supported';
  647. $files = drupal_system_listing("/\.inc$/", $path, 'name', 0);
  648. foreach ($files as $module_name => $file) {
  649. if (module_exists($module_name)) {
  650. include_once($file->uri);
  651. }
  652. }
  653. $loaded = TRUE;
  654. }
  655. }
  656. /**
  657. * Implementation of hook_simpletest().
  658. */
  659. function user_import_simpletest() {
  660. $module_name = 'user_import';
  661. $dir = drupal_get_path('module', $module_name) . '/tests';
  662. $tests = file_scan_directory($dir, '\.test$');
  663. return array_keys($tests);
  664. }
  665. /**
  666. * @param $filepath
  667. * @param $filename
  668. * @param $old_filename
  669. * @param $ftp
  670. * @param bool $message
  671. */
  672. function _user_import_file_deletion($filepath, $filename, $old_filename, $ftp, $message = TRUE) {
  673. $path_parts = explode(':', $filepath);
  674. if ($path_parts[0] == 'private') {
  675. // Delete files in the private files directory that have been uploaded by sftp/ftp.
  676. file_unmanaged_delete($filepath);
  677. }
  678. else {
  679. // Delete files uploaded through browser.
  680. $file = new stdClass();
  681. $file->uri = $filepath;
  682. $file->filename = $filename;
  683. $file->fid = db_query("SELECT fid FROM {file_managed} WHERE uri = :filepath", array(':filepath' => $filepath))->fetchField();;
  684. $removed = file_delete($file);
  685. }
  686. if (!$message) {
  687. return;
  688. }
  689. if (empty($removed)) {
  690. drupal_set_message(t("File error: file '%old_filename' (%filename) could not be deleted.", array(
  691. '%old_filename' => $oldfilename,
  692. '%filename' => $filename
  693. )), 'error');
  694. }
  695. else {
  696. drupal_set_message(t("File '%old_filename' was deleted.", array('%old_filename' => $old_filename)));
  697. }
  698. return;
  699. }
  700. /**
  701. * Implementation of hook_mail().
  702. */
  703. function user_import_mail($key, &$message, $params) {
  704. switch ($key) {
  705. case 'welcome':
  706. $message['subject'] = (empty($params['subject'])) ? _user_mail_text('register_admin_created_subject', $message['language'], $params) : strtr($params['subject'], $params);
  707. $body = (empty($params['body'])) ? _user_mail_text('register_admin_created_body', $message['language'], $params) : strtr($params['body'], $params);
  708. if ($params['email_format'] == 1) {
  709. $message['headers']['Content-Type'] = 'text/html; charset=UTF-8';
  710. $body_head = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  711. <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  712. <head>
  713. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />';
  714. if (!empty($params['css'])) {
  715. $body_head .= '<style type="text/css">' . check_plain($params['css']) . '</style>';
  716. }
  717. $message['body'][] = $body_head . '</head><body>' . $body . '</body></html>';
  718. }
  719. else {
  720. $message['body'][] = $body;
  721. }
  722. break;
  723. }
  724. }
  725. /**
  726. * Modify the drupal mail system to send HTML emails.
  727. *
  728. * See http://drupal.org/node/900794.
  729. */
  730. class UserImportMailSystem implements MailSystemInterface {
  731. /**
  732. * Concatenate and wrap the e-mail body.
  733. *
  734. * @param $message
  735. * A message array, as described in hook_mail_alter().
  736. *
  737. * @return
  738. * The formatted $message.
  739. */
  740. public function format(array $message) {
  741. $message['body'] = implode("\n\n", $message['body']);
  742. return $message;
  743. }
  744. /**
  745. * Send an e-mail message, using Drupal variables and default settings.
  746. *
  747. * @see <a href="http://php.net/manual/en/function.mail.php
  748. * " title="http://php.net/manual/en/function.mail.php
  749. * " rel="nofollow">http://php.net/manual/en/function.mail.php
  750. * </a> * @see drupal_mail()
  751. *
  752. * @param $message
  753. * A message array, as described in hook_mail_alter().
  754. * @return
  755. * TRUE if the mail was successfully accepted, otherwise FALSE.
  756. */
  757. public function mail(array $message) {
  758. $mimeheaders = array();
  759. foreach ($message['headers'] as $name => $value) {
  760. $mimeheaders[] = $name . ': ' . mime_header_encode($value);
  761. }
  762. $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
  763. return mail(
  764. $message['to'],
  765. mime_header_encode($message['subject']),
  766. // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
  767. // on Unix and CRLF on Windows. Drupal automatically guesses the
  768. // line-ending format appropriate for your system. If you need to
  769. // override this, adjust $conf['mail_line_endings'] in settings.php.
  770. preg_replace('@\r?\n@', $line_endings, $message['body']),
  771. // For headers, PHP's API suggests that we use CRLF normally,
  772. // but some MTAs incorrectly replace LF with CRLF. See #234403.
  773. join("\n", $mimeheaders)
  774. );
  775. }
  776. }