PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/application/libraries/datamapper.php

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