PageRenderTime 88ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/application/libraries/datamapper.php

https://bitbucket.org/ramo_carlo/datamapper
PHP | 6718 lines | 3346 code | 823 blank | 2549 comment | 582 complexity | 40efb620b0121439ee9ab63d376c5edc MD5 | raw file
  1. <?php
  2. /**
  3. * Data Mapper ORM Class
  4. *
  5. * Transforms database tables into objects.
  6. *
  7. * @license MIT License
  8. * @package DataMapper ORM
  9. * @category DataMapper ORM
  10. * @author Harro Verton
  11. * @author Phil DeJarnett (up to v1.7.1)
  12. * @author Simon Stenhouse (up to v1.6.0)
  13. * @link http://datamapper.wanwizard.eu/
  14. * @version 1.8.3-dev
  15. */
  16. /**
  17. * Key for storing pre-converted classnames
  18. */
  19. define('DMZ_CLASSNAMES_KEY', '_dmz_classnames');
  20. /**
  21. * DMZ version
  22. */
  23. define('DMZ_VERSION', '1.8.3-dev');
  24. /**
  25. * Data Mapper Class
  26. *
  27. * Transforms database tables into objects.
  28. *
  29. * @package DataMapper ORM
  30. *
  31. * Properties (for code completion)
  32. * @property CI_DB_driver $db The CodeIgniter Database Library
  33. * @property CI_Loader $load The CodeIgnter Loader Library
  34. * @property CI_Language $lang The CodeIgniter Language Library
  35. * @property CI_Config $config The CodeIgniter Config Library
  36. * @property CI_Form_validation $form_validation The CodeIgniter Form Validation Library
  37. *
  38. *
  39. * Define some of the magic methods:
  40. *
  41. * Get By:
  42. * @method DataMapper get_by_id() get_by_id(int $value) Looks up an item by its ID.
  43. * @method DataMapper get_by_FIELD() get_by_FIELD(mixed $value) Looks up an item by a specific FIELD. Ex: get_by_name($user_name);
  44. * @method DataMapper get_by_related() get_by_related(mixed $related, string $field = NULL, string $value = NULL) Get results based on a related item.
  45. * @method DataMapper get_by_related_RELATEDFIELD() get_by_related_RELATEDFIELD(string $field = NULL, string $value = NULL) Get results based on a RELATEDFIELD. Ex: get_by_related_user('id', $userid);
  46. *
  47. * Save and Delete
  48. * @method DataMapper save_RELATEDFIELD() save_RELATEDFIELD(mixed $object) Saves relationship(s) using the specified RELATEDFIELD. Ex: save_user($user);
  49. * @method DataMapper delete_RELATEDFIELD() delete_RELATEDFIELD(mixed $object) Deletes relationship(s) using the specified RELATEDFIELD. Ex: delete_user($user);
  50. *
  51. * Related:
  52. * @method DataMapper where_related() where_related(mixed $related, string $field = NULL, string $value = NULL) Limits results based on a related field.
  53. * @method DataMapper where_between_related() where_related(mixed $related, string $field = NULL, string $value1 = NULL, string $value2 = NULL) Limits results based on a related field, via BETWEEN.
  54. * @method DataMapper or_where_related() or_where_related(mixed $related, string $field = NULL, string $value = NULL) Limits results based on a related field, via OR.
  55. * @method DataMapper where_in_related() where_in_related(mixed $related, string $field, array $values) Limits results by comparing a related field to a range of values.
  56. * @method DataMapper or_where_in_related() or_where_in_related(mixed $related, string $field, array $values) Limits results by comparing a related field to a range of values.
  57. * @method DataMapper where_not_in_related() where_not_in_related(mixed $related, string $field, array $values) Limits results by comparing a related field to a range of values.
  58. * @method DataMapper or_where_not_in_related() or_where_not_in_related(mixed $related, string $field, array $values) Limits results by comparing a related field to a range of values.
  59. * @method DataMapper like_related() like_related(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a related field to a value.
  60. * @method DataMapper or_like_related() like_related(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a related field to a value.
  61. * @method DataMapper not_like_related() like_related(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a related field to a value.
  62. * @method DataMapper or_not_like_related() like_related(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a related field to a value.
  63. * @method DataMapper ilike_related() like_related(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a related field to a value (case insensitive).
  64. * @method DataMapper or_ilike_related() like_related(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a related field to a value (case insensitive).
  65. * @method DataMapper not_ilike_related() like_related(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a related field to a value (case insensitive).
  66. * @method DataMapper or_not_ilike_related() like_related(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a related field to a value (case insensitive).
  67. * @method DataMapper group_by_related() group_by_related(mixed $related, string $field) Groups the query by a related field.
  68. * @method DataMapper having_related() having_related(mixed $related, string $field, string $value) Groups the querying using a HAVING clause.
  69. * @method DataMapper or_having_related() having_related(mixed $related, string $field, string $value) Groups the querying using a HAVING clause, via OR.
  70. * @method DataMapper order_by_related() order_by_related(mixed $related, string $field, string $direction) Orders the query based on a related field.
  71. *
  72. *
  73. * Join Fields:
  74. * @method DataMapper where_join_field() where_join_field(mixed $related, string $field = NULL, string $value = NULL) Limits results based on a join field.
  75. * @method DataMapper where_between_join_field() where_related(mixed $related, string $field = NULL, string $value1 = NULL, string $value2 = NULL) Limits results based on a join field, via BETWEEN.
  76. * @method DataMapper or_where_join_field() or_where_join_field(mixed $related, string $field = NULL, string $value = NULL) Limits results based on a join field, via OR.
  77. * @method DataMapper where_in_join_field() where_in_join_field(mixed $related, string $field, array $values) Limits results by comparing a join field to a range of values.
  78. * @method DataMapper or_where_in_join_field() or_where_in_join_field(mixed $related, string $field, array $values) Limits results by comparing a join field to a range of values.
  79. * @method DataMapper where_not_in_join_field() where_not_in_join_field(mixed $related, string $field, array $values) Limits results by comparing a join field to a range of values.
  80. * @method DataMapper or_where_not_in_join_field() or_where_not_in_join_field(mixed $related, string $field, array $values) Limits results by comparing a join field to a range of values.
  81. * @method DataMapper like_join_field() like_join_field(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a join field to a value.
  82. * @method DataMapper or_like_join_field() like_join_field(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a join field to a value.
  83. * @method DataMapper not_like_join_field() like_join_field(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a join field to a value.
  84. * @method DataMapper or_not_like_join_field() like_join_field(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a join field to a value.
  85. * @method DataMapper ilike_join_field() like_join_field(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a join field to a value (case insensitive).
  86. * @method DataMapper or_ilike_join_field() like_join_field(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a join field to a value (case insensitive).
  87. * @method DataMapper not_ilike_join_field() like_join_field(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a join field to a value (case insensitive).
  88. * @method DataMapper or_not_ilike_join_field() like_join_field(mixed $related, string $field, string $value, string $match = 'both') Limits results by matching a join field to a value (case insensitive).
  89. * @method DataMapper group_by_join_field() group_by_join_field(mixed $related, string $field) Groups the query by a join field.
  90. * @method DataMapper having_join_field() having_join_field(mixed $related, string $field, string $value) Groups the querying using a HAVING clause.
  91. * @method DataMapper or_having_join_field() having_join_field(mixed $related, string $field, string $value) Groups the querying using a HAVING clause, via OR.
  92. * @method DataMapper order_by_join_field() order_by_join_field(mixed $related, string $field, string $direction) Orders the query based on a join field.
  93. *
  94. * SQL Functions:
  95. * @method DataMapper select_func() select_func(string $function_name, mixed $args,..., string $alias) Selects the result of a SQL function. Alias is required.
  96. * @method DataMapper where_func() where_func(string $function_name, mixed $args,..., string $value) Limits results based on a SQL function.
  97. * @method DataMapper or_where_func() or_where_func(string $function_name, mixed $args,..., string $value) Limits results based on a SQL function, via OR.
  98. * @method DataMapper where_in_func() where_in_func(string $function_name, mixed $args,..., array $values) Limits results by comparing a SQL function to a range of values.
  99. * @method DataMapper or_where_in_func() or_where_in_func(string $function_name, mixed $args,..., array $values) Limits results by comparing a SQL function to a range of values.
  100. * @method DataMapper where_not_in_func() where_not_in_func(string $function_name, string $field, array $values) Limits results by comparing a SQL function to a range of values.
  101. * @method DataMapper or_where_not_in_func() or_where_not_in_func(string $function_name, mixed $args,..., array $values) Limits results by comparing a SQL function to a range of values.
  102. * @method DataMapper like_func() like_func(string $function_name, mixed $args,..., string $value) Limits results by matching a SQL function to a value.
  103. * @method DataMapper or_like_func() like_func(string $function_name, mixed $args,..., string $value) Limits results by matching a SQL function to a value.
  104. * @method DataMapper not_like_func() like_func(string $function_name, mixed $args,..., string $value) Limits results by matching a SQL function to a value.
  105. * @method DataMapper or_not_like_func() like_func(string $function_name, mixed $args,..., string $value) Limits results by matching a SQL function to a value.
  106. * @method DataMapper ilike_func() like_func(string $function_name, mixed $args,..., string $value) Limits results by matching a SQL function to a value (case insensitive).
  107. * @method DataMapper or_ilike_func() like_func(string $function_name, mixed $args,..., string $value) Limits results by matching a SQL function to a value (case insensitive).
  108. * @method DataMapper not_ilike_func() like_func(string $function_name, mixed $args,..., string $value) Limits results by matching a SQL function to a value (case insensitive).
  109. * @method DataMapper or_not_ilike_func() like_func(string $function_name, mixed $args,..., string $value) Limits results by matching a SQL function to a value (case insensitive).
  110. * @method DataMapper group_by_func() group_by_func(string $function_name, mixed $args,...) Groups the query by a SQL function.
  111. * @method DataMapper having_func() having_func(string $function_name, mixed $args,..., string $value) Groups the querying using a HAVING clause.
  112. * @method DataMapper or_having_func() having_func(string $function_name, mixed $args,..., string $value) Groups the querying using a HAVING clause, via OR.
  113. * @method DataMapper order_by_func() order_by_func(string $function_name, mixed $args,..., string $direction) Orders the query based on a SQL function.
  114. *
  115. * Field -> SQL functions:
  116. * @method DataMapper where_field_field_func() where_field_func($field, string $function_name, mixed $args,...) Limits results based on a SQL function.
  117. * @method DataMapper where_between_field_field_func() where_between_field_func($field, string $function_name, mixed $args,...) Limits results based on a SQL function, via BETWEEN.
  118. * @method DataMapper or_where_field_field_func() or_where_field_func($field, string $function_name, mixed $args,...) Limits results based on a SQL function, via OR.
  119. * @method DataMapper where_in_field_field_func() where_in_field_func($field, string $function_name, mixed $args,...) Limits results by comparing a SQL function to a range of values.
  120. * @method DataMapper or_where_in_field_field_func() or_where_in_field_func($field, string $function_name, mixed $args,...) Limits results by comparing a SQL function to a range of values.
  121. * @method DataMapper where_not_in_field_field_func() where_not_in_field_func($field, string $function_name, string $field) Limits results by comparing a SQL function to a range of values.
  122. * @method DataMapper or_where_not_in_field_field_func() or_where_not_in_field_func($field, string $function_name, mixed $args,...) Limits results by comparing a SQL function to a range of values.
  123. * @method DataMapper like_field_field_func() like_field_func($field, string $function_name, mixed $args,...) Limits results by matching a SQL function to a value.
  124. * @method DataMapper or_like_field_field_func() like_field_func($field, string $function_name, mixed $args,...) Limits results by matching a SQL function to a value.
  125. * @method DataMapper not_like_field_field_func() like_field_func($field, string $function_name, mixed $args,...) Limits results by matching a SQL function to a value.
  126. * @method DataMapper or_not_like_field_field_func() like_field_func($field, string $function_name, mixed $args,...) Limits results by matching a SQL function to a value.
  127. * @method DataMapper ilike_field_field_func() like_field_func($field, string $function_name, mixed $args,...) Limits results by matching a SQL function to a value (case insensitive).
  128. * @method DataMapper or_ilike_field_field_func() like_field_func($field, string $function_name, mixed $args,...) Limits results by matching a SQL function to a value (case insensitive).
  129. * @method DataMapper not_ilike_field_field_func() like_field_func($field, string $function_name, mixed $args,...) Limits results by matching a SQL function to a value (case insensitive).
  130. * @method DataMapper or_not_ilike_field_field_func() like_field_func($field, string $function_name, mixed $args,...) Limits results by matching a SQL function to a value (case insensitive).
  131. * @method DataMapper group_by_field_field_func() group_by_field_func($field, string $function_name, mixed $args,...) Groups the query by a SQL function.
  132. * @method DataMapper having_field_field_func() having_field_func($field, string $function_name, mixed $args,...) Groups the querying using a HAVING clause.
  133. * @method DataMapper or_having_field_field_func() having_field_func($field, string $function_name, mixed $args,...) Groups the querying using a HAVING clause, via OR.
  134. * @method DataMapper order_by_field_field_func() order_by_field_func($field, string $function_name, mixed $args,...) Orders the query based on a SQL function.
  135. *
  136. * Subqueries:
  137. * @method DataMapper select_subquery() select_subquery(DataMapper $subquery, string $alias) Selects the result of a function. Alias is required.
  138. * @method DataMapper where_subquery() where_subquery(mixed $subquery_or_field, mixed $value_or_subquery) Limits results based on a subquery.
  139. * @method DataMapper or_where_subquery() or_where_subquery(mixed $subquery_or_field, mixed $value_or_subquery) Limits results based on a subquery, via OR.
  140. * @method DataMapper where_in_subquery() where_in_subquery(mixed $subquery_or_field, mixed $values_or_subquery) Limits results by comparing a subquery to a range of values.
  141. * @method DataMapper or_where_in_subquery() or_where_in_subquery(mixed $subquery_or_field, mixed $values_or_subquery) Limits results by comparing a subquery to a range of values.
  142. * @method DataMapper where_not_in_subquery() where_not_in_subquery(mixed $subquery_or_field, string $field, mixed $values_or_subquery) Limits results by comparing a subquery to a range of values.
  143. * @method DataMapper or_where_not_in_subquery() or_where_not_in_subquery(mixed $subquery_or_field, mixed $values_or_subquery) Limits results by comparing a subquery to a range of values.
  144. * @method DataMapper like_subquery() like_subquery(DataMapper $subquery, string $value, string $match = 'both') Limits results by matching a subquery to a value.
  145. * @method DataMapper or_like_subquery() like_subquery(DataMapper $subquery, string $value, string $match = 'both') Limits results by matching a subquery to a value.
  146. * @method DataMapper not_like_subquery() like_subquery(DataMapper $subquery, string $value, string $match = 'both') Limits results by matching a subquery to a value.
  147. * @method DataMapper or_not_like_subquery() like_subquery(DataMapper $subquery, string $value, string $match = 'both') Limits results by matching a subquery to a value.
  148. * @method DataMapper ilike_subquery() like_subquery(DataMapper $subquery, string $value, string $match = 'both') Limits results by matching a subquery to a value (case insensitive).
  149. * @method DataMapper or_ilike_subquery() like_subquery(DataMapper $subquery, string $value, string $match = 'both') Limits results by matching a subquery to a value (case insensitive).
  150. * @method DataMapper not_ilike_subquery() like_subquery(DataMapper $subquery, string $value, string $match = 'both') Limits results by matching a subquery to a value (case insensitive).
  151. * @method DataMapper or_not_ilike_subquery() like_subquery(DataMapper $subquery, string $value, string $match = 'both') Limits results by matching a subquery to a value (case insensitive).
  152. * @method DataMapper having_subquery() having_subquery(string $field, DataMapper $subquery) Groups the querying using a HAVING clause.
  153. * @method DataMapper or_having_subquery() having_subquery(string $field, DataMapper $subquery) Groups the querying using a HAVING clause, via OR.
  154. * @method DataMapper order_by_subquery() order_by_subquery(DataMapper $subquery, string $direction) Orders the query based on a subquery.
  155. *
  156. * Related Subqueries:
  157. * @method DataMapper where_related_subquery() where_related_subquery(mixed $related_model, string $related_field, DataMapper $subquery) Limits results based on a subquery.
  158. * @method DataMapper or_where_related_subquery() or_where_related_subquery(mixed $related_model, string $related_field, DataMapper $subquery) Limits results based on a subquery, via OR.
  159. * @method DataMapper where_in_related_subquery() where_in_related_subquery(mixed $related_model, string $related_field, DataMapper $subquery) Limits results by comparing a subquery to a range of values.
  160. * @method DataMapper or_where_in_related_subquery() or_where_in_related_subquery(mixed $related_model, string $related_field, DataMapper $subquery) Limits results by comparing a subquery to a range of values.
  161. * @method DataMapper where_not_in_related_subquery() where_not_in_related_subquery(mixed $related_model, string $related_field, DataMapper $subquery) Limits results by comparing a subquery to a range of values.
  162. * @method DataMapper or_where_not_in_related_subquery() or_where_not_in_related_subquery(mixed $related_model, string $related_field, DataMapper $subquery) Limits results by comparing a subquery to a range of values.
  163. * @method DataMapper having_related_subquery() having_related_subquery(mixed $related_model, string $related_field, DataMapper $subquery) Groups the querying using a HAVING clause.
  164. * @method DataMapper or_having_related_subquery() having_related_subquery(mixed $related_model, string $related_field, DataMapper $subquery) Groups the querying using a HAVING clause, via OR.
  165. *
  166. * Array Extension:
  167. * @method array to_array() to_array($fields = '') NEEDS ARRAY EXTENSION. Converts this object into an associative array. @link DMZ_Array::to_array
  168. * @method array all_to_array() all_to_array($fields = '') NEEDS ARRAY EXTENSION. Converts the all array into an associative array. @link DMZ_Array::all_to_array
  169. * @method array|bool from_array() from_array($data, $fields = '', $save = FALSE) NEEDS ARRAY EXTENSION. Converts $this->all into an associative array. @link DMZ_Array::all_to_array
  170. *
  171. * CSV Extension
  172. * @method bool csv_export() csv_export($filename, $fields = '', $include_header = TRUE) NEEDS CSV EXTENSION. Exports this object as a CSV file.
  173. * @method array csv_import() csv_import($filename, $fields = '', $header_row = TRUE, $callback = NULL) NEEDS CSV EXTENSION. Imports a CSV file into this object.
  174. *
  175. * JSON Extension:
  176. * @method string to_json() to_json($fields = '', $pretty_print = FALSE) NEEDS JSON EXTENSION. Converts this object into a JSON string.
  177. * @method string all_to_json() all_to_json($fields = '', $pretty_print = FALSE) NEEDS JSON EXTENSION. Converts the all array into a JSON string.
  178. * @method bool from_json() from_json($json, $fields = '') NEEDS JSON EXTENSION. Imports the values from a JSON string into this object.
  179. * @method void set_json_content_type() set_json_content_type() NEEDS JSON EXTENSION. Sets the content type header to Content-Type: application/json.
  180. *
  181. * SimpleCache Extension:
  182. * @method DataMapper get_cached() get_cached($limit = '', $offset = '') NEEDS SIMPLECACHE EXTENSION. Enables cacheable queries.
  183. * @method DataMapper clear_cache() get_cached($segment,...) NEEDS SIMPLECACHE EXTENSION. Clears a cache for the specfied segment.
  184. *
  185. * Translate Extension:
  186. *
  187. * Nestedsets Extension:
  188. *
  189. */
  190. class DataMapper implements IteratorAggregate {
  191. /**
  192. * Stores the shared configuration
  193. * @var array
  194. */
  195. static $config = array();
  196. /**
  197. * Stores settings that are common across a specific Model
  198. * @var array
  199. */
  200. static $common = array(DMZ_CLASSNAMES_KEY => array());
  201. /**
  202. * Stores global extensions
  203. * @var array
  204. */
  205. static $global_extensions = array();
  206. /**
  207. * Used to override unset default properties.
  208. * @var array
  209. */
  210. static $_dmz_config_defaults = array(
  211. 'prefix' => '',
  212. 'join_prefix' => '',
  213. 'error_prefix' => '<span class="error">',
  214. 'error_suffix' => '</span>',
  215. 'created_field' => 'created',
  216. 'updated_field' => 'updated',
  217. 'local_time' => FALSE,
  218. 'unix_timestamp' => FALSE,
  219. 'timestamp_format' => 'Y-m-d H:i:s',
  220. 'lang_file_format' => 'model_${model}',
  221. 'field_label_lang_format' => '${model}_${field}',
  222. 'auto_transaction' => FALSE,
  223. 'auto_populate_has_many' => FALSE,
  224. 'auto_populate_has_one' => TRUE,
  225. 'all_array_uses_ids' => FALSE,
  226. 'db_params' => '',
  227. 'extensions' => array(),
  228. 'extensions_path' => 'datamapper',
  229. );
  230. /**
  231. * Contains any errors that occur during validation, saving, or other
  232. * database access.
  233. * @var DM_Error_Object
  234. */
  235. public $error;
  236. /**
  237. * Used to keep track of the original values from the database, to
  238. * prevent unecessarily changing fields.
  239. * @var object
  240. */
  241. public $stored;
  242. /**
  243. * The name of the table for this model (may be automatically generated
  244. * from the classname).
  245. * @var string
  246. */
  247. public $table = '';
  248. /**
  249. * The singular name for this model (may be automatically generated from
  250. * the classname).
  251. * @var string
  252. */
  253. public $model = '';
  254. /**
  255. * The primary key used for this models table
  256. * the classname).
  257. * @var string
  258. */
  259. public $primary_key = 'id';
  260. /**
  261. * The result of validate is stored here.
  262. * @var bool
  263. */
  264. public $valid = FALSE;
  265. /**
  266. * delete relations on delete of an object. Defaults to TRUE.
  267. * set to FALSE if you RDBMS takes care of this using constraints
  268. * @var bool
  269. */
  270. public $cascade_delete = TRUE;
  271. /**
  272. * Contains the database fields for this object.
  273. * ** Automatically configured **
  274. * @var array
  275. */
  276. public $fields = array();
  277. /**
  278. * Contains the result of the last query.
  279. * @var array
  280. */
  281. public $all = array();
  282. /**
  283. * Semi-private field used to track the parent model/id if there is one.
  284. * @var array
  285. */
  286. public $parent = array();
  287. /**
  288. * Contains the validation rules, label, and get_rules for each field.
  289. * @var array
  290. */
  291. public $validation = array();
  292. /**
  293. * Contains any related objects of which this model is related one or more times.
  294. * @var array
  295. */
  296. public $has_many = array();
  297. /**
  298. * Contains any related objects of which this model is singularly related.
  299. * @var array
  300. */
  301. public $has_one = array();
  302. /**
  303. * Used to enable or disable the production cache.
  304. * This should really only be set in the global configuration.
  305. * @var bool
  306. */
  307. public $production_cache = FALSE;
  308. /**
  309. * If a query returns more than the number of rows specified here,
  310. * then it will be automatically freed after a get.
  311. * @var int
  312. */
  313. public $free_result_threshold = 100;
  314. /**
  315. * This can be specified as an array of fields to sort by if no other
  316. * sorting or selection has occurred.
  317. * @var mixed
  318. */
  319. public $default_order_by = NULL;
  320. // tracks whether or not the object has already been validated
  321. protected $_validated = FALSE;
  322. // tracks whether validation needs to be forced before save
  323. protected $_force_validation = FALSE;
  324. // Tracks the columns that need to be instantiated after a GET
  325. protected $_instantiations = NULL;
  326. // Tracks get_rules, matches, and intval rules, to spped up _to_object
  327. protected $_field_tracking = NULL;
  328. // used to track related queries in deep relationships.
  329. protected $_query_related = array();
  330. // If true before a related get(), any extra fields on the join table will be added.
  331. protected $_include_join_fields = FALSE;
  332. // If true before a save, this will force the next save to be new.
  333. protected $_force_save_as_new = FALSE;
  334. // If true, the next where statement will not be prefixed with an AND or OR.
  335. protected $_where_group_started = FALSE;
  336. // Tracks total number of groups created
  337. protected $_group_count = 0;
  338. // storage for additional model paths for the autoloader
  339. protected static $model_paths = array();
  340. /**
  341. * Constructors (both PHP4 and PHP5 style, to stay compatible)
  342. *
  343. * Initialize DataMapper.
  344. * @param int $id if provided, load in the object specified by that ID.
  345. */
  346. public function __construct($id = NULL)
  347. {
  348. return $this->DataMapper($id);
  349. }
  350. public function DataMapper($id = NULL)
  351. {
  352. $this->_dmz_assign_libraries();
  353. $this_class = strtolower(get_class($this));
  354. $is_dmz = $this_class == 'datamapper';
  355. if($is_dmz)
  356. {
  357. $this->_load_languages();
  358. $this->_load_helpers();
  359. }
  360. // this is to ensure that singular is only called once per model
  361. if(isset(DataMapper::$common[DMZ_CLASSNAMES_KEY][$this_class])) {
  362. $common_key = DataMapper::$common[DMZ_CLASSNAMES_KEY][$this_class];
  363. } else {
  364. DataMapper::$common[DMZ_CLASSNAMES_KEY][$this_class] = $common_key = singular($this_class);
  365. }
  366. // Determine model name
  367. if (empty($this->model))
  368. {
  369. $this->model = $common_key;
  370. }
  371. // If model is 'datamapper' then this is the initial autoload by CodeIgniter
  372. if ($is_dmz)
  373. {
  374. // Load config settings
  375. $this->config->load('datamapper', TRUE, TRUE);
  376. // Get and store config settings
  377. DataMapper::$config = $this->config->item('datamapper');
  378. // now double check that all required config values were set
  379. foreach(DataMapper::$_dmz_config_defaults as $config_key => $config_value)
  380. {
  381. if( ! array_key_exists($config_key, DataMapper::$config))
  382. {
  383. DataMapper::$config[$config_key] = $config_value;
  384. }
  385. }
  386. DataMapper::_load_extensions(DataMapper::$global_extensions, DataMapper::$config['extensions']);
  387. unset(DataMapper::$config['extensions']);
  388. return;
  389. }
  390. // Load stored config settings by reference
  391. foreach (DataMapper::$config as $config_key => &$config_value)
  392. {
  393. // Only if they're not already set
  394. if ( ! property_exists($this, $config_key))
  395. {
  396. $this->{$config_key} = $config_value;
  397. }
  398. }
  399. // Load model settings if not in common storage
  400. if ( ! isset(DataMapper::$common[$common_key]))
  401. {
  402. // load language file, if requested and it exists
  403. if(!empty($this->lang_file_format))
  404. {
  405. $lang_file = str_replace(array('${model}', '${table}'), array($this->model, $this->table), $this->lang_file_format);
  406. $deft_lang = $this->config->item('language');
  407. $idiom = ($deft_lang == '') ? 'english' : $deft_lang;
  408. if(file_exists(APPPATH.'language/'.$idiom.'/'.$lang_file.'_lang'.EXT))
  409. {
  410. $this->lang->load($lang_file, $idiom);
  411. }
  412. }
  413. $loaded_from_cache = FALSE;
  414. // Load in the production cache for this model, if it exists
  415. if( ! empty(DataMapper::$config['production_cache']))
  416. {
  417. // check if it's a fully qualified path first
  418. if (!is_dir($cache_folder = DataMapper::$config['production_cache']))
  419. {
  420. // if not, it's relative to the application path
  421. $cache_folder = APPPATH . DataMapper::$config['production_cache'];
  422. }
  423. if(file_exists($cache_folder) && is_dir($cache_folder) && is_writeable($cache_folder))
  424. {
  425. $cache_file = $cache_folder . '/' . $common_key . EXT;
  426. if(file_exists($cache_file))
  427. {
  428. include($cache_file);
  429. if(isset($cache))
  430. {
  431. DataMapper::$common[$common_key] =& $cache;
  432. unset($cache);
  433. // allow subclasses to add initializations
  434. if(method_exists($this, 'post_model_init'))
  435. {
  436. $this->post_model_init(TRUE);
  437. }
  438. // Load extensions (they are not cacheable)
  439. $this->_initiate_local_extensions($common_key);
  440. $loaded_from_cache = TRUE;
  441. }
  442. }
  443. }
  444. }
  445. if(! $loaded_from_cache)
  446. {
  447. // Determine table name
  448. if (empty($this->table))
  449. {
  450. $this->table = strtolower(plural(get_class($this)));
  451. }
  452. // Add prefix to table
  453. $this->table = $this->prefix . $this->table;
  454. $this->_field_tracking = array(
  455. 'get_rules' => array(),
  456. 'matches' => array(),
  457. 'intval' => array('id')
  458. );
  459. // Convert validation into associative array by field name
  460. $associative_validation = array();
  461. foreach ($this->validation as $name => $validation)
  462. {
  463. if(is_string($name)) {
  464. $validation['field'] = $name;
  465. } else {
  466. $name = $validation['field'];
  467. }
  468. // clean up possibly missing fields
  469. if( ! isset($validation['rules']))
  470. {
  471. $validation['rules'] = array();
  472. }
  473. // Populate associative validation array
  474. $associative_validation[$name] = $validation;
  475. if (!empty($validation['get_rules']))
  476. {
  477. $this->_field_tracking['get_rules'][] = $name;
  478. }
  479. // Check if there is a "matches" validation rule
  480. if (isset($validation['rules']['matches']))
  481. {
  482. $this->_field_tracking['matches'][$name] = $validation['rules']['matches'];
  483. }
  484. }
  485. // set up id column, if not set
  486. if(!isset($associative_validation['id']))
  487. {
  488. // label is set below, to prevent caching language-based labels
  489. $associative_validation['id'] = array(
  490. 'field' => 'id',
  491. 'rules' => array('integer')
  492. );
  493. }
  494. $this->validation = $associative_validation;
  495. // Force all other has_one ITFKs to integers on get
  496. foreach($this->has_one as $related => $rel_props)
  497. {
  498. $field = $related . '_id';
  499. if( in_array($field, $this->fields) &&
  500. ( ! isset($this->validation[$field]) || // does not have a validation key or...
  501. ! isset($this->validation[$field]['get_rules'])) && // a get_rules key...
  502. ( ! isset($this->validation[$related]) || // nor does the related have a validation key or...
  503. ! isset($this->validation[$related]['get_rules'])) ) // a get_rules key
  504. {
  505. // assume an int
  506. $this->_field_tracking['intval'][] = $field;
  507. }
  508. }
  509. // Get and store the table's field names and meta data
  510. $fields = $this->db->field_data($this->table);
  511. // Store only the field names and ensure validation list includes all fields
  512. foreach ($fields as $field)
  513. {
  514. // Populate fields array
  515. $this->fields[] = $field->name;
  516. // Add validation if current field has none
  517. if ( ! isset($this->validation[$field->name]))
  518. {
  519. // label is set below, to prevent caching language-based labels
  520. $this->validation[$field->name] = array('field' => $field->name, 'rules' => array());
  521. }
  522. }
  523. // convert simple has_one and has_many arrays into more advanced ones
  524. foreach(array('has_one', 'has_many') as $arr)
  525. {
  526. foreach ($this->{$arr} as $related_field => $rel_props)
  527. {
  528. // process the relationship
  529. $this->_relationship($arr, $rel_props, $related_field);
  530. }
  531. }
  532. // allow subclasses to add initializations
  533. if(method_exists($this, 'post_model_init'))
  534. {
  535. $this->post_model_init(FALSE);
  536. }
  537. // Store common model settings
  538. foreach (array('table', 'fields', 'validation',
  539. 'has_one', 'has_many', '_field_tracking') as $item)
  540. {
  541. DataMapper::$common[$common_key][$item] = $this->{$item};
  542. }
  543. // store the item to the production cache
  544. $this->production_cache();
  545. // Load extensions last, so they aren't cached.
  546. $this->_initiate_local_extensions($common_key);
  547. }
  548. // define any custom module path present so we can find the model
  549. foreach(array('has_one', 'has_many') as $arr)
  550. {
  551. foreach ($this->{$arr} as $related_field => $rel_props)
  552. {
  553. // process the model custom paths if present
  554. if( isset($rel_props['model_path']))
  555. {
  556. $rel_props['model_path'] = rtrim($rel_props['model_path'], '/') . '/';
  557. if ( is_dir($rel_props['model_path'].'models') && ! in_array($rel_props['model_path'], self::$model_paths))
  558. {
  559. self::$model_paths[] = $rel_props['model_path'];
  560. }
  561. }
  562. }
  563. }
  564. // Finally, localize the labels here (because they shouldn't be cached
  565. // This also sets any missing labels.
  566. $validation =& DataMapper::$common[$common_key]['validation'];
  567. foreach($validation as $field => &$val)
  568. {
  569. // Localize label if necessary
  570. $val['label'] = $this->localize_label($field,
  571. isset($val['label']) ?
  572. $val['label'] :
  573. FALSE);
  574. }
  575. unset($validation);
  576. }
  577. // Load stored common model settings by reference
  578. foreach(DataMapper::$common[$common_key] as $key => &$value)
  579. {
  580. $this->{$key} = $value;
  581. }
  582. // Clear object properties to set at default values
  583. $this->clear();
  584. if( ! empty($id) && is_numeric($id))
  585. {
  586. $this->get_by_id(intval($id));
  587. }
  588. }
  589. // --------------------------------------------------------------------
  590. /**
  591. * Reloads in the configuration data for a model. This is mainly
  592. * used to handle language changes. Only this instance and new instances
  593. * will see the changes.
  594. */
  595. public function reinitialize_model()
  596. {
  597. // determine the classname
  598. $this_class = strtolower(get_class($this));
  599. // this is to ensure that singular is only called once per model
  600. if(isset(DataMapper::$common[DMZ_CLASSNAMES_KEY][$this_class])) {
  601. $common_key = DataMapper::$common[DMZ_CLASSNAMES_KEY][$this_class];
  602. } else {
  603. DataMapper::$common[DMZ_CLASSNAMES_KEY][$this_class] = $common_key = singular($this_class);
  604. }
  605. unset(DataMapper::$common[$common_key]);
  606. $model = get_class($this);
  607. new $model(); // re-initialze
  608. // Load stored common model settings by reference
  609. foreach(DataMapper::$common[$common_key] as $key => &$value)
  610. {
  611. $this->{$key} =& $value;
  612. }
  613. }
  614. // --------------------------------------------------------------------
  615. /**
  616. * Autoload
  617. *
  618. * Autoloads object classes that are used with DataMapper.
  619. * This method will look in any model directories available to CI.
  620. *
  621. * Note:
  622. * It is important that they are autoloaded as loading them manually with
  623. * CodeIgniter's loader class will cause DataMapper's __get and __set functions
  624. * to not function.
  625. *
  626. * @param string $class Name of class to load.
  627. */
  628. public static function autoload($class)
  629. {
  630. static $CI = NULL;
  631. // get the CI instance
  632. is_null($CI) AND $CI =& get_instance();
  633. // Don't attempt to autoload CI_ , EE_, or custom prefixed classes
  634. if (in_array(substr($class, 0, 3), array('CI_', 'EE_')) OR strpos($class, $CI->config->item('subclass_prefix')) === 0)
  635. {
  636. return;
  637. }
  638. // Prepare class
  639. $class = strtolower($class);
  640. // Prepare path
  641. $paths = array();
  642. if (method_exists($CI->load, 'get_package_paths'))
  643. {
  644. // use CI 2.0 loader's model paths
  645. $paths = $CI->load->get_package_paths(false);
  646. }
  647. foreach (array_merge(array(APPPATH),$paths, self::$model_paths) as $path)
  648. {
  649. // Prepare file
  650. $file = $path . 'models/' . $class . EXT;
  651. // Check if file exists, require_once if it does
  652. if (file_exists($file))
  653. {
  654. require_once($file);
  655. break;
  656. }
  657. }
  658. // if class not loaded, do a recursive search of model paths for the class
  659. if (! class_exists($class))
  660. {
  661. foreach($paths as $path)
  662. {
  663. $found = DataMapper::recursive_require_once($class, $path . 'models');
  664. if($found)
  665. {
  666. break;
  667. }
  668. }
  669. }
  670. }
  671. // --------------------------------------------------------------------
  672. /**
  673. * Add Model Path
  674. *
  675. * Manually add paths for the model autoloader
  676. *
  677. * @param mixed $paths path or array of paths to search
  678. */
  679. public static function add_model_path($paths)
  680. {
  681. // make sure paths is an array
  682. is_array($paths) OR $paths = array($paths);
  683. foreach($paths as $path)
  684. {
  685. $path = rtrim($path, '/') . '/';
  686. if ( is_dir($path.'models') && ! in_array($path, self::$model_paths))
  687. {
  688. self::$model_paths[] = $path;
  689. }
  690. }
  691. }
  692. // --------------------------------------------------------------------
  693. /**
  694. * Recursive Require Once
  695. *
  696. * Recursively searches the path for the class, require_once if found.
  697. *
  698. * @param string $class Name of class to look for
  699. * @param string $path Current path to search
  700. */
  701. protected static function recursive_require_once($class, $path)
  702. {
  703. $found = FALSE;
  704. if(is_dir($path))
  705. {
  706. $handle = opendir($path);
  707. if ($handle)
  708. {
  709. while (FALSE !== ($dir = readdir($handle)))
  710. {
  711. // If dir does not contain a dot
  712. if (strpos($dir, '.') === FALSE)
  713. {
  714. // Prepare recursive path
  715. $recursive_path = $path . '/' . $dir;
  716. // Prepare file
  717. $file = $recursive_path . '/' . $class . EXT;
  718. // Check if file exists, require_once if it does
  719. if (file_exists($file))
  720. {
  721. require_once($file);
  722. $found = TRUE;
  723. break;
  724. }
  725. else if (is_dir($recursive_path))
  726. {
  727. // Do a recursive search of the path for the class
  728. DataMapper::recursive_require_once($class, $recursive_path);
  729. }
  730. }
  731. }
  732. closedir($handle);
  733. }
  734. }
  735. return $found;
  736. }
  737. // --------------------------------------------------------------------
  738. /**
  739. * Loads in any extensions used by this class or globally.
  740. *
  741. * @param array $extensions List of extensions to add to.
  742. * @param array $name List of new extensions to load.
  743. */
  744. protected static function _load_extensions(&$extensions, $names)
  745. {
  746. static $CI = NULL;
  747. // get the CI instance
  748. is_null($CI) AND $CI =& get_instance();
  749. $class_prefixes = array(
  750. 0 => 'DMZ_',
  751. 1 => 'DataMapper_',
  752. 2 => $CI->config->item('subclass_prefix'),
  753. 3 => 'CI_'
  754. );
  755. foreach($names as $name => $options)
  756. {
  757. if( ! is_string($name))
  758. {
  759. $name = $options;
  760. $options = NULL;
  761. }
  762. // only load an extension if it wasn't already loaded in this context
  763. if(isset($extensions[$name]))
  764. {
  765. return;
  766. }
  767. if( ! isset($extensions['_methods']))
  768. {
  769. $extensions['_methods'] = array();
  770. }
  771. // determine the file name and class name
  772. $file = DataMapper::$config['extensions_path'] . '/' . $name . EXT;
  773. if ( ! file_exists($file))
  774. {
  775. if(strpos($name, '/') === FALSE)
  776. {
  777. $file = APPPATH . DataMapper::$config['extensions_path'] . '/' . $name . EXT;
  778. $ext = $name;
  779. }
  780. else
  781. {
  782. $file = APPPATH . $name . EXT;
  783. $ext = array_pop(explode('/', $name));
  784. }
  785. if(!file_exists($file))
  786. {
  787. show_error('DataMapper Error: loading extension ' . $name . ': File not found.');
  788. }
  789. }
  790. else
  791. {
  792. $ext = $name;
  793. }
  794. // load class
  795. include_once($file);
  796. // Allow for DMZ_Extension, DataMapper_Extension, etc.
  797. foreach($class_prefixes as $index => $prefix)
  798. {
  799. if(class_exists($prefix.$ext))
  800. {
  801. if($index == 2) // "MY_"
  802. {
  803. // Load in the library this class is based on
  804. $CI->load->library($ext);
  805. }
  806. $ext = $prefix.$ext;
  807. break;
  808. }
  809. }
  810. if(!class_exists($ext))
  811. {
  812. show_error("DataMapper Error: Unable to find a class for extension $name.");
  813. }
  814. // create class
  815. if(is_null($options))
  816. {
  817. $o = new $ext(NULL, isset($this) ? $this : NULL);
  818. }
  819. else
  820. {
  821. $o = new $ext($options, isset($this) ? $this : NULL);
  822. }
  823. $extensions[$name] = $o;
  824. // figure out which methods can be called on this class.
  825. $methods = get_class_methods($ext);
  826. foreach($methods as $m)
  827. {
  828. // do not load private methods or methods already loaded.
  829. if($m[0] !== '_' &&
  830. is_callable(array($o, $m)) &&
  831. ! isset($extensions['_methods'][$m])
  832. ) {
  833. // store this method.
  834. $extensions['_methods'][$m] = $name;
  835. }
  836. }
  837. }
  838. }
  839. // --------------------------------------------------------------------
  840. /**
  841. * Loads the extensions that are local to this model.
  842. * @param string $common_key Shared key to save extenions to.
  843. */
  844. protected function _initiate_local_extensions($common_key)
  845. {
  846. if(!empty($this->extensions))
  847. {
  848. $extensions = $this->extensions;
  849. $this->extensions = array();
  850. DataMapper::_load_extensions($this->extensions, $extensions);
  851. }
  852. else
  853. {
  854. // ensure an empty array
  855. $this->extensions = array('_methods' => array());
  856. }
  857. // bind to the shared key, for dynamic loading
  858. DataMapper::$common[$common_key]['extensions'] =& $this->extensions;
  859. }
  860. // --------------------------------------------------------------------
  861. /**
  862. * Dynamically load an extension when needed.
  863. * @param object $name Name of the extension (or array of extensions).
  864. * @param array $options Options for the extension
  865. * @param boolean $local If TRUE, only loads the extension into this object
  866. */
  867. public function load_extension($name, $options = NULL, $local = FALSE)
  868. {
  869. if( ! is_array($name))
  870. {
  871. if( ! is_null($options))
  872. {
  873. $name = array($name => $options);
  874. }
  875. else
  876. {
  877. $name = array($name);
  878. }
  879. }
  880. // called individually to ensure that the array is modified directly
  881. // (and not copied instead)
  882. if($local)
  883. {
  884. DataMapper::_load_extensions($this->extensions, $name);
  885. }
  886. else
  887. {
  888. DataMapper::_load_extensions(DataMapper::$global_extensions, $name);
  889. }
  890. }
  891. // --------------------------------------------------------------------
  892. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  893. * *
  894. * Magic methods *
  895. * *
  896. * The following are methods to override the default PHP behaviour. *
  897. * *
  898. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  899. // --------------------------------------------------------------------
  900. /**
  901. * Magic Get
  902. *
  903. * Returns the value of the named property.
  904. * If named property is a related item, instantiate it first.
  905. *
  906. * This method also instantiates the DB object and the form_validation
  907. * objects as necessary
  908. *
  909. * @ignore
  910. * @param string $name Name of property to look for
  911. * @return mixed
  912. */
  913. public function __get($name)
  914. {
  915. static $CI = NULL;
  916. // get the CI instance
  917. is_null($CI) AND $CI =& get_instance();
  918. // We dynamically get DB when needed, and create a copy.
  919. // This allows multiple queries to be generated at the same time.
  920. if($name == 'db')
  921. {
  922. if($this->db_params === FALSE)
  923. {
  924. if ( ! isset($CI->db) || ! is_object($CI->db) || ! isset($CI->db->dbdriver) )
  925. {
  926. show_error('DataMapper Error: CodeIgniter database library not loaded.');
  927. }
  928. $this->db =& $CI->db;
  929. }
  930. else
  931. {
  932. if($this->db_params == '' || $this->db_params === TRUE)
  933. {
  934. if ( ! isset($CI->db) || ! is_object($CI->db) || ! isset($CI->db->dbdriver) )
  935. {
  936. show_error('DataMapper Error: CodeIgniter database library not loaded.');
  937. }
  938. // ensure the shared DB is disconnected, even if the app exits uncleanly
  939. if(!isset($CI->db->_has_shutdown_hook))
  940. {
  941. register_shutdown_function(array($CI->db, 'close'));
  942. $CI->db->_has_shutdown_hook = TRUE;
  943. }
  944. // clone, so we don't create additional connections to the DB
  945. $this->db = clone($CI->db);
  946. $this->db->dm_call_method('_reset_select');
  947. }
  948. else
  949. {
  950. // connecting to a different database, so we *must* create additional copies.
  951. // It is up to the developer to close the connection!
  952. $this->db = $CI->load->database($this->db_params, TRUE, TRUE);
  953. }
  954. // these items are shared (for debugging)
  955. if(is_object($CI->db) && isset($CI->db->dbdriver))
  956. {
  957. $this->db->queries =& $CI->db->queries;
  958. $this->db->query_times =& $CI->db->query_times;
  959. }
  960. }
  961. // ensure the created DB is disconnected, even if the app exits uncleanly
  962. if(!isset($this->db->_has_shutdown_hook))
  963. {
  964. register_shutdown_function(array($this->db, 'close'));
  965. $this->db->_has_shutdown_hook = TRUE;
  966. }
  967. return $this->db;
  968. }
  969. // Special case to get form_validation when first accessed
  970. if($name == 'form_validation')
  971. {
  972. if ( ! isset($this->form_validation) )
  973. {
  974. isset($CI->form_validation) OR $CI->load->library('form_validation');
  975. $this->form_validation =& $CI->form_validation;
  976. $this->lang->load('form_validation');
  977. }
  978. return $this->form_validation;
  979. }
  980. $has_many = isset($this->has_many[$name]);
  981. $has_one = isset($this->has_one[$name]);
  982. // If named property is a "has many" or "has one" related item
  983. if ($has_many || $has_one)
  984. {
  985. $related_properties = $has_many ? $this->has_many[$name] : $this->has_one[$name];
  986. // Instantiate it before accessing
  987. $class = $related_properties['class'];
  988. $this->{$name} = new $class();
  989. // Store parent data
  990. $this->{$name}->parent = array('model' => $related_properties['other_field'], 'id' => $this->id);
  991. // Check if Auto Populate for "has many" or "has one" is on
  992. // (but only if this object exists in the DB, and we aren't instantiating)
  993. if ($this->exists() &&
  994. ($has_many && ($this->auto_populate_has_many || $this->has_many[$name]['auto_populate'])) || ($has_one && ($this->auto_populate_has_one || $this->has_one[$name]['auto_populate'])))
  995. {
  996. $this->{$name}->get();
  997. }
  998. return $this->{$name};
  999. }
  1000. $name_single = singular($name);
  1001. if($name_single !== $name) {
  1002. // possibly return single form of name
  1003. $test = $this->{$name_single};
  1004. if(is_object($test)) {
  1005. return $test;
  1006. }
  1007. }
  1008. return NULL;
  1009. }
  1010. // --------------------------------------------------------------------
  1011. /**
  1012. * Used several places to temporarily override the auto_populate setting
  1013. * @ignore
  1014. * @param string $related Related Name
  1015. * @return DataMapper|NULL
  1016. */
  1017. protected function &_get_without_auto_populating($related)
  1018. {
  1019. $b_many = $this->auto_populate_has_many;
  1020. $b_one = $this->auto_populate_has_one;
  1021. $this->auto_populate_has_many = FALSE;
  1022. $this->auto_populate_has_one = FALSE;
  1023. $ret =& $this->{$related};
  1024. $this->auto_populate_has_many = $b_many;
  1025. $this->auto_populate_has_one = $b_one;
  1026. return $ret;
  1027. }
  1028. // --------------------------------------------------------------------
  1029. /**
  1030. * Magic Call
  1031. *
  1032. * Calls special methods, or extension methods.
  1033. *
  1034. * @ignore
  1035. * @param string $method Method name
  1036. * @param array $arguments Arguments to method
  1037. * @return mixed
  1038. */
  1039. public function __call($method, $arguments)
  1040. {
  1041. // List of watched method names
  1042. // NOTE: order matters: make sure more specific items are listed before
  1043. // less specific items
  1044. static $watched_methods = array(
  1045. 'save_', 'delete_',
  1046. 'get_by_related_', 'get_by_related', 'get_by_',
  1047. '_related_subquery', '_subquery',
  1048. '_related_', '_related',
  1049. '_join_field',
  1050. '_field_func', '_func'
  1051. );
  1052. $ext = NULL;
  1053. // attempt to call an extension first
  1054. if($this->_extension_method_exists($method, 'local'))
  1055. {
  1056. $name = $this->extensions['_methods'][$method];
  1057. $ext = $this->extensions[$name];
  1058. }
  1059. elseif($this->_extension_method_exists($method, 'global'))
  1060. {
  1061. $name = DataMapper::$global_extensions['_methods'][$method];
  1062. $ext = DataMapper::$global_extensions[$name];
  1063. }
  1064. else
  1065. {
  1066. foreach ($watched_methods as $watched_method)
  1067. {
  1068. // See if called method is a watched method
  1069. if (strpos($method, $watched_method) !== FALSE)
  1070. {
  1071. $pieces = explode($watched_method, $method);
  1072. if ( ! empty($pieces[0]) && ! empty($pieces[1]))
  1073. {
  1074. // Watched method is in the middle
  1075. return $this->{'_' . trim($watched_method, '_')}($pieces[0], array_merge(array($pieces[1]), $arguments));
  1076. }
  1077. else
  1078. {
  1079. // Watched method is a prefix or suffix
  1080. return $this->{'_' . trim($watched_method, '_')}(str_replace($watched_method, '', $method), $arguments);
  1081. }
  1082. }
  1083. }
  1084. }
  1085. if( ! is_null($ext))
  1086. {
  1087. array_unshift($arguments, $this);
  1088. return call_user_func_array(array($ext, $method), $arguments);
  1089. }
  1090. // show an error, for debugging's sake.
  1091. throw new Exception("Unable to call the method \"$method\" on the class " . get_class($this));
  1092. }
  1093. // --------------------------------------------------------------------
  1094. /**
  1095. * Returns TRUE or FALSE if the method exists in the extensions.
  1096. *
  1097. * @param object $method Method to look for.
  1098. * @param object $which One of 'both', 'local', or 'global'
  1099. * @return bool TRUE if the method can be called.
  1100. */
  1101. protected function _extension_method_exists($method, $which = 'both') {
  1102. $found = FALSE;
  1103. if($which != 'global') {
  1104. $found = ! empty($this->extensions) && isset($this->extensions['_methods'][$method]);
  1105. }
  1106. if( ! $found && $which != 'local' ) {
  1107. $found = ! empty(DataMapper::$global_extensions) && isset(DataMapper::$global_extensions['_methods'][$method]);
  1108. }
  1109. return $found;
  1110. }
  1111. // --------------------------------------------------------------------
  1112. /**
  1113. * Magic Clone
  1114. *
  1115. * Allows for a less shallow clone than the default PHP clone.
  1116. *
  1117. * @ignore
  1118. */
  1119. public function __clone()
  1120. {
  1121. foreach ($this as $key => $value)
  1122. {
  1123. if (is_object($value) && $key != 'db')
  1124. {
  1125. $this->{$key} = clone($value);
  1126. }
  1127. }
  1128. }
  1129. // --------------------------------------------------------------------
  1130. /**
  1131. * To String
  1132. *
  1133. * Converts the current object into a string.
  1134. * Should be overridden by extended objects.
  1135. *
  1136. * @return string
  1137. */
  1138. public function __toString()
  1139. {
  1140. return ucfirst($this->model);
  1141. }
  1142. // --------------------------------------------------------------------
  1143. /**
  1144. * Allows the all array to be iterated over without
  1145. * having to specify it.
  1146. *
  1147. * @return Iterator An iterator for the all array
  1148. */
  1149. public function getIterator() {
  1150. if(isset($this->_dm_dataset_iterator)) {
  1151. return $this->_dm_dataset_iterator;
  1152. } else {
  1153. return new ArrayIterator($this->all);
  1154. }
  1155. }
  1156. // --------------------------------------------------------------------
  1157. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1158. * *
  1159. * Main methods *
  1160. * *
  1161. * The following are methods that form the main *
  1162. * functionality of DataMapper. *
  1163. * *
  1164. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1165. // --------------------------------------------------------------------
  1166. /**
  1167. * Get
  1168. *
  1169. * Get objects from the database.
  1170. *
  1171. * @param integer|NULL $limit Limit the number of results.
  1172. * @param integer|NULL $offset Offset the results when limiting.
  1173. * @return DataMapper Returns self for method chaining.
  1174. */
  1175. public function get($limit = NULL, $offset = NULL)
  1176. {
  1177. // Check if this is a related object and if so, perform a related get
  1178. if (! $this->_handle_related())
  1179. {
  1180. // invalid get request, return this for chaining.
  1181. return $this;
  1182. } // Else fall through to a normal get
  1183. $query = FALSE;
  1184. // Check if object has been validated (skipped for related items)
  1185. if ($this->_validated && empty($this->parent))
  1186. {
  1187. // Reset validated
  1188. $this->_validated = FALSE;
  1189. // Use this objects properties
  1190. $data = $this->_to_array(TRUE);
  1191. if ( ! empty($data))
  1192. {
  1193. // Clear this object to make way for new data
  1194. $this->clear();
  1195. // Set up default order by (if available)
  1196. $this->_handle_default_order_by();
  1197. // Get by objects properties
  1198. $query = $this->db->get_where($this->table, $data, $limit, $offset);
  1199. } // FIXME: notify user if nothing was set?
  1200. }
  1201. else
  1202. {
  1203. // Clear this object to make way for new data
  1204. $this->clear();
  1205. // Set up default order by (if available)
  1206. $this->_handle_default_order_by();
  1207. // Get by built up query
  1208. $query = $this->db->get($this->table, $limit, $offset);
  1209. }
  1210. // Convert the query result into DataMapper objects
  1211. if($query)
  1212. {
  1213. $this->_process_query($query);
  1214. }
  1215. // For method chaining
  1216. return $this;
  1217. }
  1218. // --------------------------------------------------------------------
  1219. /**
  1220. * Returns the SQL string of the current query (SELECTs ONLY).
  1221. * NOTE: This also _clears_ the current query info.
  1222. *
  1223. * This can be used to generate subqueries.
  1224. *
  1225. * @param integer|NULL $limit Limit the number of results.
  1226. * @param integer|NULL $offset Offset the results when limiting.
  1227. * @return string SQL as a string.
  1228. */
  1229. public function get_sql($limit = NULL, $offset = NULL, $handle_related = FALSE)
  1230. {
  1231. if($handle_related) {
  1232. $this->_handle_related();
  1233. }
  1234. $this->db->dm_call_method('_track_aliases', $this->table);
  1235. $this->db->from($this->table);
  1236. $this->_handle_default_order_by();
  1237. if ( ! is_null($limit))
  1238. {
  1239. $this->limit($limit, $offset);
  1240. }
  1241. $sql = $this->db->dm_call_method('_compile_select');
  1242. $this->_clear_after_query();
  1243. return $sql;
  1244. }
  1245. // --------------------------------------------------------------------
  1246. /**
  1247. * Runs the query, but returns the raw CodeIgniter results
  1248. * NOTE: This also _clears_ the current query info.
  1249. *
  1250. * @param integer|NULL $limit Limit the number of results.
  1251. * @param integer|NULL $offset Offset the results when limiting.
  1252. * @return CI_DB_result Result Object
  1253. */
  1254. public function get_raw($limit = NULL, $offset = NULL, $handle_related = TRUE)
  1255. {
  1256. if($handle_related) {
  1257. $this->_handle_related();
  1258. }
  1259. $this->_handle_default_order_by();
  1260. $query = $this->db->get($this->table, $limit, $offset);
  1261. $this->_clear_after_query();
  1262. return $query;
  1263. }
  1264. // --------------------------------------------------------------------
  1265. /**
  1266. * Returns a streamable result set for large queries.
  1267. * Usage:
  1268. * $rs = $object->get_iterated();
  1269. * $size = $rs->count;
  1270. * foreach($rs as $o) {
  1271. * // handle $o
  1272. * }
  1273. * $rs can be looped through more than once.
  1274. *
  1275. * @param integer|NULL $limit Limit the number of results.
  1276. * @param integer|NULL $offset Offset the results when limiting.
  1277. * @return DataMapper Returns self for method chaining.
  1278. */
  1279. public function get_iterated($limit = NULL, $offset = NULL)
  1280. {
  1281. // clone $this, so we keep track of instantiations, etc.
  1282. // because these are cleared after the call to get_raw
  1283. $object = $this->get_clone();
  1284. // need to clear query from the clone
  1285. $object->db->dm_call_method('_reset_select');
  1286. // Clear the query related list from the clone
  1287. $object->_query_related = array();
  1288. // Build iterator
  1289. $this->_dm_dataset_iterator = new DM_DatasetIterator($object, $this->get_raw($limit, $offset, TRUE));
  1290. return $this;
  1291. }
  1292. // --------------------------------------------------------------------
  1293. /**
  1294. * Convenience method that runs a query based on pages.
  1295. * This object will have two new values, $query_total_pages and
  1296. * $query_total_rows, which can be used to determine how many pages and
  1297. * how many rows are available in total, respectively.
  1298. *
  1299. * @param int $page Page (1-based) to start on, or row (0-based) to start on
  1300. * @param int $page_size Number of rows in a page
  1301. * @param bool $page_num_by_rows When TRUE, $page is the starting row, not the starting page
  1302. * @param bool $iterated Internal Use Only
  1303. * @return DataMapper Returns self for method chaining.
  1304. */
  1305. public function get_paged($page = 1, $page_size = 50, $page_num_by_rows = FALSE, $info_object = 'paged', $iterated = FALSE)
  1306. {
  1307. // first, duplicate this query, so we have a copy for the query
  1308. $count_query = $this->get_clone(TRUE);
  1309. if($page_num_by_rows)
  1310. {
  1311. $page = 1 + floor(intval($page) / $page_size);
  1312. }
  1313. // never less than 1
  1314. $page = max(1, intval($page));
  1315. $offset = $page_size * ($page - 1);
  1316. // for performance, we clear out the select AND the order by statements,
  1317. // since they aren't necessary and might slow down the query.
  1318. $count_query->db->dm_set('ar_select', NULL);
  1319. $count_query->db->dm_set('ar_orderby', NULL);
  1320. $total = $count_query->db->dm_get('ar_distinct') ? $count_query->count_distinct() : $count_query->count();
  1321. // common vars
  1322. $last_row = $page_size * floor($total / $page_size);
  1323. $total_pages = ceil($total / $page_size);
  1324. if($offset >= $last_row)
  1325. {
  1326. // too far!
  1327. $offset = $last_row;
  1328. $page = $total_pages;
  1329. }
  1330. // now query this object
  1331. if($iterated)
  1332. {
  1333. $this->get_iterated($page_size, $offset);
  1334. }
  1335. else
  1336. {
  1337. $this->get($page_size, $offset);
  1338. }
  1339. $this->{$info_object} = new stdClass();
  1340. $this->{$info_object}->page_size = $page_size;
  1341. $this->{$info_object}->items_on_page = $this->result_count();
  1342. $this->{$info_object}->current_page = $page;
  1343. $this->{$info_object}->current_row = $offset;
  1344. $this->{$info_object}->total_rows = $total;
  1345. $this->{$info_object}->last_row = $last_row;
  1346. $this->{$info_object}->total_pages = $total_pages;
  1347. $this->{$info_object}->has_previous = $offset > 0;
  1348. $this->{$info_object}->previous_page = max(1, $page-1);
  1349. $this->{$info_object}->previous_row = max(0, $offset-$page_size);
  1350. $this->{$info_object}->has_next = $page < $total_pages;
  1351. $this->{$info_object}->next_page = min($total_pages, $page+1);
  1352. $this->{$info_object}->next_row = min($last_row, $offset+$page_size);
  1353. return $this;
  1354. }
  1355. // --------------------------------------------------------------------
  1356. /**
  1357. * Runs get_paged, but as an Iterable.
  1358. *
  1359. * @see get_paged
  1360. * @param int $page Page (1-based) to start on, or row (0-based) to start on
  1361. * @param int $page_size Number of rows in a page
  1362. * @param bool $page_num_by_rows When TRUE, $page is the starting row, not the starting page
  1363. * @param bool $iterated Internal Use Only
  1364. * @return DataMapper Returns self for method chaining.
  1365. */
  1366. public function get_paged_iterated($page = 1, $page_size = 50, $page_num_by_rows = FALSE, $info_object = 'paged')
  1367. {
  1368. return $this->get_paged($page, $page_size, $page_num_by_rows, $info_object, TRUE);
  1369. }
  1370. // --------------------------------------------------------------------
  1371. /**
  1372. * Forces this object to be INSERTed, even if it has an ID.
  1373. *
  1374. * @param mixed $object See save.
  1375. * @param string $related_field See save.
  1376. * @return bool Result of the save.
  1377. */
  1378. public function save_as_new($object = '', $related_field = '')
  1379. {
  1380. $this->_force_save_as_new = TRUE;
  1381. return $this->save($object, $related_field);
  1382. }
  1383. // --------------------------------------------------------------------
  1384. /**
  1385. * Save
  1386. *
  1387. * Saves the current record, if it validates.
  1388. * If object is supplied, saves relations between this object and the supplied object(s).
  1389. *
  1390. * @param mixed $object Optional object to save or array of objects to save.
  1391. * @param string $related_field Optional string to save the object as a specific relationship.
  1392. * @return bool Success or Failure of the validation and save.
  1393. */
  1394. public function save($object = '', $related_field = '')
  1395. {
  1396. // Temporarily store the success/failure
  1397. $result = array();
  1398. // Validate this objects properties
  1399. $this->validate($object, $related_field);
  1400. // If validation passed
  1401. if ($this->valid)
  1402. {
  1403. // Begin auto transaction
  1404. $this->_auto_trans_begin();
  1405. $trans_complete_label = array();
  1406. // Get current timestamp
  1407. $timestamp = $this->_get_generated_timestamp();
  1408. // Check if object has a 'created' field, and it is not already set
  1409. if (in_array($this->created_field, $this->fields) && empty($this->{$this->created_field}))
  1410. {
  1411. $this->{$this->created_field} = $timestamp;
  1412. }
  1413. // SmartSave: if there are objects being saved, and they are stored
  1414. // as in-table foreign keys, we can save them at this step.
  1415. if( ! empty($object))
  1416. {
  1417. if( ! is_array($object))
  1418. {
  1419. $object = array($object);
  1420. }
  1421. $this->_save_itfk($object, $related_field);
  1422. }
  1423. // Convert this object to array
  1424. $data = $this->_to_array();
  1425. if ( ! empty($data))
  1426. {
  1427. if ( ! $this->_force_save_as_new && ! empty($data['id']))
  1428. {
  1429. // Prepare data to send only changed fields
  1430. foreach ($data as $field => $value)
  1431. {
  1432. // Unset field from data if it hasn't been changed
  1433. if ($this->{$field} === $this->stored->{$field})
  1434. {
  1435. unset($data[$field]);
  1436. }
  1437. }
  1438. // if there are changes, check if we need to update the update timestamp
  1439. if (count($data) && in_array($this->updated_field, $this->fields) && ! isset($data[$this->updated_field]))
  1440. {
  1441. // update it now
  1442. $data[$this->updated_field] = $this->{$this->updated_field} = $timestamp;
  1443. }
  1444. // Only go ahead with save if there is still data
  1445. if ( ! empty($data))
  1446. {
  1447. // Update existing record
  1448. $this->db->where('id', $this->id);
  1449. $this->db->update($this->table, $data);
  1450. $trans_complete_label[] = 'update';
  1451. }
  1452. // Reset validated
  1453. $this->_validated = FALSE;
  1454. $result[] = TRUE;
  1455. }
  1456. else
  1457. {
  1458. // Prepare data to send only populated fields
  1459. foreach ($data as $field => $value)
  1460. {
  1461. // Unset field from data
  1462. if ( ! isset($value))
  1463. {
  1464. unset($data[$field]);
  1465. }
  1466. }
  1467. // Create new record
  1468. $this->db->insert($this->table, $data);
  1469. if( ! $this->_force_save_as_new)
  1470. {
  1471. // Assign new ID
  1472. $this->id = $this->db->insert_id();
  1473. }
  1474. $trans_complete_label[] = 'insert';
  1475. // Reset validated
  1476. $this->_validated = FALSE;
  1477. $result[] = TRUE;
  1478. }
  1479. }
  1480. $this->_refresh_stored_values();
  1481. // Check if a relationship is being saved
  1482. if ( ! empty($object))
  1483. {
  1484. // save recursively
  1485. $this->_save_related_recursive($object, $related_field);
  1486. $trans_complete_label[] = 'relationships';
  1487. }
  1488. if(!empty($trans_complete_label))
  1489. {
  1490. $trans_complete_label = 'save (' . implode(', ', $trans_complete_label) . ')';
  1491. }
  1492. else
  1493. {
  1494. $trans_complete_label = '-nothing done-';
  1495. }
  1496. $this->_auto_trans_complete($trans_complete_label);
  1497. }
  1498. $this->_force_save_as_new = FALSE;
  1499. // If no failure was recorded, return TRUE
  1500. return ( ! empty($result) && ! in_array(FALSE, $result));
  1501. }
  1502. // --------------------------------------------------------------------
  1503. /**
  1504. * Recursively saves arrays of objects if they are In-Table Foreign Keys.
  1505. * @ignore
  1506. * @param object $objects Objects to save. This array may be modified.
  1507. * @param object $related_field Related Field name (empty is OK)
  1508. */
  1509. protected function _save_itfk( &$objects, $related_field)
  1510. {
  1511. foreach($objects as $index => $o)
  1512. {
  1513. if(is_int($index))
  1514. {
  1515. $rf = $related_field;
  1516. }
  1517. else
  1518. {
  1519. $rf = $index;
  1520. }
  1521. if(is_array($o))
  1522. {
  1523. $this->_save_itfk($o, $rf);
  1524. if(empty($o))
  1525. {
  1526. unset($objects[$index]);
  1527. }
  1528. }
  1529. else
  1530. {
  1531. if(empty($rf)) {
  1532. $rf = $o->model;
  1533. }
  1534. $related_properties = $this->_get_related_properties($rf);
  1535. $other_column = $related_properties['join_other_as'] . '_id';
  1536. if(isset($this->has_one[$rf]) && in_array($other_column, $this->fields))
  1537. {
  1538. // unset, so that it doesn't get re-saved later.
  1539. unset($objects[$index]);
  1540. if($this->{$other_column} != $o->id)
  1541. {
  1542. // ITFK: store on the table
  1543. $this->{$other_column} = $o->id;
  1544. // Remove reverse relationships for one-to-ones
  1545. $this->_remove_other_one_to_one($rf, $o);
  1546. }
  1547. }
  1548. }
  1549. }
  1550. }
  1551. // --------------------------------------------------------------------
  1552. /**
  1553. * Recursively saves arrays of objects.
  1554. *
  1555. * @ignore
  1556. * @param object $object Array of objects to save, or single object
  1557. * @param object $related_field Default related field name (empty is OK)
  1558. * @return bool TRUE or FALSE if an error occurred.
  1559. */
  1560. protected function _save_related_recursive($object, $related_field)
  1561. {
  1562. if(is_array($object))
  1563. {
  1564. $success = TRUE;
  1565. foreach($object as $rk => $o)
  1566. {
  1567. if(is_int($rk))
  1568. {
  1569. $rk = $related_field;
  1570. }
  1571. $rec_success = $this->_save_related_recursive($o, $rk);
  1572. $success = $success && $rec_success;
  1573. }
  1574. return $success;
  1575. }
  1576. else
  1577. {
  1578. return $this->_save_relation($object, $related_field);
  1579. }
  1580. }
  1581. // --------------------------------------------------------------------
  1582. /**
  1583. * _Save
  1584. *
  1585. * Used by __call to process related saves.
  1586. *
  1587. * @ignore
  1588. * @param mixed $related_field
  1589. * @param array $arguments
  1590. * @return bool
  1591. */
  1592. protected function _save($related_field, $arguments)
  1593. {
  1594. return $this->save($arguments[0], $related_field);
  1595. }
  1596. // --------------------------------------------------------------------
  1597. /**
  1598. * Update
  1599. *
  1600. * Allows updating of more than one row at once.
  1601. *
  1602. * @param object $field A field to update, or an array of fields => values
  1603. * @param object $value The new value
  1604. * @param object $escape_values If false, don't escape the values
  1605. * @return bool TRUE or FALSE on success or failure
  1606. */
  1607. public function update($field, $value = NULL, $escape_values = TRUE)
  1608. {
  1609. if( ! is_array($field))
  1610. {
  1611. $field = array($field => $value);
  1612. }
  1613. else if($value === FALSE)
  1614. {
  1615. $escape_values = FALSE;
  1616. }
  1617. if(empty($field))
  1618. {
  1619. show_error("Nothing was provided to update.");
  1620. }
  1621. // Check if object has an 'updated' field
  1622. if (in_array($this->updated_field, $this->fields))
  1623. {
  1624. $timestamp = $this->_get_generated_timestamp();
  1625. if( ! $escape_values)
  1626. {
  1627. $timestamp = $this->db->escape($timestamp);
  1628. }
  1629. // Update updated datetime
  1630. $field[$this->updated_field] = $timestamp;
  1631. }
  1632. foreach($field as $k => $v)
  1633. {
  1634. if( ! $escape_values)
  1635. {
  1636. // attempt to add the table name
  1637. $v = $this->add_table_name($v);
  1638. }
  1639. $this->db->set($k, $v, $escape_values);
  1640. }
  1641. return $this->db->update($this->table);
  1642. }
  1643. // --------------------------------------------------------------------
  1644. /**
  1645. * Update All
  1646. *
  1647. * Updates all items that are in the all array.
  1648. *
  1649. * @param object $field A field to update, or an array of fields => values
  1650. * @param object $value The new value
  1651. * @param object $escape_values If false, don't escape the values
  1652. * @return bool TRUE or FALSE on success or failure
  1653. */
  1654. public function update_all($field, $value = NULL, $escape_values = TRUE)
  1655. {
  1656. $ids = array();
  1657. foreach($this->all as $object)
  1658. {
  1659. $ids[] = $object->id;
  1660. }
  1661. if(empty($ids))
  1662. {
  1663. return FALSE;
  1664. }
  1665. $this->where_in('id', $ids);
  1666. return $this->update($field, $value, $escape_values);
  1667. }
  1668. // --------------------------------------------------------------------
  1669. /**
  1670. * Gets a timestamp to use when saving.
  1671. * @return mixed
  1672. */
  1673. protected function _get_generated_timestamp()
  1674. {
  1675. // Get current timestamp
  1676. $timestamp = ($this->local_time) ? date($this->timestamp_format) : gmdate($this->timestamp_format);
  1677. // Check if unix timestamp
  1678. return ($this->unix_timestamp) ? strtotime($timestamp) : $timestamp;
  1679. }
  1680. // --------------------------------------------------------------------
  1681. /**
  1682. * Delete
  1683. *
  1684. * Deletes the current record.
  1685. * If object is supplied, deletes relations between this object and the supplied object(s).
  1686. *
  1687. * @param mixed $object If specified, delete the relationship to the object or array of objects.
  1688. * @param string $related_field Can be used to specify which relationship to delete.
  1689. * @return bool Success or Failure of the delete.
  1690. */
  1691. public function delete($object = '', $related_field = '')
  1692. {
  1693. if (empty($object) && ! is_array($object))
  1694. {
  1695. if ( ! empty($this->id))
  1696. {
  1697. // Begin auto transaction
  1698. $this->_auto_trans_begin();
  1699. // Delete all "has many" and "has one" relations for this object first
  1700. foreach (array('has_many', 'has_one') as $type)
  1701. {
  1702. foreach ($this->{$type} as $model => $properties)
  1703. {
  1704. // do we want cascading delete's?
  1705. if ($properties['cascade_delete'])
  1706. {
  1707. // Prepare model
  1708. $class = $properties['class'];
  1709. $object = new $class();
  1710. $this_model = $properties['join_self_as'];
  1711. $other_model = $properties['join_other_as'];
  1712. // Determine relationship table name
  1713. $relationship_table = $this->_get_relationship_table($object, $model);
  1714. // We have to just set NULL for in-table foreign keys that
  1715. // are pointing at this object
  1716. if($relationship_table == $object->table && // ITFK
  1717. // NOT ITFKs that point at the other object
  1718. ! ($object->table == $this->table && // self-referencing has_one join
  1719. in_array($other_model . '_id', $this->fields)) // where the ITFK is for the other object
  1720. )
  1721. {
  1722. $data = array($this_model . '_id' => NULL);
  1723. // Update table to remove relationships
  1724. $this->db->where($this_model . '_id', $this->id);
  1725. $this->db->update($object->table, $data);
  1726. }
  1727. else if ($relationship_table != $this->table)
  1728. {
  1729. $data = array($this_model . '_id' => $this->id);
  1730. // Delete relation
  1731. $this->db->delete($relationship_table, $data);
  1732. }
  1733. // Else, no reason to delete the relationships on this table
  1734. }
  1735. }
  1736. }
  1737. // Delete the object itself
  1738. $this->db->where('id', $this->id);
  1739. $this->db->delete($this->table);
  1740. // Complete auto transaction
  1741. $this->_auto_trans_complete('delete');
  1742. // Clear this object
  1743. $this->clear();
  1744. return TRUE;
  1745. }
  1746. }
  1747. else if (is_array($object))
  1748. {
  1749. // Begin auto transaction
  1750. $this->_auto_trans_begin();
  1751. // Temporarily store the success/failure
  1752. $result = array();
  1753. foreach ($object as $rel_field => $obj)
  1754. {
  1755. if (is_int($rel_field))
  1756. {
  1757. $rel_field = $related_field;
  1758. }
  1759. if (is_array($obj))
  1760. {
  1761. foreach ($obj as $r_f => $o)
  1762. {
  1763. if (is_int($r_f))
  1764. {
  1765. $r_f = $rel_field;
  1766. }
  1767. $result[] = $this->_delete_relation($o, $r_f);
  1768. }
  1769. }
  1770. else
  1771. {
  1772. $result[] = $this->_delete_relation($obj, $rel_field);
  1773. }
  1774. }
  1775. // Complete auto transaction
  1776. $this->_auto_trans_complete('delete (relationship)');
  1777. // If no failure was recorded, return TRUE
  1778. if ( ! in_array(FALSE, $result))
  1779. {
  1780. return TRUE;
  1781. }
  1782. }
  1783. else
  1784. {
  1785. // Begin auto transaction
  1786. $this->_auto_trans_begin();
  1787. // Temporarily store the success/failure
  1788. $result = $this->_delete_relation($object, $related_field);
  1789. // Complete auto transaction
  1790. $this->_auto_trans_complete('delete (relationship)');
  1791. return $result;
  1792. }
  1793. return FALSE;
  1794. }
  1795. // --------------------------------------------------------------------
  1796. /**
  1797. * _Delete
  1798. *
  1799. * Used by __call to process related deletes.
  1800. *
  1801. * @ignore
  1802. * @param string $related_field
  1803. * @param array $arguments
  1804. * @return bool
  1805. */
  1806. protected function _delete($related_field, $arguments)
  1807. {
  1808. return $this->delete($arguments[0], $related_field);
  1809. }
  1810. // --------------------------------------------------------------------
  1811. /**
  1812. * Delete All
  1813. *
  1814. * Deletes all records in this objects all list.
  1815. *
  1816. * @return bool Success or Failure of the delete
  1817. */
  1818. public function delete_all()
  1819. {
  1820. $success = TRUE;
  1821. foreach($this as $item)
  1822. {
  1823. if ( ! empty($item->id))
  1824. {
  1825. $success_temp = $item->delete();
  1826. $success = $success && $success_temp;
  1827. }
  1828. }
  1829. $this->clear();
  1830. return $success;
  1831. }
  1832. // --------------------------------------------------------------------
  1833. /**
  1834. * Truncate
  1835. *
  1836. * Deletes all records in this objects table.
  1837. *
  1838. * @return bool Success or Failure of the truncate
  1839. */
  1840. public function truncate()
  1841. {
  1842. // Begin auto transaction
  1843. $this->_auto_trans_begin();
  1844. // Delete all "has many" and "has one" relations for this object first
  1845. foreach (array('has_many', 'has_one') as $type)
  1846. {
  1847. foreach ($this->{$type} as $model => $properties)
  1848. {
  1849. // do we want cascading delete's?
  1850. if ($properties['cascade_delete'])
  1851. {
  1852. // Prepare model
  1853. $class = $properties['class'];
  1854. $object = new $class();
  1855. $this_model = $properties['join_self_as'];
  1856. $other_model = $properties['join_other_as'];
  1857. // Determine relationship table name
  1858. $relationship_table = $this->_get_relationship_table($object, $model);
  1859. // We have to just set NULL for in-table foreign keys that
  1860. // are pointing at this object
  1861. if($relationship_table == $object->table && // ITFK
  1862. // NOT ITFKs that point at the other object
  1863. ! ($object->table == $this->table && // self-referencing has_one join
  1864. in_array($other_model . '_id', $this->fields)) // where the ITFK is for the other object
  1865. )
  1866. {
  1867. $data = array($this_model . '_id' => NULL);
  1868. // Update table to remove all ITFK relations
  1869. $this->db->update($object->table, $data);
  1870. }
  1871. else if ($relationship_table != $this->table)
  1872. {
  1873. // Delete all relationship records
  1874. $this->db->truncate($relationship_table);
  1875. }
  1876. // Else, no reason to delete the relationships on this table
  1877. }
  1878. }
  1879. }
  1880. // Delete all records
  1881. $this->db->truncate($this->table);
  1882. // Complete auto transaction
  1883. $this->_auto_trans_complete('truncate');
  1884. // Clear this object
  1885. $this->clear();
  1886. return TRUE;
  1887. }
  1888. // --------------------------------------------------------------------
  1889. /**
  1890. * Refresh All
  1891. *
  1892. * Removes any empty objects in this objects all list.
  1893. * Only needs to be used if you are looping through the all list
  1894. * a second time and you have deleted a record the first time through.
  1895. *
  1896. * @return bool FALSE if the $all array was already empty.
  1897. */
  1898. public function refresh_all()
  1899. {
  1900. if ( ! empty($this->all))
  1901. {
  1902. $all = array();
  1903. foreach ($this->all as $item)
  1904. {
  1905. if ( ! empty($item->id))
  1906. {
  1907. $all[] = $item;
  1908. }
  1909. }
  1910. $this->all = $all;
  1911. return TRUE;
  1912. }
  1913. return FALSE;
  1914. }
  1915. // --------------------------------------------------------------------
  1916. /**
  1917. * Validate
  1918. *
  1919. * Validates the value of each property against the assigned validation rules.
  1920. *
  1921. * @param mixed $object Objects included with the validation [from save()].
  1922. * @param string $related_field See save.
  1923. * @return DataMapper Returns $this for method chanining.
  1924. */
  1925. public function validate($object = '', $related_field = '')
  1926. {
  1927. // Return if validation has already been run
  1928. if ($this->_validated)
  1929. {
  1930. // For method chaining
  1931. return $this;
  1932. }
  1933. // Set validated as having been run
  1934. $this->_validated = TRUE;
  1935. // Clear errors
  1936. $this->error = new DM_Error_Object();
  1937. // Loop through each property to be validated
  1938. foreach ($this->validation as $field => $validation)
  1939. {
  1940. if(empty($validation['rules']))
  1941. {
  1942. continue;
  1943. }
  1944. // Get validation settings
  1945. $rules = $validation['rules'];
  1946. // Will validate differently if this is for a related item
  1947. $related = (isset($this->has_many[$field]) || isset($this->has_one[$field]));
  1948. // Check if property has changed since validate last ran
  1949. if ($related || $this->_force_validation || ! isset($this->stored->{$field}) || $this->{$field} !== $this->stored->{$field})
  1950. {
  1951. // Only validate if field is related or required or has a value
  1952. if ( ! $related && ! in_array('required', $rules) && ! in_array('always_validate', $rules))
  1953. {
  1954. if ( ! isset($this->{$field}) || $this->{$field} === '')
  1955. {
  1956. continue;
  1957. }
  1958. }
  1959. $label = ( ! empty($validation['label'])) ? $validation['label'] : $field;
  1960. // Loop through each rule to validate this property against
  1961. foreach ($rules as $rule => $param)
  1962. {
  1963. // Check for parameter
  1964. if (is_numeric($rule))
  1965. {
  1966. $rule = $param;
  1967. $param = '';
  1968. }
  1969. // Clear result
  1970. $result = '';
  1971. // Clear message
  1972. $line = FALSE;
  1973. // Check rule exists
  1974. if ($related)
  1975. {
  1976. // Prepare rule to use different language file lines
  1977. $rule = 'related_' . $rule;
  1978. $arg = $object;
  1979. if( ! empty($related_field)) {
  1980. $arg = array($related_field => $object);
  1981. }
  1982. if (method_exists($this, '_' . $rule))
  1983. {
  1984. // Run related rule from DataMapper or the class extending DataMapper
  1985. $line = $result = $this->{'_' . $rule}($arg, $field, $param);
  1986. }
  1987. else if($this->_extension_method_exists('rule_' . $rule))
  1988. {
  1989. $line = $result = $this->{'rule_' . $rule}($arg, $field, $param);
  1990. }
  1991. }
  1992. else if (method_exists($this, '_' . $rule))
  1993. {
  1994. // Run rule from DataMapper or the class extending DataMapper
  1995. $line = $result = $this->{'_' . $rule}($field, $param);
  1996. }
  1997. else if($this->_extension_method_exists('rule_' . $rule))
  1998. {
  1999. // Run an extension-based rule.
  2000. $line = $result = $this->{'rule_' . $rule}($field, $param);
  2001. }
  2002. else if (method_exists($this->form_validation, $rule))
  2003. {
  2004. // Run rule from CI Form Validation
  2005. $result = $this->form_validation->{$rule}($this->{$field}, $param);
  2006. }
  2007. else if (function_exists($rule))
  2008. {
  2009. // Run rule from PHP
  2010. $this->{$field} = $rule($this->{$field});
  2011. }
  2012. // Add an error message if the rule returned FALSE
  2013. if (is_string($line) || $result === FALSE)
  2014. {
  2015. if(!is_string($line))
  2016. {
  2017. if (FALSE === ($line = $this->lang->dm_line($rule)))
  2018. {
  2019. // Get corresponding error from language file
  2020. $line = 'Unable to access an error message corresponding to your rule name: '.$rule.'.';
  2021. }
  2022. }
  2023. // Check if param is an array
  2024. if (is_array($param))
  2025. {
  2026. // Convert into a string so it can be used in the error message
  2027. $param = implode(', ', $param);
  2028. // Replace last ", " with " or "
  2029. if (FALSE !== ($pos = strrpos($param, ', ')))
  2030. {
  2031. $param = substr_replace($param, ' or ', $pos, 2);
  2032. }
  2033. }
  2034. // Check if param is a validation field
  2035. if (isset($this->validation[$param]))
  2036. {
  2037. // Change it to the label value
  2038. $param = $this->validation[$param]['label'];
  2039. }
  2040. // Add error message
  2041. $this->error_message($field, sprintf($line, $label, $param));
  2042. // Escape to prevent further error checks
  2043. break;
  2044. }
  2045. }
  2046. }
  2047. }
  2048. // Set whether validation passed
  2049. $this->valid = empty($this->error->all);
  2050. // For method chaining
  2051. return $this;
  2052. }
  2053. // --------------------------------------------------------------------
  2054. /**
  2055. * Skips validation for the next call to save.
  2056. * Note that this also prevents the validation routine from running until the next get.
  2057. *
  2058. * @param object $skip If FALSE, re-enables validation.
  2059. * @return DataMapper Returns self for method chaining.
  2060. */
  2061. public function skip_validation($skip = TRUE)
  2062. {
  2063. $this->_validated = $skip;
  2064. $this->valid = $skip;
  2065. return $this;
  2066. }
  2067. // --------------------------------------------------------------------
  2068. /**
  2069. * Force revalidation for the next call to save.
  2070. * This allows you to run validation rules on fields that haven't been modified
  2071. *
  2072. * @param object $force If TRUE, forces validation on all fields.
  2073. * @return DataMapper Returns self for method chaining.
  2074. */
  2075. public function force_validation($force = TRUE)
  2076. {
  2077. $this->_force_validation = $force;
  2078. return $this;
  2079. }
  2080. // --------------------------------------------------------------------
  2081. /**
  2082. * Clear
  2083. *
  2084. * Clears the current object.
  2085. */
  2086. public function clear()
  2087. {
  2088. // Clear the all list
  2089. $this->all = array();
  2090. // Clear errors
  2091. $this->error = new DM_Error_Object();
  2092. // Clear this objects properties and set blank error messages in case they are accessed
  2093. foreach ($this->fields as $field)
  2094. {
  2095. $this->{$field} = NULL;
  2096. }
  2097. // Clear this objects "has many" related objects
  2098. foreach ($this->has_many as $related => $properties)
  2099. {
  2100. unset($this->{$related});
  2101. }
  2102. // Clear this objects "has one" related objects
  2103. foreach ($this->has_one as $related => $properties)
  2104. {
  2105. unset($this->{$related});
  2106. }
  2107. // Clear the query related list
  2108. $this->_query_related = array();
  2109. // Clear and refresh stored values
  2110. $this->stored = new stdClass();
  2111. // Clear the saved iterator
  2112. unset($this->_dm_dataset_iterator);
  2113. $this->_refresh_stored_values();
  2114. }
  2115. // --------------------------------------------------------------------
  2116. /**
  2117. * Clears the db object after processing a query, or returning the
  2118. * SQL for a query.
  2119. *
  2120. * @ignore
  2121. */
  2122. protected function _clear_after_query()
  2123. {
  2124. // clear the query as if it was run
  2125. $this->db->dm_call_method('_reset_select');
  2126. // in case some include_related instantiations were set up, clear them
  2127. $this->_instantiations = NULL;
  2128. // Clear the query related list (Thanks to TheJim)
  2129. $this->_query_related = array();
  2130. // Clear the saved iterator
  2131. unset($this->_dm_dataset_iterator);
  2132. }
  2133. // --------------------------------------------------------------------
  2134. /**
  2135. * Count
  2136. *
  2137. * Returns the total count of the object records from the database.
  2138. * If on a related object, returns the total count of related objects records.
  2139. *
  2140. * @param array $exclude_ids A list of ids to exlcude from the count
  2141. * @return int Number of rows in query.
  2142. */
  2143. public function count($exclude_ids = NULL, $column = NULL, $related_id = NULL)
  2144. {
  2145. // Check if related object
  2146. if ( ! empty($this->parent))
  2147. {
  2148. // Prepare model
  2149. $related_field = $this->parent['model'];
  2150. $related_properties = $this->_get_related_properties($related_field);
  2151. $class = $related_properties['class'];
  2152. $other_model = $related_properties['join_other_as'];
  2153. $this_model = $related_properties['join_self_as'];
  2154. $object = new $class();
  2155. // Determine relationship table name
  2156. $relationship_table = $this->_get_relationship_table($object, $related_field);
  2157. // To ensure result integrity, group all previous queries
  2158. $where = $this->db->dm_get('ar_where');
  2159. if( ! empty($where))
  2160. {
  2161. // if the relationship table is different from our table, include our table in the count query
  2162. if ($relationship_table != $this->table)
  2163. {
  2164. $this->db->join($this->table, $this->table . '.id = ' . $relationship_table . '.' . $this_model.'_id', 'LEFT OUTER');
  2165. }
  2166. $arwhere = $this->db->dm_get('ar_where');
  2167. array_unshift($arwhere, '( ');
  2168. $arwhere[] = ' )';
  2169. $this->db->dm_set('ar_where', $arwhere);
  2170. }
  2171. // We have to query special for in-table foreign keys that
  2172. // are pointing at this object
  2173. if($relationship_table == $object->table && // ITFK
  2174. // NOT ITFKs that point at the other object
  2175. ! ($object->table == $this->table && // self-referencing has_one join
  2176. in_array($other_model . '_id', $this->fields)) // where the ITFK is for the other object
  2177. )
  2178. {
  2179. // ITFK on the other object's table
  2180. $this->db->where('id', $this->parent['id'])->where($this_model . '_id IS NOT NULL');
  2181. }
  2182. else
  2183. {
  2184. // All other cases
  2185. $this->db->where($relationship_table . '.' . $other_model . '_id', $this->parent['id']);
  2186. }
  2187. if(!empty($exclude_ids))
  2188. {
  2189. $this->db->where_not_in($relationship_table . '.' . $this_model . '_id', $exclude_ids);
  2190. }
  2191. if($column == 'id')
  2192. {
  2193. $column = $relationship_table . '.' . $this_model . '_id';
  2194. }
  2195. if(!empty($related_id))
  2196. {
  2197. $this->db->where($this_model . '_id', $related_id);
  2198. }
  2199. $this->db->from($relationship_table);
  2200. }
  2201. else
  2202. {
  2203. $this->db->from($this->table);
  2204. if(!empty($exclude_ids))
  2205. {
  2206. $this->db->where_not_in('id', $exclude_ids);
  2207. }
  2208. if(!empty($related_id))
  2209. {
  2210. $this->db->where('id', $related_id);
  2211. }
  2212. $column = $this->add_table_name($column);
  2213. }
  2214. // Manually overridden to allow for COUNT(DISTINCT COLUMN)
  2215. $select = $this->db->_count_string;
  2216. if(!empty($column))
  2217. {
  2218. // COUNT DISTINCT
  2219. $select = 'SELECT COUNT(DISTINCT ' . $this->db->dm_call_method('_protect_identifiers', $column) . ') AS ';
  2220. }
  2221. $sql = $this->db->dm_call_method('_compile_select', $select . $this->db->dm_call_method('_protect_identifiers', 'numrows'));
  2222. $query = $this->db->query($sql);
  2223. $this->db->dm_call_method('_reset_select');
  2224. if ($query->num_rows() == 0)
  2225. {
  2226. return 0;
  2227. }
  2228. $row = $query->row();
  2229. return intval($row->numrows);
  2230. }
  2231. // --------------------------------------------------------------------
  2232. /**
  2233. * Count Distinct
  2234. *
  2235. * Returns the total count of distinct object records from the database.
  2236. * If on a related object, returns the total count of related objects records.
  2237. *
  2238. * @param array $exclude_ids A list of ids to exlcude from the count
  2239. * @param string $column If provided, use this column for the DISTINCT instead of 'id'
  2240. * @return int Number of rows in query.
  2241. */
  2242. public function count_distinct($exclude_ids = NULL, $column = 'id')
  2243. {
  2244. return $this->count($exclude_ids, $column);
  2245. }
  2246. // --------------------------------------------------------------------
  2247. /**
  2248. * Convenience method to return the number of items from
  2249. * the last call to get.
  2250. *
  2251. * @return int
  2252. */
  2253. public function result_count() {
  2254. if(isset($this->_dm_dataset_iterator)) {
  2255. return $this->_dm_dataset_iterator->result_count();
  2256. } else {
  2257. return count($this->all);
  2258. }
  2259. }
  2260. // --------------------------------------------------------------------
  2261. /**
  2262. * Exists
  2263. *
  2264. * Returns TRUE if the current object has a database record.
  2265. *
  2266. * @return bool
  2267. */
  2268. public function exists()
  2269. {
  2270. // returns TRUE if the id of this object is set and not empty, OR
  2271. // there are items in the ALL array.
  2272. return isset($this->id) ? !empty($this->id) : ($this->result_count() > 0);
  2273. }
  2274. // --------------------------------------------------------------------
  2275. /**
  2276. * Query
  2277. *
  2278. * Runs the specified query and populates the current object with the results.
  2279. *
  2280. * Warning: Use at your own risk. This will only be as reliable as your query.
  2281. *
  2282. * @param string $sql The query to process
  2283. * @param array|bool $binds Array of values to bind (see CodeIgniter)
  2284. * @return DataMapper Returns self for method chaining.
  2285. */
  2286. public function query($sql, $binds = FALSE)
  2287. {
  2288. // Get by objects properties
  2289. $query = $this->db->query($sql, $binds);
  2290. $this->_process_query($query);
  2291. // For method chaining
  2292. return $this;
  2293. }
  2294. // --------------------------------------------------------------------
  2295. /**
  2296. * Check Last Query
  2297. * Renders the last DB query performed.
  2298. *
  2299. * @param array $delims Delimiters for the SQL string.
  2300. * @param bool $return_as_string If TRUE, don't output automatically.
  2301. * @return string Last db query formatted as a string.
  2302. */
  2303. public function check_last_query($delims = array('<pre>', '</pre>'), $return_as_string = FALSE) {
  2304. $q = wordwrap($this->db->last_query(), 100, "\n\t");
  2305. if(!empty($delims)) {
  2306. $q = implode($q, $delims);
  2307. }
  2308. if($return_as_string === FALSE) {
  2309. echo $q;
  2310. }
  2311. return $q;
  2312. }
  2313. // --------------------------------------------------------------------
  2314. /**
  2315. * Error Message
  2316. *
  2317. * Adds an error message to this objects error object.
  2318. *
  2319. * @param string $field Field to set the error on.
  2320. * @param string $error Error message.
  2321. */
  2322. public function error_message($field, $error)
  2323. {
  2324. if ( ! empty($field) && ! empty($error))
  2325. {
  2326. // Set field specific error
  2327. $this->error->{$field} = $this->error_prefix . $error . $this->error_suffix;
  2328. // Add field error to errors all list
  2329. $this->error->all[$field] = $this->error->{$field};
  2330. // Append field error to error message string
  2331. $this->error->string .= $this->error->{$field};
  2332. }
  2333. }
  2334. // --------------------------------------------------------------------
  2335. /**
  2336. * Get Clone
  2337. *
  2338. * Returns a clone of the current object.
  2339. *
  2340. * @return DataMapper Cloned copy of this object.
  2341. */
  2342. public function get_clone($force_db = FALSE)
  2343. {
  2344. $temp = clone($this);
  2345. // This must be left in place, even with the __clone method,
  2346. // or else the DB will not be copied over correctly.
  2347. if($force_db ||
  2348. (($this->db_params !== FALSE) && isset($this->db)) )
  2349. {
  2350. // create a copy of $this->db
  2351. $temp->db = clone($this->db);
  2352. }
  2353. return $temp;
  2354. }
  2355. // --------------------------------------------------------------------
  2356. /**
  2357. * Get Copy
  2358. *
  2359. * Returns an unsaved copy of the current object.
  2360. *
  2361. * @return DataMapper Cloned copy of this object with an empty ID for saving as new.
  2362. */
  2363. public function get_copy($force_db = FALSE)
  2364. {
  2365. $copy = $this->get_clone($force_db);
  2366. $copy->id = NULL;
  2367. return $copy;
  2368. }
  2369. // --------------------------------------------------------------------
  2370. /**
  2371. * Get By
  2372. *
  2373. * Gets objects by specified field name and value.
  2374. *
  2375. * @ignore
  2376. * @param string $field Field to look at.
  2377. * @param array $value Arguments to this method.
  2378. * @return DataMapper Returns self for method chaining.
  2379. */
  2380. protected function _get_by($field, $value = array())
  2381. {
  2382. if (isset($value[0]))
  2383. {
  2384. $this->where($field, $value[0]);
  2385. }
  2386. return $this->get();
  2387. }
  2388. // --------------------------------------------------------------------
  2389. /**
  2390. * Get By Related
  2391. *
  2392. * Gets objects by specified related object and optionally by field name and value.
  2393. *
  2394. * @ignore
  2395. * @param mixed $model Related Model or Object
  2396. * @param array $arguments Arguments to the where method
  2397. * @return DataMapper Returns self for method chaining.
  2398. */
  2399. protected function _get_by_related($model, $arguments = array())
  2400. {
  2401. if ( ! empty($model))
  2402. {
  2403. // Add model to start of arguments
  2404. $arguments = array_merge(array($model), $arguments);
  2405. }
  2406. $this->_related('where', $arguments);
  2407. return $this->get();
  2408. }
  2409. // --------------------------------------------------------------------
  2410. /**
  2411. * Handles the adding the related part of a query if $parent is set
  2412. *
  2413. * @ignore
  2414. * @return bool Success or failure
  2415. */
  2416. protected function _handle_related()
  2417. {
  2418. if ( ! empty($this->parent))
  2419. {
  2420. $has_many = array_key_exists($this->parent['model'], $this->has_many);
  2421. $has_one = array_key_exists($this->parent['model'], $this->has_one);
  2422. // If this is a "has many" or "has one" related item
  2423. if ($has_many || $has_one)
  2424. {
  2425. if( ! $this->_get_relation($this->parent['model'], $this->parent['id']))
  2426. {
  2427. return FALSE;
  2428. }
  2429. }
  2430. else
  2431. {
  2432. // provide feedback on errors
  2433. $this_model = get_class($this);
  2434. show_error("DataMapper Error: '".$this->parent['model']."' is not a valid parent relationship for $this_model. Are your relationships configured correctly?");
  2435. }
  2436. }
  2437. return TRUE;
  2438. }
  2439. // --------------------------------------------------------------------
  2440. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2441. * *
  2442. * Active Record methods *
  2443. * *
  2444. * The following are methods used to provide Active Record *
  2445. * functionality for data retrieval. *
  2446. * *
  2447. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2448. // --------------------------------------------------------------------
  2449. /**
  2450. * Add Table Name
  2451. *
  2452. * Adds the table name to a field if necessary
  2453. *
  2454. * @param string $field Field to add the table name to.
  2455. * @return string Possibly modified field name.
  2456. */
  2457. public function add_table_name($field)
  2458. {
  2459. // only add table if the field doesn't contain a dot (.) or open parentheses
  2460. if (preg_match('/[\.\(]/', $field) == 0)
  2461. {
  2462. // split string into parts, add field
  2463. $field_parts = explode(',', $field);
  2464. $field = '';
  2465. foreach ($field_parts as $part)
  2466. {
  2467. if ( ! empty($field))
  2468. {
  2469. $field .= ', ';
  2470. }
  2471. $part = ltrim($part);
  2472. // handle comparison operators on where
  2473. $subparts = explode(' ', $part, 2);
  2474. if ($subparts[0] == '*' || in_array($subparts[0], $this->fields))
  2475. {
  2476. $field .= $this->table . '.' . $part;
  2477. }
  2478. else
  2479. {
  2480. $field .= $part;
  2481. }
  2482. }
  2483. }
  2484. return $field;
  2485. }
  2486. // --------------------------------------------------------------------
  2487. /**
  2488. * Creates a SQL-function with the given (optional) arguments.
  2489. *
  2490. * Each argument can be one of several forms:
  2491. * 1) An un escaped string value, which will be automatically escaped: "hello"
  2492. * 2) An escaped value or non-string, which is copied directly: "'hello'" 123, etc
  2493. * 3) An operator, *, or a non-escaped string is copied directly: "[non-escaped]" ">", etc
  2494. * 4) A field on this model: "@property" (Also, "@<whatever>" will be copied directly
  2495. * 5) A field on a related or deeply related model: "@model/property" "@model/other_model/property"
  2496. * 6) An array, which is processed recursively as a forumla.
  2497. *
  2498. * @param string $function_name Function name.
  2499. * @param mixed $args,... (Optional) Any commands that need to be passed to the function.
  2500. * @return string The new SQL function string.
  2501. */
  2502. public function func($function_name)
  2503. {
  2504. $ret = $function_name . '(';
  2505. $args = func_get_args();
  2506. // pop the function name
  2507. array_shift($args);
  2508. $comma = '';
  2509. foreach($args as $arg)
  2510. {
  2511. $ret .= $comma . $this->_process_function_arg($arg);
  2512. if(empty($comma))
  2513. {
  2514. $comma = ', ';
  2515. }
  2516. }
  2517. $ret .= ')';
  2518. return $ret;
  2519. }
  2520. // private method to convert function arguments into SQL
  2521. protected function _process_function_arg($arg, $is_formula = FALSE)
  2522. {
  2523. $ret = '';
  2524. if(is_array($arg)) {
  2525. // formula
  2526. foreach($arg as $func => $formula_arg) {
  2527. if(!empty($ret)) {
  2528. $ret .= ' ';
  2529. }
  2530. if(is_numeric($func)) {
  2531. // process non-functions
  2532. $ret .= $this->_process_function_arg($formula_arg, TRUE);
  2533. } else {
  2534. // recursively process functions within functions
  2535. $func_args = array_merge(array($func), (array)$formula_arg);
  2536. $ret .= call_user_func_array(array($this, 'func'), $func_args);
  2537. }
  2538. }
  2539. return $ret;
  2540. }
  2541. $operators = array(
  2542. 'AND', 'OR', 'NOT', // binary logic
  2543. '<', '>', '<=', '>=', '=', '<>', '!=', // comparators
  2544. '+', '-', '*', '/', '%', '^', // basic maths
  2545. '|/', '||/', '!', '!!', '@', '&', '|', '#', '~', // advanced maths
  2546. '<<', '>>'); // binary operators
  2547. if(is_string($arg))
  2548. {
  2549. if( ($is_formula && in_array($arg, $operators)) ||
  2550. $arg == '*' ||
  2551. ($arg[0] == "'" && $arg[strlen($arg)-1] == "'") ||
  2552. ($arg[0] == "[" && $arg[strlen($arg)-1] == "]") )
  2553. {
  2554. // simply add already-escaped strings, the special * value, or operators in formulas
  2555. if($arg[0] == "[" && $arg[strlen($arg)-1] == "]") {
  2556. // Arguments surrounded by square brackets are added directly, minus the brackets
  2557. $arg = substr($arg, 1, -1);
  2558. }
  2559. $ret .= $arg;
  2560. }
  2561. else if($arg[0] == '@')
  2562. {
  2563. // model or sub-model property
  2564. $arg = substr($arg, 1);
  2565. if(strpos($arg, '/') !== FALSE)
  2566. {
  2567. // related property
  2568. if(strpos($arg, 'parent/') === 0)
  2569. {
  2570. // special parent property for subqueries
  2571. $ret .= str_replace('parent/', '${parent}.', $arg);
  2572. }
  2573. else
  2574. {
  2575. $rel_elements = explode('/', $arg);
  2576. $property = array_pop($rel_elements);
  2577. $table = $this->_add_related_table(implode('/', $rel_elements));
  2578. $ret .= $this->db->protect_identifiers($table . '.' . $property);
  2579. }
  2580. }
  2581. else
  2582. {
  2583. $ret .= $this->db->protect_identifiers($this->add_table_name($arg));
  2584. }
  2585. }
  2586. else
  2587. {
  2588. $ret .= $this->db->escape($arg);
  2589. }
  2590. }
  2591. else
  2592. {
  2593. $ret .= $arg;
  2594. }
  2595. return $ret;
  2596. }
  2597. // --------------------------------------------------------------------
  2598. /**
  2599. * Used by the magic method for select_func, {where}_func, etc
  2600. *
  2601. * @ignore
  2602. * @param object $query Name of query function
  2603. * @param array $args Arguments for func()
  2604. * @return DataMapper Returns self for method chaining.
  2605. */
  2606. protected function _func($query, $args)
  2607. {
  2608. if(count($args) < 2)
  2609. {
  2610. throw new Exception("Invalid number of arguments to {$query}_func: must be at least 2 arguments.");
  2611. }
  2612. if($query == 'select')
  2613. {
  2614. $alias = array_pop($args);
  2615. $value = call_user_func_array(array($this, 'func'), $args);
  2616. $value .= " AS $alias";
  2617. // we can't use the normal select method, because CI likes to breaky
  2618. $this->_add_to_select_directly($value);
  2619. return $this;
  2620. }
  2621. else
  2622. {
  2623. $param = array_pop($args);
  2624. $value = call_user_func_array(array($this, 'func'), $args);
  2625. return $this->{$query}($value, $param);
  2626. }
  2627. }
  2628. // --------------------------------------------------------------------
  2629. /**
  2630. * Used by the magic method for {where}_field_func, etc.
  2631. *
  2632. * @ignore
  2633. * @param string $query Name of query function
  2634. * @param array $args Arguments for func()
  2635. * @return DataMapper Returns self for method chaining.
  2636. */
  2637. protected function _field_func($query, $args)
  2638. {
  2639. if(count($args) < 2)
  2640. {
  2641. throw new Exception("Invalid number of arguments to {$query}_field_func: must be at least 2 arguments.");
  2642. }
  2643. $field = array_shift($args);
  2644. $func = call_user_func_array(array($this, 'func'), $args);
  2645. return $this->_process_special_query_clause($query, $field, $func);
  2646. }
  2647. // --------------------------------------------------------------------
  2648. /**
  2649. * Used by the magic method for select_subquery {where}_subquery, etc
  2650. *
  2651. * @ignore
  2652. * @param string $query Name of query function
  2653. * @param array $args Arguments for subquery
  2654. * @return DataMapper Returns self for method chaining.
  2655. */
  2656. protected function _subquery($query, $args)
  2657. {
  2658. if(count($args) < 1)
  2659. {
  2660. throw new Exception("Invalid arguments on {$query}_subquery: must be at least one argument.");
  2661. }
  2662. if($query == 'select')
  2663. {
  2664. if(count($args) < 2)
  2665. {
  2666. throw new Exception('Invalid number of arguments to select_subquery: must be exactly 2 arguments.');
  2667. }
  2668. $sql = $this->_parse_subquery_object($args[0]);
  2669. $alias = $args[1];
  2670. // we can't use the normal select method, because CI likes to breaky
  2671. $this->_add_to_select_directly("$sql AS $alias");
  2672. return $this;
  2673. }
  2674. else
  2675. {
  2676. $object = $field = $value = NULL;
  2677. if(is_object($args[0]) ||
  2678. (is_string($args[0]) && !isset($args[1])) )
  2679. {
  2680. $field = $this->_parse_subquery_object($args[0]);
  2681. if(isset($args[1])) {
  2682. $value = $this->db->protect_identifiers($this->add_table_name($args[1]));
  2683. }
  2684. }
  2685. else
  2686. {
  2687. $field = $this->add_table_name($args[0]);
  2688. $value = $args[1];
  2689. if(is_object($value))
  2690. {
  2691. $value = $this->_parse_subquery_object($value);
  2692. }
  2693. }
  2694. $extra = NULL;
  2695. if(isset($args[2])) {
  2696. $extra = $args[2];
  2697. }
  2698. return $this->_process_special_query_clause($query, $field, $value, $extra);
  2699. }
  2700. }
  2701. // --------------------------------------------------------------------
  2702. /**
  2703. * Parses and protects a subquery.
  2704. * Automatically replaces the special ${parent} argument with a reference to
  2705. * this table.
  2706. *
  2707. * Also replaces all table references that would overlap with this object.
  2708. *
  2709. * @ignore
  2710. * @param object $sql SQL string to process
  2711. * @return string Processed SQL string.
  2712. */
  2713. protected function _parse_subquery_object($sql)
  2714. {
  2715. if(is_object($sql))
  2716. {
  2717. $sql = '(' . $sql->get_sql() . ')';
  2718. }
  2719. // Table Name pattern should be
  2720. $tablename = $this->db->dm_call_method('_escape_identifiers', $this->table);
  2721. $table_pattern = '(?:' . preg_quote($this->table) . '|' . preg_quote($tablename) . '|\(' . preg_quote($tablename) . '\))';
  2722. $fieldname = $this->db->dm_call_method('_escape_identifiers', '__field__');
  2723. $field_pattern = '([-\w]+|' . str_replace('__field__', '[-\w]+', preg_quote($fieldname)) . ')';
  2724. // replace all table.field references
  2725. // pattern ends up being [^_](table|`table`).(field|`field`)
  2726. // the NOT _ at the beginning is to prevent replacing of advanced relationship table references.
  2727. $pattern = '/([^_])' . $table_pattern . '\.' . $field_pattern . '/i';
  2728. // replacement ends up being `table_subquery`.`$1`
  2729. $replacement = '$1' . $this->db->dm_call_method('_escape_identifiers', $this->table . '_subquery') . '.$2';
  2730. $sql = preg_replace($pattern, $replacement, $sql);
  2731. // now replace all "table table" aliases
  2732. // important: the space at the end is required
  2733. $pattern = "/$table_pattern $table_pattern /i";
  2734. $replacement = $tablename . ' ' . $this->db->dm_call_method('_escape_identifiers', $this->table . '_subquery') . ' ';
  2735. $sql = preg_replace($pattern, $replacement, $sql);
  2736. // now replace "FROM table" for self relationships
  2737. $pattern = "/FROM $table_pattern([,\\s])/i";
  2738. $replacement = "FROM $tablename " . $this->db->dm_call_method('_escape_identifiers', $this->table . '_subquery') . '$1';
  2739. $sql = preg_replace($pattern, $replacement, $sql);
  2740. $sql = str_replace("\n", "\n\t", $sql);
  2741. return str_replace('${parent}', $this->table, $sql);
  2742. }
  2743. // --------------------------------------------------------------------
  2744. /**
  2745. * Manually adds an item to the SELECT column, to prevent it from
  2746. * being broken by AR->select
  2747. *
  2748. * @ignore
  2749. * @param string $value New SELECT value
  2750. */
  2751. protected function _add_to_select_directly($value)
  2752. {
  2753. // copied from system/database/DB_activerecord.php
  2754. $var = $this->db->dm_get('ar_select');
  2755. $var[] = $value;
  2756. $this->db->dm_set('ar_select', $var);
  2757. if ($this->db->dm_get('ar_caching') === TRUE)
  2758. {
  2759. $var = $this->db->dm_get('ar_cache_select');
  2760. $var[] = $value;
  2761. $this->db->dm_set('ar_cache_select', $var);
  2762. $var = $this->db->dm_get('ar_cache_exists');
  2763. $var[] = 'select';
  2764. $this->db->dm_set('ar_cache_exists', $var);
  2765. }
  2766. }
  2767. // --------------------------------------------------------------------
  2768. /**
  2769. * Handles specialized where clauses, like subqueries and functions
  2770. *
  2771. * @ignore
  2772. * @param string $query Query function
  2773. * @param string $field Field for Query function
  2774. * @param mixed $value Value for Query function
  2775. * @param mixed $extra If included, overrides the default assumption of FALSE for the third parameter to $query
  2776. * @return DataMapper Returns self for method chaining.
  2777. */
  2778. protected function _process_special_query_clause($query, $field, $value, $extra = NULL) {
  2779. if(strpos($query, 'where_in') !== FALSE) {
  2780. $query = str_replace('_in', '', $query);
  2781. $field .= ' IN ';
  2782. } else if(strpos($query, 'where_not_in') !== FALSE) {
  2783. $query = str_replace('_not_in', '', $query);
  2784. $field .= ' NOT IN ';
  2785. }
  2786. if(is_null($extra)) {
  2787. $extra = FALSE;
  2788. }
  2789. return $this->{$query}($field, $value, $extra);
  2790. }
  2791. // --------------------------------------------------------------------
  2792. /**
  2793. * Select
  2794. *
  2795. * Sets the SELECT portion of the query.
  2796. *
  2797. * @param mixed $select Field(s) to select, array or comma separated string
  2798. * @param bool $escape If FALSE, don't escape this field (Probably won't work)
  2799. * @return DataMapper Returns self for method chaining.
  2800. */
  2801. public function select($select = '*', $escape = NULL)
  2802. {
  2803. if ($escape !== FALSE) {
  2804. if (!is_array($select)) {
  2805. $select = $this->add_table_name($select);
  2806. } else {
  2807. $updated = array();
  2808. foreach ($select as $sel) {
  2809. $updated = $this->add_table_name($sel);
  2810. }
  2811. $select = $updated;
  2812. }
  2813. }
  2814. $this->db->select($select, $escape);
  2815. // For method chaining
  2816. return $this;
  2817. }
  2818. // --------------------------------------------------------------------
  2819. /**
  2820. * Select Max
  2821. *
  2822. * Sets the SELECT MAX(field) portion of a query.
  2823. *
  2824. * @param string $select Field to look at.
  2825. * @param string $alias Alias of the MAX value.
  2826. * @return DataMapper Returns self for method chaining.
  2827. */
  2828. public function select_max($select = '', $alias = '')
  2829. {
  2830. // Check if this is a related object
  2831. if ( ! empty($this->parent))
  2832. {
  2833. $alias = ($alias != '') ? $alias : $select;
  2834. }
  2835. $this->db->select_max($this->add_table_name($select), $alias);
  2836. // For method chaining
  2837. return $this;
  2838. }
  2839. // --------------------------------------------------------------------
  2840. /**
  2841. * Select Min
  2842. *
  2843. * Sets the SELECT MIN(field) portion of a query.
  2844. *
  2845. * @param string $select Field to look at.
  2846. * @param string $alias Alias of the MIN value.
  2847. * @return DataMapper Returns self for method chaining.
  2848. */
  2849. public function select_min($select = '', $alias = '')
  2850. {
  2851. // Check if this is a related object
  2852. if ( ! empty($this->parent))
  2853. {
  2854. $alias = ($alias != '') ? $alias : $select;
  2855. }
  2856. $this->db->select_min($this->add_table_name($select), $alias);
  2857. // For method chaining
  2858. return $this;
  2859. }
  2860. // --------------------------------------------------------------------
  2861. /**
  2862. * Select Avg
  2863. *
  2864. * Sets the SELECT AVG(field) portion of a query.
  2865. *
  2866. * @param string $select Field to look at.
  2867. * @param string $alias Alias of the AVG value.
  2868. * @return DataMapper Returns self for method chaining.
  2869. */
  2870. public function select_avg($select = '', $alias = '')
  2871. {
  2872. // Check if this is a related object
  2873. if ( ! empty($this->parent))
  2874. {
  2875. $alias = ($alias != '') ? $alias : $select;
  2876. }
  2877. $this->db->select_avg($this->add_table_name($select), $alias);
  2878. // For method chaining
  2879. return $this;
  2880. }
  2881. // --------------------------------------------------------------------
  2882. /**
  2883. * Select Sum
  2884. *
  2885. * Sets the SELECT SUM(field) portion of a query.
  2886. *
  2887. * @param string $select Field to look at.
  2888. * @param string $alias Alias of the SUM value.
  2889. * @return DataMapper Returns self for method chaining.
  2890. */
  2891. public function select_sum($select = '', $alias = '')
  2892. {
  2893. // Check if this is a related object
  2894. if ( ! empty($this->parent))
  2895. {
  2896. $alias = ($alias != '') ? $alias : $select;
  2897. }
  2898. $this->db->select_sum($this->add_table_name($select), $alias);
  2899. // For method chaining
  2900. return $this;
  2901. }
  2902. // --------------------------------------------------------------------
  2903. /**
  2904. * Distinct
  2905. *
  2906. * Sets the flag to add DISTINCT to the query.
  2907. *
  2908. * @param bool $value Set to FALSE to turn back off DISTINCT
  2909. * @return DataMapper Returns self for method chaining.
  2910. */
  2911. public function distinct($value = TRUE)
  2912. {
  2913. $this->db->distinct($value);
  2914. // For method chaining
  2915. return $this;
  2916. }
  2917. // --------------------------------------------------------------------
  2918. /**
  2919. * Get Where
  2920. *
  2921. * Get items matching the where clause.
  2922. *
  2923. * @param mixed $where See where()
  2924. * @param integer|NULL $limit Limit the number of results.
  2925. * @param integer|NULL $offset Offset the results when limiting.
  2926. * @return DataMapper Returns self for method chaining.
  2927. */
  2928. public function get_where($where = array(), $limit = NULL, $offset = NULL)
  2929. {
  2930. $this->where($where);
  2931. return $this->get($limit, $offset);
  2932. }
  2933. // --------------------------------------------------------------------
  2934. /**
  2935. * Starts a query group.
  2936. *
  2937. * @param string $not (Internal use only)
  2938. * @param string $type (Internal use only)
  2939. * @return DataMapper Returns self for method chaining.
  2940. */
  2941. public function group_start($not = '', $type = 'AND ')
  2942. {
  2943. // Increment group count number to make them unique
  2944. $this->_group_count++;
  2945. // in case groups are being nested
  2946. $type = $this->_get_prepend_type($type);
  2947. $this->_where_group_started = TRUE;
  2948. $prefix = (count($this->db->dm_get('ar_where')) == 0 AND count($this->db->dm_get('ar_cache_where')) == 0) ? '' : $type;
  2949. $value = $prefix . $not . str_repeat(' ', $this->_group_count) . ' (';
  2950. $var = $this->db->dm_get('ar_where');
  2951. $var[] = $value;
  2952. $this->db->dm_set('ar_where', $var);
  2953. if ($this->db->dm_get('ar_caching'))
  2954. {
  2955. $var = $this->db->dm_get('ar_cache_where');
  2956. $var[] = $value;
  2957. $this->db->dm_set('ar_cache_where', $var);
  2958. }
  2959. return $this;
  2960. }
  2961. // --------------------------------------------------------------------
  2962. /**
  2963. * Starts a query group, but ORs the group
  2964. * @return DataMapper Returns self for method chaining.
  2965. */
  2966. public function or_group_start()
  2967. {
  2968. return $this->group_start('', 'OR ');
  2969. }
  2970. // --------------------------------------------------------------------
  2971. /**
  2972. * Starts a query group, but NOTs the group
  2973. * @return DataMapper Returns self for method chaining.
  2974. */
  2975. public function not_group_start()
  2976. {
  2977. return $this->group_start('NOT ', 'OR ');
  2978. }
  2979. // --------------------------------------------------------------------
  2980. /**
  2981. * Starts a query group, but OR NOTs the group
  2982. * @return DataMapper Returns self for method chaining.
  2983. */
  2984. public function or_not_group_start()
  2985. {
  2986. return $this->group_start('NOT ', 'OR ');
  2987. }
  2988. // --------------------------------------------------------------------
  2989. /**
  2990. * Ends a query group.
  2991. * @return DataMapper Returns self for method chaining.
  2992. */
  2993. public function group_end()
  2994. {
  2995. $value = str_repeat(' ', $this->_group_count) . ')';
  2996. $var = $this->db->dm_get('ar_where');
  2997. $var[] = $value;
  2998. $this->db->dm_set('ar_where', $var);
  2999. if($this->db->ar_caching) $this->db->ar_cache_where[] = $value;
  3000. $this->_where_group_started = FALSE;
  3001. return $this;
  3002. }
  3003. // --------------------------------------------------------------------
  3004. /**
  3005. * protected function to convert the AND or OR prefix to '' when starting
  3006. * a group.
  3007. *
  3008. * @ignore
  3009. * @param object $type Current type value
  3010. * @return New type value
  3011. */
  3012. protected function _get_prepend_type($type)
  3013. {
  3014. if($this->_where_group_started)
  3015. {
  3016. $type = '';
  3017. $this->_where_group_started = FALSE;
  3018. }
  3019. return $type;
  3020. }
  3021. // --------------------------------------------------------------------
  3022. /**
  3023. * Where
  3024. *
  3025. * Sets the WHERE portion of the query.
  3026. * Separates multiple calls with AND.
  3027. *
  3028. * Called by get_where()
  3029. *
  3030. * @param mixed $key A field or array of fields to check.
  3031. * @param mixed $value For a single field, the value to compare to.
  3032. * @param bool $escape If FALSE, the field is not escaped.
  3033. * @return DataMapper Returns self for method chaining.
  3034. */
  3035. public function where($key, $value = NULL, $escape = TRUE)
  3036. {
  3037. return $this->_where($key, $value, 'AND ', $escape);
  3038. }
  3039. // --------------------------------------------------------------------
  3040. /**
  3041. * Or Where
  3042. *
  3043. * Sets the WHERE portion of the query.
  3044. * Separates multiple calls with OR.
  3045. *
  3046. * @param mixed $key A field or array of fields to check.
  3047. * @param mixed $value For a single field, the value to compare to.
  3048. * @param bool $escape If FALSE, the field is not escaped.
  3049. * @return DataMapper Returns self for method chaining.
  3050. */
  3051. public function or_where($key, $value = NULL, $escape = TRUE)
  3052. {
  3053. return $this->_where($key, $value, 'OR ', $escape);
  3054. }
  3055. // --------------------------------------------------------------------
  3056. /**
  3057. * Where
  3058. *
  3059. * Called by where() or or_where().
  3060. *
  3061. * @ignore
  3062. * @param mixed $key A field or array of fields to check.
  3063. * @param mixed $value For a single field, the value to compare to.
  3064. * @param string $type Type of addition (AND or OR)
  3065. * @param bool $escape If FALSE, the field is not escaped.
  3066. * @return DataMapper Returns self for method chaining.
  3067. */
  3068. protected function _where($key, $value = NULL, $type = 'AND ', $escape = NULL)
  3069. {
  3070. if ( ! is_array($key))
  3071. {
  3072. $key = array($key => $value);
  3073. }
  3074. foreach ($key as $k => $v)
  3075. {
  3076. $new_k = $this->add_table_name($k);
  3077. $this->db->dm_call_method('_where', $new_k, $v, $this->_get_prepend_type($type), $escape);
  3078. }
  3079. // For method chaining
  3080. return $this;
  3081. }
  3082. // --------------------------------------------------------------------
  3083. /**
  3084. * Where Between
  3085. *
  3086. * Sets the WHERE field BETWEEN 'value1' AND 'value2' SQL query joined with
  3087. * AND if appropriate.
  3088. *
  3089. * @param string $key A field to check.
  3090. * @param mixed $value value to start with
  3091. * @param mixed $value value to end with
  3092. * @return DataMapper Returns self for method chaining.
  3093. */
  3094. public function where_between($key = NULL, $value1 = NULL, $value2 = NULL)
  3095. {
  3096. return $this->_where_between($key, $value1, $value2);
  3097. }
  3098. // --------------------------------------------------------------------
  3099. /**
  3100. * Where Between
  3101. *
  3102. * Sets the WHERE field BETWEEN 'value1' AND 'value2' SQL query joined with
  3103. * AND if appropriate.
  3104. *
  3105. * @param string $key A field to check.
  3106. * @param mixed $value value to start with
  3107. * @param mixed $value value to end with
  3108. * @return DataMapper Returns self for method chaining.
  3109. */
  3110. public function where_not_between($key = NULL, $value1 = NULL, $value2 = NULL)
  3111. {
  3112. return $this->_where_between($key, $value1, $value2, TRUE);
  3113. }
  3114. // --------------------------------------------------------------------
  3115. /**
  3116. * Where Between
  3117. *
  3118. * Sets the WHERE field BETWEEN 'value1' AND 'value2' SQL query joined with
  3119. * AND if appropriate.
  3120. *
  3121. * @param string $key A field to check.
  3122. * @param mixed $value value to start with
  3123. * @param mixed $value value to end with
  3124. * @return DataMapper Returns self for method chaining.
  3125. */
  3126. public function or_where_between($key = NULL, $value1 = NULL, $value2 = NULL)
  3127. {
  3128. return $this->_where_between($key, $value1, $value2, FALSE, 'OR ');
  3129. }
  3130. // --------------------------------------------------------------------
  3131. /**
  3132. * Where Between
  3133. *
  3134. * Sets the WHERE field BETWEEN 'value1' AND 'value2' SQL query joined with
  3135. * AND if appropriate.
  3136. *
  3137. * @param string $key A field to check.
  3138. * @param mixed $value value to start with
  3139. * @param mixed $value value to end with
  3140. * @return DataMapper Returns self for method chaining.
  3141. */
  3142. public function or_where_not_between($key = NULL, $value1 = NULL, $value2 = NULL)
  3143. {
  3144. return $this->_where_between($key, $value1, $value2, TRUE, 'OR ');
  3145. }
  3146. // --------------------------------------------------------------------
  3147. /**
  3148. * Where In
  3149. *
  3150. * Sets the WHERE field IN ('item', 'item') SQL query joined with
  3151. * AND if appropriate.
  3152. *
  3153. * @param string $key A field to check.
  3154. * @param array $values An array of values to compare against
  3155. * @return DataMapper Returns self for method chaining.
  3156. */
  3157. public function where_in($key = NULL, $values = NULL)
  3158. {
  3159. return $this->_where_in($key, $values);
  3160. }
  3161. // --------------------------------------------------------------------
  3162. /**
  3163. * Or Where In
  3164. *
  3165. * Sets the WHERE field IN ('item', 'item') SQL query joined with
  3166. * OR if appropriate.
  3167. *
  3168. * @param string $key A field to check.
  3169. * @param array $values An array of values to compare against
  3170. * @return DataMapper Returns self for method chaining.
  3171. */
  3172. public function or_where_in($key = NULL, $values = NULL)
  3173. {
  3174. return $this->_where_in($key, $values, FALSE, 'OR ');
  3175. }
  3176. // --------------------------------------------------------------------
  3177. /**
  3178. * Where Not In
  3179. *
  3180. * Sets the WHERE field NOT IN ('item', 'item') SQL query joined with
  3181. * AND if appropriate.
  3182. *
  3183. * @param string $key A field to check.
  3184. * @param array $values An array of values to compare against
  3185. * @return DataMapper Returns self for method chaining.
  3186. */
  3187. public function where_not_in($key = NULL, $values = NULL)
  3188. {
  3189. return $this->_where_in($key, $values, TRUE);
  3190. }
  3191. // --------------------------------------------------------------------
  3192. /**
  3193. * Or Where Not In
  3194. *
  3195. * Sets the WHERE field NOT IN ('item', 'item') SQL query joined wuth
  3196. * OR if appropriate.
  3197. *
  3198. * @param string $key A field to check.
  3199. * @param array $values An array of values to compare against
  3200. * @return DataMapper Returns self for method chaining.
  3201. */
  3202. public function or_where_not_in($key = NULL, $values = NULL)
  3203. {
  3204. return $this->_where_in($key, $values, TRUE, 'OR ');
  3205. }
  3206. // --------------------------------------------------------------------
  3207. /**
  3208. * Where In
  3209. *
  3210. * Called by where_in(), or_where_in(), where_not_in(), or or_where_not_in().
  3211. *
  3212. * @ignore
  3213. * @param string $key A field to check.
  3214. * @param array $values An array of values to compare against
  3215. * @param bool $not If TRUE, use NOT IN instead of IN.
  3216. * @param string $type The type of connection (AND or OR)
  3217. * @return DataMapper Returns self for method chaining.
  3218. */
  3219. protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ')
  3220. {
  3221. $type = $this->_get_prepend_type($type);
  3222. if ($values instanceOf DataMapper)
  3223. {
  3224. $arr = array();
  3225. foreach ($values as $value)
  3226. {
  3227. $arr[] = $value->id;
  3228. }
  3229. $values = $arr;
  3230. }
  3231. $this->db->dm_call_method('_where_in', $this->add_table_name($key), $values, $not, $type);
  3232. // For method chaining
  3233. return $this;
  3234. }
  3235. // --------------------------------------------------------------------
  3236. /**
  3237. * Where Between
  3238. *
  3239. * Called by where_between(), or_where_between(), where_not_between(), or or_where_not_between().
  3240. *
  3241. * @ignore
  3242. * @param string $key A field to check.
  3243. * @param mixed $value value to start with
  3244. * @param mixed $value value to end with
  3245. * @param bool $not If TRUE, use NOT IN instead of IN.
  3246. * @param string $type The type of connection (AND or OR)
  3247. * @return DataMapper Returns self for method chaining.
  3248. */
  3249. protected function _where_between($key = NULL, $value1 = NULL, $value2 = NULL, $not = FALSE, $type = 'AND ')
  3250. {
  3251. $type = $this->_get_prepend_type($type);
  3252. $this->db->dm_call_method('_where', $this->add_table_name($key)." ".($not?"NOT ":"")."BETWEEN ".$this->db->escape($value1)." AND ".$this->db->escape($value2), NULL, $type, NULL);
  3253. // For method chaining
  3254. return $this;
  3255. }
  3256. // --------------------------------------------------------------------
  3257. /**
  3258. * Like
  3259. *
  3260. * Sets the %LIKE% portion of the query.
  3261. * Separates multiple calls with AND.
  3262. *
  3263. * @param mixed $field A field or array of fields to check.
  3264. * @param mixed $match For a single field, the value to compare to.
  3265. * @param string $side One of 'both', 'before', or 'after'
  3266. * @return DataMapper Returns self for method chaining.
  3267. */
  3268. public function like($field, $match = '', $side = 'both')
  3269. {
  3270. return $this->_like($field, $match, 'AND ', $side);
  3271. }
  3272. // --------------------------------------------------------------------
  3273. /**
  3274. * Not Like
  3275. *
  3276. * Sets the NOT LIKE portion of the query.
  3277. * Separates multiple calls with AND.
  3278. *
  3279. * @param mixed $field A field or array of fields to check.
  3280. * @param mixed $match For a single field, the value to compare to.
  3281. * @param string $side One of 'both', 'before', or 'after'
  3282. * @return DataMapper Returns self for method chaining.
  3283. */
  3284. public function not_like($field, $match = '', $side = 'both')
  3285. {
  3286. return $this->_like($field, $match, 'AND ', $side, 'NOT');
  3287. }
  3288. // --------------------------------------------------------------------
  3289. /**
  3290. * Or Like
  3291. *
  3292. * Sets the %LIKE% portion of the query.
  3293. * Separates multiple calls with OR.
  3294. *
  3295. * @param mixed $field A field or array of fields to check.
  3296. * @param mixed $match For a single field, the value to compare to.
  3297. * @param string $side One of 'both', 'before', or 'after'
  3298. * @return DataMapper Returns self for method chaining.
  3299. */
  3300. public function or_like($field, $match = '', $side = 'both')
  3301. {
  3302. return $this->_like($field, $match, 'OR ', $side);
  3303. }
  3304. // --------------------------------------------------------------------
  3305. /**
  3306. * Or Not Like
  3307. *
  3308. * Sets the NOT LIKE portion of the query.
  3309. * Separates multiple calls with OR.
  3310. *
  3311. * @param mixed $field A field or array of fields to check.
  3312. * @param mixed $match For a single field, the value to compare to.
  3313. * @param string $side One of 'both', 'before', or 'after'
  3314. * @return DataMapper Returns self for method chaining.
  3315. */
  3316. public function or_not_like($field, $match = '', $side = 'both')
  3317. {
  3318. return $this->_like($field, $match, 'OR ', $side, 'NOT');
  3319. }
  3320. // --------------------------------------------------------------------
  3321. /**
  3322. * ILike
  3323. *
  3324. * Sets the case-insensitive %LIKE% portion of the query.
  3325. *
  3326. * @param mixed $field A field or array of fields to check.
  3327. * @param mixed $match For a single field, the value to compare to.
  3328. * @param string $side One of 'both', 'before', or 'after'
  3329. * @return DataMapper Returns self for method chaining.
  3330. */
  3331. public function ilike($field, $match = '', $side = 'both')
  3332. {
  3333. return $this->_like($field, $match, 'AND ', $side, '', TRUE);
  3334. }
  3335. // --------------------------------------------------------------------
  3336. /**
  3337. * Not ILike
  3338. *
  3339. * Sets the case-insensitive NOT LIKE portion of the query.
  3340. * Separates multiple calls with AND.
  3341. *
  3342. * @param mixed $field A field or array of fields to check.
  3343. * @param mixed $match For a single field, the value to compare to.
  3344. * @param string $side One of 'both', 'before', or 'after'
  3345. * @return DataMapper Returns self for method chaining.
  3346. */
  3347. public function not_ilike($field, $match = '', $side = 'both')
  3348. {
  3349. return $this->_like($field, $match, 'AND ', $side, 'NOT', TRUE);
  3350. }
  3351. // --------------------------------------------------------------------
  3352. /**
  3353. * Or Like
  3354. *
  3355. * Sets the case-insensitive %LIKE% portion of the query.
  3356. * Separates multiple calls with OR.
  3357. *
  3358. * @param mixed $field A field or array of fields to check.
  3359. * @param mixed $match For a single field, the value to compare to.
  3360. * @param string $side One of 'both', 'before', or 'after'
  3361. * @return DataMapper Returns self for method chaining.
  3362. */
  3363. public function or_ilike($field, $match = '', $side = 'both')
  3364. {
  3365. return $this->_like($field, $match, 'OR ', $side, '', TRUE);
  3366. }
  3367. // --------------------------------------------------------------------
  3368. /**
  3369. * Or Not Like
  3370. *
  3371. * Sets the case-insensitive NOT LIKE portion of the query.
  3372. * Separates multiple calls with OR.
  3373. *
  3374. * @param mixed $field A field or array of fields to check.
  3375. * @param mixed $match For a single field, the value to compare to.
  3376. * @param string $side One of 'both', 'before', or 'after'
  3377. * @return DataMapper Returns self for method chaining.
  3378. */
  3379. public function or_not_ilike($field, $match = '', $side = 'both')
  3380. {
  3381. return $this->_like($field, $match, 'OR ', $side, 'NOT', TRUE);
  3382. }
  3383. // --------------------------------------------------------------------
  3384. /**
  3385. * _Like
  3386. *
  3387. * Private function to do actual work.
  3388. * NOTE: this does NOT use the built-in ActiveRecord LIKE function.
  3389. *
  3390. * @ignore
  3391. * @param mixed $field A field or array of fields to check.
  3392. * @param mixed $match For a single field, the value to compare to.
  3393. * @param string $type The type of connection (AND or OR)
  3394. * @param string $side One of 'both', 'before', or 'after'
  3395. * @param string $not 'NOT' or ''
  3396. * @param bool $no_case If TRUE, configure to ignore case.
  3397. * @return DataMapper Returns self for method chaining.
  3398. */
  3399. protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '', $no_case = FALSE)
  3400. {
  3401. if ( ! is_array($field))
  3402. {
  3403. $field = array($field => $match);
  3404. }
  3405. foreach ($field as $k => $v)
  3406. {
  3407. $new_k = $this->add_table_name($k);
  3408. if ($new_k != $k)
  3409. {
  3410. $field[$new_k] = $v;
  3411. unset($field[$k]);
  3412. }
  3413. }
  3414. // Taken from CodeIgniter's Active Record because (for some reason)
  3415. // it is stored separately that normal where statements.
  3416. foreach ($field as $k => $v)
  3417. {
  3418. if($no_case)
  3419. {
  3420. $k = 'UPPER(' . $this->db->protect_identifiers($k) .')';
  3421. $v = strtoupper($v);
  3422. }
  3423. $f = "$k $not LIKE ";
  3424. if ($side == 'before')
  3425. {
  3426. $m = "%{$v}";
  3427. }
  3428. elseif ($side == 'after')
  3429. {
  3430. $m = "{$v}%";
  3431. }
  3432. else
  3433. {
  3434. $m = "%{$v}%";
  3435. }
  3436. $this->_where($f, $m, $type, TRUE);
  3437. }
  3438. // For method chaining
  3439. return $this;
  3440. }
  3441. // --------------------------------------------------------------------
  3442. /**
  3443. * Group By
  3444. *
  3445. * Sets the GROUP BY portion of the query.
  3446. *
  3447. * @param string $by Field to group by
  3448. * @return DataMapper Returns self for method chaining.
  3449. */
  3450. public function group_by($by)
  3451. {
  3452. $this->db->group_by($this->add_table_name($by));
  3453. // For method chaining
  3454. return $this;
  3455. }
  3456. // --------------------------------------------------------------------
  3457. /**
  3458. * Having
  3459. *
  3460. * Sets the HAVING portion of the query.
  3461. * Separates multiple calls with AND.
  3462. *
  3463. * @param string $key Field to compare.
  3464. * @param string $value value to compare to.
  3465. * @param bool $escape If FALSE, don't escape the value.
  3466. * @return DataMapper Returns self for method chaining.
  3467. */
  3468. public function having($key, $value = '', $escape = TRUE)
  3469. {
  3470. return $this->_having($key, $value, 'AND ', $escape);
  3471. }
  3472. // --------------------------------------------------------------------
  3473. /**
  3474. * Or Having
  3475. *
  3476. * Sets the OR HAVING portion of the query.
  3477. * Separates multiple calls with OR.
  3478. *
  3479. * @param string $key Field to compare.
  3480. * @param string $value value to compare to.
  3481. * @param bool $escape If FALSE, don't escape the value.
  3482. * @return DataMapper Returns self for method chaining.
  3483. */
  3484. public function or_having($key, $value = '', $escape = TRUE)
  3485. {
  3486. return $this->_having($key, $value, 'OR ', $escape);
  3487. }
  3488. // --------------------------------------------------------------------
  3489. /**
  3490. * Having
  3491. *
  3492. * Sets the HAVING portion of the query.
  3493. * Separates multiple calls with AND.
  3494. *
  3495. * @ignore
  3496. * @param string $key Field to compare.
  3497. * @param string $value value to compare to.
  3498. * @param string $type Type of connection (AND or OR)
  3499. * @param bool $escape If FALSE, don't escape the value.
  3500. * @return DataMapper Returns self for method chaining.
  3501. */
  3502. protected function _having($key, $value = '', $type = 'AND ', $escape = TRUE)
  3503. {
  3504. $this->db->dm_call_method('_having', $this->add_table_name($key), $value, $type, $escape);
  3505. // For method chaining
  3506. return $this;
  3507. }
  3508. // --------------------------------------------------------------------
  3509. /**
  3510. * Order By
  3511. *
  3512. * Sets the ORDER BY portion of the query.
  3513. *
  3514. * @param string $orderby Field to order by
  3515. * @param string $direction One of 'ASC' or 'DESC' Defaults to 'ASC'
  3516. * @return DataMapper Returns self for method chaining.
  3517. */
  3518. public function order_by($orderby, $direction = '')
  3519. {
  3520. // prefix the field with the table name if no prefix is given
  3521. strpos($orderby, '.') === FALSE AND $orderby = $this->add_table_name($orderby);
  3522. $this->db->order_by($orderby, $direction);
  3523. // For method chaining
  3524. return $this;
  3525. }
  3526. // --------------------------------------------------------------------
  3527. /**
  3528. * Adds in the defaut order_by items, if there are any, and
  3529. * order_by hasn't been overridden.
  3530. * @ignore
  3531. */
  3532. protected function _handle_default_order_by()
  3533. {
  3534. if(empty($this->default_order_by))
  3535. {
  3536. return;
  3537. }
  3538. $sel = $this->table . '.' . '*';
  3539. $sel_protect = $this->db->protect_identifiers($sel);
  3540. // only add the items if there isn't an existing order_by,
  3541. // AND the select statement is empty or includes * or table.* or `table`.*
  3542. if(empty($this->db->ar_orderby) &&
  3543. (
  3544. empty($this->db->ar_select) ||
  3545. in_array('*', $this->db->ar_select) ||
  3546. in_array($sel_protect, $this->db->ar_select) ||
  3547. in_array($sel, $this->db->ar_select)
  3548. ))
  3549. {
  3550. foreach($this->default_order_by as $k => $v) {
  3551. if(is_int($k)) {
  3552. $k = $v;
  3553. $v = '';
  3554. }
  3555. $k = $this->add_table_name($k);
  3556. $this->order_by($k, $v);
  3557. }
  3558. }
  3559. }
  3560. // --------------------------------------------------------------------
  3561. /**
  3562. * Limit
  3563. *
  3564. * Sets the LIMIT portion of the query.
  3565. *
  3566. * @param integer $limit Limit the number of results.
  3567. * @param integer|NULL $offset Offset the results when limiting.
  3568. * @return DataMapper Returns self for method chaining.
  3569. */
  3570. public function limit($value, $offset = '')
  3571. {
  3572. $this->db->limit($value, $offset);
  3573. // For method chaining
  3574. return $this;
  3575. }
  3576. // --------------------------------------------------------------------
  3577. /**
  3578. * Offset
  3579. *
  3580. * Sets the OFFSET portion of the query.
  3581. *
  3582. * @param integer $offset Offset the results when limiting.
  3583. * @return DataMapper Returns self for method chaining.
  3584. */
  3585. public function offset($offset)
  3586. {
  3587. $this->db->offset($offset);
  3588. // For method chaining
  3589. return $this;
  3590. }
  3591. // --------------------------------------------------------------------
  3592. /**
  3593. * Start Cache
  3594. *
  3595. * Starts AR caching.
  3596. */
  3597. public function start_cache()
  3598. {
  3599. $this->db->start_cache();
  3600. }
  3601. // --------------------------------------------------------------------
  3602. /**
  3603. * Stop Cache
  3604. *
  3605. * Stops AR caching.
  3606. */
  3607. public function stop_cache()
  3608. {
  3609. $this->db->stop_cache();
  3610. }
  3611. // --------------------------------------------------------------------
  3612. /**
  3613. * Flush Cache
  3614. *
  3615. * Empties the AR cache.
  3616. */
  3617. public function flush_cache()
  3618. {
  3619. $this->db->flush_cache();
  3620. }
  3621. // --------------------------------------------------------------------
  3622. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  3623. * *
  3624. * Transaction methods *
  3625. * *
  3626. * The following are methods used for transaction handling. *
  3627. * *
  3628. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  3629. // --------------------------------------------------------------------
  3630. /**
  3631. * Trans Off
  3632. *
  3633. * This permits transactions to be disabled at run-time.
  3634. *
  3635. */
  3636. public function trans_off()
  3637. {
  3638. $this->db->trans_enabled = FALSE;
  3639. }
  3640. // --------------------------------------------------------------------
  3641. /**
  3642. * Trans Strict
  3643. *
  3644. * When strict mode is enabled, if you are running multiple groups of
  3645. * transactions, if one group fails all groups will be rolled back.
  3646. * If strict mode is disabled, each group is treated autonomously, meaning
  3647. * a failure of one group will not affect any others.
  3648. *
  3649. * @param bool $mode Set to false to disable strict mode.
  3650. */
  3651. public function trans_strict($mode = TRUE)
  3652. {
  3653. $this->db->trans_strict($mode);
  3654. }
  3655. // --------------------------------------------------------------------
  3656. /**
  3657. * Trans Start
  3658. *
  3659. * Start a transaction.
  3660. *
  3661. * @param bool $test_mode Set to TRUE to only run a test (and not commit)
  3662. */
  3663. public function trans_start($test_mode = FALSE)
  3664. {
  3665. $this->db->trans_start($test_mode);
  3666. }
  3667. // --------------------------------------------------------------------
  3668. /**
  3669. * Trans Complete
  3670. *
  3671. * Complete a transaction.
  3672. *
  3673. * @return bool Success or Failure
  3674. */
  3675. public function trans_complete()
  3676. {
  3677. return $this->db->trans_complete();
  3678. }
  3679. // --------------------------------------------------------------------
  3680. /**
  3681. * Trans Begin
  3682. *
  3683. * Begin a transaction.
  3684. *
  3685. * @param bool $test_mode Set to TRUE to only run a test (and not commit)
  3686. * @return bool Success or Failure
  3687. */
  3688. public function trans_begin($test_mode = FALSE)
  3689. {
  3690. return $this->db->trans_begin($test_mode);
  3691. }
  3692. // --------------------------------------------------------------------
  3693. /**
  3694. * Trans Status
  3695. *
  3696. * Lets you retrieve the transaction flag to determine if it has failed.
  3697. *
  3698. * @return bool Returns FALSE if the transaction has failed.
  3699. */
  3700. public function trans_status()
  3701. {
  3702. return $this->db->trans_status();
  3703. }
  3704. // --------------------------------------------------------------------
  3705. /**
  3706. * Trans Commit
  3707. *
  3708. * Commit a transaction.
  3709. *
  3710. * @return bool Success or Failure
  3711. */
  3712. public function trans_commit()
  3713. {
  3714. return $this->db->trans_commit();
  3715. }
  3716. // --------------------------------------------------------------------
  3717. /**
  3718. * Trans Rollback
  3719. *
  3720. * Rollback a transaction.
  3721. *
  3722. * @return bool Success or Failure
  3723. */
  3724. public function trans_rollback()
  3725. {
  3726. return $this->db->trans_rollback();
  3727. }
  3728. // --------------------------------------------------------------------
  3729. /**
  3730. * Auto Trans Begin
  3731. *
  3732. * Begin an auto transaction if enabled.
  3733. *
  3734. */
  3735. protected function _auto_trans_begin()
  3736. {
  3737. // Begin auto transaction
  3738. if ($this->auto_transaction)
  3739. {
  3740. $this->trans_begin();
  3741. }
  3742. }
  3743. // --------------------------------------------------------------------
  3744. /**
  3745. * Auto Trans Complete
  3746. *
  3747. * Complete an auto transaction if enabled.
  3748. *
  3749. * @param string $label Name for this transaction.
  3750. */
  3751. protected function _auto_trans_complete($label = 'complete')
  3752. {
  3753. // Complete auto transaction
  3754. if ($this->auto_transaction)
  3755. {
  3756. // Check if successful
  3757. if (!$this->trans_complete())
  3758. {
  3759. $rule = 'transaction';
  3760. // Get corresponding error from language file
  3761. if (FALSE === ($line = $this->lang->dm_line($rule)))
  3762. {
  3763. $line = 'Unable to access the ' . $rule .' error message.';
  3764. }
  3765. // Add transaction error message
  3766. $this->error_message($rule, sprintf($line, $label));
  3767. // Set validation as failed
  3768. $this->valid = FALSE;
  3769. }
  3770. }
  3771. }
  3772. // --------------------------------------------------------------------
  3773. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  3774. * *
  3775. * Related methods *
  3776. * *
  3777. * The following are methods used for managing related records. *
  3778. * *
  3779. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  3780. // --------------------------------------------------------------------
  3781. /**
  3782. * get_related_properties
  3783. *
  3784. * Located the relationship properties for a given field or model
  3785. * Can also optionally attempt to convert the $related_field to
  3786. * singular, and look up on that. It will modify the $related_field if
  3787. * the conversion to singular returns a result.
  3788. *
  3789. * $related_field can also be a deep relationship, such as
  3790. * 'post/editor/group', in which case the $related_field will be processed
  3791. * recursively, and the return value will be $user->has_NN['group'];
  3792. *
  3793. * @ignore
  3794. * @param mixed $related_field Name of related field or related object.
  3795. * @param bool $try_singular If TRUE, automatically tries to look for a singular name if not found.
  3796. * @return array Associative array of related properties.
  3797. */
  3798. public function _get_related_properties(&$related_field, $try_singular = FALSE)
  3799. {
  3800. // Handle deep relationships
  3801. if(strpos($related_field, '/') !== FALSE)
  3802. {
  3803. $rfs = explode('/', $related_field);
  3804. $last = $this;
  3805. $prop = NULL;
  3806. foreach($rfs as &$rf)
  3807. {
  3808. $prop = $last->_get_related_properties($rf, $try_singular);
  3809. if(is_null($prop))
  3810. {
  3811. break;
  3812. }
  3813. $last =& $last->_get_without_auto_populating($rf);
  3814. }
  3815. if( ! is_null($prop))
  3816. {
  3817. // update in case any items were converted to singular.
  3818. $related_field = implode('/', $rfs);
  3819. }
  3820. return $prop;
  3821. }
  3822. else
  3823. {
  3824. if (isset($this->has_many[$related_field]))
  3825. {
  3826. return $this->has_many[$related_field];
  3827. }
  3828. else if (isset($this->has_one[$related_field]))
  3829. {
  3830. return $this->has_one[$related_field];
  3831. }
  3832. else
  3833. {
  3834. if($try_singular)
  3835. {
  3836. $rf = singular($related_field);
  3837. $ret = $this->_get_related_properties($rf);
  3838. if( is_null($ret))
  3839. {
  3840. show_error("Unable to relate {$this->model} with $related_field.");
  3841. }
  3842. else
  3843. {
  3844. $related_field = $rf;
  3845. return $ret;
  3846. }
  3847. }
  3848. else
  3849. {
  3850. // not related
  3851. return NULL;
  3852. }
  3853. }
  3854. }
  3855. }
  3856. // --------------------------------------------------------------------
  3857. /**
  3858. * Add Related Table
  3859. *
  3860. * Adds the table of a related item, and joins it to this class.
  3861. * Returns the name of that table for further queries.
  3862. *
  3863. * If $related_field is deep, then this adds all necessary relationships
  3864. * to the query.
  3865. *
  3866. * @ignore
  3867. * @param mixed $object The object (or related field) to look up.
  3868. * @param string $related_field Related field name for object
  3869. * @param string $id_only Private, do not use.
  3870. * @param object $db Private, do not use.
  3871. * @param array $query_related Private, do not use.
  3872. * @param string $name_prepend Private, do not use.
  3873. * @param string $this_table Private, do not use.
  3874. * @return string Name of the related table, or table.field if ID_Only
  3875. */
  3876. public function _add_related_table($object, $related_field = '', $id_only = FALSE, $db = NULL, &$query_related = NULL, $name_prepend = '', $this_table = NULL)
  3877. {
  3878. if ( is_string($object))
  3879. {
  3880. // only a model was passed in, not an object
  3881. $related_field = $object;
  3882. $object = NULL;
  3883. }
  3884. else if (empty($related_field))
  3885. {
  3886. // model was not passed, so get the Object's native model
  3887. $related_field = $object->model;
  3888. }
  3889. $related_field = strtolower($related_field);
  3890. // Handle deep relationships
  3891. if(strpos($related_field, '/') !== FALSE)
  3892. {
  3893. $rfs = explode('/', $related_field);
  3894. $last = $this;
  3895. $prepend = '';
  3896. $object_as = NULL;
  3897. foreach($rfs as $index => $rf)
  3898. {
  3899. // if this is the last item added, we can use the $id_only
  3900. // shortcut to prevent unnecessarily adding the last table.
  3901. $temp_id_only = $id_only;
  3902. if($temp_id_only) {
  3903. if($index < count($rfs)-1) {
  3904. $temp_id_only = FALSE;
  3905. }
  3906. }
  3907. $object_as = $last->_add_related_table($rf, '', $temp_id_only, $this->db, $this->_query_related, $prepend, $object_as);
  3908. $prepend .= $rf . '_';
  3909. $last =& $last->_get_without_auto_populating($rf);
  3910. }
  3911. return $object_as;
  3912. }
  3913. $related_properties = $this->_get_related_properties($related_field);
  3914. $class = $related_properties['class'];
  3915. $this_model = $related_properties['join_self_as'];
  3916. $other_model = $related_properties['join_other_as'];
  3917. if (empty($object))
  3918. {
  3919. // no object was passed in, so create one
  3920. $object = new $class();
  3921. }
  3922. if(is_null($query_related))
  3923. {
  3924. $query_related =& $this->_query_related;
  3925. }
  3926. if(is_null($this_table))
  3927. {
  3928. $this_table = $this->table;
  3929. }
  3930. // Determine relationship table name
  3931. $relationship_table = $this->_get_relationship_table($object, $related_field);
  3932. // only add $related_field to the table name if the 'class' and 'related_field' aren't equal
  3933. // and the related object is in a different table
  3934. if ( ($class == $related_field) && ($this->table != $object->table) )
  3935. {
  3936. $object_as = $name_prepend . $object->table;
  3937. $relationship_as = $name_prepend . $relationship_table;
  3938. }
  3939. else
  3940. {
  3941. $object_as = $name_prepend . $related_field . '_' . $object->table;
  3942. $relationship_as = str_replace('.', '_', $name_prepend . $related_field . '_' . $relationship_table);
  3943. }
  3944. $other_column = $other_model . '_id';
  3945. $this_column = $this_model . '_id' ;
  3946. if(is_null($db)) {
  3947. $db = $this->db;
  3948. }
  3949. // Force the selection of the current object's columns
  3950. if (empty($db->ar_select))
  3951. {
  3952. $db->select($this->table . '.*');
  3953. }
  3954. // the extra in_array column check is for has_one self references
  3955. if ($relationship_table == $this->table && in_array($other_column, $this->fields))
  3956. {
  3957. // has_one relationship without a join table
  3958. if($id_only)
  3959. {
  3960. // nothing to join, just return the correct data
  3961. $object_as = $this_table . '.' . $other_column;
  3962. }
  3963. else if ( ! in_array($object_as, $query_related))
  3964. {
  3965. $db->join($object->table . ' ' .$object_as, $object_as . '.id = ' . $this_table . '.' . $other_column, 'LEFT OUTER');
  3966. $query_related[] = $object_as;
  3967. }
  3968. }
  3969. // the extra in_array column check is for has_one self references
  3970. else if ($relationship_table == $object->table && in_array($this_column, $object->fields))
  3971. {
  3972. // has_one relationship without a join table
  3973. if ( ! in_array($object_as, $query_related))
  3974. {
  3975. $db->join($object->table . ' ' .$object_as, $this_table . '.id = ' . $object_as . '.' . $this_column, 'LEFT OUTER');
  3976. $query_related[] = $object_as;
  3977. }
  3978. if($id_only)
  3979. {
  3980. // include the column name
  3981. $object_as .= '.id';
  3982. }
  3983. }
  3984. else
  3985. {
  3986. // has_one or has_many with a normal join table
  3987. // Add join if not already included
  3988. if ( ! in_array($relationship_as, $query_related))
  3989. {
  3990. $db->join($relationship_table . ' ' . $relationship_as, $this_table . '.id = ' . $relationship_as . '.' . $this_column, 'LEFT OUTER');
  3991. if($this->_include_join_fields) {
  3992. $fields = $db->field_data($relationship_table);
  3993. foreach($fields as $key => $f)
  3994. {
  3995. if($f->name == $this_column || $f->name == $other_column)
  3996. {
  3997. unset($fields[$key]);
  3998. }
  3999. }
  4000. // add all other fields
  4001. $selection = '';
  4002. foreach ($fields as $field)
  4003. {
  4004. $new_field = 'join_'.$field->name;
  4005. if (!empty($selection))
  4006. {
  4007. $selection .= ', ';
  4008. }
  4009. $selection .= $relationship_as.'.'.$field->name.' AS '.$new_field;
  4010. }
  4011. $db->select($selection);
  4012. // now reset the flag
  4013. $this->_include_join_fields = FALSE;
  4014. }
  4015. $query_related[] = $relationship_as;
  4016. }
  4017. if($id_only)
  4018. {
  4019. // no need to add the whole table
  4020. $object_as = $relationship_as . '.' . $other_column;
  4021. }
  4022. else if ( ! in_array($object_as, $query_related))
  4023. {
  4024. // Add join if not already included
  4025. $db->join($object->table . ' ' . $object_as, $object_as . '.id = ' . $relationship_as . '.' . $other_column, 'LEFT OUTER');
  4026. $query_related[] = $object_as;
  4027. }
  4028. }
  4029. return $object_as;
  4030. }
  4031. // --------------------------------------------------------------------
  4032. /**
  4033. * Related
  4034. *
  4035. * Sets the specified related query.
  4036. *
  4037. * @ignore
  4038. * @param string $query Query String
  4039. * @param array $arguments Arguments to process
  4040. * @param mixed $extra Used to prevent escaping in special circumstances.
  4041. * @return DataMapper Returns self for method chaining.
  4042. */
  4043. protected function _related($query, $arguments = array(), $extra = NULL)
  4044. {
  4045. if ( ! empty($query) && ! empty($arguments))
  4046. {
  4047. $object = $field = $value = NULL;
  4048. $next_arg = 1;
  4049. // Prepare model
  4050. if (is_object($arguments[0]))
  4051. {
  4052. $object = $arguments[0];
  4053. $related_field = $object->model;
  4054. // Prepare field and value
  4055. $field = (isset($arguments[1])) ? $arguments[1] : 'id';
  4056. $value = (isset($arguments[2])) ? $arguments[2] : $object->id;
  4057. $next_arg = 3;
  4058. }
  4059. else
  4060. {
  4061. $related_field = $arguments[0];
  4062. // the TRUE allows conversion to singular
  4063. $related_properties = $this->_get_related_properties($related_field, TRUE);
  4064. $class = $related_properties['class'];
  4065. // enables where_related_{model}($object)
  4066. if(isset($arguments[1]) && is_object($arguments[1]))
  4067. {
  4068. $object = $arguments[1];
  4069. // Prepare field and value
  4070. $field = (isset($arguments[2])) ? $arguments[2] : 'id';
  4071. $value = (isset($arguments[3])) ? $arguments[3] : $object->id;
  4072. $next_arg = 4;
  4073. }
  4074. else
  4075. {
  4076. $object = new $class();
  4077. // Prepare field and value
  4078. $field = (isset($arguments[1])) ? $arguments[1] : 'id';
  4079. $value = (isset($arguments[2])) ? $arguments[2] : NULL;
  4080. $next_arg = 3;
  4081. }
  4082. }
  4083. if(preg_replace('/[!=<> ]/ ', '', $field) == 'id')
  4084. {
  4085. // special case to prevent joining unecessary tables
  4086. $field = $this->_add_related_table($object, $related_field, TRUE);
  4087. }
  4088. else
  4089. {
  4090. // Determine relationship table name, and join the tables
  4091. $object_table = $this->_add_related_table($object, $related_field);
  4092. $field = $object_table . '.' . $field;
  4093. }
  4094. if(is_string($value) && strpos($value, '${parent}') !== FALSE) {
  4095. $extra = FALSE;
  4096. }
  4097. // allow special arguments to be passed into query methods
  4098. if(is_null($extra)) {
  4099. if(isset($arguments[$next_arg])) {
  4100. $extra = $arguments[$next_arg];
  4101. }
  4102. }
  4103. // Add query clause
  4104. if(is_null($extra))
  4105. {
  4106. // convert where to where_in if the value is an array or a DM object
  4107. if ($query == 'where')
  4108. {
  4109. if ( is_array($value) )
  4110. {
  4111. switch(count($value))
  4112. {
  4113. case 0:
  4114. $value = NULL;
  4115. break;
  4116. case 1:
  4117. $value = reset($value);
  4118. break;
  4119. default:
  4120. $query = 'where_in';
  4121. break;
  4122. }
  4123. }
  4124. elseif ( $value instanceOf DataMapper )
  4125. {
  4126. switch($value->result_count())
  4127. {
  4128. case 0:
  4129. $value = NULL;
  4130. break;
  4131. case 1:
  4132. $value = $value->id;
  4133. break;
  4134. default:
  4135. $query = 'where_in';
  4136. break;
  4137. }
  4138. }
  4139. }
  4140. $this->{$query}($field, $value);
  4141. }
  4142. else
  4143. {
  4144. $this->{$query}($field, $value, $extra);
  4145. }
  4146. }
  4147. // For method chaining
  4148. return $this;
  4149. }
  4150. // --------------------------------------------------------------------
  4151. /**
  4152. * Magic method to process a subquery for a related object.
  4153. * The format for this should be
  4154. * $object->{where}_related_subquery($related_item, $related_field, $subquery)
  4155. * related_field is optional
  4156. *
  4157. * @ignore
  4158. * @param string $query Query Method
  4159. * @param object $args Arguments for the query
  4160. * @return DataMapper Returns self for method chaining.
  4161. */
  4162. protected function _related_subquery($query, $args)
  4163. {
  4164. $rel_object = $args[0];
  4165. $field = $value = NULL;
  4166. if(isset($args[2])) {
  4167. $field = $args[1];
  4168. $value = $args[2];
  4169. } else {
  4170. $field = 'id';
  4171. $value = $args[1];
  4172. }
  4173. if(is_object($value))
  4174. {
  4175. // see 25_activerecord.php
  4176. $value = $this->_parse_subquery_object($value);
  4177. }
  4178. if(strpos($query, 'where_in') !== FALSE) {
  4179. $query = str_replace('_in', '', $query);
  4180. $field .= ' IN ';
  4181. }
  4182. return $this->_related($query, array($rel_object, $field, $value), FALSE);
  4183. }
  4184. // --------------------------------------------------------------------
  4185. /**
  4186. * Is Related To
  4187. * If this object is related to the provided object, returns TRUE.
  4188. * Otherwise returns FALSE.
  4189. * Optionally can be provided a related field and ID.
  4190. *
  4191. * @param mixed $related_field The related object or field name
  4192. * @param int $id ID to compare to if $related_field is a string
  4193. * @return bool TRUE or FALSE if this object is related to $related_field
  4194. */
  4195. public function is_related_to($related_field, $id = NULL)
  4196. {
  4197. if(is_object($related_field))
  4198. {
  4199. $id = $related_field->id;
  4200. $related_field = $related_field->model;
  4201. }
  4202. return ($this->{$related_field}->count(NULL, NULL, $id) > 0);
  4203. }
  4204. // --------------------------------------------------------------------
  4205. /**
  4206. * Include Related
  4207. *
  4208. * Joins specified values of a has_one object into the current query
  4209. * If $fields is NULL or '*', then all columns are joined (may require instantiation of the other object)
  4210. * If $fields is a single string, then just that column is joined.
  4211. * Otherwise, $fields should be an array of column names.
  4212. *
  4213. * $append_name can be used to override the default name to append, or set it to FALSE to prevent appending.
  4214. *
  4215. * @param mixed $related_field The related object or field name
  4216. * @param array $fields The fields to join (NULL or '*' means all fields, or use a single field or array of fields)
  4217. * @param bool $append_name The name to use for joining (with '_'), or FALSE to disable.
  4218. * @param bool $instantiate If TRUE, the results are instantiated into objects
  4219. * @return DataMapper Returns self for method chaining.
  4220. */
  4221. public function include_related($related_field, $fields = NULL, $append_name = TRUE, $instantiate = FALSE)
  4222. {
  4223. if (is_object($related_field))
  4224. {
  4225. $object = $related_field;
  4226. $related_field = $object->model;
  4227. $related_properties = $this->_get_related_properties($related_field);
  4228. }
  4229. else
  4230. {
  4231. // the TRUE allows conversion to singular
  4232. $related_properties = $this->_get_related_properties($related_field, TRUE);
  4233. $class = $related_properties['class'];
  4234. $object = new $class();
  4235. }
  4236. if(is_null($fields) || $fields == '*')
  4237. {
  4238. $fields = $object->fields;
  4239. }
  4240. else if ( ! is_array($fields))
  4241. {
  4242. $fields = array((string)$fields);
  4243. }
  4244. $rfs = explode('/', $related_field);
  4245. $last = $this;
  4246. foreach($rfs as $rf)
  4247. {
  4248. // prevent populating the related items.
  4249. $last =& $last->_get_without_auto_populating($rf);
  4250. }
  4251. $table = $this->_add_related_table($object, $related_field);
  4252. $append = '';
  4253. if($append_name !== FALSE)
  4254. {
  4255. if($append_name === TRUE)
  4256. {
  4257. $append = str_replace('/', '_', $related_field);
  4258. }
  4259. else
  4260. {
  4261. $append = $append_name;
  4262. }
  4263. $append .= '_';
  4264. }
  4265. // now add fields
  4266. $selection = '';
  4267. $property_map = array();
  4268. foreach ($fields as $field)
  4269. {
  4270. $new_field = $append . $field;
  4271. // prevent collisions
  4272. if(in_array($new_field, $this->fields)) {
  4273. if($instantiate && $field == 'id' && $new_field != 'id') {
  4274. $property_map[$new_field] = $field;
  4275. }
  4276. continue;
  4277. }
  4278. if (!empty($selection))
  4279. {
  4280. $selection .= ', ';
  4281. }
  4282. $selection .= $table.'.'.$field.' AS '.$new_field;
  4283. if($instantiate) {
  4284. $property_map[$new_field] = $field;
  4285. }
  4286. }
  4287. if(empty($selection))
  4288. {
  4289. log_message('debug', "DataMapper Warning (include_related): No fields were selected for {$this->model} on $related_field.");
  4290. }
  4291. else
  4292. {
  4293. if($instantiate)
  4294. {
  4295. if(is_null($this->_instantiations))
  4296. {
  4297. $this->_instantiations = array();
  4298. }
  4299. $this->_instantiations[$related_field] = $property_map;
  4300. }
  4301. $this->db->select($selection);
  4302. }
  4303. // For method chaining
  4304. return $this;
  4305. }
  4306. /**
  4307. * Legacy version of include_related
  4308. * DEPRECATED: Will be removed by 2.0
  4309. * @deprecated Please use include_related
  4310. */
  4311. public function join_related($related_field, $fields = NULL, $append_name = TRUE)
  4312. {
  4313. return $this->include_related($related_field, $fields, $append_name);
  4314. }
  4315. // --------------------------------------------------------------------
  4316. /**
  4317. * Includes the number of related items using a subquery.
  4318. *
  4319. * Default alias is {$related_field}_count
  4320. *
  4321. * @param mixed $related_field Field to count
  4322. * @param string $alias Alternative alias.
  4323. * @return DataMapper Returns self for method chaining.
  4324. */
  4325. public function include_related_count($related_field, $alias = NULL)
  4326. {
  4327. if (is_object($related_field))
  4328. {
  4329. $object = $related_field;
  4330. $related_field = $object->model;
  4331. $related_properties = $this->_get_related_properties($related_field);
  4332. }
  4333. else
  4334. {
  4335. // the TRUE allows conversion to singular
  4336. $related_properties = $this->_get_related_properties($related_field, TRUE);
  4337. $class = $related_properties['class'];
  4338. $object = new $class();
  4339. }
  4340. if(is_null($alias))
  4341. {
  4342. $alias = $related_field . '_count';
  4343. }
  4344. // Force the selection of the current object's columns
  4345. if (empty($this->db->ar_select))
  4346. {
  4347. $this->db->select($this->table . '.*');
  4348. }
  4349. // now generate a subquery for counting the related objects
  4350. $object->select_func('COUNT', '*', 'count');
  4351. $this_rel = $related_properties['other_field'];
  4352. $tablename = $object->_add_related_table($this, $this_rel);
  4353. $object->where($tablename . '.`id` = ', $this->db->dm_call_method('_escape_identifiers', '${parent}.id'), FALSE);
  4354. $this->select_subquery($object, $alias);
  4355. return $this;
  4356. }
  4357. // --------------------------------------------------------------------
  4358. /**
  4359. * Get Relation
  4360. *
  4361. * Finds all related records of this objects current record.
  4362. *
  4363. * @ignore
  4364. * @param mixed $related_field Related field or object
  4365. * @param int $id ID of related field or object
  4366. * @return bool Sucess or Failure
  4367. */
  4368. protected function _get_relation($related_field, $id)
  4369. {
  4370. // No related items
  4371. if (empty($related_field) || empty($id))
  4372. {
  4373. // Reset query
  4374. $this->db->dm_call_method('_reset_select');
  4375. return FALSE;
  4376. }
  4377. // To ensure result integrity, group all previous queries
  4378. if( ! empty($this->db->ar_where))
  4379. {
  4380. array_unshift($this->db->ar_where, '( ');
  4381. $this->db->ar_where[] = ' )';
  4382. }
  4383. // query all items related to the given model
  4384. $this->where_related($related_field, 'id', $id);
  4385. return TRUE;
  4386. }
  4387. // --------------------------------------------------------------------
  4388. /**
  4389. * Save Relation
  4390. *
  4391. * Saves the relation between this and the other object.
  4392. *
  4393. * @ignore
  4394. * @param DataMapper DataMapper Object to related to this object
  4395. * @param string Specific related field if necessary.
  4396. * @return bool Success or Failure
  4397. */
  4398. protected function _save_relation($object, $related_field = '')
  4399. {
  4400. if (empty($related_field))
  4401. {
  4402. $related_field = $object->model;
  4403. }
  4404. // the TRUE allows conversion to singular
  4405. $related_properties = $this->_get_related_properties($related_field, TRUE);
  4406. if ( ! empty($related_properties) && $this->exists() && $object->exists())
  4407. {
  4408. $this_model = $related_properties['join_self_as'];
  4409. $other_model = $related_properties['join_other_as'];
  4410. $other_field = $related_properties['other_field'];
  4411. // Determine relationship table name
  4412. $relationship_table = $this->_get_relationship_table($object, $related_field);
  4413. if($relationship_table == $this->table &&
  4414. // catch for self relationships.
  4415. in_array($other_model . '_id', $this->fields))
  4416. {
  4417. $this->{$other_model . '_id'} = $object->id;
  4418. $ret = $this->save();
  4419. // remove any one-to-one relationships with the other object
  4420. $this->_remove_other_one_to_one($related_field, $object);
  4421. return $ret;
  4422. }
  4423. else if($relationship_table == $object->table)
  4424. {
  4425. $object->{$this_model . '_id'} = $this->id;
  4426. $ret = $object->save();
  4427. // remove any one-to-one relationships with this object
  4428. $object->_remove_other_one_to_one($other_field, $this);
  4429. return $ret;
  4430. }
  4431. else
  4432. {
  4433. $data = array($this_model . '_id' => $this->id, $other_model . '_id' => $object->id);
  4434. // Check if relation already exists
  4435. $query = $this->db->get_where($relationship_table, $data, NULL, NULL);
  4436. if ($query->num_rows() == 0)
  4437. {
  4438. // If this object has a "has many" relationship with the other object
  4439. if (isset($this->has_many[$related_field]))
  4440. {
  4441. // If the other object has a "has one" relationship with this object
  4442. if (isset($object->has_one[$other_field]))
  4443. {
  4444. // And it has an existing relation
  4445. $query = $this->db->get_where($relationship_table, array($other_model . '_id' => $object->id), 1, 0);
  4446. if ($query->num_rows() > 0)
  4447. {
  4448. // Find and update the other objects existing relation to relate with this object
  4449. $this->db->where($other_model . '_id', $object->id);
  4450. $this->db->update($relationship_table, $data);
  4451. }
  4452. else
  4453. {
  4454. // Add the relation since one doesn't exist
  4455. $this->db->insert($relationship_table, $data);
  4456. }
  4457. return TRUE;
  4458. }
  4459. else if (isset($object->has_many[$other_field]))
  4460. {
  4461. // We can add the relation since this specific relation doesn't exist, and a "has many" to "has many" relationship exists between the objects
  4462. $this->db->insert($relationship_table, $data);
  4463. // Self relationships can be defined as reciprocal -- save the reverse relationship at the same time
  4464. if ($related_properties['reciprocal'])
  4465. {
  4466. $data = array($this_model . '_id' => $object->id, $other_model . '_id' => $this->id);
  4467. $this->db->insert($relationship_table, $data);
  4468. }
  4469. return TRUE;
  4470. }
  4471. }
  4472. // If this object has a "has one" relationship with the other object
  4473. else if (isset($this->has_one[$related_field]))
  4474. {
  4475. // And it has an existing relation
  4476. $query = $this->db->get_where($relationship_table, array($this_model . '_id' => $this->id), 1, 0);
  4477. if ($query->num_rows() > 0)
  4478. {
  4479. // Find and update the other objects existing relation to relate with this object
  4480. $this->db->where($this_model . '_id', $this->id);
  4481. $this->db->update($relationship_table, $data);
  4482. }
  4483. else
  4484. {
  4485. // Add the relation since one doesn't exist
  4486. $this->db->insert($relationship_table, $data);
  4487. }
  4488. return TRUE;
  4489. }
  4490. }
  4491. else
  4492. {
  4493. // Relationship already exists
  4494. return TRUE;
  4495. }
  4496. }
  4497. }
  4498. else
  4499. {
  4500. if( ! $object->exists())
  4501. {
  4502. $msg = 'dm_save_rel_noobj';
  4503. }
  4504. else if( ! $this->exists())
  4505. {
  4506. $msg = 'dm_save_rel_nothis';
  4507. }
  4508. else
  4509. {
  4510. $msg = 'dm_save_rel_failed';
  4511. }
  4512. $msg = $this->lang->dm_line($msg);
  4513. $this->error_message($related_field, sprintf($msg, $related_field));
  4514. }
  4515. return FALSE;
  4516. }
  4517. // --------------------------------------------------------------------
  4518. /**
  4519. * Remove Other One-to-One
  4520. * Removes other relationships on a one-to-one ITFK relationship
  4521. *
  4522. * @ignore
  4523. * @param string $rf Related field to look at.
  4524. * @param DataMapper $object Object to look at.
  4525. */
  4526. protected function _remove_other_one_to_one($rf, $object)
  4527. {
  4528. if( ! $object->exists())
  4529. {
  4530. return;
  4531. }
  4532. $related_properties = $this->_get_related_properties($rf, TRUE);
  4533. if( ! array_key_exists($related_properties['other_field'], $object->has_one))
  4534. {
  4535. return;
  4536. }
  4537. // This should be a one-to-one relationship with an ITFK if we got this far.
  4538. $other_column = $related_properties['join_other_as'] . '_id';
  4539. $c = get_class($this);
  4540. $update = new $c();
  4541. $update->where($other_column, $object->id);
  4542. if($this->exists())
  4543. {
  4544. $update->where('id <>', $this->id);
  4545. }
  4546. $update->update($other_column, NULL);
  4547. }
  4548. // --------------------------------------------------------------------
  4549. /**
  4550. * Delete Relation
  4551. *
  4552. * Deletes the relation between this and the other object.
  4553. *
  4554. * @ignore
  4555. * @param DataMapper $object Object to remove the relationship to.
  4556. * @param string $related_field Optional specific related field
  4557. * @return bool Success or Failure
  4558. */
  4559. protected function _delete_relation($object, $related_field = '')
  4560. {
  4561. if (empty($related_field))
  4562. {
  4563. $related_field = $object->model;
  4564. }
  4565. // the TRUE allows conversion to singular
  4566. $related_properties = $this->_get_related_properties($related_field, TRUE);
  4567. if ( ! empty($related_properties) && ! empty($this->id) && ! empty($object->id))
  4568. {
  4569. $this_model = $related_properties['join_self_as'];
  4570. $other_model = $related_properties['join_other_as'];
  4571. // Determine relationship table name
  4572. $relationship_table = $this->_get_relationship_table($object, $related_field);
  4573. if ($relationship_table == $this->table &&
  4574. // catch for self relationships.
  4575. in_array($other_model . '_id', $this->fields))
  4576. {
  4577. $this->{$other_model . '_id'} = NULL;
  4578. $this->save();
  4579. }
  4580. else if ($relationship_table == $object->table)
  4581. {
  4582. $object->{$this_model . '_id'} = NULL;
  4583. $object->save();
  4584. }
  4585. else
  4586. {
  4587. $data = array($this_model . '_id' => $this->id, $other_model . '_id' => $object->id);
  4588. // Delete relation
  4589. $this->db->delete($relationship_table, $data);
  4590. // Delete reverse direction if a reciprocal self relationship
  4591. if ($related_properties['reciprocal'])
  4592. {
  4593. $data = array($this_model . '_id' => $object->id, $other_model . '_id' => $this->id);
  4594. $this->db->delete($relationship_table, $data);
  4595. }
  4596. }
  4597. // Clear related object so it is refreshed on next access
  4598. unset($this->{$related_field});
  4599. return TRUE;
  4600. }
  4601. return FALSE;
  4602. }
  4603. // --------------------------------------------------------------------
  4604. /**
  4605. * Get Relationship Table
  4606. *
  4607. * Determines the relationship table between this object and $object.
  4608. *
  4609. * @ignore
  4610. * @param DataMapper $object Object that we are interested in.
  4611. * @param string $related_field Optional specific related field.
  4612. * @return string The name of the table this relationship is stored on.
  4613. */
  4614. public function _get_relationship_table($object, $related_field = '')
  4615. {
  4616. $prefix = $object->prefix;
  4617. $table = $object->table;
  4618. if (empty($related_field))
  4619. {
  4620. $related_field = $object->model;
  4621. }
  4622. $related_properties = $this->_get_related_properties($related_field);
  4623. $this_model = $related_properties['join_self_as'];
  4624. $other_model = $related_properties['join_other_as'];
  4625. $other_field = $related_properties['other_field'];
  4626. if (isset($this->has_one[$related_field]))
  4627. {
  4628. // see if the relationship is in this table
  4629. if (in_array($other_model . '_id', $this->fields))
  4630. {
  4631. return $this->table;
  4632. }
  4633. }
  4634. if (isset($object->has_one[$other_field]))
  4635. {
  4636. // see if the relationship is in this table
  4637. if (in_array($this_model . '_id', $object->fields))
  4638. {
  4639. return $object->table;
  4640. }
  4641. }
  4642. // was a join table defined for this relation?
  4643. if ( ! empty($related_properties['join_table']) )
  4644. {
  4645. $relationship_table = $related_properties['join_table'];
  4646. }
  4647. else
  4648. {
  4649. $relationship_table = '';
  4650. // Check if self referencing
  4651. if ($this->table == $table)
  4652. {
  4653. // use the model names from related_properties
  4654. $p_this_model = plural($this_model);
  4655. $p_other_model = plural($other_model);
  4656. $relationship_table = ($p_this_model < $p_other_model) ? $p_this_model . '_' . $p_other_model : $p_other_model . '_' . $p_this_model;
  4657. }
  4658. else
  4659. {
  4660. $relationship_table = ($this->table < $table) ? $this->table . '_' . $table : $table . '_' . $this->table;
  4661. }
  4662. // Remove all occurances of the prefix from the relationship table
  4663. $relationship_table = str_replace($prefix, '', str_replace($this->prefix, '', $relationship_table));
  4664. // So we can prefix the beginning, using the join prefix instead, if it is set
  4665. $relationship_table = (empty($this->join_prefix)) ? $this->prefix . $relationship_table : $this->join_prefix . $relationship_table;
  4666. }
  4667. return $relationship_table;
  4668. }
  4669. // --------------------------------------------------------------------
  4670. /**
  4671. * Count Related
  4672. *
  4673. * Returns the number of related items in the database and in the related object.
  4674. * Used by the _related_(required|min|max) validation rules.
  4675. *
  4676. * @ignore
  4677. * @param string $related_field The related field.
  4678. * @param mixed $object Object or array to include in the count.
  4679. * @return int Number of related items.
  4680. */
  4681. protected function _count_related($related_field, $object = '')
  4682. {
  4683. $count = 0;
  4684. // lookup relationship info
  4685. // the TRUE allows conversion to singular
  4686. $rel_properties = $this->_get_related_properties($related_field, TRUE);
  4687. $class = $rel_properties['class'];
  4688. $ids = array();
  4689. if ( ! empty($object))
  4690. {
  4691. $count = $this->_count_related_objects($related_field, $object, '', $ids);
  4692. $ids = array_unique($ids);
  4693. }
  4694. if ( ! empty($related_field) && ! empty($this->id))
  4695. {
  4696. $one = isset($this->has_one[$related_field]);
  4697. // don't bother looking up relationships if this is a $has_one and we already have one.
  4698. if( (!$one) || empty($ids))
  4699. {
  4700. // Prepare model
  4701. $object = new $class();
  4702. // Store parent data
  4703. $object->parent = array('model' => $rel_properties['other_field'], 'id' => $this->id);
  4704. // pass in IDs to exclude from the count
  4705. $count += $object->count($ids);
  4706. }
  4707. }
  4708. return $count;
  4709. }
  4710. // --------------------------------------------------------------------
  4711. /**
  4712. * Private recursive function to count the number of objects
  4713. * in a passed in array (or a single object)
  4714. *
  4715. * @ignore
  4716. * @param string $compare related field (model) to compare to
  4717. * @param mixed $object Object or array to count
  4718. * @param string $related_field related field of $object
  4719. * @param array $ids list of IDs we've already found.
  4720. * @return int Number of items found.
  4721. */
  4722. protected function _count_related_objects($compare, $object, $related_field, &$ids)
  4723. {
  4724. $count = 0;
  4725. if (is_array($object))
  4726. {
  4727. // loop through array to check for objects
  4728. foreach ($object as $rel_field => $obj)
  4729. {
  4730. if ( ! is_string($rel_field))
  4731. {
  4732. // if this object doesn't have a related field, use the parent related field
  4733. $rel_field = $related_field;
  4734. }
  4735. $count += $this->_count_related_objects($compare, $obj, $rel_field, $ids);
  4736. }
  4737. }
  4738. else
  4739. {
  4740. // if this object doesn't have a related field, use the model
  4741. if (empty($related_field))
  4742. {
  4743. $related_field = $object->model;
  4744. }
  4745. // if this object is the same relationship type, it counts
  4746. if ($related_field == $compare && $object->exists())
  4747. {
  4748. $ids[] = $object->id;
  4749. $count++;
  4750. }
  4751. }
  4752. return $count;
  4753. }
  4754. // --------------------------------------------------------------------
  4755. /**
  4756. * Include Join Fields
  4757. *
  4758. * If TRUE, the any extra fields on the join table will be included
  4759. *
  4760. * @param bool $include If FALSE, turns back off the directive.
  4761. * @return DataMapper Returns self for method chaining.
  4762. */
  4763. public function include_join_fields($include = TRUE)
  4764. {
  4765. $this->_include_join_fields = $include;
  4766. return $this;
  4767. }
  4768. // --------------------------------------------------------------------
  4769. /**
  4770. * Set Join Field
  4771. *
  4772. * Sets the value on a join table based on the related field
  4773. * If $related_field is an array, then the array should be
  4774. * in the form $related_field => $object or array($object)
  4775. *
  4776. * @param mixed $related_field An object or array.
  4777. * @param mixed $field Field or array of fields to set.
  4778. * @param mixed $value Value for a single field to set.
  4779. * @param mixed $object Private for recursion, do not use.
  4780. * @return DataMapper Returns self for method chaining.
  4781. */
  4782. public function set_join_field($related_field, $field, $value = NULL, $object = NULL)
  4783. {
  4784. $related_ids = array();
  4785. if (is_array($related_field))
  4786. {
  4787. // recursively call this on the array passed in.
  4788. foreach ($related_field as $key => $object)
  4789. {
  4790. $this->set_join_field($key, $field, $value, $object);
  4791. }
  4792. return;
  4793. }
  4794. else if (is_object($related_field))
  4795. {
  4796. $object = $related_field;
  4797. $related_field = $object->model;
  4798. $related_ids[] = $object->id;
  4799. $related_properties = $this->_get_related_properties($related_field);
  4800. }
  4801. else
  4802. {
  4803. // the TRUE allows conversion to singular
  4804. $related_properties = $this->_get_related_properties($related_field, TRUE);
  4805. if (is_null($object))
  4806. {
  4807. $class = $related_properties['class'];
  4808. $object = new $class();
  4809. }
  4810. }
  4811. // Determine relationship table name
  4812. $relationship_table = $this->_get_relationship_table($object, $related_field);
  4813. if (empty($object))
  4814. {
  4815. // no object was passed in, so create one
  4816. $class = $related_properties['class'];
  4817. $object = new $class();
  4818. }
  4819. $this_model = $related_properties['join_self_as'];
  4820. $other_model = $related_properties['join_other_as'];
  4821. if (! is_array($field))
  4822. {
  4823. $field = array( $field => $value );
  4824. }
  4825. if ( ! is_array($object))
  4826. {
  4827. $object = array($object);
  4828. }
  4829. if (empty($object))
  4830. {
  4831. $this->db->where($this_model . '_id', $this->id);
  4832. $this->db->update($relationship_table, $field);
  4833. }
  4834. else
  4835. {
  4836. foreach ($object as $obj)
  4837. {
  4838. $this->db->where($this_model . '_id', $this->id);
  4839. $this->db->where($other_model . '_id', $obj->id);
  4840. $this->db->update($relationship_table, $field);
  4841. }
  4842. }
  4843. // For method chaining
  4844. return $this;
  4845. }
  4846. // --------------------------------------------------------------------
  4847. /**
  4848. * Join Field
  4849. *
  4850. * Adds a query of a join table's extra field
  4851. * Accessed via __call
  4852. *
  4853. * @ignore
  4854. * @param string $query Query method.
  4855. * @param array $arguments Arguments for query.
  4856. * @return DataMapper Returns self for method chaining.
  4857. */
  4858. protected function _join_field($query, $arguments)
  4859. {
  4860. if ( ! empty($query) && count($arguments) >= 3)
  4861. {
  4862. $object = $field = $value = NULL;
  4863. // Prepare model
  4864. if (is_object($arguments[0]))
  4865. {
  4866. $object = $arguments[0];
  4867. $related_field = $object->model;
  4868. }
  4869. else
  4870. {
  4871. $related_field = $arguments[0];
  4872. // the TRUE allows conversion to singular
  4873. $related_properties = $this->_get_related_properties($related_field, TRUE);
  4874. $class = $related_properties['class'];
  4875. $object = new $class();
  4876. }
  4877. // Prepare field and value
  4878. $field = $arguments[1];
  4879. $value = $arguments[2];
  4880. // Determine relationship table name, and join the tables
  4881. $rel_table = $this->_get_relationship_table($object, $related_field);
  4882. // Add query clause
  4883. $extra = NULL;
  4884. if(count($arguments) > 3) {
  4885. $extra = $arguments[3];
  4886. }
  4887. if(is_null($extra)) {
  4888. $this->{$query}($rel_table . '.' . $field, $value);
  4889. } else {
  4890. $this->{$query}($rel_table . '.' . $field, $value, $extra);
  4891. }
  4892. }
  4893. // For method chaining
  4894. return $this;
  4895. }
  4896. // --------------------------------------------------------------------
  4897. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  4898. * *
  4899. * Related Validation methods *
  4900. * *
  4901. * The following are methods used to validate the *
  4902. * relationships of this object. *
  4903. * *
  4904. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  4905. // --------------------------------------------------------------------
  4906. /**
  4907. * Related Required (pre-process)
  4908. *
  4909. * Checks if the related object has the required related item
  4910. * or if the required relation already exists.
  4911. *
  4912. * @ignore
  4913. */
  4914. protected function _related_required($object, $model)
  4915. {
  4916. return ($this->_count_related($model, $object) == 0) ? FALSE : TRUE;
  4917. }
  4918. // --------------------------------------------------------------------
  4919. /**
  4920. * Related Min Size (pre-process)
  4921. *
  4922. * Checks if the value of a property is at most the minimum size.
  4923. *
  4924. * @ignore
  4925. */
  4926. protected function _related_min_size($object, $model, $size = 0)
  4927. {
  4928. return ($this->_count_related($model, $object) < $size) ? FALSE : TRUE;
  4929. }
  4930. // --------------------------------------------------------------------
  4931. /**
  4932. * Related Max Size (pre-process)
  4933. *
  4934. * Checks if the value of a property is at most the maximum size.
  4935. *
  4936. * @ignore
  4937. */
  4938. protected function _related_max_size($object, $model, $size = 0)
  4939. {
  4940. return ($this->_count_related($model, $object) > $size) ? FALSE : TRUE;
  4941. }
  4942. // --------------------------------------------------------------------
  4943. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  4944. * *
  4945. * Validation methods *
  4946. * *
  4947. * The following are methods used to validate the *
  4948. * values of this objects properties. *
  4949. * *
  4950. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  4951. // --------------------------------------------------------------------
  4952. /**
  4953. * Always Validate
  4954. *
  4955. * Does nothing, but forces a validation even if empty (for non-required fields)
  4956. *
  4957. * @ignore
  4958. */
  4959. protected function _always_validate()
  4960. {
  4961. }
  4962. // --------------------------------------------------------------------
  4963. /**
  4964. * Alpha Dash Dot (pre-process)
  4965. *
  4966. * Alpha-numeric with underscores, dashes and full stops.
  4967. *
  4968. * @ignore
  4969. */
  4970. protected function _alpha_dash_dot($field)
  4971. {
  4972. return ( ! preg_match('/^([\.-a-z0-9_-])+$/i', $this->{$field})) ? FALSE : TRUE;
  4973. }
  4974. // --------------------------------------------------------------------
  4975. /**
  4976. * Alpha Slash Dot (pre-process)
  4977. *
  4978. * Alpha-numeric with underscores, dashes, forward slashes and full stops.
  4979. *
  4980. * @ignore
  4981. */
  4982. protected function _alpha_slash_dot($field)
  4983. {
  4984. return ( ! preg_match('/^([\.\/-a-z0-9_-])+$/i', $this->{$field})) ? FALSE : TRUE;
  4985. }
  4986. // --------------------------------------------------------------------
  4987. /**
  4988. * Matches (pre-process)
  4989. *
  4990. * Match one field to another.
  4991. * This replaces the version in CI_Form_validation.
  4992. *
  4993. * @ignore
  4994. */
  4995. protected function _matches($field, $other_field)
  4996. {
  4997. return ($this->{$field} !== $this->{$other_field}) ? FALSE : TRUE;
  4998. }
  4999. // --------------------------------------------------------------------
  5000. /**
  5001. * Min Date (pre-process)
  5002. *
  5003. * Checks if the value of a property is at least the minimum date.
  5004. *
  5005. * @ignore
  5006. */
  5007. protected function _min_date($field, $date)
  5008. {
  5009. return (strtotime($this->{$field}) < strtotime($date)) ? FALSE : TRUE;
  5010. }
  5011. // --------------------------------------------------------------------
  5012. /**
  5013. * Max Date (pre-process)
  5014. *
  5015. * Checks if the value of a property is at most the maximum date.
  5016. *
  5017. * @ignore
  5018. */
  5019. protected function _max_date($field, $date)
  5020. {
  5021. return (strtotime($this->{$field}) > strtotime($date)) ? FALSE : TRUE;
  5022. }
  5023. // --------------------------------------------------------------------
  5024. /**
  5025. * Min Size (pre-process)
  5026. *
  5027. * Checks if the value of a property is at least the minimum size.
  5028. *
  5029. * @ignore
  5030. */
  5031. protected function _min_size($field, $size)
  5032. {
  5033. return ($this->{$field} < $size) ? FALSE : TRUE;
  5034. }
  5035. // --------------------------------------------------------------------
  5036. /**
  5037. * Max Size (pre-process)
  5038. *
  5039. * Checks if the value of a property is at most the maximum size.
  5040. *
  5041. * @ignore
  5042. */
  5043. protected function _max_size($field, $size)
  5044. {
  5045. return ($this->{$field} > $size) ? FALSE : TRUE;
  5046. }
  5047. // --------------------------------------------------------------------
  5048. /**
  5049. * Unique (pre-process)
  5050. *
  5051. * Checks if the value of a property is unique.
  5052. * If the property belongs to this object, we can ignore it.
  5053. *
  5054. * @ignore
  5055. */
  5056. protected function _unique($field)
  5057. {
  5058. if ( ! empty($this->{$field}))
  5059. {
  5060. $query = $this->db->get_where($this->table, array($field => $this->{$field}), 1, 0);
  5061. if ($query->num_rows() > 0)
  5062. {
  5063. $row = $query->row();
  5064. // If unique value does not belong to this object
  5065. if ($this->id != $row->id)
  5066. {
  5067. // Then it is not unique
  5068. return FALSE;
  5069. }
  5070. }
  5071. }
  5072. // No matches found so is unique
  5073. return TRUE;
  5074. }
  5075. // --------------------------------------------------------------------
  5076. /**
  5077. * Unique Pair (pre-process)
  5078. *
  5079. * Checks if the value of a property, paired with another, is unique.
  5080. * If the properties belongs to this object, we can ignore it.
  5081. *
  5082. * @ignore
  5083. */
  5084. protected function _unique_pair($field, $other_field = '')
  5085. {
  5086. if ( ! empty($this->{$field}) && ! empty($this->{$other_field}))
  5087. {
  5088. $query = $this->db->get_where($this->table, array($field => $this->{$field}, $other_field => $this->{$other_field}), 1, 0);
  5089. if ($query->num_rows() > 0)
  5090. {
  5091. $row = $query->row();
  5092. // If unique pair value does not belong to this object
  5093. if ($this->id != $row->id)
  5094. {
  5095. // Then it is not a unique pair
  5096. return FALSE;
  5097. }
  5098. }
  5099. }
  5100. // No matches found so is unique
  5101. return TRUE;
  5102. }
  5103. // --------------------------------------------------------------------
  5104. /**
  5105. * Valid Date (pre-process)
  5106. *
  5107. * Checks whether the field value is a valid DateTime.
  5108. *
  5109. * @ignore
  5110. */
  5111. protected function _valid_date($field)
  5112. {
  5113. // Ignore if empty
  5114. if (empty($this->{$field}))
  5115. {
  5116. return TRUE;
  5117. }
  5118. $date = date_parse($this->{$field});
  5119. return checkdate($date['month'], $date['day'],$date['year']);
  5120. }
  5121. // --------------------------------------------------------------------
  5122. /**
  5123. * Valid Date Group (pre-process)
  5124. *
  5125. * Checks whether the field value, grouped with other field values, is a valid DateTime.
  5126. *
  5127. * @ignore
  5128. */
  5129. protected function _valid_date_group($field, $fields = array())
  5130. {
  5131. // Ignore if empty
  5132. if (empty($this->{$field}))
  5133. {
  5134. return TRUE;
  5135. }
  5136. $date = date_parse($this->{$fields['year']} . '-' . $this->{$fields['month']} . '-' . $this->{$fields['day']});
  5137. return checkdate($date['month'], $date['day'],$date['year']);
  5138. }
  5139. // --------------------------------------------------------------------
  5140. /**
  5141. * Valid Match (pre-process)
  5142. *
  5143. * Checks whether the field value matches one of the specified array values.
  5144. *
  5145. * @ignore
  5146. */
  5147. protected function _valid_match($field, $param = array())
  5148. {
  5149. return in_array($this->{$field}, $param);
  5150. }
  5151. // --------------------------------------------------------------------
  5152. /**
  5153. * Boolean (pre-process)
  5154. *
  5155. * Forces a field to be either TRUE or FALSE.
  5156. * Uses PHP's built-in boolean conversion.
  5157. *
  5158. * @ignore
  5159. */
  5160. protected function _boolean($field)
  5161. {
  5162. $this->{$field} = (boolean)$this->{$field};
  5163. }
  5164. // --------------------------------------------------------------------
  5165. /**
  5166. * Encode PHP Tags (prep)
  5167. *
  5168. * Convert PHP tags to entities.
  5169. * This replaces the version in CI_Form_validation.
  5170. *
  5171. * @ignore
  5172. */
  5173. protected function _encode_php_tags($field)
  5174. {
  5175. $this->{$field} = encode_php_tags($this->{$field});
  5176. }
  5177. // --------------------------------------------------------------------
  5178. /**
  5179. * Prep for Form (prep)
  5180. *
  5181. * Converts special characters to allow HTML to be safely shown in a form.
  5182. * This replaces the version in CI_Form_validation.
  5183. *
  5184. * @ignore
  5185. */
  5186. protected function _prep_for_form($field)
  5187. {
  5188. $this->{$field} = $this->form_validation->prep_for_form($this->{$field});
  5189. }
  5190. // --------------------------------------------------------------------
  5191. /**
  5192. * Prep URL (prep)
  5193. *
  5194. * Adds "http://" to URLs if missing.
  5195. * This replaces the version in CI_Form_validation.
  5196. *
  5197. * @ignore
  5198. */
  5199. protected function _prep_url($field)
  5200. {
  5201. $this->{$field} = $this->form_validation->prep_url($this->{$field});
  5202. }
  5203. // --------------------------------------------------------------------
  5204. /**
  5205. * Strip Image Tags (prep)
  5206. *
  5207. * Strips the HTML from image tags leaving the raw URL.
  5208. * This replaces the version in CI_Form_validation.
  5209. *
  5210. * @ignore
  5211. */
  5212. protected function _strip_image_tags($field)
  5213. {
  5214. $this->{$field} = strip_image_tags($this->{$field});
  5215. }
  5216. // --------------------------------------------------------------------
  5217. /**
  5218. * XSS Clean (prep)
  5219. *
  5220. * Runs the data through the XSS filtering function, described in the Input Class page.
  5221. * This replaces the version in CI_Form_validation.
  5222. *
  5223. * @ignore
  5224. */
  5225. protected function _xss_clean($field, $is_image = FALSE)
  5226. {
  5227. $this->{$field} = xss_clean($this->{$field}, $is_image);
  5228. }
  5229. // --------------------------------------------------------------------
  5230. /**
  5231. * Trim
  5232. * Custom trim rule that ignores NULL values
  5233. *
  5234. * @ignore
  5235. */
  5236. protected function _trim($field) {
  5237. if( ! empty($this->{$field})) {
  5238. $this->{$field} = trim($this->{$field});
  5239. }
  5240. }
  5241. // --------------------------------------------------------------------
  5242. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5243. * *
  5244. * Common methods *
  5245. * *
  5246. * The following are common methods used by other methods. *
  5247. * *
  5248. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5249. // --------------------------------------------------------------------
  5250. /**
  5251. * A specialized language lookup function that will automatically
  5252. * insert the model, table, and (optional) field into a key, and return the
  5253. * language result for the replaced key.
  5254. *
  5255. * @param string $key Basic key to use
  5256. * @param string $field Optional field value
  5257. * @return string|bool
  5258. */
  5259. public function localize_by_model($key, $field = NULL)
  5260. {
  5261. $s = array('${model}', '${table}');
  5262. $r = array($this->model, $this->table);
  5263. if(!is_null($field))
  5264. {
  5265. $s[] = '${field}';
  5266. $r[] = $field;
  5267. }
  5268. $key = str_replace($s, $r, $key);
  5269. return $this->lang->dm_line($key);
  5270. }
  5271. // --------------------------------------------------------------------
  5272. /**
  5273. * Variant that handles looking up a field labels
  5274. * @param string $field Name of field
  5275. * @param string|bool $label If not FALSE overrides default label.
  5276. * @return string|bool
  5277. */
  5278. public function localize_label($field, $label = FALSE)
  5279. {
  5280. if($label === FALSE)
  5281. {
  5282. $label = $field;
  5283. if(!empty($this->field_label_lang_format))
  5284. {
  5285. $label = $this->localize_by_model($this->field_label_lang_format, $field);
  5286. if($label === FALSE)
  5287. {
  5288. $label = $field;
  5289. }
  5290. }
  5291. }
  5292. else if(strpos($label, 'lang:') === 0)
  5293. {
  5294. $label = $this->localize_by_model(substr($label, 5), $field);
  5295. }
  5296. return $label;
  5297. }
  5298. // --------------------------------------------------------------------
  5299. /**
  5300. * Allows you to define has_one relations at runtime
  5301. * @param string name of the model to make a relation with
  5302. * @param array optional, array with advanced relationship definitions
  5303. * @return bool
  5304. */
  5305. public function has_one( $parm1 = NULL, $parm2 = NULL )
  5306. {
  5307. if ( is_null($parm1) && is_null($parm2) )
  5308. {
  5309. return FALSE;
  5310. }
  5311. elseif ( is_array($parm2) )
  5312. {
  5313. return $this->_relationship('has_one', $parm2, $parm1);
  5314. }
  5315. else
  5316. {
  5317. return $this->_relationship('has_one', $parm1, 0);
  5318. }
  5319. }
  5320. // --------------------------------------------------------------------
  5321. /**
  5322. * Allows you to define has_many relations at runtime
  5323. * @param string name of the model to make a relation with
  5324. * @param array optional, array with advanced relationship definitions
  5325. * @return bool
  5326. */
  5327. public function has_many( $parm1 = NULL, $parm2 = NULL )
  5328. {
  5329. if ( is_null($parm1) && is_null($parm2) )
  5330. {
  5331. return FALSE;
  5332. }
  5333. elseif ( is_array($parm2) )
  5334. {
  5335. return $this->_relationship('has_many', $parm2, $parm1);
  5336. }
  5337. else
  5338. {
  5339. return $this->_relationship('has_many', $parm1, 0);
  5340. }
  5341. }
  5342. // --------------------------------------------------------------------
  5343. /**
  5344. * Creates or updates the production schema cache file for this model
  5345. * @param void
  5346. * @return void
  5347. */
  5348. public function production_cache()
  5349. {
  5350. // if requested, store the item to the production cache
  5351. if( ! empty(DataMapper::$config['production_cache']))
  5352. {
  5353. // check if it's a fully qualified path first
  5354. if (!is_dir($cache_folder = DataMapper::$config['production_cache']))
  5355. {
  5356. // if not, it's relative to the application path
  5357. $cache_folder = APPPATH . DataMapper::$config['production_cache'];
  5358. }
  5359. if(file_exists($cache_folder) && is_dir($cache_folder) && is_writeable($cache_folder))
  5360. {
  5361. $common_key = DataMapper::$common[DMZ_CLASSNAMES_KEY][strtolower(get_class($this))];
  5362. $cache_file = $cache_folder . '/' . $common_key . EXT;
  5363. $cache = "<"."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); \n";
  5364. $cache .= '$cache = ' . var_export(DataMapper::$common[$common_key], TRUE) . ';';
  5365. if ( ! $fp = @fopen($cache_file, 'w'))
  5366. {
  5367. show_error('Error creating production cache file: ' . $cache_file);
  5368. }
  5369. flock($fp, LOCK_EX);
  5370. fwrite($fp, $cache);
  5371. flock($fp, LOCK_UN);
  5372. fclose($fp);
  5373. @chmod($cache_file, FILE_WRITE_MODE);
  5374. }
  5375. }
  5376. }
  5377. // --------------------------------------------------------------------
  5378. /**
  5379. * Define a new relationship for the current model
  5380. */
  5381. protected function _relationship($type = '', $definition = array(), $name = 0)
  5382. {
  5383. // check the parameters
  5384. if (empty($type) OR ! in_array($type, array('has_one','has_many')))
  5385. {
  5386. return FALSE;
  5387. }
  5388. // allow for simple (old-style) associations
  5389. if (is_int($name))
  5390. {
  5391. // delete the old style entry, we're going to convert it
  5392. if (isset($this->{$type}[$name]))
  5393. {
  5394. unset($this->{$type}[$name]);
  5395. }
  5396. $name = $definition;
  5397. }
  5398. // get the current relationships
  5399. $new = (array) $this->{$type};
  5400. // convert value into array if necessary
  5401. if ( ! is_array($definition))
  5402. {
  5403. $definition = array('class' => $definition);
  5404. }
  5405. else if ( ! isset($definition['class']))
  5406. {
  5407. // if already an array, ensure that the class attribute is set
  5408. $definition['class'] = $name;
  5409. }
  5410. if( ! isset($definition['other_field']))
  5411. {
  5412. // add this model as the model to use in queries if not set
  5413. $definition['other_field'] = $this->model;
  5414. }
  5415. if( ! isset($definition['join_self_as']))
  5416. {
  5417. // add this model as the model to use in queries if not set
  5418. $definition['join_self_as'] = $definition['other_field'];
  5419. }
  5420. if( ! isset($definition['join_other_as']))
  5421. {
  5422. // add the key as the model to use in queries if not set
  5423. $definition['join_other_as'] = $name;
  5424. }
  5425. if( ! isset($definition['join_table']))
  5426. {
  5427. // by default, automagically determine the join table name
  5428. $definition['join_table'] = '';
  5429. }
  5430. if(isset($definition['reciprocal']))
  5431. {
  5432. // only allow a reciprocal relationship to be defined if this is a has_many self relationship
  5433. $definition['reciprocal'] = ($definition['reciprocal'] && $type == 'has_many' && $definition['class'] == strtolower(get_class($this)));
  5434. }
  5435. else
  5436. {
  5437. $definition['reciprocal'] = FALSE;
  5438. }
  5439. if(!isset($definition['auto_populate']) OR ! is_bool($definition['auto_populate']))
  5440. {
  5441. $definition['auto_populate'] = NULL;
  5442. }
  5443. if(!isset($definition['cascade_delete']) OR ! is_bool($definition['cascade_delete']))
  5444. {
  5445. $definition['cascade_delete'] = $this->cascade_delete;
  5446. }
  5447. $new[$name] = $definition;
  5448. // load in labels for each not-already-set field
  5449. if(!isset($this->validation[$name]))
  5450. {
  5451. $label = $this->localize_label($name);
  5452. if(!empty($label))
  5453. {
  5454. // label is re-set below, to prevent caching language-based labels
  5455. $this->validation[$name] = array('field' => $name, 'rules' => array());
  5456. }
  5457. }
  5458. // replace the old array
  5459. $this->{$type} = $new;
  5460. }
  5461. // --------------------------------------------------------------------
  5462. /**
  5463. * To Array
  5464. *
  5465. * Converts this objects current record into an array for database queries.
  5466. * If validate is TRUE (getting by objects properties) empty objects are ignored.
  5467. *
  5468. * @ignore
  5469. * @param bool $validate
  5470. * @return array
  5471. */
  5472. protected function _to_array($validate = FALSE)
  5473. {
  5474. $data = array();
  5475. foreach ($this->fields as $field)
  5476. {
  5477. if ($validate && ! isset($this->{$field}))
  5478. {
  5479. continue;
  5480. }
  5481. $data[$field] = $this->{$field};
  5482. }
  5483. return $data;
  5484. }
  5485. // --------------------------------------------------------------------
  5486. /**
  5487. * Process Query
  5488. *
  5489. * Converts a query result into an array of objects.
  5490. * Also updates this object
  5491. *
  5492. * @ignore
  5493. * @param CI_DB_result $query
  5494. */
  5495. protected function _process_query($query)
  5496. {
  5497. if ($query->num_rows() > 0)
  5498. {
  5499. // Populate all with records as objects
  5500. $this->all = array();
  5501. $this->_to_object($this, $query->row());
  5502. // don't bother recreating the first item.
  5503. $index = ($this->all_array_uses_ids && isset($this->id)) ? $this->id : 0;
  5504. $this->all[$index] = $this->get_clone();
  5505. if($query->num_rows() > 1)
  5506. {
  5507. $model = get_class($this);
  5508. $first = TRUE;
  5509. foreach ($query->result() as $row)
  5510. {
  5511. if($first)
  5512. {
  5513. $first = FALSE;
  5514. continue;
  5515. }
  5516. $item = new $model();
  5517. $this->_to_object($item, $row);
  5518. if($this->all_array_uses_ids && isset($item->id))
  5519. {
  5520. $this->all[$item->id] = $item;
  5521. }
  5522. else
  5523. {
  5524. $this->all[] = $item;
  5525. }
  5526. }
  5527. }
  5528. // remove instantiations
  5529. $this->_instantiations = NULL;
  5530. // free large queries
  5531. if($query->num_rows() > $this->free_result_threshold)
  5532. {
  5533. $query->free_result();
  5534. }
  5535. }
  5536. else
  5537. {
  5538. // Refresh stored values is called by _to_object normally
  5539. $this->_refresh_stored_values();
  5540. }
  5541. }
  5542. // --------------------------------------------------------------------
  5543. /**
  5544. * To Object
  5545. * Copies the values from a query result row to an object.
  5546. * Also initializes that object by running get rules, and
  5547. * refreshing stored values on the object.
  5548. *
  5549. * Finally, if any "instantiations" are requested, those related objects
  5550. * are created off of query results
  5551. *
  5552. * This is only public so that the iterator can access it.
  5553. *
  5554. * @ignore
  5555. * @param DataMapper $item Item to configure
  5556. * @param object $row Query results
  5557. */
  5558. public function _to_object($item, $row)
  5559. {
  5560. // Populate this object with values from first record
  5561. foreach ($row as $key => $value)
  5562. {
  5563. $item->{$key} = $value;
  5564. }
  5565. foreach ($this->fields as $field)
  5566. {
  5567. if (! isset($row->{$field}))
  5568. {
  5569. $item->{$field} = NULL;
  5570. }
  5571. }
  5572. // Force IDs to integers
  5573. foreach($this->_field_tracking['intval'] as $field)
  5574. {
  5575. if(isset($item->{$field}))
  5576. {
  5577. $item->{$field} = intval($item->{$field});
  5578. }
  5579. }
  5580. if (!empty($this->_field_tracking['get_rules']))
  5581. {
  5582. $item->_run_get_rules();
  5583. }
  5584. $item->_refresh_stored_values();
  5585. if($this->_instantiations) {
  5586. foreach($this->_instantiations as $related_field => $field_map) {
  5587. // convert fields to a 'row' object
  5588. $row = new stdClass();
  5589. foreach($field_map as $item_field => $c_field) {
  5590. $row->{$c_field} = $item->{$item_field};
  5591. }
  5592. // get the related item
  5593. $c =& $item->_get_without_auto_populating($related_field);
  5594. // set the values
  5595. $c->_to_object($c, $row);
  5596. // also set up the ->all array
  5597. $c->all = array();
  5598. $c->all[0] = $c->get_clone();
  5599. }
  5600. }
  5601. }
  5602. // --------------------------------------------------------------------
  5603. /**
  5604. * Run Get Rules
  5605. *
  5606. * Processes values loaded from the database
  5607. *
  5608. * @ignore
  5609. */
  5610. protected function _run_get_rules()
  5611. {
  5612. // Loop through each property to be validated
  5613. foreach ($this->_field_tracking['get_rules'] as $field)
  5614. {
  5615. // Get validation settings
  5616. $rules = $this->validation[$field]['get_rules'];
  5617. // only process non-empty keys that are not specifically
  5618. // set to be null
  5619. if( ! isset($this->{$field}) && ! in_array('allow_null', $rules))
  5620. {
  5621. if(isset($this->has_one[$field]))
  5622. {
  5623. // automatically process $item_id values
  5624. $field = $field . '_id';
  5625. if( ! isset($this->{$field}) && ! in_array('allow_null', $rules))
  5626. {
  5627. continue;
  5628. }
  5629. } else {
  5630. continue;
  5631. }
  5632. }
  5633. // Loop through each rule to validate this property against
  5634. foreach ($rules as $rule => $param)
  5635. {
  5636. // Check for parameter
  5637. if (is_numeric($rule))
  5638. {
  5639. $rule = $param;
  5640. $param = '';
  5641. }
  5642. if($rule == 'allow_null')
  5643. {
  5644. continue;
  5645. }
  5646. if (method_exists($this, '_' . $rule))
  5647. {
  5648. // Run rule from DataMapper or the class extending DataMapper
  5649. $result = $this->{'_' . $rule}($field, $param);
  5650. }
  5651. else if($this->_extension_method_exists('rule_' . $rule))
  5652. {
  5653. // Run an extension-based rule.
  5654. $result = $this->{'rule_' . $rule}($field, $param);
  5655. }
  5656. else if (method_exists($this->form_validation, $rule))
  5657. {
  5658. // Run rule from CI Form Validation
  5659. $result = $this->form_validation->{$rule}($this->{$field}, $param);
  5660. }
  5661. else if (function_exists($rule))
  5662. {
  5663. // Run rule from PHP
  5664. $result = $rule($this->{$field});
  5665. }
  5666. else
  5667. {
  5668. show_error("could not run get_rule '$rule'");
  5669. }
  5670. $this->{$field} = $result;
  5671. }
  5672. }
  5673. }
  5674. // --------------------------------------------------------------------
  5675. /**
  5676. * Refresh Stored Values
  5677. *
  5678. * Refreshes the stored values with the current values.
  5679. *
  5680. * @ignore
  5681. */
  5682. protected function _refresh_stored_values()
  5683. {
  5684. // Update stored values
  5685. foreach ($this->fields as $field)
  5686. {
  5687. $this->stored->{$field} = $this->{$field};
  5688. }
  5689. // If there is a "matches" validation rule, match the field value with the other field value
  5690. foreach ($this->_field_tracking['matches'] as $field_name => $match_name)
  5691. {
  5692. $this->{$field_name} = $this->stored->{$field_name} = $this->{$match_name};
  5693. }
  5694. }
  5695. // --------------------------------------------------------------------
  5696. /**
  5697. * Assign Libraries
  5698. *
  5699. * Originally used by CodeIgniter, now just logs a warning.
  5700. *
  5701. * @ignore
  5702. */
  5703. public function _assign_libraries()
  5704. {
  5705. log_message('debug', "Warning: A DMZ model ({$this->model}) was either loaded via autoload, or manually. DMZ automatically loads models, so this is unnecessary.");
  5706. }
  5707. // --------------------------------------------------------------------
  5708. /**
  5709. * Assign Libraries
  5710. *
  5711. * Assigns required CodeIgniter libraries to DataMapper.
  5712. *
  5713. * @ignore
  5714. */
  5715. protected function _dmz_assign_libraries()
  5716. {
  5717. static $CI;
  5718. if ($CI || $CI =& get_instance())
  5719. {
  5720. // make sure these exists to not trip __get()
  5721. $this->load = NULL;
  5722. $this->config = NULL;
  5723. $this->lang = NULL;
  5724. // access to the loader
  5725. $this->load =& $CI->load;
  5726. // to the config
  5727. $this->config =& $CI->config;
  5728. // and the language class
  5729. $this->lang =& $CI->lang;
  5730. }
  5731. }
  5732. // --------------------------------------------------------------------
  5733. /**
  5734. * Load Languages
  5735. *
  5736. * Loads required language files.
  5737. *
  5738. * @ignore
  5739. */
  5740. protected function _load_languages()
  5741. {
  5742. // Load the DataMapper language file
  5743. $this->lang->load('datamapper');
  5744. }
  5745. // --------------------------------------------------------------------
  5746. /**
  5747. * Load Helpers
  5748. *
  5749. * Loads required CodeIgniter helpers.
  5750. *
  5751. * @ignore
  5752. */
  5753. protected function _load_helpers()
  5754. {
  5755. // Load inflector helper for singular and plural functions
  5756. $this->load->helper('inflector');
  5757. // Load security helper for prepping functions
  5758. $this->load->helper('security');
  5759. }
  5760. }
  5761. /**
  5762. * Simple class to prevent errors with unset fields.
  5763. * @package DMZ
  5764. *
  5765. * @param string $FIELD Get the error message for a given field or custom error
  5766. * @param string $RELATED Get the error message for a given relationship
  5767. * @param string $transaction Get the transaction error.
  5768. */
  5769. class DM_Error_Object {
  5770. /**
  5771. * Array of all error messages.
  5772. * @var array
  5773. */
  5774. public $all = array();
  5775. /**
  5776. * String containing entire error message.
  5777. * @var string
  5778. */
  5779. public $string = '';
  5780. /**
  5781. * All unset fields are returned as empty strings by default.
  5782. * @ignore
  5783. * @param string $field
  5784. * @return string Empty string
  5785. */
  5786. public function __get($field) {
  5787. return '';
  5788. }
  5789. }
  5790. /**
  5791. * Iterator for get_iterated
  5792. *
  5793. * @package DMZ
  5794. */
  5795. class DM_DatasetIterator implements Iterator, Countable
  5796. {
  5797. /**
  5798. * The parent DataMapper object that contains important info.
  5799. * @var DataMapper
  5800. */
  5801. protected $parent;
  5802. /**
  5803. * The temporary DM object used in the loops.
  5804. * @var DataMapper
  5805. */
  5806. protected $object;
  5807. /**
  5808. * Results array
  5809. * @var array
  5810. */
  5811. protected $result;
  5812. /**
  5813. * Number of results
  5814. * @var int
  5815. */
  5816. protected $count;
  5817. /**
  5818. * Current position
  5819. * @var int
  5820. */
  5821. protected $pos;
  5822. /**
  5823. * @param DataMapper $object Should be cloned ahead of time
  5824. * @param DB_result $query result from a CI DB query
  5825. */
  5826. function __construct($object, $query)
  5827. {
  5828. // store the object as a main object
  5829. $this->parent = $object;
  5830. // clone the parent object, so it can be manipulated safely.
  5831. $this->object = $object->get_clone();
  5832. // Now get the information on the current query object
  5833. $this->result = $query->result();
  5834. $this->count = count($this->result);
  5835. $this->pos = 0;
  5836. }
  5837. /**
  5838. * Gets the item at the current index $pos
  5839. * @return DataMapper
  5840. */
  5841. function current()
  5842. {
  5843. return $this->get($this->pos);
  5844. }
  5845. function key()
  5846. {
  5847. return $this->pos;
  5848. }
  5849. /**
  5850. * Gets the item at index $index
  5851. * @param int $index
  5852. * @return DataMapper
  5853. */
  5854. function get($index) {
  5855. // clear to ensure that the item is not duplicating data
  5856. $this->object->clear();
  5857. // set the current values on the object
  5858. $this->parent->_to_object($this->object, $this->result[$index]);
  5859. return $this->object;
  5860. }
  5861. function next()
  5862. {
  5863. $this->pos++;
  5864. }
  5865. function rewind()
  5866. {
  5867. $this->pos = 0;
  5868. }
  5869. function valid()
  5870. {
  5871. return ($this->pos < $this->count);
  5872. }
  5873. /**
  5874. * Returns the number of results
  5875. * @return int
  5876. */
  5877. function count()
  5878. {
  5879. return $this->count;
  5880. }
  5881. // Alias for count();
  5882. function result_count() {
  5883. return $this->count;
  5884. }
  5885. }
  5886. // --------------------------------------------------------------------------
  5887. /**
  5888. * Autoload
  5889. *
  5890. * Autoloads object classes that are used with DataMapper.
  5891. * Must be at end due to implements IteratorAggregate...
  5892. */
  5893. spl_autoload_register('DataMapper::autoload');
  5894. /* End of file datamapper.php */
  5895. /* Location: ./application/models/datamapper.php */