TripalImporter.inc 22 KB

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