sbo__relationship.inc 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. <?php
  2. class sbo__relationship extends ChadoField {
  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. // The default lable for this field.
  11. public static $default_label = 'Relationship';
  12. // The default description for this field.
  13. public static $description = 'Relationships between records.';
  14. // Provide a list of instance specific settings. These can be access within
  15. // the instanceSettingsForm. When the instanceSettingsForm is submitted
  16. // then Drupal with automatically change these settings for the instnace.
  17. // It is recommended to put settings at the instance level whenever possible.
  18. // If you override this variable in a child class be sure to replicate the
  19. // term_name, term_vocab, term_accession and term_fixed keys as these are
  20. // required for all TripalFields.
  21. public static $default_instance_settings = array(
  22. // The short name for the vocabulary (e.g. shcema, SO, GO, PATO, etc.).
  23. 'term_vocabulary' => 'SBO',
  24. // The name of the term.
  25. 'term_name' => 'Relationship',
  26. // The unique ID (i.e. accession) of the term.
  27. 'term_accession' => '0000374',
  28. // Set to TRUE if the site admin is allowed to change the term
  29. // type. This will create form elements when editing the field instance
  30. // to allow the site admin to change the term settings above.
  31. 'term_fixed' => FALSE,
  32. // Inidates if this field should be automatically attached to display
  33. // or web services or if this field should be loaded separately. This
  34. // is convenient for speed. Fields that are slow should for loading
  35. // should ahve auto_attach set to FALSE so tha their values can be
  36. // attached asyncronously.
  37. 'auto_attach' => FALSE,
  38. // Settings to help the site admin control how relationship types and
  39. // valid subject/objects can be selected by the user.
  40. 'relationships' => array(
  41. 'option1_vocabs' => '',
  42. 'option2_vocab' => '',
  43. 'option2_parent' => '',
  44. 'relationship_types' => '',
  45. ),
  46. // The number of items to show on a page.
  47. 'items_per_page' => 10,
  48. );
  49. // The default widget for this field.
  50. public static $default_widget = 'sbo__relationship_widget';
  51. // The default formatter for this field.
  52. public static $default_formatter = 'sbo__relationship_formatter';
  53. // --------------------------------------------------------------------------
  54. // PROTECTED CLASS MEMBERS -- DO NOT OVERRIDE
  55. // --------------------------------------------------------------------------
  56. // An array containing details about the field. The format of this array
  57. // is the same as that returned by field_info_fields()
  58. protected $field;
  59. // An array containing details about an instance of the field. A field does
  60. // not have to have an instance. But if dealing with an instance (such as
  61. // when using the widgetForm, formatterSettingsForm, etc.) it should be set.
  62. protected $instance;
  63. /**
  64. * @see TripalField::elements()
  65. */
  66. public function elementInfo() {
  67. $field_term = $this->getFieldTermID();
  68. return array(
  69. $field_term => array(
  70. 'operations' => array('eq', 'contains', 'starts'),
  71. 'sortable' => FALSE,
  72. 'searchable' => FALSE,
  73. 'type' => 'xs:complexType',
  74. 'readonly' => FALSE,
  75. 'elements' => array(
  76. 'SIO:000493' => array(
  77. 'searchable' => FALSE,
  78. 'name' => 'relationship_clause',
  79. 'label' => 'Relationship Clause',
  80. 'help' => 'An English phrase describing the relationships.',
  81. 'sortable' => FALSE,
  82. 'type' => 'xs:string',
  83. 'readonly' => TRUE,
  84. 'required' => FALSE,
  85. ),
  86. 'local:relationship_subject' => array(
  87. 'searchable' => FALSE,
  88. 'name' => 'relationship_subject',
  89. 'operations' => array('eq', 'ne', 'contains', 'starts'),
  90. 'sortable' => FALSE,
  91. 'type' => 'xs:complexType',
  92. 'readonly' => FALSE,
  93. 'required' => TRUE,
  94. 'elements' => array(
  95. 'rdfs:type' => array(
  96. 'name' => 'type',
  97. 'searchable' => TRUE,
  98. 'label' => 'Relationship Subject Type',
  99. 'help' => 'The subject\'s data type in a relationship clause',
  100. 'operations' => array('eq', 'ne', 'contains', 'starts'),
  101. 'sortable' => TRUE,
  102. 'type' => 'xs:string',
  103. 'readonly' => FALSE,
  104. 'required' => TRUE,
  105. ),
  106. 'schema:name' => array(
  107. 'name' => 'name',
  108. 'searchable' => TRUE,
  109. 'label' => 'Relationship Subject Name',
  110. 'help' => 'The subject\'s name in a relationship clause',
  111. 'operations' => array('eq', 'ne', 'contains', 'starts'),
  112. 'sortable' => TRUE,
  113. 'type' => 'xs:string',
  114. 'readonly' => FALSE,
  115. 'required' => TRUE,
  116. ),
  117. 'entity' => array(
  118. 'searchable' => FALSE,
  119. 'sortable' => FALSE,
  120. )
  121. ),
  122. ),
  123. 'local:relationship_type' => array(
  124. 'searchable' => TRUE,
  125. 'name' => 'relationship_type',
  126. 'operations' => array('eq', 'ne', 'contains', 'starts'),
  127. 'sortable' => TRUE,
  128. 'type' => 'xs:string',
  129. 'readonly' => FALSE,
  130. 'required' => TRUE,
  131. ),
  132. 'local:relationship_object' => array(
  133. 'searchable' => FALSE,
  134. 'name' => 'relationship_object',
  135. 'operations' => array('eq', 'ne', 'contains', 'starts'),
  136. 'sortable' => FALSE,
  137. 'type' => 'xs:complexType',
  138. 'readonly' => FALSE,
  139. 'required' => TRUE,
  140. 'elements' => array(
  141. 'rdfs:type' => array(
  142. 'searchable' => TRUE,
  143. 'name' => 'object_type',
  144. 'label' => 'Relationship Object Type',
  145. 'help' => 'The objects\'s data type in a relationship clause',
  146. 'operations' => array('eq', 'ne', 'contains', 'starts'),
  147. 'sortable' => TRUE,
  148. 'type' => 'xs:string',
  149. 'readonly' => FALSE,
  150. 'required' => TRUE,
  151. ),
  152. 'schema:name' => array(
  153. 'searchable' => TRUE,
  154. 'name' => 'object_name',
  155. 'label' => 'Relationship Object Name',
  156. 'help' => 'The objects\'s name in a relationship clause',
  157. 'operations' => array('eq', 'ne', 'contains', 'starts'),
  158. 'sortable' => TRUE,
  159. 'type' => 'xs:string',
  160. 'readonly' => FALSE,
  161. 'required' => TRUE,
  162. ),
  163. 'entity' => array(
  164. 'searchable' => FALSE,
  165. 'sortable' => FALSE,
  166. )
  167. ),
  168. ),
  169. ),
  170. )
  171. );
  172. }
  173. private function loadRelationship($relationship, &$entity, $delta) {
  174. $field_name = $this->field['field_name'];
  175. $field_table = $this->instance['settings']['chado_table'];
  176. $base_table = $this->instance['settings']['base_table'];
  177. $rel_acc = $relationship->type_id->dbxref_id->db_id->name . ':' . $relationship->type_id->dbxref_id->accession;
  178. $rel_type = $relationship->type_id->name;
  179. $verb = $this->get_rel_verb($rel_type);
  180. // Get the foreign keys for the subject and object tables
  181. $subject_fkey_table = '';
  182. $object_fkey_table = '';
  183. $schema = chado_get_schema($field_table);
  184. $pkey = $schema['primary key'][0];
  185. $fkey_lcolumn = key($schema['foreign keys'][$base_table]['columns']);
  186. $fkey_rcolumn = $schema['foreign keys'][$base_table]['columns'][$fkey_lcolumn];
  187. // Not all tables have the columns named 'subject_id' and 'object_id'.
  188. // some have variations on that name and we need to determine what they are.
  189. $fkeys = $schema['foreign keys'];
  190. $subject_id_key = 'subject_id';
  191. $object_id_key = 'object_id';
  192. foreach ($fkeys as $fktable => $details) {
  193. foreach ($details['columns'] as $fkey_lcolumn => $fkey_rcolumn) {
  194. if (preg_match('/^subject_.*id/', $fkey_lcolumn)) {
  195. $subject_fkey_table = $fktable;
  196. $subject_id_key = $fkey_lcolumn;
  197. }
  198. if (preg_match('/^object_.*id/', $fkey_lcolumn)) {
  199. $object_fkey_table = $fktable;
  200. $object_id_key = $fkey_lcolumn;
  201. }
  202. }
  203. }
  204. // Get the schemas for the subject and object table. These should
  205. // be the same as the base table but just to be safe we'll get them
  206. // separately.
  207. $subject_schema = chado_get_schema($subject_fkey_table);
  208. $subject_pkey = $subject_schema['primary key'][0];
  209. $object_schema = chado_get_schema($object_fkey_table);
  210. $object_pkey = $object_schema['primary key'][0];
  211. // Not all realtionshp tables have a name field (e.g. organism_relationship)
  212. // threfore in some cases we need to dig a bit deeper to get the entity
  213. // name and the entity type name.
  214. $subject_name = '';
  215. $subject_type = '';
  216. $object_name = '';
  217. $object_type = '';
  218. // The linked to table of a relationship linker table may not always
  219. // have a type_id or name field. So we have to be a bit more
  220. // specific about how we set some variables.
  221. switch ($relationship->tablename) {
  222. case 'acquisition_relationship':
  223. $subject_type = 'acquisition';
  224. $object_type = 'acquisition';
  225. break;
  226. case 'analysis_relationship':
  227. $subject_type = 'analysis';
  228. $object_type = 'analysis';
  229. break;
  230. case 'biomaterial_relationship':
  231. $subject_type = 'biomaterial';
  232. $object_type = 'biomaterial';
  233. break;
  234. case 'cell_line_relationship':
  235. $subject_type = 'cell_line';
  236. $object_type = 'cell_line';
  237. break;
  238. case 'element_relationship':
  239. $subject_name = $relationship->$subject_id_key->feature_id->name;
  240. $object_name = $relationship->$object_id_key->feature_id->name;
  241. break;
  242. case 'organism_relationship':
  243. $subject_name = $relationship->$subject_id_key->genus . ' ' . $relationship->$subject_id_key->species;
  244. $object_name = $relationship->$object_id_key->genus . ' ' . $relationship->$object_id_key->species;
  245. $subject_type = 'organism';
  246. $object_type = 'organism';
  247. break;
  248. case 'project_relationship':
  249. $subject_type = 'project';
  250. $object_type = 'project';
  251. break;
  252. case 'phylonode_relationship':
  253. $subject_name = $relationship->$subject_id_key->label;
  254. $object_name = $relationship->$object_id_key->label;
  255. break;
  256. case 'pub_relationship':
  257. $subject_name = $relationship->$subject_id_key->uniquename;
  258. $object_name = $relationship->$object_id_key->uniquename;
  259. break;
  260. case 'quantification_relationship':
  261. $subject_type = 'quantification';
  262. $object_type = 'quantification';
  263. break;
  264. default:
  265. $subject_name = isset($relationship->$subject_id_key->name) ? $relationship->$subject_id_key->name : '';
  266. $subject_type = isset($relationship->$subject_id_key->type_id) ? $relationship->$subject_id_key->type_id->name : '';
  267. $object_name = isset($relationship->$object_id_key->name) ? $relationship->$object_id_key->name : '';
  268. $object_type = isset($relationship->$object_id_key->type_id) ? $relationship->$object_id_key->type_id->name : '';
  269. }
  270. $entity->{$field_name}['und'][$delta]['value'] = array(
  271. 'local:relationship_subject' => array(
  272. 'rdfs:type' => $subject_type,
  273. 'schema:name' => $subject_name,
  274. ),
  275. 'local:relationship_type' => $relationship->type_id->name,
  276. 'local:relationship_object' => array(
  277. 'rdfs:type' => $object_type,
  278. 'schema:name' => $object_name,
  279. 'entity' => 'TripalEntity:' . $entity->id,
  280. )
  281. );
  282. // If the subject or object have a unqiuename then add that in for refernce.
  283. if (property_exists($relationship->$subject_id_key, 'uniquename')) {
  284. $entity->{$field_name}['und'][$delta]['value']['local:relationship_subject']['data:0842'] = $relationship->$subject_id_key->uniquename;
  285. }
  286. if (property_exists($relationship->$object_id_key, 'uniquename')) {
  287. $entity->{$field_name}['und'][$delta]['value']['local:relationship_object']['data:0842'] = $relationship->$object_id_key->uniquename;
  288. }
  289. // If the subject or object have an organism then add that in for reference.
  290. if (property_exists($relationship->$subject_id_key, 'organism_id')) {
  291. $entity->{$field_name}['und'][$delta]['value']['local:relationship_subject']['OBI:0100026'] = $relationship->$subject_id_key->organism_id->genus . ' ' . $relationship->$subject_id_key->organism_id->species;
  292. }
  293. if (property_exists($relationship->$object_id_key, 'organism_id')) {
  294. $entity->{$field_name}['und'][$delta]['value']['local:relationship_object']['OBI:0100026'] = $relationship->$object_id_key->organism_id->genus . ' ' . $relationship->$object_id_key->organism_id->species;
  295. }
  296. // Add in the TripalEntity ids if these base records in the relationship
  297. // are published.
  298. if (property_exists($relationship->$subject_id_key, 'entity_id')) {
  299. $entity_id = $relationship->$subject_id_key->entity_id;
  300. $entity->{$field_name}['und'][$delta]['value']['local:relationship_subject']['entity'] = 'TripalEntity:' . $entity_id;
  301. }
  302. if (property_exists($relationship->$object_id_key, 'entity_id')) {
  303. $entity_id = $relationship->$object_id_key->entity_id;
  304. $entity->{$field_name}['und'][$delta]['value']['local:relationship_object']['entity'] = 'TripalEntity:' . $entity_id;
  305. }
  306. // Add the clause to the values array. The clause is a written version
  307. // of the relationships.
  308. $rel_type_clean = lcfirst(preg_replace('/_/', ' ', $rel_type));
  309. // Remember the current entity could be either the subject or object!
  310. // Example: The genetic_marker, MARKER1 , derives from the sequence_variant, VARIANT1.
  311. // The above relationship will be shown both on marker and variant pages
  312. // and as such both subject and object names need to be shown.
  313. $clause = 'The ' . $subject_type . ', ' .
  314. $subject_name . ', ' . $verb . ' ' . $rel_type_clean . ' the ' .
  315. $object_type . ', ' . $object_name . '.';
  316. $entity->{$field_name}['und'][$delta]['value']['SIO:000493'] = $clause;
  317. // Adding a label allows us to provide a single text value for the
  318. // entire field. It is this text value that can be used in tab/csv
  319. // downloaders.
  320. $entity->{$field_name}['und'][$delta]['value']['rdfs:label'] = $clause;
  321. $entity->{$field_name}['und'][$delta]['chado-' . $field_table . '__' . $pkey] = $relationship->$pkey;
  322. $entity->{$field_name}['und'][$delta]['chado-' . $field_table . '__' . $subject_id_key] = $relationship->$subject_id_key->$subject_pkey;
  323. $entity->{$field_name}['und'][$delta]['chado-' . $field_table . '__type_id'] = $relationship->type_id->cvterm_id;
  324. $entity->{$field_name}['und'][$delta]['chado-' . $field_table . '__' . $object_id_key] = $relationship->$object_id_key->$object_pkey;
  325. // For the widget to work properly we will preform values.
  326. $entity->{$field_name}['und'][$delta]['type_name'] = $relationship->type_id->name;
  327. $entity->{$field_name}['und'][$delta]['subject_name'] = $subject_name . ' [id: ' . $relationship->$subject_id_key->$subject_pkey . ']';
  328. $entity->{$field_name}['und'][$delta]['object_name'] = $object_name . ' [id: ' . $relationship->$object_id_key->$object_pkey . ']';
  329. if (array_key_exists('value', $schema['fields'])) {
  330. $entity->{$field_name}['und'][$delta]['chado-' . $field_table . '__value'] = $relationship->value;
  331. }
  332. if (array_key_exists('rank', $schema['fields'])) {
  333. $entity->{$field_name}['und'][$delta]['chado-' . $field_table . '__rank'] = $relationship->rank;
  334. }
  335. }
  336. /**
  337. *
  338. * @see TripalField::load()
  339. */
  340. public function load($entity) {
  341. $settings = $this->field['settings'];
  342. $record = $entity->chado_record;
  343. $bundle = tripal_load_bundle_entity(array('name' => $entity->bundle));
  344. $field_name = $this->field['field_name'];
  345. $field_type = $this->field['type'];
  346. $field_table = $this->instance['settings']['chado_table'];
  347. $field_column = $this->instance['settings']['chado_column'];
  348. $base_table = $this->instance['settings']['base_table'];
  349. // Get the PKey for this table
  350. $schema = chado_get_schema($field_table);
  351. $pkey = $schema['primary key'][0];
  352. $fkey_lcolumn = key($schema['foreign keys'][$base_table]['columns']);
  353. $fkey_rcolumn = $schema['foreign keys'][$base_table]['columns'][$fkey_lcolumn];
  354. // If we don't have a chado record return before creating a stub for this field!
  355. if (!$record) {
  356. return;
  357. }
  358. // Not all tables have the columns named 'subject_id' and 'object_id'.
  359. // some have variations on that name and we need to determine what they are.
  360. $fkeys = $schema['foreign keys'];
  361. $subject_id_key = 'subject_id';
  362. $object_id_key = 'object_id';
  363. foreach ($fkeys as $fktable => $details) {
  364. foreach ($details['columns'] as $fkey_lcolumn => $fkey_rcolumn) {
  365. if (preg_match('/^subject_.*id/', $fkey_lcolumn)) {
  366. $subject_id_key = $fkey_lcolumn;
  367. }
  368. if (preg_match('/^object_.*id/', $fkey_lcolumn)) {
  369. $object_id_key = $fkey_lcolumn;
  370. }
  371. }
  372. }
  373. // Set some defaults for the empty record.
  374. $entity->{$field_name}['und'][0] = array(
  375. 'value' => '',
  376. 'chado-' . $field_table . '__' . $pkey => '',
  377. 'chado-' . $field_table . '__' . $subject_id_key => '',
  378. 'chado-' . $field_table . '__' . $object_id_key => '',
  379. 'chado-' . $field_table . '__type_id' => '',
  380. // These elements don't need to follow the naming scheme above
  381. // becasue we don't need the chado_field_storage to try and
  382. // save these values.
  383. 'object_name' => '',
  384. 'subject_name' => '',
  385. 'type_name' => '',
  386. );
  387. // If the table has rank and value fields then add those to the default
  388. // value array.
  389. if (array_key_exists('value', $schema['fields'])) {
  390. $entity->{$field_name}['und'][0]['chado-' . $field_table . '__value'] = '';
  391. }
  392. if (array_key_exists('rank', $schema['fields'])) {
  393. $entity->{$field_name}['und'][0]['chado-' . $field_table . '__rank'] = '';
  394. }
  395. // If we have no record then just return.
  396. if (!$record) {
  397. return;
  398. }
  399. // Expand the object to include the relationships.
  400. $options = array(
  401. 'return_array' => 1,
  402. // we don't want to fully recurse we only need information about the
  403. // relationship type and the object and subject
  404. 'include_fk' => array(
  405. 'type_id' => 1,
  406. $object_id_key => array(
  407. 'type_id' => 1,
  408. 'organism_id' => 1,
  409. ),
  410. $subject_id_key => array(
  411. 'type_id' => 1,
  412. 'organism_id' => 1,
  413. ),
  414. ),
  415. );
  416. $rel_table = $base_table . '_relationship';
  417. $schema = chado_get_schema($rel_table);
  418. if (array_key_exists('rank', $schema['fields'])) {
  419. $options['order_by'] = array('rank' => 'ASC');
  420. }
  421. $record = chado_expand_var($record, 'table', $rel_table, $options);
  422. if (!$record->$rel_table) {
  423. return;
  424. }
  425. // Load the subject relationships
  426. $i = 0;
  427. if (isset($record->$rel_table->$subject_id_key)) {
  428. $srelationships = $record->$rel_table->$subject_id_key;
  429. foreach ($srelationships as $relationship) {
  430. $this->loadRelationship($relationship, $entity, $i);
  431. $i++;
  432. }
  433. }
  434. // Load the object relationships
  435. if (isset($record->$rel_table->$object_id_key)) {
  436. $orelationships = $record->$rel_table->$object_id_key;
  437. foreach ($orelationships as $relationship) {
  438. $this->loadRelationship($relationship, $entity, $i);
  439. $i++;
  440. }
  441. }
  442. }
  443. /**
  444. * @see ChadoField::query()
  445. */
  446. public function query($query, $condition) {
  447. $alias = $this->field['field_name'];
  448. $chado_table = $this->instance['settings']['chado_table'];
  449. $base_table = $this->instance['settings']['base_table'];
  450. $bschema = chado_get_schema($base_table);
  451. $bpkey = $bschema['primary key'][0];
  452. $operator = $condition['operator'];
  453. // Bulid the list of expected elements that will be provided.
  454. $field_term_id = $this->getFieldTermID();
  455. $rel_subject = $field_term_id . ',local:relationship_subject';
  456. $rel_subject_type = $rel_subject . ',' . 'rdfs:type';
  457. $rel_subject_name = $rel_subject . ',' . 'schema:name';
  458. $rel_subject_identifier = $rel_subject . ',' . 'data:0842';
  459. $rel_type = $field_term_id . ',local:relationship_type';
  460. $rel_object = $field_term_id . ',local:relationship_object';
  461. $rel_object_type = $rel_object . ',' . 'rdfs:type';
  462. $rel_object_name = $rel_object . ',' . 'schema:name';
  463. $rel_object_identifier = $rel_object . ',' . 'data:0842';
  464. // Filter by the name of the subject or object.
  465. if ($condition['column'] == $rel_subject_name) {
  466. $this->queryJoinOnce($query, $chado_table, $alias, "base.$bpkey = $alias.object_id");
  467. $this->queryJoinOnce($query, $base_table, 'base2', "base2.$bpkey = $alias.subject_id");
  468. $query->condition("base2.name", $condition['value'], $operator);
  469. }
  470. if ($condition['column'] == $rel_object_name) {
  471. $this->queryJoinOnce($query, $chado_table, $alias, "base.$bpkey = $alias.subject_id");
  472. $this->queryJoinOnce($query, $base_table, 'base2', "base2.$bpkey = $alias.object_id");
  473. $query->condition("base2.name", $condition['value'], $operator);
  474. }
  475. // Filter by unique name of the subject or object.
  476. if ($condition['column'] == $rel_subject_identifier) {
  477. $this->queryJoinOnce($query, $chado_table, $alias, "base.$bpkey = $alias.object_id");
  478. $this->queryJoinOnce($query, $base_table, 'base2', "base2.$bpkey = $alias.subject_id");
  479. $query->condition("base2.uniquename", $condition['value'], $operator);
  480. }
  481. if ($condition['column'] == $rel_object_identifier) {
  482. $this->queryJoinOnce($query, $chado_table, $alias, "base.$bpkey = $alias.subject_id");
  483. $this->queryJoinOnce($query, $base_table, 'base2', "base2.$bpkey = $alias.object_id");
  484. $query->condition("base2.uniquename", $condition['value'], $operator);
  485. }
  486. // Filter by the type of the subject or object
  487. if ($condition['column'] == $rel_subject_type) {
  488. $this->queryJoinOnce($query, $chado_table, $alias, "base.$bpkey = $alias.object_id");
  489. $this->queryJoinOnce($query, $base_table, 'base2', "base2.$bpkey = $alias.subject_id");
  490. $this->queryJoinOnce($query, 'cvterm', 'SubjectCVT', "SubjectCVT.cvterm_id = base2.type_id");
  491. $this->queryJoinOnce($query, "SubjectCVT.name", $condition['value'], $operator);
  492. }
  493. if ($condition['column'] == $rel_object_type) {
  494. $this->queryJoinOnce($query, $chado_table, $alias, "base.$bpkey = $alias.subject_id");
  495. $this->queryJoinOnce($query, $base_table, 'base2', "base2.$bpkey = $alias.object_id");
  496. $this->queryJoinOnce($query, 'cvterm', 'ObjectCVT', "ObjectCVT.cvterm_id = base2.type_id");
  497. $query->condition("ObjectCVT.name", $condition['value'], $operator);
  498. }
  499. // Filter by relationship type
  500. if ($condition['column'] == 'relationship.relationship_type') {
  501. // This filter commented out because it's way to slow...
  502. // $this->queryJoinOnce($query, $chado_table, $alias, "base.$bpkey = $alias.subject_id OR base.$bpkey = $alias.object_id");
  503. // $this->queryJoinOnce($query, 'cvterm', 'RelTypeCVT', "RelTypeCVT.cvterm_id = $alias.type_id");
  504. // $query->condition("RelTypeCVT.name", $condition['value'], $operator);
  505. }
  506. }
  507. /**
  508. * A helper function to define English verbs for relationship types.
  509. *
  510. * @param $rel_type
  511. * The vocabulary term name for the relationship.
  512. *
  513. * @return
  514. * The verb to use when creating a sentence of the relationship.
  515. */
  516. private function get_rel_verb($rel_type) {
  517. $rel_type_clean = lcfirst(preg_replace('/_/', ' ', $rel_type));
  518. $verb = '';
  519. switch ($rel_type_clean) {
  520. case 'integral part of':
  521. case 'instance of':
  522. $verb = 'is an';
  523. break;
  524. case 'proper part of':
  525. case 'transformation of':
  526. case 'genome of':
  527. case 'part of':
  528. $verb = 'is a';
  529. case 'position of':
  530. case 'sequence of':
  531. case 'variant of':
  532. $verb = 'is a';
  533. break;
  534. case 'derives from':
  535. case 'connects on':
  536. case 'contains':
  537. case 'finishes':
  538. case 'guides':
  539. case 'has origin':
  540. case 'has part':
  541. case 'has quality':
  542. case 'is a maternal parent of':
  543. case 'is a paternal parent of':
  544. case 'is consecutive sequence of':
  545. case 'maximally overlaps':
  546. case 'overlaps':
  547. case 'starts':
  548. break;
  549. default:
  550. $verb = 'is';
  551. }
  552. return $verb;
  553. }
  554. /**
  555. *
  556. * @see TripalField::settingsForm()
  557. */
  558. public function instanceSettingsForm() {
  559. $element = parent::instanceSettingsForm();
  560. $element['items_per_page'] = array(
  561. '#type' => 'textfield',
  562. '#title' => 'Items per Page',
  563. '#description' => t('The number of items that should appear on each page. A pager is provided if more than this number of items exist.'),
  564. '#default_value' => $this->instance['settings']['items_per_page'],
  565. );
  566. //$element = parent::instanceSettingsForm();
  567. $element['relationships'] = array(
  568. '#type' => 'fieldset',
  569. '#title' => 'Allowed Relationship Types',
  570. '#description' => t('There are three ways that relationship types
  571. can be limited for users who have permission to add new relationships.
  572. Please select the most appropriate for you use case. By default
  573. all vocabularies are provided to the user which allows use of any
  574. term for the relationship type.'),
  575. '#collapsed' => TRUE,
  576. '#collapsible' => TRUE,
  577. );
  578. // $element['instructions'] = array(
  579. // '#type' => 'item',
  580. // '#markup' => 'You may provide a list of terms that will be available in a select box
  581. // as the relationship types. This select box will replace the vocabulary select box if the
  582. // following value is set.'
  583. // );
  584. $vocs = chado_get_cv_select_options();
  585. $element['relationships']['option1'] = array(
  586. '#type' => 'item',
  587. '#title' => 'Option #1',
  588. '#description' => t('Use this option to limit the vocabularies that a user .
  589. could use to specify relationship types. With this option any term in .
  590. the vocabulary can be used for the relationship type. You may select
  591. more than one vocabulary.'),
  592. );
  593. $element['relationships']['option1_vocabs'] = array(
  594. '#type' => 'select',
  595. '#multiple' => TRUE,
  596. '#options' => $vocs,
  597. '#size' => 6,
  598. '#default_value' => $this->instance['settings']['relationships']['option1_vocabs'],
  599. // TODO add ajax here so that the relationship autocomplete below works
  600. );
  601. $element['relationships']['option2'] = array(
  602. '#type' => 'item',
  603. '#title' => '<b>Option #2</b>',
  604. '#description' => 'Some vocabularies are heirarchichal (an ontology). Within this
  605. heirarchy groups of related terms typically fall under a common parent. If you
  606. wish to limit the list of terms that a user can use for the relationship type,
  607. you can provide the parent term here. Then, only that term\'s children will
  608. be avilable for use as a relationship type.',
  609. );
  610. $element['relationships']['option2_vocab'] = array(
  611. '#type' => 'select',
  612. '#description' => 'Specify Default Vocabulary',
  613. '#multiple' => FALSE,
  614. '#options' => $vocs,
  615. '#default_value' => $this->instance['settings']['relationships']['option2_vocab'],
  616. '#ajax' => array(
  617. 'callback' => "sbo__relationship_instance_settings_form_ajax_callback",
  618. 'wrapper' => 'relationships-option2-parent',
  619. 'effect' => 'fade',
  620. 'method' => 'replace'
  621. ),
  622. );
  623. $element['relationships']['option2_parent'] = array(
  624. '#type' => 'textfield',
  625. '#description' => 'Specify a Heirarchical Parent Term',
  626. '#default_value' => $this->instance['settings']['relationships']['option2_parent'],
  627. '#autocomplete_path' => "admin/tripal/storage/chado/auto_name/cvterm/",
  628. '#prefix' => '<div id=relationships-option2-parent>',
  629. '#suffix' => '</div>'
  630. );
  631. $element['relationships']['option3'] = array(
  632. '#type' => 'item',
  633. '#title' => 'Option #3',
  634. '#description' => 'Provide terms separated by a new line. The term provided should be
  635. unique and distinguishable by the name. You can use a bar | to separate a vocabulary
  636. and a term to allow more specific assignment.',
  637. );
  638. $element['relationships']['relationship_types'] = array(
  639. '#type' => 'textarea',
  640. '#default_value' => $this->instance['settings']['relationships']['relationship_types'],
  641. );
  642. return $element;
  643. }
  644. /**
  645. *
  646. * @param unknown $form
  647. * @param unknown $form_state
  648. */
  649. public function instanceSettingsFormValidate($form, &$form_state) {
  650. // Get relationships settings
  651. $settings = $form_state['values']['instance']['settings']['relationships'];
  652. $form_state['values']['instance']['settings']['relationships']['relationship_types']= trim($settings['relationship_types']);
  653. // Make sure only one option is selected
  654. $option1test = $settings['option1_vocabs'];
  655. $option1 = isset($settings['option1_vocabs']) && array_pop($option1test);
  656. $option2 = (isset($settings['option2_vocab']) && $settings['option2_vocab']) || $settings['option2_parent'];
  657. $option3 = isset($settings['relationship_types']) && trim($settings['relationship_types']);
  658. if ($option1 && ($option2 || $option3) == 1 ||
  659. $option2 && ($option1 || $option3) == 1 ||
  660. $option3 && ($option1 || $option2) == 1) {
  661. form_set_error("instance][settings][relationships", t("Only one option is allowed to limit the relationship types."));
  662. return;
  663. }
  664. // For option3, make sure the supplied types are valid cvterms
  665. if ($option3) {
  666. $rel_types = explode(PHP_EOL, $settings['relationship_types']);
  667. foreach($rel_types AS $type) {
  668. $type = trim($type);
  669. // Ignore empty lines
  670. if ($type == '') {
  671. continue;
  672. }
  673. // Find the matching cvterm
  674. $sql = "SELECT cvterm_id FROM {cvterm} WHERE name = :name";
  675. $results = chado_query($sql, array(':name' => $type));
  676. $terms = array();
  677. while ($obj = $results->fetchObject()) {
  678. $terms[] = $obj;
  679. }
  680. // Don't save the form if a term can not be found or it matches more than one cvterm
  681. $cv = '';
  682. if (count($terms) == 0) {
  683. // If a term can not be found, maybe the type contains '|', parse it as 'vocabulary|cvterm'
  684. if (strpos($type, '|')) {
  685. $tmp = explode('|', $type, 2);
  686. $type = trim($tmp[1]);
  687. $cv = chado_get_cv(array('name' => trim($tmp[0])));
  688. if($cv) {
  689. $sql = "SELECT cvterm_id FROM {cvterm} WHERE name = :name AND cv_id = :cv_id";
  690. $results = chado_query($sql, array(':name' => $type, ':cv_id' => $cv->cv_id));
  691. while ($obj = $results->fetchObject()) {
  692. $terms[] = $obj;
  693. }
  694. }
  695. else {
  696. $cv = $tmp[0];
  697. }
  698. }
  699. if (count($terms) != 1) {
  700. $message = "The term '@type' can not be found.";
  701. $token = array('@type' => $type);
  702. if ($cv) {
  703. $message = "The term '@type' can not be found within the vocabulary '@vocab'.";
  704. $token['@vocab'] = $cv;
  705. }
  706. form_set_error("instance][settings][relationships][relationship_types",
  707. t($message, $token));
  708. }
  709. }
  710. else if (count($terms) > 1) {
  711. // If a type matches more than one term, parse it as 'vocabulary|cvterm' and try again
  712. if (strpos($type, '|')) {
  713. $tmp = explode('|', $type, 2);
  714. $type = trim($tmp[1]);
  715. $cv = chado_get_cv(array('name' => trim($tmp[0])));
  716. if ($cv) {
  717. $sql = "SELECT cvterm_id FROM {cvterm} WHERE name = :name AND cv_id = :cv_id";
  718. $results = chado_query($sql, array(':name' => $type, ':cv_id' => $cv->cv_id));
  719. while ($obj = $results->fetchObject()) {
  720. $terms[] = $obj;
  721. }
  722. }
  723. }
  724. if(count($terms) != 1) {
  725. form_set_error("instance][settings][relationships][relationship_types",
  726. t("The term '@type' matches more than one term. Please specify its vocabulary in the format of 'vocabulary|@type'.", array('@type' => $type)));
  727. }
  728. }
  729. }
  730. }
  731. // For option2: Make sure the parent term is a valid cvterm
  732. if ($option2) {
  733. $cv_id = $settings['option2_vocab'];
  734. $supertype = $settings['option2_parent'];
  735. $term = chado_get_cvterm(array(
  736. 'name' => trim($supertype),
  737. 'cv_id' => $cv_id,
  738. ));
  739. // Tripal cv autocomplete also allow cvterm synonyms, if the parent term doesn't match
  740. // a cvterm, try cvtermsynonym
  741. if (!$term) {
  742. $synonym = chado_get_cvterm(
  743. array(
  744. 'synonym' => array(
  745. 'name' => trim($supertype),
  746. )
  747. )
  748. );
  749. if ($synonym && $synonym->cv_id->cv_id == $cv_id) {
  750. $term = $synonym;
  751. }
  752. }
  753. if (!isset($term->cvterm_id)) {
  754. form_set_error("instance][settings][relationships][option2_parent",
  755. t("The term '@type' is not a valid term for the vocabulary selected.", array('@type' => $supertype)));
  756. }
  757. }
  758. }
  759. /**
  760. * @see TripalField::validate()
  761. */
  762. public function validate($entity_type, $entity, $langcode, $items, &$errors) {
  763. // If we don't have an entity then we don't want to validate. The case
  764. // where this could happen is when a user is editing the field settings
  765. // and trying to set a default value. In that case there's no entity and
  766. // we don't want to validate. There will always be an entity for creation
  767. // and update operations of a content type.
  768. if (!$entity) {
  769. return;
  770. }
  771. $field_name = $this->field['field_name'];
  772. $field_type = $this->field['type'];
  773. $field_table = $this->instance['settings']['chado_table'];
  774. $field_column = $this->instance['settings']['chado_column'];
  775. $base_table = $this->instance['settings']['base_table'];
  776. $schema = chado_get_schema($field_table);
  777. $fkeys = $schema['foreign keys'];
  778. // 'nd_reagent_relationship' and 'project_relationship' have different column names from
  779. // subject_id/object_id. Do a pattern matching to get the column names.
  780. $subject_id_key = 'subject_id';
  781. $object_id_key = 'object_id';
  782. foreach ($schema['foreign keys'][$base_table]['columns'] AS $lcolum => $rcolum) {
  783. if (preg_match('/^subject_.*id/', $lcolum)) {
  784. $subject_id_key = $lcolum;
  785. }
  786. else if (preg_match('/^object_.*id/', $lcolum)) {
  787. $object_id_key = $lcolum;
  788. }
  789. }
  790. foreach ($items as $delta => $item) {
  791. $subject_id = $item['chado-' . $field_table . '__' . $subject_id_key];
  792. $object_id = $item['chado-' . $field_table . '__' . $object_id_key];
  793. $type_id = $item['chado-' . $field_table . '__type_id'];
  794. $type_id = isset($item['type_id']) ? $item['chado-' . $field_table . '__type_id'] : $type_id;
  795. $type_name = isset($item['type_name']) ? $item['type_name'] : '';
  796. $subject_name = $item['subject_name'];
  797. $object_name = $item['object_name'];
  798. // If the row is empty then just continue, there's nothing to validate.
  799. if (!$type_id and !$type_name and !$subject_name and !$object_name) {
  800. continue;
  801. }
  802. // Make sure we have values for all of the fields.
  803. $form_error = FALSE;
  804. if (!$type_name && !$type_id) {
  805. $errors[$field_name][$delta]['und'][] = array(
  806. 'error' => 'sbo__relationship',
  807. 'message' => t("Please provide the type of relationship."),
  808. );
  809. }
  810. if ($entity and !$subject_name) {
  811. $errors[$field_name][$delta]['und'][] = array(
  812. 'error' => 'sbo__relationship',
  813. 'message' => t("Please provide the subject of the relationship."),
  814. );
  815. }
  816. if ($entity and !$object_name) {
  817. $errors[$field_name][$delta]['und'][] = array(
  818. 'error' => 'sbo__relationship',
  819. 'message' => t("Please provide the object of the relationship."),
  820. );
  821. }
  822. if ($form_error) {
  823. continue;
  824. }
  825. // Before submitting this form we need to make sure that our subject_id and
  826. // object_ids are real records. There are two ways to get the record, either
  827. // just with the text value or with an [id: \d+] string embedded. If the
  828. // later we will pull it out.
  829. $subject_id = '';
  830. $fkey_rcolumn = $fkeys[$base_table]['columns'][$subject_id_key];
  831. $matches = array();
  832. if ($entity) {
  833. if(preg_match('/\[id: (\d+)\]/', $subject_name, $matches)) {
  834. $subject_id = $matches[1];
  835. $values = array($fkey_rcolumn => $subject_id);
  836. $subject = chado_select_record($base_table, array($fkey_rcolumn), $values);
  837. if (count($subject) == 0) {
  838. $errors[$field_name][$delta]['und'][] = array(
  839. 'error' => 'sbo__relationship',
  840. 'message' => t("The subject record cannot be found using the specified id (e.g. [id: xx])."),
  841. );
  842. }
  843. }
  844. else {
  845. $values = array('uniquename' => $subject_name);
  846. $subject = chado_select_record($base_table, array($fkey_rcolumn), $values);
  847. if (count($subject) == 0) {
  848. $errors[$field_name][$delta]['und'][] = array(
  849. 'error' => 'sbo__relationship',
  850. 'message' => t("The subject record cannot be found. Please check spelling."),
  851. );
  852. }
  853. elseif (count($subject) > 1) {
  854. $errors[$field_name][$delta]['und'][] = array(
  855. 'error' => 'sbo__relationship',
  856. 'message' => t("The subject is not unique and therefore the relationship cannot be made."),
  857. );
  858. }
  859. }
  860. }
  861. // Now check for a matching object.
  862. $object_id = '';
  863. $fkey_rcolumn = $fkeys[$base_table]['columns'][$object_id_key];
  864. $matches = array();
  865. if ($entity) {
  866. if (preg_match('/\[id: (\d+)\]/', $object_name, $matches)) {
  867. $object_id = $matches[1];
  868. $values = array($fkey_rcolumn => $object_id);
  869. $object = chado_select_record($base_table, array($fkey_rcolumn), $values);
  870. if (count($subject) == 0) {
  871. $errors[$field_name][$delta]['und'][] = array(
  872. 'error' => 'sbo__relationship',
  873. 'message' => t("The object record cannot be found using the specified id (e.g. [id: xx])."),
  874. );
  875. }
  876. }
  877. else {
  878. $values = array('uniquename' => $object_name);
  879. $object = chado_select_record($base_table, array($fkey_rcolumn), $values);
  880. if (count($object) == 0) {
  881. $errors[$field_name][$delta]['und'][] = array(
  882. 'error' => 'sbo__relationship',
  883. 'message' => t("The object record cannot be found. Please check spelling."),
  884. );;
  885. }
  886. elseif (count($object) > 1) {
  887. $errors[$field_name][$delta]['und'][] = array(
  888. 'error' => 'sbo__relationship',
  889. 'message' => t("The object is not unique and therefore the relationship cannot be made."),
  890. );
  891. }
  892. }
  893. }
  894. // Make sure that either our object or our subject refers to the base record.
  895. if ($entity) {
  896. $chado_record_id = $entity->chado_record_id;
  897. if ($object_id != $chado_record_id and $subject_id != $chado_record_id) {
  898. $errors[$field_name][$delta]['und'][] = array(
  899. 'error' => 'sbo__relationship',
  900. 'message' => t("Either the subject or the object in the relationship must refer to this record."),
  901. );
  902. }
  903. // Make sure that the object and subject are not both the same thing.
  904. if ($object_id == $subject_id) {
  905. $errors[$field_name][$delta]['und'][] = array(
  906. 'error' => 'sbo__relationship',
  907. 'message' => t("The subject and the object in the relationship cannot both refer to the same record."),
  908. );
  909. }
  910. }
  911. }
  912. }
  913. /**
  914. * @see ChadoField::queryOrder()
  915. */
  916. public function queryOrder($query, $order) {
  917. }
  918. }