TripalImporter.inc 20 KB

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