TripalImporter.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. <?php
  2. class TripalImporter {
  3. // --------------------------------------------------------------------------
  4. // EDITABLE STATIC CONSTANTS
  5. //
  6. // The following constants SHOULD be set for each descendent class. They are
  7. // used by the static functions to provide information to Drupal about
  8. // the field and it's default widget and formatter.
  9. // --------------------------------------------------------------------------
  10. /**
  11. * The name of this loader. This name will be presented to the site
  12. * user.
  13. */
  14. public static $name = 'Tripal Loader';
  15. /**
  16. * The machine name for this loader. This name will be used to construct
  17. * the URL for the loader.
  18. */
  19. public static $machine_name = 'tripal_loader';
  20. /**
  21. * A brief description for this loader. This description will be
  22. * presented to the site user.
  23. */
  24. public static $description = 'A base loader for all Tripal loaders';
  25. /**
  26. * An array containing the extensions of allowed file types.
  27. */
  28. public static $file_types = array();
  29. /**
  30. * Provides information to the user about the file upload. Typically this
  31. * may include a description of the file types allowed.
  32. */
  33. public static $upload_description = '';
  34. /**
  35. * The title that should appear above the upload button.
  36. */
  37. public static $upload_title = 'File Upload';
  38. /**
  39. * If the loader should require an analysis record. To maintain provenance
  40. * we should always indiate where the data we are uploading comes from.
  41. * The method that Tripal attempts to use for this by associating upload files
  42. * with an analysis record. The analysis record provides the details for
  43. * how the file was created or obtained. Set this to FALSE if the loader
  44. * should not require an analysis when loading. if $use_analysis is set to
  45. * true then the form values will have an 'analysis_id' key in the $form_state
  46. * array on submitted forms.
  47. */
  48. public static $use_analysis = TRUE;
  49. /**
  50. * If the $use_analysis value is set above then this value indicates if the
  51. * analysis should be required.
  52. */
  53. public static $require_analysis = TRUE;
  54. /**
  55. * Text that should appear on the button at the bottom of the importer
  56. * form.
  57. */
  58. public static $button_text = 'Import File';
  59. /**
  60. * Indicates the methods that the file uploader will support.
  61. */
  62. public static $methods = array(
  63. // Allow the user to upload a file to the server.
  64. 'file_upload' => TRUE,
  65. // Allow the user to provide the path on the Tripal server for the file.
  66. 'file_local' => TRUE,
  67. // Allow the user to provide a remote URL for the file.
  68. 'file_remote' => TRUE,
  69. );
  70. /**
  71. * Indicates if the file must be provided. An example when it may not be
  72. * necessary to require that the user provide a file for uploading if the
  73. * loader keeps track of previous files and makes those available for
  74. * selection.
  75. */
  76. public static $file_required = TRUE;
  77. /**
  78. * The array of arguments used for this loader. Each argument should
  79. * be a separate array containing a machine_name, name, and description
  80. * keys. This information is used to build the help text for the loader.
  81. */
  82. public static $argument_list = array();
  83. /**
  84. * Indicates how many files are allowed to be uploaded. By default this is
  85. * set to allow only one file. Change to any positive number. A value of
  86. * zero indicates an unlimited number of uploaded files are allowed.
  87. */
  88. public static $cardinality = 1;
  89. /**
  90. * Be default, all loaders are automaticlly added to the Admin >
  91. * Tripal > Data Laders menu. However, if this loader should be
  92. * made available via a different menu path, then set it here. If the
  93. * value is empty then the path will be the default.
  94. */
  95. public static $menu_path = '';
  96. // --------------------------------------------------------------------------
  97. // PRIVATE MEMBERS -- DO NOT EDIT or OVERRIDE
  98. // --------------------------------------------------------------------------
  99. /**
  100. * The number of items that this importer needs to process. A progress
  101. * can be calculated by dividing the number of items process by this
  102. * number.
  103. */
  104. private $total_items;
  105. /**
  106. * The number of items that have been handled so far. This must never
  107. * be below 0 and never exceed $total_items;
  108. */
  109. private $num_handled;
  110. /**
  111. * The interval when the job progress should be updated. Updating the job
  112. * progress incurrs a database write which takes time and if it occurs to
  113. * frequently can slow down the loader. This should be a value between
  114. * 0 and 100 to indicate a percent interval (e.g. 1 means update the
  115. * progress every time the num_handled increases by 1%).
  116. */
  117. private $interval;
  118. /**
  119. * Each time the job progress is updated this variable gets set. It is
  120. * used to calculate if the $interval has passed for the next update.
  121. */
  122. private $prev_update;
  123. /**
  124. * The job that this importer is associated with. This is needed for
  125. * updating the status of the job.
  126. */
  127. protected $job;
  128. /**
  129. * The arguments needed for the importer. This is a list of key/value
  130. * pairs in an associative array.
  131. */
  132. protected $arguments;
  133. /**
  134. * The ID for this import record.
  135. */
  136. protected $import_id;
  137. /**
  138. * Prior to running an importer it must be prepared to make sure the file
  139. * is available. Preparing the importer will download all the necessary
  140. * files. This value is set to TRUE after the importer is prepared for
  141. * funning.
  142. */
  143. protected $is_prepared;
  144. // --------------------------------------------------------------------------
  145. // CONSTRUCTORS
  146. // --------------------------------------------------------------------------
  147. /**
  148. * Instantiates a new TripalImporter object.
  149. *
  150. * @param TripalJob $job
  151. * An optional TripalJob object that this loader is associated with.
  152. */
  153. public function __construct(TripalJob $job = NULL) {
  154. // Intialize the private member variables.
  155. $this->is_prepared = FALSE;
  156. $this->import_id = NULL;
  157. $this->arguments = array();
  158. $this->job = NULL;
  159. $this->total_items = 0;
  160. $this->interval = 1;
  161. $this->num_handled = 0;
  162. $this->prev_update = 0;
  163. }
  164. /**
  165. * Instantiates a new TripalImporter object using the import record ID.
  166. *
  167. * This function will automatically instantiate the correct TripalImporter
  168. * child class that is appropriate for the provided ID.
  169. *
  170. * @param $import_id
  171. * The ID of the import recrod.
  172. * @return
  173. * An TripalImporter object of the appropriate child class.
  174. */
  175. static public function byID($import_id) {
  176. // Get the importer.
  177. $import = db_select('tripal_import', 'ti')
  178. ->fields('ti')
  179. ->condition('ti.import_id', $import_id)
  180. ->execute()
  181. ->fetchObject();
  182. if (!$import) {
  183. throw new Exception('Cannot find an importer that matches the given import ID.');
  184. }
  185. $class = $import->class;
  186. tripal_load_include_importer_class($class);
  187. if (class_exists($class)) {
  188. $loader = new $class();
  189. $loader->load($import_id);
  190. return $loader;
  191. }
  192. else {
  193. throw new Exception('Cannot find the matching class for this import record.');
  194. }
  195. }
  196. /**
  197. * Associate this importer with the Tripal job that is running it.
  198. *
  199. * Associating an import with a job will allow the importer to log messages
  200. * to the job log.
  201. *
  202. * @param TripalJob $job
  203. * An instnace of a TripalJob.
  204. */
  205. public function setJob(TripalJob $job) {
  206. $this->job = $job;
  207. }
  208. /**
  209. * Creates a new importer record.
  210. *
  211. * @param $run_args
  212. * An associative array of the arguments needed to run the importer. Each
  213. * importer will have its own defined set of arguments.
  214. *
  215. * @param $file_details
  216. * An associative array with one of the following keys:
  217. * -fid: provides the Drupal managed File ID for the file.
  218. * -file_local: provides the full path to the file on the server.
  219. * -file_remote: provides the remote URL for the file.
  220. * This argument is optional if the loader does not use the built-in
  221. * file loader.
  222. *
  223. * @throws Exception
  224. */
  225. public function create($run_args, $file_details = array()) {
  226. global $user;
  227. $class = get_called_class();
  228. try {
  229. // Build the values for the tripal_importer table insert.
  230. $values = array(
  231. 'uid' => $user->uid,
  232. 'class' => $class,
  233. 'submit_date' => time(),
  234. );
  235. // Build the arguments array, which consists of the run arguments
  236. // and the file.
  237. $arguments = array(
  238. 'run_args' => $run_args,
  239. 'files' => array(),
  240. );
  241. // Get the file argument.
  242. $has_file = 0;
  243. if (array_key_exists('file_local', $file_details)) {
  244. $arguments['files'][] = array(
  245. 'file_local' => $file_details['file_local'],
  246. 'file_path' => $file_details['file_local']
  247. );
  248. $has_file++;
  249. }
  250. if (array_key_exists('file_remote', $file_details)) {
  251. $arguments['files'][] = array(
  252. 'file_remote' => $file_details['file_remote']
  253. );
  254. $has_file++;
  255. }
  256. if (array_key_exists('fid', $file_details)) {
  257. $values['fid'] = $file_details['fid'];
  258. // Handle multiple file uploads.
  259. if (preg_match('/\|/', $file_details['fid'])) {
  260. $fids = explode('|', $file_details['fid']);
  261. foreach ($fids as $fid) {
  262. $file = file_load($fid);
  263. $arguments['files'][] = array(
  264. 'file_path' => drupal_realpath($file->uri),
  265. 'fid' => $fid
  266. );
  267. $has_file++;
  268. }
  269. }
  270. // Handle a single file.
  271. else {
  272. $fid = $file_details['fid'];
  273. $file = file_load($fid);
  274. $arguments['files'][] = array(
  275. 'file_path' => drupal_realpath($file->uri),
  276. 'fid' => $fid
  277. );
  278. $has_file++;
  279. // For backwards compatibility add the old 'file' element.
  280. $arguments['file'] = array(
  281. 'file_path' => drupal_realpath($file->uri),
  282. 'fid' => $fid
  283. );
  284. }
  285. }
  286. // Validate the $file_details argument.
  287. if ($has_file == 0 and $class::$file_required == TRUE) {
  288. throw new Exception("Must provide a proper file identifier for the \$file_details argument.");
  289. }
  290. // Store the arguments in the class and serialize for table insertion.
  291. $this->arguments = $arguments;
  292. $values['arguments'] = serialize($arguments);
  293. // Insert the importer record.
  294. $import_id = db_insert('tripal_import')
  295. ->fields($values)
  296. ->execute();
  297. $this->import_id = $import_id;
  298. }
  299. catch (Exception $e){
  300. throw new Exception('Cannot create importer: ' . $e->getMessage());
  301. }
  302. }
  303. /**
  304. * Loads an existing import record into this object.
  305. *
  306. * @param $import_id
  307. * The ID of the import record.
  308. */
  309. public function load($import_id) {
  310. $class = get_called_class();
  311. // Get the importer.
  312. $import = db_select('tripal_import', 'ti')
  313. ->fields('ti')
  314. ->condition('ti.import_id', $import_id)
  315. ->execute()
  316. ->fetchObject();
  317. if (!$import) {
  318. throw new Exception('Cannot find an importer that matches the given import ID.');
  319. }
  320. if ($import->class != $class) {
  321. throw new Exception('The importer specified by the given ID does not match this importer class.');
  322. }
  323. $this->arguments = unserialize($import->arguments);
  324. $this->import_id = $import_id;
  325. }
  326. /**
  327. * Submits the importer for execution as a job.
  328. *
  329. * @return
  330. * The ID of the newly submitted job.
  331. */
  332. public function submitJob() {
  333. global $user;
  334. $class = get_called_class();
  335. if (!$this->import_id) {
  336. throw new Exception('Cannot submit an importer job without an import record. Please run create() first.');
  337. }
  338. // Add a job to run the importer.
  339. try {
  340. $args = array($this->import_id);
  341. $includes = array(
  342. module_load_include('inc', 'tripal', 'api/tripal.importer.api'),
  343. );
  344. $job_id = tripal_add_job($class::$button_text, 'tripal',
  345. 'tripal_run_importer', $args, $user->uid, 10, $includes);
  346. return $job_id;
  347. }
  348. catch (Exception $e){
  349. throw new Exception('Cannot create importer job: ' . $e->getMessage());
  350. }
  351. }
  352. /**
  353. * Prepares the importer files for execution.
  354. *
  355. * This function must be run prior to the run() function to ensure that
  356. * the import file is ready to go.
  357. */
  358. public function prepareFiles() {
  359. $class = get_called_class();
  360. // If no file is required then just indicate that all is good to go.
  361. if ($class::$file_required == FALSE) {
  362. $this->is_prepared = TRUE;
  363. return;
  364. }
  365. try {
  366. for($i = 0; $i < count($this->arguments['files']); $i++) {
  367. if (!empty($this->arguments['files'][$i]['file_remote'])) {
  368. $file_remote = $this->arguments['files'][$i]['file_remote'];
  369. $this->logMessage('Download file: !file_remote...', array('!file_remote' => $file_remote));
  370. // If this file is compressed then keepthe .gz extension so we can
  371. // uncompress it.
  372. $ext = '';
  373. if (preg_match('/^(.*?)\.gz$/', $file_remote)) {
  374. $ext = '.gz';
  375. }
  376. // Create a temporary file.
  377. $temp = tempnam("temporary://", 'import_') . $ext;
  378. $this->logMessage("Saving as: !file", array('!file' => $temp));
  379. $url_fh = fopen($file_remote, "r");
  380. $tmp_fh = fopen($temp, "w");
  381. if (!$url_fh) {
  382. throw new Exception(t("Unable to download the remote file at %url. Could a firewall be blocking outgoing connections?",
  383. array('%url', $file_remote)));
  384. }
  385. // Write the contents of the remote file to the temp file.
  386. while (!feof($url_fh)) {
  387. fwrite($tmp_fh, fread($url_fh, 255), 255);
  388. }
  389. // Set the path to the file for the importer to use.
  390. $this->arguments['files'][$i]['file_path'] = $temp;
  391. $this->is_prepared = TRUE;
  392. }
  393. // Is this file compressed? If so, then uncompress it
  394. $matches = array();
  395. if (preg_match('/^(.*?)\.gz$/', $this->arguments['files'][$i]['file_path'], $matches)) {
  396. $this->logMessage("Uncompressing: !file", array('!file' => $this->arguments['files'][$i]['file_path']));
  397. $buffer_size = 4096;
  398. $new_file_path = $matches[1];
  399. $gzfile = gzopen($this->arguments['files'][$i]['file_path'], 'rb');
  400. $out_file = fopen($new_file_path, 'wb');
  401. if (!$out_file) {
  402. throw new Exception("Cannot uncompress file: new temporary file, '$new_file_path', cannot be created.");
  403. }
  404. // Keep repeating until the end of the input file
  405. while (!gzeof($gzfile)) {
  406. // Read buffer-size bytes
  407. // Both fwrite and gzread and binary-safe
  408. fwrite($out_file, gzread($gzfile, $buffer_size));
  409. }
  410. // Files are done, close files
  411. fclose($out_file);
  412. gzclose($gzfile);
  413. // Now remove the .gz file and reset the file_path to the new
  414. // uncompressed version.
  415. unlink($this->arguments['files'][$i]['file_path']);
  416. $this->arguments['files'][$i]['file_path'] = $new_file_path;
  417. }
  418. }
  419. }
  420. catch (Exception $e){
  421. throw new Exception('Cannot prepare the importer: ' . $e->getMessage());
  422. }
  423. }
  424. /**
  425. * Cleans up any temporary files that were created by the prepareFile().
  426. *
  427. * This function should be called after a run() to remove any temporary
  428. * files and keep them from building up on the server.
  429. */
  430. public function cleanFile() {
  431. try {
  432. // If a remote file was downloaded then remove it.
  433. for($i = 0; $i < count($this->arguments['files']); $i++) {
  434. if (!empty($this->arguments['files'][$i]['file_remote']) and
  435. file_exists($this->arguments['files'][$i]['file_path'])) {
  436. $this->logMessage('Removing downloaded file...');
  437. unlink($this->arguments['files'][$i]['file_path']);
  438. $this->is_prepared = FALSE;
  439. }
  440. }
  441. }
  442. catch (Exception $e){
  443. throw new Exception('Cannot prepare the importer: ' . $e->getMessage());
  444. }
  445. }
  446. /**
  447. * Logs a message for the importer.
  448. *
  449. * There is no distinction between status messages and error logs. Any
  450. * message that is intended for the user to review the status of the loading
  451. * can be provided here. If this importer is associated with a job then
  452. * the logging is passed on to the job for storage.
  453. *
  454. * Messages that are are of severity TRIPAL_CRITICAL or TRIPAL_ERROR
  455. * are also logged to the watchdog.
  456. *
  457. * @param $message
  458. * The message to store in the log. Keep $message translatable by not
  459. * concatenating dynamic values into it! Variables in the message should
  460. * be added by using placeholder strings alongside the variables argument
  461. * to declare the value of the placeholders. See t() for documentation on
  462. * how $message and $variables interact.
  463. * @param $variables
  464. * Array of variables to replace in the message on display or NULL if
  465. * message is already translated or not possible to translate.
  466. * @param $severity
  467. * The severity of the message; one of the following values:
  468. * - TRIPAL_CRITICAL: Critical conditions.
  469. * - TRIPAL_ERROR: Error conditions.
  470. * - TRIPAL_WARNING: Warning conditions.
  471. * - TRIPAL_NOTICE: Normal but significant conditions.
  472. * - TRIPAL_INFO: (default) Informational messages.
  473. * - TRIPAL_DEBUG: Debug-level messages.
  474. */
  475. public function logMessage($message, $variables = array(), $severity = TRIPAL_INFO) {
  476. // Generate a translated message.
  477. $tmessage = t($message, $variables);
  478. // If we have a job then pass along the messaging to the job.
  479. if ($this->job) {
  480. $this->job->logMessage($message, $variables, $severity);
  481. }
  482. // If we don't have a job then just use the drpual_set_message.
  483. else {
  484. // Report this message to watchdog or set a message.
  485. if ($severity == TRIPAL_CRITICAL or $severity == TRIPAL_ERROR) {
  486. drupal_set_message($tmessage, 'error');
  487. }
  488. if ($severity == TRIPAL_WARNING) {
  489. drupal_set_message($tmessage, 'warning');
  490. }
  491. }
  492. }
  493. /**
  494. * Sets the total number if items to be processed.
  495. *
  496. * This should typically be called near the beginning of the loading process
  497. * to indicate the number of items that must be processed.
  498. *
  499. * @param $total_items
  500. * The total number of items to process.
  501. */
  502. protected function setTotalItems($total_items) {
  503. $this->total_items = $total_items;
  504. }
  505. /**
  506. * Adds to the count of the total number of items that have been handled.
  507. *
  508. * @param $num_handled
  509. */
  510. protected function addItemsHandled($num_handled) {
  511. $items_handled = $this->num_handled = $this->num_handled + $num_handled;
  512. $this->setItemsHandled($items_handled);
  513. }
  514. /**
  515. * Sets the number of items that have been processed.
  516. *
  517. * This should be called anytime the loader wants to indicate how many
  518. * items have been processed. The amount of progress will be
  519. * calculated using this number. If the amount of items handled exceeds
  520. * the interval specified then the progress is reported to the user. If
  521. * this loader is associated with a job then the job progress is also updated.
  522. *
  523. * @param $total_handled
  524. * The total number of items that have been processed.
  525. */
  526. protected function setItemsHandled($total_handled) {
  527. // First set the number of items handled.
  528. $this->num_handled = $total_handled;
  529. if ($total_handled == 0) {
  530. $memory = number_format(memory_get_usage());
  531. print "Percent complete: 0%. Memory: " . $memory . " bytes.\r";
  532. return;
  533. }
  534. // Now see if we need to report to the user the percent done. A message
  535. // will be printed on the command-line if the job is run there.
  536. $percent = sprintf("%.2f", ($this->num_handled / $this->total_items) * 100);
  537. $diff = $percent - $this->prev_update;
  538. if ($diff >= $this->interval) {
  539. $memory = number_format(memory_get_usage());
  540. print "Percent complete: " . $percent . "%. Memory: " . $memory . " bytes.\r";
  541. // If we have a job the update the job progress too.
  542. if ($this->job) {
  543. $this->job->setProgress($percent);
  544. }
  545. $this->prev_update = $diff;
  546. }
  547. }
  548. /**
  549. * Updates the percent interval when the job progress is updated.
  550. *
  551. * Updating the job
  552. * progress incurrs a database write which takes time and if it occurs to
  553. * frequently can slow down the loader. This should be a value between
  554. * 0 and 100 to indicate a percent interval (e.g. 1 means update the
  555. * progress every time the num_handled increases by 1%).
  556. *
  557. * @param $interval
  558. * A number between 0 and 100.
  559. */
  560. protected function setInterval($interval) {
  561. $this->interval = $interval;
  562. }
  563. // --------------------------------------------------------------------------
  564. // OVERRIDEABLE FUNCTIONS
  565. // --------------------------------------------------------------------------
  566. /**
  567. * Provides form elements to be added to the loader form.
  568. *
  569. * These form elements are added after the file uploader section that
  570. * is automaticaly provided by the TripalImporter.
  571. *
  572. * @return
  573. * A $form array.
  574. */
  575. public function form($form, &$form_state) {
  576. return $form;
  577. }
  578. /**
  579. * Handles submission of the form elements.
  580. *
  581. * The form elements provided in the implementation of the form() function
  582. * can be used for special submit if needed.
  583. */
  584. public function formSubmit($form, &$form_state) {
  585. }
  586. /**
  587. * Handles validation of the form elements.
  588. *
  589. * The form elements provided in the implementation of the form() function
  590. * should be validated using this function.
  591. */
  592. public function formValidate($form, &$form_state) {
  593. }
  594. /**
  595. * Performs the import.
  596. */
  597. public function run() {
  598. }
  599. /**
  600. * Performs the import.
  601. */
  602. public function postRun() {
  603. }
  604. }