TripalImporter.inc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. // Create a temporary file.
  336. $temp = tempnam("temporary://", 'import_');
  337. $url_fh = fopen($file_remote, "r");
  338. $tmp_fh = fopen($temp, "w");
  339. if (!$url_fh) {
  340. throw new Exception(t("Unable to download the remote file at %url. Could a firewall be blocking outgoing connections?",
  341. array('%url', $file_remote)));
  342. }
  343. // Write the contents of the remote file to the temp file.
  344. while (!feof($url_fh)) {
  345. fwrite($tmp_fh, fread($url_fh, 255), 255);
  346. }
  347. // Set the path to the file for the importer to use.
  348. $this->arguments['file']['file_path'] = $temp;
  349. $this->is_prepared = TRUE;
  350. }
  351. }
  352. catch (Exception $e){
  353. throw new Exception('Cannot prepare the importer: ' . $e->getMessage());
  354. }
  355. }
  356. /**
  357. * Cleans up any temporary files that were created by the prepareFile().
  358. *
  359. * This function should be called after a run() to remove any temporary
  360. * files and keep them from building up on the server.
  361. */
  362. public function cleanFile() {
  363. try {
  364. // If a remote file was downloaded then remove it.
  365. if (!empty($this->arguments['file']['file_remote']) and
  366. file_exists($this->arguments['file']['file_path'])) {
  367. $this->logMessage('Removing downloaded file...');
  368. unlink($this->arguments['file']['file_path']);
  369. $this->is_prepared = FALSE;
  370. }
  371. }
  372. catch (Exception $e){
  373. throw new Exception('Cannot prepare the importer: ' . $e->getMessage());
  374. }
  375. }
  376. /**
  377. * Logs a message for the importer.
  378. *
  379. * There is no distinction between status messages and error logs. Any
  380. * message that is intended for the user to review the status of the loading
  381. * can be provided here. If this importer is associated with a job then
  382. * the logging is passed on to the job for storage.
  383. *
  384. * Messages that are are of severity TRIPAL_CRITICAL or TRIPAL_ERROR
  385. * are also logged to the watchdog.
  386. *
  387. * @param $message
  388. * The message to store in the log. Keep $message translatable by not
  389. * concatenating dynamic values into it! Variables in the message should
  390. * be added by using placeholder strings alongside the variables argument
  391. * to declare the value of the placeholders. See t() for documentation on
  392. * how $message and $variables interact.
  393. * @param $variables
  394. * Array of variables to replace in the message on display or NULL if
  395. * message is already translated or not possible to translate.
  396. * @param $severity
  397. * The severity of the message; one of the following values:
  398. * - TRIPAL_CRITICAL: Critical conditions.
  399. * - TRIPAL_ERROR: Error conditions.
  400. * - TRIPAL_WARNING: Warning conditions.
  401. * - TRIPAL_NOTICE: Normal but significant conditions.
  402. * - TRIPAL_INFO: (default) Informational messages.
  403. * - TRIPAL_DEBUG: Debug-level messages.
  404. */
  405. public function logMessage($message, $variables = array(), $severity = TRIPAL_INFO) {
  406. // Generate a translated message.
  407. $tmessage = t($message, $variables);
  408. // If we have a job then pass along the messaging to the job.
  409. if ($this->job) {
  410. $this->job->logMessage($message, $variables, $severity);
  411. }
  412. // If we don't have a job then just use the drpual_set_message.
  413. else {
  414. // Report this message to watchdog or set a message.
  415. if ($severity == TRIPAL_CRITICAL or $severity == TRIPAL_ERROR) {
  416. drupal_set_message($tmessage, 'error');
  417. }
  418. if ($severity == TRIPAL_WARNING) {
  419. drupal_set_message($tmessage, 'warning');
  420. }
  421. }
  422. }
  423. /**
  424. * Sets the total number if items to be processed.
  425. *
  426. * This should typically be called near the beginning of the loading process
  427. * to indicate the number of items that must be processed.
  428. *
  429. * @param $total_items
  430. * The total number of items to process.
  431. */
  432. protected function setTotalItems($total_items) {
  433. $this->total_items = $total_items;
  434. }
  435. /**
  436. * Adds to the count of the total number of items that have been handle.d
  437. * @param unknown $num_handled
  438. */
  439. protected function addItemsHandled($num_handled) {
  440. $items_handled = $this->num_handled = $this->num_handled + $num_handled;
  441. $this->setItemsHandled($items_handled);
  442. }
  443. /**
  444. * Sets the number of items that have been processed.
  445. *
  446. * This should be called anytime the loader wants to indicate how many
  447. * items have been processed. The amount of progress will be
  448. * calculated using this number. If the amount of items handled exceeds
  449. * the interval specified then the progress is reported to the user. If
  450. * this loader is associated with a job then the job progress is also updated.
  451. *
  452. * @param $total_handled
  453. * The total number of items that have been processed.
  454. */
  455. protected function setItemsHandled($total_handled) {
  456. // First set the number of items handled.
  457. $this->num_handled = $total_handled;
  458. if ($total_handled == 0) {
  459. $memory = number_format(memory_get_usage());
  460. print "Percent complete: 0%. Memory: " . $memory . " bytes.\r";
  461. return;
  462. }
  463. // Now see if we need to report to the user the percent done. A message
  464. // will be printed on the command-line if the job is run there.
  465. $percent = sprintf("%.2f", ($this->num_handled / $this->total_items) * 100);
  466. $diff = $percent - $this->prev_update;
  467. if ($diff >= $this->interval) {
  468. $memory = number_format(memory_get_usage());
  469. print "Percent complete: " . $percent . "%. Memory: " . $memory . " bytes.\r";
  470. // If we have a job the update the job progress too.
  471. if ($this->job) {
  472. $this->job->setProgress($percent);
  473. }
  474. $this->prev_update = $diff;
  475. }
  476. }
  477. /**
  478. * Updates the percent interval when the job progress is updated.
  479. *
  480. * Updating the job
  481. * progress incurrs a database write which takes time and if it occurs to
  482. * frequently can slow down the loader. This should be a value between
  483. * 0 and 100 to indicate a percent interval (e.g. 1 means update the
  484. * progress every time the num_handled increases by 1%).
  485. *
  486. * @param $interval
  487. * A number between 0 and 100.
  488. */
  489. protected function setInterval($interval) {
  490. $this->interval = $interval;
  491. }
  492. // --------------------------------------------------------------------------
  493. // OVERRIDEABLE FUNCTIONS
  494. // --------------------------------------------------------------------------
  495. /**
  496. * Provides form elements to be added to the loader form.
  497. *
  498. * These form elements are added after the file uploader section that
  499. * is automaticaly provided by the TripalImporter.
  500. *
  501. * @return
  502. * A $form array.
  503. */
  504. public function form($form, &$form_state) {
  505. return $form;
  506. }
  507. /**
  508. * Handles submission of the form elements.
  509. *
  510. * The form elements provided in the implementation of the form() function
  511. * can be used for special submit if needed.
  512. */
  513. public function formSubmit($form, &$form_state) {
  514. }
  515. /**
  516. * Handles validation of the form elements.
  517. *
  518. * The form elements provided in the implementation of the form() function
  519. * should be validated using this function.
  520. */
  521. public function formValidate($form, &$form_state) {
  522. }
  523. /**
  524. * Performs the import.
  525. */
  526. public function run() {
  527. }
  528. }