PageRenderTime 73ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 1ms

/application/libraries/datamapper.php

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