Model.php 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457
  1. <?php
  2. /**
  3. * Object-relational mapper.
  4. *
  5. * DBO-backed object data model, for mapping database tables to Cake objects.
  6. *
  7. * PHP versions 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.Model
  18. * @since CakePHP(tm) v 0.10.0.0
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. /**
  22. * Included libs
  23. */
  24. App::uses('ClassRegistry', 'Utility');
  25. App::uses('Validation', 'Utility');
  26. App::uses('String', 'Utility');
  27. App::uses('Set', 'Utility');
  28. App::uses('BehaviorCollection', 'Model');
  29. App::uses('ModelBehavior', 'Model');
  30. App::uses('ConnectionManager', 'Model');
  31. App::uses('Xml', 'Utility');
  32. /**
  33. * Object-relational mapper.
  34. *
  35. * DBO-backed object data model.
  36. * Automatically selects a database table name based on a pluralized lowercase object class name
  37. * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
  38. * The table is required to have at least 'id auto_increment' primary key.
  39. *
  40. * @package Cake.Model
  41. * @link http://book.cakephp.org/2.0/en/models.html
  42. */
  43. class Model extends Object {
  44. /**
  45. * The name of the DataSource connection that this Model uses
  46. *
  47. * The value must be an attribute name that you defined in `app/Config/database.php`
  48. * or created using `ConnectionManager::create()`.
  49. *
  50. * @var string
  51. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
  52. */
  53. public $useDbConfig = 'default';
  54. /**
  55. * Custom database table name, or null/false if no table association is desired.
  56. *
  57. * @var string
  58. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#useTable
  59. */
  60. public $useTable = null;
  61. /**
  62. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
  63. *
  64. * This field is also used in `find('list')` when called with no extra parameters in the fields list
  65. *
  66. * @var string
  67. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayField
  68. */
  69. public $displayField = null;
  70. /**
  71. * Value of the primary key ID of the record that this model is currently pointing to.
  72. * Automatically set after database insertions.
  73. *
  74. * @var mixed
  75. */
  76. public $id = false;
  77. /**
  78. * Container for the data that this model gets from persistent storage (usually, a database).
  79. *
  80. * @var array
  81. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data
  82. */
  83. public $data = array();
  84. /**
  85. * Table name for this Model.
  86. *
  87. * @var string
  88. */
  89. public $table = false;
  90. /**
  91. * The name of the primary key field for this model.
  92. *
  93. * @var string
  94. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primaryKey
  95. */
  96. public $primaryKey = null;
  97. /**
  98. * Field-by-field table metadata.
  99. *
  100. * @var array
  101. */
  102. protected $_schema = null;
  103. /**
  104. * List of validation rules. It must be an array with the field name as key and using
  105. * as value one of the following possibilities
  106. *
  107. * ### Validating using regular expressions
  108. *
  109. * {{{
  110. * public $validate = array(
  111. * 'name' => '/^[a-z].+$/i'
  112. * );
  113. * }}}
  114. *
  115. * ### Validating using methods (no parameters)
  116. *
  117. * {{{
  118. * public $validate = array(
  119. * 'name' => 'notEmpty'
  120. * );
  121. * }}}
  122. *
  123. * ### Validating using methods (with parameters)
  124. *
  125. * {{{
  126. * public $validate = array(
  127. * 'age' => array(
  128. * 'rule' => array('between', 5, 25)
  129. * )
  130. * );
  131. * }}}
  132. *
  133. * ### Validating using custom method
  134. *
  135. * {{{
  136. * public $validate = array(
  137. * 'password' => array(
  138. * 'rule' => array('customValidation')
  139. * )
  140. * );
  141. * public function customValidation($data) {
  142. * // $data will contain array('password' => 'value')
  143. * if (isset($this->data[$this->alias]['password2'])) {
  144. * return $this->data[$this->alias]['password2'] === current($data);
  145. * }
  146. * return true;
  147. * }
  148. * }}}
  149. *
  150. * ### Validations with messages
  151. *
  152. * The messages will be used in Model::$validationErrors and can be used in the FormHelper
  153. *
  154. * {{{
  155. * public $validate = array(
  156. * 'age' => array(
  157. * 'rule' => array('between', 5, 25),
  158. * 'message' => array('The age must be between %d and %d.')
  159. * )
  160. * );
  161. * }}}
  162. *
  163. * ### Multiple validations to the same field
  164. *
  165. * {{{
  166. * public $validate = array(
  167. * 'login' => array(
  168. * array(
  169. * 'rule' => 'alphaNumeric',
  170. * 'message' => 'Only alphabets and numbers allowed',
  171. * 'last' => true
  172. * ),
  173. * array(
  174. * 'rule' => array('minLength', 8),
  175. * 'message' => array('Minimum length of %d characters')
  176. * )
  177. * )
  178. * );
  179. * }}}
  180. *
  181. * ### Valid keys in validations
  182. *
  183. * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters
  184. * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf
  185. * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true]
  186. * - `required`: Boolean value to indicate if the field must be present on save
  187. * - `allowEmpty`: Boolean value to indicate if the field can be empty
  188. * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create
  189. *
  190. * @var array
  191. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
  192. * @link http://book.cakephp.org/2.0/en/models/data-validation.html
  193. */
  194. public $validate = array();
  195. /**
  196. * List of validation errors.
  197. *
  198. * @var array
  199. */
  200. public $validationErrors = array();
  201. /**
  202. * Name of the validation string domain to use when translating validation errors.
  203. *
  204. * @var string
  205. */
  206. public $validationDomain = null;
  207. /**
  208. * Database table prefix for tables in model.
  209. *
  210. * @var string
  211. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix
  212. */
  213. public $tablePrefix = null;
  214. /**
  215. * Name of the model.
  216. *
  217. * @var string
  218. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name
  219. */
  220. public $name = null;
  221. /**
  222. * Alias name for model.
  223. *
  224. * @var string
  225. */
  226. public $alias = null;
  227. /**
  228. * List of table names included in the model description. Used for associations.
  229. *
  230. * @var array
  231. */
  232. public $tableToModel = array();
  233. /**
  234. * Whether or not to cache queries for this model. This enables in-memory
  235. * caching only, the results are not stored beyond the current request.
  236. *
  237. * @var boolean
  238. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cacheQueries
  239. */
  240. public $cacheQueries = false;
  241. /**
  242. * Detailed list of belongsTo associations.
  243. *
  244. * ### Basic usage
  245. *
  246. * `public $belongsTo = array('Group', 'Department');`
  247. *
  248. * ### Detailed configuration
  249. *
  250. * {{{
  251. * public $belongsTo = array(
  252. * 'Group',
  253. * 'Department' => array(
  254. * 'className' => 'Department',
  255. * 'foreignKey' => 'department_id'
  256. * )
  257. * );
  258. * }}}
  259. *
  260. * ### Possible keys in association
  261. *
  262. * - `className`: the classname of the model being associated to the current model.
  263. * If you’re defining a ‘Profile belongsTo User’ relationship, the className key should equal ‘User.’
  264. * - `foreignKey`: the name of the foreign key found in the current model. This is
  265. * especially handy if you need to define multiple belongsTo relationships. The default
  266. * value for this key is the underscored, singular name of the other model, suffixed with ‘_id’.
  267. * - `conditions`: An SQL fragment used to filter related model records. It’s good
  268. * practice to use model names in SQL fragments: “User.active = 1” is always
  269. * better than just “active = 1.”
  270. * - `type`: the type of the join to use in the SQL query, default is LEFT which
  271. * may not fit your needs in all situations, INNER may be helpful when you want
  272. * everything from your main and associated models or nothing at all!(effective
  273. * when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner)
  274. * - `fields`: A list of fields to be retrieved when the associated model data is
  275. * fetched. Returns all fields by default.
  276. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  277. * - `counterCache`: If set to true the associated Model will automatically increase or
  278. * decrease the “[singular_model_name]_count” field in the foreign table whenever you do
  279. * a save() or delete(). If its a string then its the field name to use. The value in the
  280. * counter field represents the number of related rows.
  281. * - `counterScope`: Optional conditions array to use for updating counter cache field.
  282. *
  283. * @var array
  284. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
  285. */
  286. public $belongsTo = array();
  287. /**
  288. * Detailed list of hasOne associations.
  289. *
  290. * ### Basic usage
  291. *
  292. * `public $hasOne = array('Profile', 'Address');`
  293. *
  294. * ### Detailed configuration
  295. *
  296. * {{{
  297. * public $hasOne = array(
  298. * 'Profile',
  299. * 'Address' => array(
  300. * 'className' => 'Address',
  301. * 'foreignKey' => 'user_id'
  302. * )
  303. * );
  304. * }}}
  305. *
  306. * ### Possible keys in association
  307. *
  308. * - `className`: the classname of the model being associated to the current model.
  309. * If you’re defining a ‘User hasOne Profile’ relationship, the className key should equal ‘Profile.’
  310. * - `foreignKey`: the name of the foreign key found in the other model. This is
  311. * especially handy if you need to define multiple hasOne relationships.
  312. * The default value for this key is the underscored, singular name of the
  313. * current model, suffixed with ‘_id’. In the example above it would default to 'user_id'.
  314. * - `conditions`: An SQL fragment used to filter related model records. It’s good
  315. * practice to use model names in SQL fragments: “Profile.approved = 1” is
  316. * always better than just “approved = 1.”
  317. * - `fields`: A list of fields to be retrieved when the associated model data is
  318. * fetched. Returns all fields by default.
  319. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  320. * - `dependent`: When the dependent key is set to true, and the model’s delete()
  321. * method is called with the cascade parameter set to true, associated model
  322. * records are also deleted. In this case we set it true so that deleting a
  323. * User will also delete her associated Profile.
  324. *
  325. * @var array
  326. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
  327. */
  328. public $hasOne = array();
  329. /**
  330. * Detailed list of hasMany associations.
  331. *
  332. * ### Basic usage
  333. *
  334. * `public $hasMany = array('Comment', 'Task');`
  335. *
  336. * ### Detailed configuration
  337. *
  338. * {{{
  339. * public $hasMany = array(
  340. * 'Comment',
  341. * 'Task' => array(
  342. * 'className' => 'Task',
  343. * 'foreignKey' => 'user_id'
  344. * )
  345. * );
  346. * }}}
  347. *
  348. * ### Possible keys in association
  349. *
  350. * - `className`: the classname of the model being associated to the current model.
  351. * If you’re defining a ‘User hasMany Comment’ relationship, the className key should equal ‘Comment.’
  352. * - `foreignKey`: the name of the foreign key found in the other model. This is
  353. * especially handy if you need to define multiple hasMany relationships. The default
  354. * value for this key is the underscored, singular name of the actual model, suffixed with ‘_id’.
  355. * - `conditions`: An SQL fragment used to filter related model records. It’s good
  356. * practice to use model names in SQL fragments: “Comment.status = 1” is always
  357. * better than just “status = 1.”
  358. * - `fields`: A list of fields to be retrieved when the associated model data is
  359. * fetched. Returns all fields by default.
  360. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  361. * - `limit`: The maximum number of associated rows you want returned.
  362. * - `offset`: The number of associated rows to skip over (given the current
  363. * conditions and order) before fetching and associating.
  364. * - `dependent`: When dependent is set to true, recursive model deletion is
  365. * possible. In this example, Comment records will be deleted when their
  366. * associated User record has been deleted.
  367. * - `exclusive`: When exclusive is set to true, recursive model deletion does
  368. * the delete with a deleteAll() call, instead of deleting each entity separately.
  369. * This greatly improves performance, but may not be ideal for all circumstances.
  370. * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model
  371. * records. This should be used in situations that require very custom results.
  372. *
  373. * @var array
  374. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
  375. */
  376. public $hasMany = array();
  377. /**
  378. * Detailed list of hasAndBelongsToMany associations.
  379. *
  380. * ### Basic usage
  381. *
  382. * `public $hasAndBelongsToMany = array('Role', 'Address');`
  383. *
  384. * ### Detailed configuration
  385. *
  386. * {{{
  387. * public $hasAndBelongsToMany = array(
  388. * 'Role',
  389. * 'Address' => array(
  390. * 'className' => 'Address',
  391. * 'foreignKey' => 'user_id',
  392. * 'associationForeignKey' => 'address_id',
  393. * 'joinTable' => 'addresses_users'
  394. * )
  395. * );
  396. * }}}
  397. *
  398. * ### Possible keys in association
  399. *
  400. * - `className`: the classname of the model being associated to the current model.
  401. * If you're defining a ‘Recipe HABTM Tag' relationship, the className key should equal ‘Tag.'
  402. * - `joinTable`: The name of the join table used in this association (if the
  403. * current table doesn't adhere to the naming convention for HABTM join tables).
  404. * - `with`: Defines the name of the model for the join table. By default CakePHP
  405. * will auto-create a model for you. Using the example above it would be called
  406. * RecipesTag. By using this key you can override this default name. The join
  407. * table model can be used just like any "regular" model to access the join table directly.
  408. * - `foreignKey`: the name of the foreign key found in the current model.
  409. * This is especially handy if you need to define multiple HABTM relationships.
  410. * The default value for this key is the underscored, singular name of the
  411. * current model, suffixed with ‘_id'.
  412. * - `associationForeignKey`: the name of the foreign key found in the other model.
  413. * This is especially handy if you need to define multiple HABTM relationships.
  414. * The default value for this key is the underscored, singular name of the other
  415. * model, suffixed with ‘_id'.
  416. * - `unique`: If true (default value) cake will first delete existing relationship
  417. * records in the foreign keys table before inserting new ones, when updating a
  418. * record. So existing associations need to be passed again when updating.
  419. * - `conditions`: An SQL fragment used to filter related model records. It's good
  420. * practice to use model names in SQL fragments: "Comment.status = 1" is always
  421. * better than just "status = 1."
  422. * - `fields`: A list of fields to be retrieved when the associated model data is
  423. * fetched. Returns all fields by default.
  424. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows.
  425. * - `limit`: The maximum number of associated rows you want returned.
  426. * - `offset`: The number of associated rows to skip over (given the current
  427. * conditions and order) before fetching and associating.
  428. * - `finderQuery`, `deleteQuery`, `insertQuery`: A complete SQL query CakePHP
  429. * can use to fetch, delete, or create new associated model records. This should
  430. * be used in situations that require very custom results.
  431. *
  432. * @var array
  433. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
  434. */
  435. public $hasAndBelongsToMany = array();
  436. /**
  437. * List of behaviors to load when the model object is initialized. Settings can be
  438. * passed to behaviors by using the behavior name as index. Eg:
  439. *
  440. * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))
  441. *
  442. * @var array
  443. * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
  444. */
  445. public $actsAs = null;
  446. /**
  447. * Holds the Behavior objects currently bound to this model.
  448. *
  449. * @var BehaviorCollection
  450. */
  451. public $Behaviors = null;
  452. /**
  453. * Whitelist of fields allowed to be saved.
  454. *
  455. * @var array
  456. */
  457. public $whitelist = array();
  458. /**
  459. * Whether or not to cache sources for this model.
  460. *
  461. * @var boolean
  462. */
  463. public $cacheSources = true;
  464. /**
  465. * Type of find query currently executing.
  466. *
  467. * @var string
  468. */
  469. public $findQueryType = null;
  470. /**
  471. * Number of associations to recurse through during find calls. Fetches only
  472. * the first level by default.
  473. *
  474. * @var integer
  475. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
  476. */
  477. public $recursive = 1;
  478. /**
  479. * The column name(s) and direction(s) to order find results by default.
  480. *
  481. * public $order = "Post.created DESC";
  482. * public $order = array("Post.view_count DESC", "Post.rating DESC");
  483. *
  484. * @var string
  485. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order
  486. */
  487. public $order = null;
  488. /**
  489. * Array of virtual fields this model has. Virtual fields are aliased
  490. * SQL expressions. Fields added to this property will be read as other fields in a model
  491. * but will not be saveable.
  492. *
  493. * `public $virtualFields = array('two' => '1 + 1');`
  494. *
  495. * Is a simplistic example of how to set virtualFields
  496. *
  497. * @var array
  498. * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields
  499. */
  500. public $virtualFields = array();
  501. /**
  502. * Default list of association keys.
  503. *
  504. * @var array
  505. */
  506. protected $_associationKeys = array(
  507. 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
  508. 'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
  509. 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
  510. 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
  511. );
  512. /**
  513. * Holds provided/generated association key names and other data for all associations.
  514. *
  515. * @var array
  516. */
  517. protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  518. /**
  519. * Holds model associations temporarily to allow for dynamic (un)binding.
  520. *
  521. * @var array
  522. */
  523. public $__backAssociation = array();
  524. /**
  525. * Back inner association
  526. *
  527. * @var array
  528. */
  529. public $__backInnerAssociation = array();
  530. /**
  531. * Back original association
  532. *
  533. * @var array
  534. */
  535. public $__backOriginalAssociation = array();
  536. /**
  537. * Back containable association
  538. *
  539. * @var array
  540. */
  541. public $__backContainableAssociation = array();
  542. /**
  543. * The ID of the model record that was last inserted.
  544. *
  545. * @var integer
  546. */
  547. protected $_insertID = null;
  548. /**
  549. * Has the datasource been configured.
  550. *
  551. * @var boolean
  552. * @see Model::getDataSource
  553. */
  554. protected $_sourceConfigured = false;
  555. /**
  556. * List of valid finder method options, supplied as the first parameter to find().
  557. *
  558. * @var array
  559. */
  560. public $findMethods = array(
  561. 'all' => true, 'first' => true, 'count' => true,
  562. 'neighbors' => true, 'list' => true, 'threaded' => true
  563. );
  564. /**
  565. * Constructor. Binds the model's database table to the object.
  566. *
  567. * If `$id` is an array it can be used to pass several options into the model.
  568. *
  569. * - id - The id to start the model on.
  570. * - table - The table to use for this model.
  571. * - ds - The connection name this model is connected to.
  572. * - name - The name of the model eg. Post.
  573. * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`.
  574. * eg. `ParentThread`
  575. *
  576. * ### Overriding Model's __construct method.
  577. *
  578. * When overriding Model::__construct() be careful to include and pass in all 3 of the
  579. * arguments to `parent::__construct($id, $table, $ds);`
  580. *
  581. * ### Dynamically creating models
  582. *
  583. * You can dynamically create model instances using the $id array syntax.
  584. *
  585. * {{{
  586. * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));
  587. * }}}
  588. *
  589. * Would create a model attached to the posts table on connection2. Dynamic model creation is useful
  590. * when you want a model object that contains no associations or attached behaviors.
  591. *
  592. * @param mixed $id Set this ID for this model on startup, can also be an array of options, see above.
  593. * @param string $table Name of database table to use.
  594. * @param string $ds DataSource connection name.
  595. */
  596. public function __construct($id = false, $table = null, $ds = null) {
  597. parent::__construct();
  598. if (is_array($id)) {
  599. extract(array_merge(
  600. array(
  601. 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig,
  602. 'name' => $this->name, 'alias' => $this->alias
  603. ),
  604. $id
  605. ));
  606. }
  607. if ($this->name === null) {
  608. $this->name = (isset($name) ? $name : get_class($this));
  609. }
  610. if ($this->alias === null) {
  611. $this->alias = (isset($alias) ? $alias : $this->name);
  612. }
  613. if ($this->primaryKey === null) {
  614. $this->primaryKey = 'id';
  615. }
  616. ClassRegistry::addObject($this->alias, $this);
  617. $this->id = $id;
  618. unset($id);
  619. if ($table === false) {
  620. $this->useTable = false;
  621. } elseif ($table) {
  622. $this->useTable = $table;
  623. }
  624. if ($ds !== null) {
  625. $this->useDbConfig = $ds;
  626. }
  627. if (is_subclass_of($this, 'AppModel')) {
  628. $merge = array('findMethods');
  629. if ($this->actsAs !== null || $this->actsAs !== false) {
  630. $merge[] = 'actsAs';
  631. }
  632. $parentClass = get_parent_class($this);
  633. if ($parentClass !== 'AppModel') {
  634. $this->_mergeVars($merge, $parentClass);
  635. }
  636. $this->_mergeVars($merge, 'AppModel');
  637. }
  638. $this->Behaviors = new BehaviorCollection();
  639. if ($this->useTable !== false) {
  640. if ($this->useTable === null) {
  641. $this->useTable = Inflector::tableize($this->name);
  642. }
  643. if ($this->displayField == null) {
  644. unset($this->displayField);
  645. }
  646. $this->table = $this->useTable;
  647. $this->tableToModel[$this->table] = $this->alias;
  648. } elseif ($this->table === false) {
  649. $this->table = Inflector::tableize($this->name);
  650. }
  651. if ($this->tablePrefix === null) {
  652. unset($this->tablePrefix);
  653. }
  654. $this->_createLinks();
  655. $this->Behaviors->init($this->alias, $this->actsAs);
  656. }
  657. /**
  658. * Handles custom method calls, like findBy<field> for DB models,
  659. * and custom RPC calls for remote data sources.
  660. *
  661. * @param string $method Name of method to call.
  662. * @param array $params Parameters for the method.
  663. * @return mixed Whatever is returned by called method
  664. */
  665. public function __call($method, $params) {
  666. $result = $this->Behaviors->dispatchMethod($this, $method, $params);
  667. if ($result !== array('unhandled')) {
  668. return $result;
  669. }
  670. $return = $this->getDataSource()->query($method, $params, $this);
  671. return $return;
  672. }
  673. /**
  674. * Handles the lazy loading of model associations by looking in the association arrays for the requested variable
  675. *
  676. * @param string $name variable tested for existence in class
  677. * @return boolean true if the variable exists (if is a not loaded model association it will be created), false otherwise
  678. */
  679. public function __isset($name) {
  680. $className = false;
  681. foreach ($this->_associations as $type) {
  682. if (isset($name, $this->{$type}[$name])) {
  683. $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className'];
  684. break;
  685. }
  686. elseif (isset($name, $this->__backAssociation[$type][$name])) {
  687. $className = empty($this->__backAssociation[$type][$name]['className']) ?
  688. $name : $this->__backAssociation[$type][$name]['className'];
  689. break;
  690. } else if ($type == 'hasAndBelongsToMany') {
  691. foreach ($this->{$type} as $k => $relation) {
  692. if (empty($relation['with'])) {
  693. continue;
  694. }
  695. if (is_array($relation['with'])) {
  696. if (key($relation['with']) === $name) {
  697. $className = $name;
  698. }
  699. } else {
  700. list($plugin, $class) = pluginSplit($relation['with']);
  701. if ($class === $name) {
  702. $className = $relation['with'];
  703. }
  704. }
  705. if ($className) {
  706. $assocKey = $k;
  707. $dynamic = !empty($relation['dynamicWith']);
  708. break(2);
  709. }
  710. }
  711. }
  712. }
  713. if (!$className) {
  714. return false;
  715. }
  716. list($plugin, $className) = pluginSplit($className);
  717. if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) {
  718. $this->{$className} = new AppModel(array(
  719. 'name' => $className,
  720. 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'],
  721. 'ds' => $this->useDbConfig
  722. ));
  723. } else {
  724. $this->_constructLinkedModel($name, $className, $plugin);
  725. }
  726. if (!empty($assocKey)) {
  727. $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table;
  728. if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) {
  729. $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey'];
  730. }
  731. }
  732. return true;
  733. }
  734. /**
  735. * Returns the value of the requested variable if it can be set by __isset()
  736. *
  737. * @param string $name variable requested for it's value or reference
  738. * @return mixed value of requested variable if it is set
  739. */
  740. public function __get($name) {
  741. if ($name === 'displayField') {
  742. return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey));
  743. }
  744. if ($name === 'tablePrefix') {
  745. $this->setDataSource();
  746. if (property_exists($this, 'tablePrefix')) {
  747. return $this->tablePrefix;
  748. }
  749. return $this->tablePrefix = null;
  750. }
  751. if (isset($this->{$name})) {
  752. return $this->{$name};
  753. }
  754. }
  755. /**
  756. * Bind model associations on the fly.
  757. *
  758. * If `$reset` is false, association will not be reset
  759. * to the originals defined in the model
  760. *
  761. * Example: Add a new hasOne binding to the Profile model not
  762. * defined in the model source code:
  763. *
  764. * `$this->User->bindModel( array('hasOne' => array('Profile')) );`
  765. *
  766. * Bindings that are not made permanent will be reset by the next Model::find() call on this
  767. * model.
  768. *
  769. * @param array $params Set of bindings (indexed by binding type)
  770. * @param boolean $reset Set to false to make the binding permanent
  771. * @return boolean Success
  772. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  773. */
  774. public function bindModel($params, $reset = true) {
  775. foreach ($params as $assoc => $model) {
  776. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  777. $this->__backAssociation[$assoc] = $this->{$assoc};
  778. }
  779. foreach ($model as $key => $value) {
  780. $assocName = $key;
  781. if (is_numeric($key)) {
  782. $assocName = $value;
  783. $value = array();
  784. }
  785. $modelName = $assocName;
  786. $this->{$assoc}[$assocName] = $value;
  787. if (property_exists($this, $assocName)) {
  788. unset($this->{$assocName});
  789. }
  790. if ($reset === false && isset($this->__backAssociation[$assoc])) {
  791. $this->__backAssociation[$assoc][$assocName] = $value;
  792. }
  793. }
  794. }
  795. $this->_createLinks();
  796. return true;
  797. }
  798. /**
  799. * Turn off associations on the fly.
  800. *
  801. * If $reset is false, association will not be reset
  802. * to the originals defined in the model
  803. *
  804. * Example: Turn off the associated Model Support request,
  805. * to temporarily lighten the User model:
  806. *
  807. * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );`
  808. *
  809. * unbound models that are not made permanent will reset with the next call to Model::find()
  810. *
  811. * @param array $params Set of bindings to unbind (indexed by binding type)
  812. * @param boolean $reset Set to false to make the unbinding permanent
  813. * @return boolean Success
  814. * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly
  815. */
  816. public function unbindModel($params, $reset = true) {
  817. foreach ($params as $assoc => $models) {
  818. if ($reset === true && !isset($this->__backAssociation[$assoc])) {
  819. $this->__backAssociation[$assoc] = $this->{$assoc};
  820. }
  821. foreach ($models as $model) {
  822. if ($reset === false && isset($this->__backAssociation[$assoc][$model])) {
  823. unset($this->__backAssociation[$assoc][$model]);
  824. }
  825. unset($this->{$assoc}[$model]);
  826. }
  827. }
  828. return true;
  829. }
  830. /**
  831. * Create a set of associations.
  832. *
  833. * @return void
  834. */
  835. protected function _createLinks() {
  836. foreach ($this->_associations as $type) {
  837. if (!is_array($this->{$type})) {
  838. $this->{$type} = explode(',', $this->{$type});
  839. foreach ($this->{$type} as $i => $className) {
  840. $className = trim($className);
  841. unset ($this->{$type}[$i]);
  842. $this->{$type}[$className] = array();
  843. }
  844. }
  845. if (!empty($this->{$type})) {
  846. foreach ($this->{$type} as $assoc => $value) {
  847. $plugin = null;
  848. if (is_numeric($assoc)) {
  849. unset ($this->{$type}[$assoc]);
  850. $assoc = $value;
  851. $value = array();
  852. if (strpos($assoc, '.') !== false) {
  853. list($plugin, $assoc) = pluginSplit($assoc);
  854. $this->{$type}[$assoc] = array('className' => $plugin. '.' . $assoc);
  855. } else {
  856. $this->{$type}[$assoc] = $value;
  857. }
  858. }
  859. $this->_generateAssociation($type, $assoc);
  860. }
  861. }
  862. }
  863. }
  864. /**
  865. * Protected helper method to create associated models of a given class.
  866. *
  867. * @param string $assoc Association name
  868. * @param string $className Class name
  869. * @param string $plugin name of the plugin where $className is located
  870. * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName'));
  871. * usage: $this->Assoc->modelMethods();
  872. *
  873. * public $hasMany = array('ModelName');
  874. * usage: $this->ModelName->modelMethods();
  875. * @return void
  876. */
  877. protected function _constructLinkedModel($assoc, $className = null, $plugin = null) {
  878. if (empty($className)) {
  879. $className = $assoc;
  880. }
  881. if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) {
  882. if ($plugin) {
  883. $plugin .= '.';
  884. }
  885. $model = array('class' => $plugin . $className, 'alias' => $assoc);
  886. $this->{$assoc} = ClassRegistry::init($model);
  887. if ($plugin) {
  888. ClassRegistry::addObject($plugin . $className, $this->{$assoc});
  889. }
  890. if ($assoc) {
  891. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  892. }
  893. }
  894. }
  895. /**
  896. * Build an array-based association from string.
  897. *
  898. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  899. * @param string $assocKey
  900. * @return void
  901. */
  902. protected function _generateAssociation($type, $assocKey) {
  903. $class = $assocKey;
  904. $dynamicWith = false;
  905. foreach ($this->_associationKeys[$type] as $key) {
  906. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  907. $data = '';
  908. switch ($key) {
  909. case 'fields':
  910. $data = '';
  911. break;
  912. case 'foreignKey':
  913. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  914. break;
  915. case 'associationForeignKey':
  916. $data = Inflector::singularize($this->{$class}->table) . '_id';
  917. break;
  918. case 'with':
  919. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  920. $dynamicWith = true;
  921. break;
  922. case 'joinTable':
  923. $tables = array($this->table, $this->{$class}->table);
  924. sort ($tables);
  925. $data = $tables[0] . '_' . $tables[1];
  926. break;
  927. case 'className':
  928. $data = $class;
  929. break;
  930. case 'unique':
  931. $data = true;
  932. break;
  933. }
  934. $this->{$type}[$assocKey][$key] = $data;
  935. }
  936. if ($dynamicWith) {
  937. $this->{$type}[$assocKey]['dynamicWith'] = true;
  938. }
  939. }
  940. }
  941. /**
  942. * Sets a custom table for your controller class. Used by your controller to select a database table.
  943. *
  944. * @param string $tableName Name of the custom table
  945. * @throws MissingTableException when database table $tableName is not found on data source
  946. * @return void
  947. */
  948. public function setSource($tableName) {
  949. $this->setDataSource($this->useDbConfig);
  950. $db = ConnectionManager::getDataSource($this->useDbConfig);
  951. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  952. if (method_exists($db, 'listSources')) {
  953. $sources = $db->listSources();
  954. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  955. throw new MissingTableException(array(
  956. 'table' => $this->tablePrefix . $tableName,
  957. 'class' => $this->alias
  958. ));
  959. }
  960. $this->_schema = null;
  961. }
  962. $this->table = $this->useTable = $tableName;
  963. $this->tableToModel[$this->table] = $this->alias;
  964. }
  965. /**
  966. * This function does two things:
  967. *
  968. * 1. it scans the array $one for the primary key,
  969. * and if that's found, it sets the current id to the value of $one[id].
  970. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  971. * 2. Returns an array with all of $one's keys and values.
  972. * (Alternative indata: two strings, which are mangled to
  973. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  974. *
  975. * @param mixed $one Array or string of data
  976. * @param string $two Value string for the alternative indata method
  977. * @return array Data with all of $one's keys and values
  978. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  979. */
  980. public function set($one, $two = null) {
  981. if (!$one) {
  982. return;
  983. }
  984. if (is_object($one)) {
  985. if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
  986. $one = $this->_normalizeXmlData(Xml::toArray($one));
  987. } else {
  988. $one = Set::reverse($one);
  989. }
  990. }
  991. if (is_array($one)) {
  992. $data = $one;
  993. if (empty($one[$this->alias])) {
  994. if ($this->getAssociated(key($one)) === null) {
  995. $data = array($this->alias => $one);
  996. }
  997. }
  998. } else {
  999. $data = array($this->alias => array($one => $two));
  1000. }
  1001. foreach ($data as $modelName => $fieldSet) {
  1002. if (is_array($fieldSet)) {
  1003. foreach ($fieldSet as $fieldName => $fieldValue) {
  1004. if (isset($this->validationErrors[$fieldName])) {
  1005. unset ($this->validationErrors[$fieldName]);
  1006. }
  1007. if ($modelName === $this->alias) {
  1008. if ($fieldName === $this->primaryKey) {
  1009. $this->id = $fieldValue;
  1010. }
  1011. }
  1012. if (is_array($fieldValue) || is_object($fieldValue)) {
  1013. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  1014. }
  1015. $this->data[$modelName][$fieldName] = $fieldValue;
  1016. }
  1017. }
  1018. }
  1019. return $data;
  1020. }
  1021. /**
  1022. * Normalize Xml::toArray() to use in Model::save()
  1023. *
  1024. * @param array $xml XML as array
  1025. * @return array
  1026. */
  1027. protected function _normalizeXmlData(array $xml) {
  1028. $return = array();
  1029. foreach ($xml as $key => $value) {
  1030. if (is_array($value)) {
  1031. $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
  1032. } elseif ($key[0] === '@') {
  1033. $return[substr($key, 1)] = $value;
  1034. } else {
  1035. $return[$key] = $value;
  1036. }
  1037. }
  1038. return $return;
  1039. }
  1040. /**
  1041. * Deconstructs a complex data type (array or object) into a single field value.
  1042. *
  1043. * @param string $field The name of the field to be deconstructed
  1044. * @param mixed $data An array or object to be deconstructed into a field
  1045. * @return mixed The resulting data that should be assigned to a field
  1046. */
  1047. public function deconstruct($field, $data) {
  1048. if (!is_array($data)) {
  1049. return $data;
  1050. }
  1051. $copy = $data;
  1052. $type = $this->getColumnType($field);
  1053. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  1054. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  1055. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  1056. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  1057. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  1058. $date = array();
  1059. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
  1060. $data['hour'] = $data['hour'] + 12;
  1061. }
  1062. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  1063. $data['hour'] = '00';
  1064. }
  1065. if ($type == 'time') {
  1066. foreach ($timeFields as $key => $val) {
  1067. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1068. $data[$val] = '00';
  1069. } elseif ($data[$val] === '') {
  1070. $data[$val] = '';
  1071. } else {
  1072. $data[$val] = sprintf('%02d', $data[$val]);
  1073. }
  1074. if (!empty($data[$val])) {
  1075. $date[$key] = $data[$val];
  1076. } else {
  1077. return null;
  1078. }
  1079. }
  1080. }
  1081. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  1082. foreach ($dateFields as $key => $val) {
  1083. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  1084. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  1085. $data[$val] = '00';
  1086. } else {
  1087. $data[$val] = sprintf('%02d', $data[$val]);
  1088. }
  1089. }
  1090. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  1091. return null;
  1092. }
  1093. if (isset($data[$val]) && !empty($data[$val])) {
  1094. $date[$key] = $data[$val];
  1095. }
  1096. }
  1097. }
  1098. if ($useNewDate && !empty($date)) {
  1099. $format = $this->getDataSource()->columns[$type]['format'];
  1100. foreach (array('m', 'd', 'H', 'i', 's') as $index) {
  1101. if (isset($date[$index])) {
  1102. $date[$index] = sprintf('%02d', $date[$index]);
  1103. }
  1104. }
  1105. return str_replace(array_keys($date), array_values($date), $format);
  1106. }
  1107. }
  1108. return $data;
  1109. }
  1110. /**
  1111. * Returns an array of table metadata (column names and types) from the database.
  1112. * $field => keys(type, null, default, key, length, extra)
  1113. *
  1114. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  1115. * @return array Array of table metadata
  1116. */
  1117. public function schema($field = false) {
  1118. if (!is_array($this->_schema) || $field === true) {
  1119. $db = $this->getDataSource();
  1120. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  1121. if (method_exists($db, 'describe') && $this->useTable !== false) {
  1122. $this->_schema = $db->describe($this);
  1123. } elseif ($this->useTable === false) {
  1124. $this->_schema = array();
  1125. }
  1126. }
  1127. if (is_string($field)) {
  1128. if (isset($this->_schema[$field])) {
  1129. return $this->_schema[$field];
  1130. } else {
  1131. return null;
  1132. }
  1133. }
  1134. return $this->_schema;
  1135. }
  1136. /**
  1137. * Returns an associative array of field names and column types.
  1138. *
  1139. * @return array Field types indexed by field name
  1140. */
  1141. public function getColumnTypes() {
  1142. $columns = $this->schema();
  1143. if (empty($columns)) {
  1144. trigger_error(__d('cake_dev', '(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()'), E_USER_WARNING);
  1145. }
  1146. $cols = array();
  1147. foreach ($columns as $field => $values) {
  1148. $cols[$field] = $values['type'];
  1149. }
  1150. return $cols;
  1151. }
  1152. /**
  1153. * Returns the column type of a column in the model.
  1154. *
  1155. * @param string $column The name of the model column
  1156. * @return string Column type
  1157. */
  1158. public function getColumnType($column) {
  1159. $db = $this->getDataSource();
  1160. $cols = $this->schema();
  1161. $model = null;
  1162. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  1163. if (strpos($column, '.')) {
  1164. list($model, $column) = explode('.', $column);
  1165. }
  1166. if ($model != $this->alias && isset($this->{$model})) {
  1167. return $this->{$model}->getColumnType($column);
  1168. }
  1169. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  1170. return $cols[$column]['type'];
  1171. }
  1172. return null;
  1173. }
  1174. /**
  1175. * Returns true if the supplied field exists in the model's database table.
  1176. *
  1177. * @param mixed $name Name of field to look for, or an array of names
  1178. * @param boolean $checkVirtual checks if the field is declared as virtual
  1179. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  1180. * If $name is an array of field names, returns the first field that exists,
  1181. * or false if none exist.
  1182. */
  1183. public function hasField($name, $checkVirtual = false) {
  1184. if (is_array($name)) {
  1185. foreach ($name as $n) {
  1186. if ($this->hasField($n, $checkVirtual)) {
  1187. return $n;
  1188. }
  1189. }
  1190. return false;
  1191. }
  1192. if ($checkVirtual && !empty($this->virtualFields)) {
  1193. if ($this->isVirtualField($name)) {
  1194. return true;
  1195. }
  1196. }
  1197. if (empty($this->_schema)) {
  1198. $this->schema();
  1199. }
  1200. if ($this->_schema != null) {
  1201. return isset($this->_schema[$name]);
  1202. }
  1203. return false;
  1204. }
  1205. /**
  1206. * Check that a method is callable on a model. This will check both the model's own methods, its
  1207. * inherited methods and methods that could be callable through behaviors.
  1208. *
  1209. * @param string $method The method to be called.
  1210. * @return boolean True on method being callable.
  1211. */
  1212. public function hasMethod($method) {
  1213. if (method_exists($this, $method)) {
  1214. return true;
  1215. }
  1216. if ($this->Behaviors->hasMethod($method)) {
  1217. return true;
  1218. }
  1219. return false;
  1220. }
  1221. /**
  1222. * Returns true if the supplied field is a model Virtual Field
  1223. *
  1224. * @param string $field Name of field to look for
  1225. * @return boolean indicating whether the field exists as a model virtual field.
  1226. */
  1227. public function isVirtualField($field) {
  1228. if (empty($this->virtualFields) || !is_string($field)) {
  1229. return false;
  1230. }
  1231. if (isset($this->virtualFields[$field])) {
  1232. return true;
  1233. }
  1234. if (strpos($field, '.') !== false) {
  1235. list($model, $field) = explode('.', $field);
  1236. if ($model == $this->alias && isset($this->virtualFields[$field])) {
  1237. return true;
  1238. }
  1239. }
  1240. return false;
  1241. }
  1242. /**
  1243. * Returns the expression for a model virtual field
  1244. *
  1245. * @param string $field Name of field to look for
  1246. * @return mixed If $field is string expression bound to virtual field $field
  1247. * If $field is null, returns an array of all model virtual fields
  1248. * or false if none $field exist.
  1249. */
  1250. public function getVirtualField($field = null) {
  1251. if ($field == null) {
  1252. return empty($this->virtualFields) ? false : $this->virtualFields;
  1253. }
  1254. if ($this->isVirtualField($field)) {
  1255. if (strpos($field, '.') !== false) {
  1256. list($model, $field) = explode('.', $field);
  1257. }
  1258. return $this->virtualFields[$field];
  1259. }
  1260. return false;
  1261. }
  1262. /**
  1263. * Initializes the model for writing a new record, loading the default values
  1264. * for those fields that are not defined in $data, and clearing previous validation errors.
  1265. * Especially helpful for saving data in loops.
  1266. *
  1267. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  1268. * schema data defaults are not merged.
  1269. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  1270. * @return array The current Model::data; after merging $data and/or defaults from database
  1271. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
  1272. */
  1273. public function create($data = array(), $filterKey = false) {
  1274. $defaults = array();
  1275. $this->id = false;
  1276. $this->data = array();
  1277. $this->validationErrors = array();
  1278. if ($data !== null && $data !== false) {
  1279. foreach ($this->schema() as $field => $properties) {
  1280. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  1281. $defaults[$field] = $properties['default'];
  1282. }
  1283. }
  1284. $this->set($defaults);
  1285. $this->set($data);
  1286. }
  1287. if ($filterKey) {
  1288. $this->set($this->primaryKey, false);
  1289. }
  1290. return $this->data;
  1291. }
  1292. /**
  1293. * Returns a list of fields from the database, and sets the current model
  1294. * data (Model::$data) with the record found.
  1295. *
  1296. * @param mixed $fields String of single field name, or an array of field names.
  1297. * @param mixed $id The ID of the record to read
  1298. * @return array Array of database fields, or false if not found
  1299. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
  1300. */
  1301. public function read($fields = null, $id = null) {
  1302. $this->validationErrors = array();
  1303. if ($id != null) {
  1304. $this->id = $id;
  1305. }
  1306. $id = $this->id;
  1307. if (is_array($this->id)) {
  1308. $id = $this->id[0];
  1309. }
  1310. if ($id !== null && $id !== false) {
  1311. $this->data = $this->find('first', array(
  1312. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1313. 'fields' => $fields
  1314. ));
  1315. return $this->data;
  1316. } else {
  1317. return false;
  1318. }
  1319. }
  1320. /**
  1321. * Returns the contents of a single field given the supplied conditions, in the
  1322. * supplied order.
  1323. *
  1324. * @param string $name Name of field to get
  1325. * @param array $conditions SQL conditions (defaults to NULL)
  1326. * @param string $order SQL ORDER BY fragment
  1327. * @return string field contents, or false if not found
  1328. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
  1329. */
  1330. public function field($name, $conditions = null, $order = null) {
  1331. if ($conditions === null && $this->id !== false) {
  1332. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1333. }
  1334. if ($this->recursive >= 1) {
  1335. $recursive = -1;
  1336. } else {
  1337. $recursive = $this->recursive;
  1338. }
  1339. $fields = $name;
  1340. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1341. if (strpos($name, '.') === false) {
  1342. if (isset($data[$this->alias][$name])) {
  1343. return $data[$this->alias][$name];
  1344. }
  1345. } else {
  1346. $name = explode('.', $name);
  1347. if (isset($data[$name[0]][$name[1]])) {
  1348. return $data[$name[0]][$name[1]];
  1349. }
  1350. }
  1351. if (isset($data[0]) && count($data[0]) > 0) {
  1352. return array_shift($data[0]);
  1353. }
  1354. } else {
  1355. return false;
  1356. }
  1357. }
  1358. /**
  1359. * Saves the value of a single field to the database, based on the current
  1360. * model ID.
  1361. *
  1362. * @param string $name Name of the table field
  1363. * @param mixed $value Value of the field
  1364. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1365. * @return boolean See Model::save()
  1366. * @see Model::save()
  1367. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read
  1368. */
  1369. public function saveField($name, $value, $validate = false) {
  1370. $id = $this->id;
  1371. $this->create(false);
  1372. if (is_array($validate)) {
  1373. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1374. } else {
  1375. $options = array('validate' => $validate, 'fieldList' => array($name));
  1376. }
  1377. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1378. }
  1379. /**
  1380. * Saves model data (based on white-list, if supplied) to the database. By
  1381. * default, validation occurs before save.
  1382. *
  1383. * @param array $data Data to save.
  1384. * @param mixed $validate Either a boolean, or an array.
  1385. * If a boolean, indicates whether or not to validate before saving.
  1386. * If an array, allows control of validate, callbacks, and fieldList
  1387. * @param array $fieldList List of fields to allow to be written
  1388. * @return mixed On success Model::$data if its not empty or true, false on failure
  1389. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html
  1390. */
  1391. public function save($data = null, $validate = true, $fieldList = array()) {
  1392. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1393. $_whitelist = $this->whitelist;
  1394. $fields = array();
  1395. if (!is_array($validate)) {
  1396. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1397. } else {
  1398. $options = array_merge($defaults, $validate);
  1399. }
  1400. if (!empty($options['fieldList'])) {
  1401. $this->whitelist = $options['fieldList'];
  1402. } elseif ($options['fieldList'] === null) {
  1403. $this->whitelist = array();
  1404. }
  1405. $this->set($data);
  1406. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1407. return false;
  1408. }
  1409. foreach (array('created', 'updated', 'modified') as $field) {
  1410. $keyPresentAndEmpty = (
  1411. isset($this->data[$this->alias]) &&
  1412. array_key_exists($field, $this->data[$this->alias]) &&
  1413. $this->data[$this->alias][$field] === null
  1414. );
  1415. if ($keyPresentAndEmpty) {
  1416. unset($this->data[$this->alias][$field]);
  1417. }
  1418. }
  1419. $exists = $this->exists();
  1420. $dateFields = array('modified', 'updated');
  1421. if (!$exists) {
  1422. $dateFields[] = 'created';
  1423. }
  1424. if (isset($this->data[$this->alias])) {
  1425. $fields = array_keys($this->data[$this->alias]);
  1426. }
  1427. if ($options['validate'] && !$this->validates($options)) {
  1428. $this->whitelist = $_whitelist;
  1429. return false;
  1430. }
  1431. $db = $this->getDataSource();
  1432. foreach ($dateFields as $updateCol) {
  1433. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1434. $default = array('formatter' => 'date');
  1435. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1436. if (!array_key_exists('format', $colType)) {
  1437. $time = strtotime('now');
  1438. } else {
  1439. $time = $colType['formatter']($colType['format']);
  1440. }
  1441. if (!empty($this->whitelist)) {
  1442. $this->whitelist[] = $updateCol;
  1443. }
  1444. $this->set($updateCol, $time);
  1445. }
  1446. }
  1447. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1448. $result = $this->Behaviors->trigger('beforeSave', array(&$this, $options), array(
  1449. 'break' => true, 'breakOn' => array(false, null)
  1450. ));
  1451. if (!$result || !$this->beforeSave($options)) {
  1452. $this->whitelist = $_whitelist;
  1453. return false;
  1454. }
  1455. }
  1456. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1457. unset($this->data[$this->alias][$this->primaryKey]);
  1458. }
  1459. $fields = $values = array();
  1460. foreach ($this->data as $n => $v) {
  1461. if (isset($this->hasAndBelongsToMany[$n])) {
  1462. if (isset($v[$n])) {
  1463. $v = $v[$n];
  1464. }
  1465. $joined[$n] = $v;
  1466. } else {
  1467. if ($n === $this->alias) {
  1468. foreach (array('created', 'updated', 'modified') as $field) {
  1469. if (array_key_exists($field, $v) && empty($v[$field])) {
  1470. unset($v[$field]);
  1471. }
  1472. }
  1473. foreach ($v as $x => $y) {
  1474. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1475. list($fields[], $values[]) = array($x, $y);
  1476. }
  1477. }
  1478. }
  1479. }
  1480. }
  1481. $count = count($fields);
  1482. if (!$exists && $count > 0) {
  1483. $this->id = false;
  1484. }
  1485. $success = true;
  1486. $created = false;
  1487. if ($count > 0) {
  1488. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1489. if (!empty($this->id)) {
  1490. $success = (bool)$db->update($this, $fields, $values);
  1491. } else {
  1492. $fInfo = $this->schema($this->primaryKey);
  1493. $isUUID = ($fInfo['length'] == 36 &&
  1494. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1495. );
  1496. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1497. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1498. $j = array_search($this->primaryKey, $fields);
  1499. $values[$j] = String::uuid();
  1500. } else {
  1501. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1502. }
  1503. }
  1504. if (!$db->create($this, $fields, $values)) {
  1505. $success = $created = false;
  1506. } else {
  1507. $created = true;
  1508. }
  1509. }
  1510. if ($success && !empty($this->belongsTo)) {
  1511. $this->updateCounterCache($cache, $created);
  1512. }
  1513. }
  1514. if (!empty($joined) && $success === true) {
  1515. $this->_saveMulti($joined, $this->id, $db);
  1516. }
  1517. if ($success && $count > 0) {
  1518. if (!empty($this->data)) {
  1519. $success = $this->data;
  1520. if ($created) {
  1521. $this->data[$this->alias][$this->primaryKey] = $this->id;
  1522. }
  1523. }
  1524. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1525. $this->Behaviors->trigger('afterSave', array(&$this, $created, $options));
  1526. $this->afterSave($created);
  1527. }
  1528. if (!empty($this->data)) {
  1529. $success = Set::merge($success, $this->data);
  1530. }
  1531. $this->data = false;
  1532. $this->_clearCache();
  1533. $this->validationErrors = array();
  1534. }
  1535. $this->whitelist = $_whitelist;
  1536. return $success;
  1537. }
  1538. /**
  1539. * Saves model hasAndBelongsToMany data to the database.
  1540. *
  1541. * @param array $joined Data to save
  1542. * @param mixed $id ID of record in this model
  1543. * @param DataSource $db
  1544. * @return void
  1545. */
  1546. protected function _saveMulti($joined, $id, $db) {
  1547. foreach ($joined as $assoc => $data) {
  1548. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1549. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1550. $keyInfo = $this->{$join}->schema($this->{$join}->primaryKey);
  1551. $isUUID = !empty($this->{$join}->primaryKey) && (
  1552. $keyInfo['length'] == 36 && (
  1553. $keyInfo['type'] === 'string' ||
  1554. $keyInfo['type'] === 'binary'
  1555. )
  1556. );
  1557. $newData = $newValues = array();
  1558. $primaryAdded = false;
  1559. $fields = array(
  1560. $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1561. $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1562. );
  1563. $idField = $db->name($this->{$join}->primaryKey);
  1564. if ($isUUID && !in_array($idField, $fields)) {
  1565. $fields[] = $idField;
  1566. $primaryAdded = true;
  1567. }
  1568. foreach ((array)$data as $row) {
  1569. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1570. $values = array($id, $row);
  1571. if ($isUUID && $primaryAdded) {
  1572. $values[] = String::uuid();
  1573. }
  1574. $newValues[] = $values;
  1575. unset($values);
  1576. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1577. $newData[] = $row;
  1578. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1579. $newData[] = $row[$join];
  1580. }
  1581. }
  1582. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1583. $conditions = array(
  1584. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1585. );
  1586. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1587. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1588. }
  1589. $links = $this->{$join}->find('all', array(
  1590. 'conditions' => $conditions,
  1591. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1592. 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
  1593. ));
  1594. $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1595. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1596. if (!empty($oldLinks)) {
  1597. $conditions[$associationForeignKey] = $oldLinks;
  1598. $db->delete($this->{$join}, $conditions);
  1599. }
  1600. }
  1601. if (!empty($newData)) {
  1602. foreach ($newData as $data) {
  1603. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1604. $this->{$join}->create($data);
  1605. $this->{$join}->save();
  1606. }
  1607. }
  1608. if (!empty($newValues)) {
  1609. $db->insertMulti($this->{$join}, $fields, $newValues);
  1610. }
  1611. }
  1612. }
  1613. }
  1614. /**
  1615. * Updates the counter cache of belongsTo associations after a save or delete operation
  1616. *
  1617. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1618. * @param boolean $created True if a new record was created, otherwise only associations with
  1619. * 'counterScope' defined get updated
  1620. * @return void
  1621. */
  1622. public function updateCounterCache($keys = array(), $created = false) {
  1623. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1624. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1625. foreach ($this->belongsTo as $parent => $assoc) {
  1626. if (!empty($assoc['counterCache'])) {
  1627. if (!is_array($assoc['counterCache'])) {
  1628. if (isset($assoc['counterScope'])) {
  1629. $assoc['counterCache'] = array($assoc['counterCache'] => $assoc['counterScope']);
  1630. } else {
  1631. $assoc['counterCache'] = array($assoc['counterCache'] => array());
  1632. }
  1633. }
  1634. $foreignKey = $assoc['foreignKey'];
  1635. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1636. foreach ($assoc['counterCache'] as $field => $conditions) {
  1637. if (!is_string($field)) {
  1638. $field = Inflector::underscore($this->alias) . '_count';
  1639. }
  1640. if (!$this->{$parent}->hasField($field)) {
  1641. continue;
  1642. }
  1643. if ($conditions === true) {
  1644. $conditions = array();
  1645. } else {
  1646. $conditions = (array)$conditions;
  1647. }
  1648. if (!array_key_exists($foreignKey, $keys)) {
  1649. $keys[$foreignKey] = $this->field($foreignKey);
  1650. }
  1651. $recursive = (empty($conditions) ? -1 : 0);
  1652. if (isset($keys['old'][$foreignKey])) {
  1653. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1654. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1655. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1656. $this->{$parent}->updateAll(
  1657. array($field => $count),
  1658. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1659. );
  1660. }
  1661. }
  1662. $conditions[$fkQuoted] = $keys[$foreignKey];
  1663. if ($recursive === 0) {
  1664. $conditions = array_merge($conditions, (array)$conditions);
  1665. }
  1666. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1667. $this->{$parent}->updateAll(
  1668. array($field => $count),
  1669. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1670. );
  1671. }
  1672. }
  1673. }
  1674. }
  1675. /**
  1676. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1677. *
  1678. * @param array $data The fields of the record that will be updated
  1679. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1680. * values, or empty if no foreign keys are updated.
  1681. */
  1682. protected function _prepareUpdateFields($data) {
  1683. $foreignKeys = array();
  1684. foreach ($this->belongsTo as $assoc => $info) {
  1685. if ($info['counterCache']) {
  1686. $foreignKeys[$assoc] = $info['foreignKey'];
  1687. }
  1688. }
  1689. $included = array_intersect($foreignKeys, array_keys($data));
  1690. if (empty($included) || empty($this->id)) {
  1691. return array();
  1692. }
  1693. $old = $this->find('first', array(
  1694. 'conditions' => array($this->primaryKey => $this->id),
  1695. 'fields' => array_values($included),
  1696. 'recursive' => -1
  1697. ));
  1698. return array_merge($data, array('old' => $old[$this->alias]));
  1699. }
  1700. /**
  1701. * Backwards compatible passthrough method for:
  1702. * saveMany(), validateMany(), saveAssociated() and validateAssociated()
  1703. *
  1704. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1705. * all its associated records.
  1706. *
  1707. * #### Options
  1708. *
  1709. * - validate: Set to false to disable validation, true to validate each record before saving,
  1710. * 'first' to validate *all* records before any are saved (default),
  1711. * or 'only' to only validate the records, but not save them.
  1712. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1713. * Should be set to false if database/table does not support transactions.
  1714. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1715. *
  1716. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1717. * records of the same type), or an array indexed by association name.
  1718. * @param array $options Options to use when saving record data, See $options above.
  1719. * @return mixed If atomic: True on success, or false on failure.
  1720. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1721. * depending on whether each record saved successfully.
  1722. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
  1723. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array
  1724. */
  1725. public function saveAll($data = null, $options = array()) {
  1726. $options = array_merge(array('validate' => 'first'), $options);
  1727. if (Set::numeric(array_keys($data))) {
  1728. if ($options['validate'] === 'only') {
  1729. return $this->validateMany($data, $options);
  1730. }
  1731. return $this->saveMany($data, $options);
  1732. }
  1733. if ($options['validate'] === 'only') {
  1734. $validatesAssoc = $this->validateAssociated($data, $options);
  1735. if (isset($this->validationErrors[$this->alias]) && $this->validationErrors[$this->alias] === false) {
  1736. return false;
  1737. }
  1738. return $validatesAssoc;
  1739. }
  1740. return $this->saveAssociated($data, $options);
  1741. }
  1742. /**
  1743. * Saves multiple individual records for a single model
  1744. *
  1745. * #### Options
  1746. *
  1747. * - validate: Set to false to disable validation, true to validate each record before saving,
  1748. * 'first' to validate *all* records before any are saved (default),
  1749. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1750. * Should be set to false if database/table does not support transactions.
  1751. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1752. *
  1753. * @param array $data Record data to save. This should be a numerically-indexed array
  1754. * @param array $options Options to use when saving record data, See $options above.
  1755. * @return mixed If atomic: True on success, or false on failure.
  1756. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1757. * depending on whether each record saved successfully.
  1758. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array
  1759. */
  1760. public function saveMany($data = null, $options = array()) {
  1761. if (empty($data)) {
  1762. $data = $this->data;
  1763. }
  1764. $options = array_merge(array('validate' => 'first', 'atomic' => true), $options);
  1765. $this->validationErrors = $validationErrors = array();
  1766. if (empty($data) && $options['validate'] !== false) {
  1767. $result = $this->save($data, $options);
  1768. return !empty($result);
  1769. }
  1770. if ($options['validate'] === 'first') {
  1771. $validates = $this->validateMany($data, $options);
  1772. if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
  1773. return $validates;
  1774. }
  1775. }
  1776. if ($options['atomic']) {
  1777. $db = $this->getDataSource();
  1778. $transactionBegun = $db->begin($this);
  1779. }
  1780. $return = array();
  1781. foreach ($data as $key => $record) {
  1782. $validates = ($this->create(null) !== null && $this->save($record, $options));
  1783. if (!$validates) {
  1784. $validationErrors[$key] = $this->validationErrors;
  1785. }
  1786. if (!$options['atomic']) {
  1787. $return[] = $validates;
  1788. } elseif (!$validates) {
  1789. break;
  1790. }
  1791. }
  1792. $this->validationErrors = $validationErrors;
  1793. if (!$options['atomic']) {
  1794. return $return;
  1795. }
  1796. if ($validates) {
  1797. if ($transactionBegun) {
  1798. return $db->commit($this) !== false;
  1799. } else {
  1800. return true;
  1801. }
  1802. }
  1803. $db->rollback($this);
  1804. return false;
  1805. }
  1806. /**
  1807. * Validates multiple individual records for a single model
  1808. *
  1809. * #### Options
  1810. *
  1811. * - atomic: If true (default), returns boolean. If false returns array.
  1812. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1813. *
  1814. * @param array $data Record data to validate. This should be a numerically-indexed array
  1815. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  1816. * @return boolean True on success, or false on failure.
  1817. * @return mixed If atomic: True on success, or false on failure.
  1818. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1819. * depending on whether each record validated successfully.
  1820. */
  1821. public function validateMany($data, $options = array()) {
  1822. $options = array_merge(array('atomic' => true), $options);
  1823. $this->validationErrors = $validationErrors = $return = array();
  1824. foreach ($data as $key => $record) {
  1825. $validates = $this->create($record) && $this->validates($options);
  1826. if (!$validates) {
  1827. $validationErrors[$key] = $this->validationErrors;
  1828. }
  1829. $return[] = $validates;
  1830. }
  1831. $this->validationErrors = $validationErrors;
  1832. if (!$options['atomic']) {
  1833. return $return;
  1834. }
  1835. if (empty($this->validationErrors)) {
  1836. return true;
  1837. }
  1838. return false;
  1839. }
  1840. /**
  1841. * Saves a single record, as well as all its directly associated records.
  1842. *
  1843. * #### Options
  1844. *
  1845. * - validate: Set to false to disable validation, true to validate each record before saving,
  1846. * 'first' to validate *all* records before any are saved (default),
  1847. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1848. * Should be set to false if database/table does not support transactions.
  1849. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1850. *
  1851. * @param array $data Record data to save. This should be an array indexed by association name.
  1852. * @param array $options Options to use when saving record data, See $options above.
  1853. * @return mixed If atomic: True on success, or false on failure.
  1854. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1855. * depending on whether each record saved successfully.
  1856. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
  1857. */
  1858. public function saveAssociated($data = null, $options = array()) {
  1859. if (empty($data)) {
  1860. $data = $this->data;
  1861. }
  1862. $options = array_merge(array('validate' => true, 'atomic' => true), $options);
  1863. $this->validationErrors = $validationErrors = array();
  1864. if (empty($data) && $options['validate'] !== false) {
  1865. $result = $this->save($data, $options);
  1866. return !empty($result);
  1867. }
  1868. if ($options['validate'] === 'first') {
  1869. $validates = $this->validateAssociated($data, $options);
  1870. if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
  1871. return $validates;
  1872. }
  1873. }
  1874. if ($options['atomic']) {
  1875. $db = $this->getDataSource();
  1876. $transactionBegun = $db->begin($this);
  1877. }
  1878. $associations = $this->getAssociated();
  1879. $return = array();
  1880. $validates = true;
  1881. foreach ($data as $association => $values) {
  1882. if (isset($associations[$association]) && $associations[$association] === 'belongsTo') {
  1883. if ($this->{$association}->create(null) !== null && $this->{$association}->save($values, $options)) {
  1884. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  1885. } else {
  1886. $validationErrors[$association] = $this->{$association}->validationErrors;
  1887. $validates = false;
  1888. }
  1889. $return[$association][] = $validates;
  1890. }
  1891. }
  1892. if ($validates && !($this->create(null) !== null && $this->save($data, $options))) {
  1893. $validationErrors[$this->alias] = $this->validationErrors;
  1894. $validates = false;
  1895. }
  1896. $return[$this->alias] = $validates;
  1897. foreach ($data as $association => $values) {
  1898. if (!$validates) {
  1899. break;
  1900. }
  1901. if (isset($associations[$association])) {
  1902. $type = $associations[$association];
  1903. switch ($type) {
  1904. case 'hasOne':
  1905. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  1906. if (!($this->{$association}->create(null) !== null && $this->{$association}->save($values, $options))) {
  1907. $validationErrors[$association] = $this->{$association}->validationErrors;
  1908. $validates = false;
  1909. }
  1910. $return[$association][] = $validates;
  1911. break;
  1912. case 'hasMany':
  1913. foreach ($values as $i => $value) {
  1914. $values[$i][$this->{$type}[$association]['foreignKey']] = $this->id;
  1915. }
  1916. $_return = $this->{$association}->saveMany($values, array_merge($options, array('atomic' => false)));
  1917. if (in_array(false, $_return, true)) {
  1918. $validationErrors[$association] = $this->{$association}->validationErrors;
  1919. $validates = false;
  1920. }
  1921. $return[$association] = $_return;
  1922. break;
  1923. }
  1924. }
  1925. }
  1926. $this->validationErrors = $validationErrors;
  1927. if (isset($validationErrors[$this->alias])) {
  1928. $this->validationErrors = $validationErrors[$this->alias];
  1929. }
  1930. if (!$options['atomic']) {
  1931. return $return;
  1932. }
  1933. if ($validates) {
  1934. if ($transactionBegun) {
  1935. return $db->commit($this) !== false;
  1936. } else {
  1937. return true;
  1938. }
  1939. }
  1940. $db->rollback($this);
  1941. return false;
  1942. }
  1943. /**
  1944. * Validates a single record, as well as all its directly associated records.
  1945. *
  1946. * #### Options
  1947. *
  1948. * - atomic: If true (default), returns boolean. If false returns array.
  1949. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1950. *
  1951. * @param array $data Record data to validate. This should be an array indexed by association name.
  1952. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  1953. * @return array|boolean If atomic: True on success, or false on failure.
  1954. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1955. * depending on whether each record validated successfully.
  1956. */
  1957. public function validateAssociated($data, $options = array()) {
  1958. $options = array_merge(array('atomic' => true), $options);
  1959. $this->validationErrors = $validationErrors = $return = array();
  1960. if (!($this->create($data) && $this->validates($options))) {
  1961. $validationErrors[$this->alias] = $this->validationErrors;
  1962. $return[$this->alias] = false;
  1963. } else {
  1964. $return[$this->alias] = true;
  1965. }
  1966. $associations = $this->getAssociated();
  1967. $validates = true;
  1968. foreach ($data as $association => $values) {
  1969. if (isset($associations[$association])) {
  1970. if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
  1971. $validates = $this->{$association}->create($values) && $this->{$association}->validates($options);
  1972. $return[$association][] = $validates;
  1973. } elseif ($associations[$association] === 'hasMany') {
  1974. $validates = $this->{$association}->validateMany($values, $options);
  1975. $return[$association] = $validates;
  1976. }
  1977. if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
  1978. $validationErrors[$association] = $this->{$association}->validationErrors;
  1979. }
  1980. }
  1981. }
  1982. $this->validationErrors = $validationErrors;
  1983. if (isset($validationErrors[$this->alias])) {
  1984. $this->validationErrors = $validationErrors[$this->alias];
  1985. }
  1986. if (!$options['atomic']) {
  1987. return $return;
  1988. }
  1989. if ($return[$this->alias] === false || !empty($this->validationErrors)) {
  1990. return false;
  1991. }
  1992. return true;
  1993. }
  1994. /**
  1995. * Updates multiple model records based on a set of conditions.
  1996. *
  1997. * @param array $fields Set of fields and values, indexed by fields.
  1998. * Fields are treated as SQL snippets, to insert literal values manually escape your data.
  1999. * @param mixed $conditions Conditions to match, true for all records
  2000. * @return boolean True on success, false on failure
  2001. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions
  2002. */
  2003. public function updateAll($fields, $conditions = true) {
  2004. return $this->getDataSource()->update($this, $fields, null, $conditions);
  2005. }
  2006. /**
  2007. * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
  2008. *
  2009. * @param mixed $id ID of record to delete
  2010. * @param boolean $cascade Set to true to delete records that depend on this record
  2011. * @return boolean True on success
  2012. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html
  2013. */
  2014. public function delete($id = null, $cascade = true) {
  2015. if (!empty($id)) {
  2016. $this->id = $id;
  2017. }
  2018. $id = $this->id;
  2019. if ($this->beforeDelete($cascade)) {
  2020. $filters = $this->Behaviors->trigger(
  2021. 'beforeDelete',
  2022. array(&$this, $cascade),
  2023. array('break' => true, 'breakOn' => array(false, null))
  2024. );
  2025. if (!$filters || !$this->exists()) {
  2026. return false;
  2027. }
  2028. $db = $this->getDataSource();
  2029. $this->_deleteDependent($id, $cascade);
  2030. $this->_deleteLinks($id);
  2031. $this->id = $id;
  2032. $updateCounterCache = false;
  2033. if (!empty($this->belongsTo)) {
  2034. foreach ($this->belongsTo as $parent => $assoc) {
  2035. if (!empty($assoc['counterCache'])) {
  2036. $updateCounterCache = true;
  2037. break;
  2038. }
  2039. }
  2040. $keys = $this->find('first', array(
  2041. 'fields' => $this->_collectForeignKeys(),
  2042. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  2043. 'recursive' => -1,
  2044. 'callbacks' => false
  2045. ));
  2046. }
  2047. if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
  2048. if ($updateCounterCache) {
  2049. $this->updateCounterCache($keys[$this->alias]);
  2050. }
  2051. $this->Behaviors->trigger('afterDelete', array(&$this));
  2052. $this->afterDelete();
  2053. $this->_clearCache();
  2054. $this->id = false;
  2055. return true;
  2056. }
  2057. }
  2058. return false;
  2059. }
  2060. /**
  2061. * Cascades model deletes through associated hasMany and hasOne child records.
  2062. *
  2063. * @param string $id ID of record that was deleted
  2064. * @param boolean $cascade Set to true to delete records that depend on this record
  2065. * @return void
  2066. */
  2067. protected function _deleteDependent($id, $cascade) {
  2068. if (!empty($this->__backAssociation)) {
  2069. $savedAssociatons = $this->__backAssociation;
  2070. $this->__backAssociation = array();
  2071. }
  2072. if ($cascade === true) {
  2073. foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
  2074. if ($data['dependent'] === true) {
  2075. $model = $this->{$assoc};
  2076. if ($data['foreignKey'] === false && $data['conditions'] && in_array($this->name, $model->getAssociated('belongsTo'))) {
  2077. $model->recursive = 0;
  2078. $conditions = array($this->escapeField(null, $this->name) => $id);
  2079. } else {
  2080. $model->recursive = -1;
  2081. $conditions = array($model->escapeField($data['foreignKey']) => $id);
  2082. if ($data['conditions']) {
  2083. $conditions = array_merge((array)$data['conditions'], $conditions);
  2084. }
  2085. }
  2086. if (isset($data['exclusive']) && $data['exclusive']) {
  2087. $model->deleteAll($conditions);
  2088. } else {
  2089. $records = $model->find('all', array(
  2090. 'conditions' => $conditions, 'fields' => $model->primaryKey
  2091. ));
  2092. if (!empty($records)) {
  2093. foreach ($records as $record) {
  2094. $model->delete($record[$model->alias][$model->primaryKey]);
  2095. }
  2096. }
  2097. }
  2098. }
  2099. }
  2100. }
  2101. if (isset($savedAssociatons)) {
  2102. $this->__backAssociation = $savedAssociatons;
  2103. }
  2104. }
  2105. /**
  2106. * Cascades model deletes through HABTM join keys.
  2107. *
  2108. * @param string $id ID of record that was deleted
  2109. * @return void
  2110. */
  2111. protected function _deleteLinks($id) {
  2112. foreach ($this->hasAndBelongsToMany as $assoc => $data) {
  2113. list($plugin, $joinModel) = pluginSplit($data['with']);
  2114. $records = $this->{$joinModel}->find('all', array(
  2115. 'conditions' => array($this->{$joinModel}->escapeField($data['foreignKey']) => $id),
  2116. 'fields' => $this->{$joinModel}->primaryKey,
  2117. 'recursive' => -1,
  2118. 'callbacks' => false
  2119. ));
  2120. if (!empty($records)) {
  2121. foreach ($records as $record) {
  2122. $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
  2123. }
  2124. }
  2125. }
  2126. }
  2127. /**
  2128. * Deletes multiple model records based on a set of conditions.
  2129. *
  2130. * @param mixed $conditions Conditions to match
  2131. * @param boolean $cascade Set to true to delete records that depend on this record
  2132. * @param boolean $callbacks Run callbacks
  2133. * @return boolean True on success, false on failure
  2134. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
  2135. */
  2136. public function deleteAll($conditions, $cascade = true, $callbacks = false) {
  2137. if (empty($conditions)) {
  2138. return false;
  2139. }
  2140. $db = $this->getDataSource();
  2141. if (!$cascade && !$callbacks) {
  2142. return $db->delete($this, $conditions);
  2143. } else {
  2144. $ids = $this->find('all', array_merge(array(
  2145. 'fields' => "{$this->alias}.{$this->primaryKey}",
  2146. 'recursive' => 0), compact('conditions'))
  2147. );
  2148. if ($ids === false) {
  2149. return false;
  2150. }
  2151. $ids = Set::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
  2152. if (empty($ids)) {
  2153. return true;
  2154. }
  2155. if ($callbacks) {
  2156. $_id = $this->id;
  2157. $result = true;
  2158. foreach ($ids as $id) {
  2159. $result = ($result && $this->delete($id, $cascade));
  2160. }
  2161. $this->id = $_id;
  2162. return $result;
  2163. } else {
  2164. foreach ($ids as $id) {
  2165. $this->_deleteLinks($id);
  2166. if ($cascade) {
  2167. $this->_deleteDependent($id, $cascade);
  2168. }
  2169. }
  2170. return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
  2171. }
  2172. }
  2173. }
  2174. /**
  2175. * Collects foreign keys from associations.
  2176. *
  2177. * @param string $type
  2178. * @return array
  2179. */
  2180. protected function _collectForeignKeys($type = 'belongsTo') {
  2181. $result = array();
  2182. foreach ($this->{$type} as $assoc => $data) {
  2183. if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
  2184. $result[$assoc] = $data['foreignKey'];
  2185. }
  2186. }
  2187. return $result;
  2188. }
  2189. /**
  2190. * Returns true if a record with the currently set ID exists.
  2191. *
  2192. * Internally calls Model::getID() to obtain the current record ID to verify,
  2193. * and then performs a Model::find('count') on the currently configured datasource
  2194. * to ascertain the existence of the record in persistent storage.
  2195. *
  2196. * @return boolean True if such a record exists
  2197. */
  2198. public function exists() {
  2199. if ($this->getID() === false) {
  2200. return false;
  2201. }
  2202. $conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
  2203. $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
  2204. return ($this->find('count', $query) > 0);
  2205. }
  2206. /**
  2207. * Returns true if a record that meets given conditions exists.
  2208. *
  2209. * @param array $conditions SQL conditions array
  2210. * @return boolean True if such a record exists
  2211. */
  2212. public function hasAny($conditions = null) {
  2213. return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
  2214. }
  2215. /**
  2216. * Queries the datasource and returns a result set array.
  2217. *
  2218. * Also used to perform notation finds, where the first argument is type of find operation to perform
  2219. * (all / first / count / neighbors / list / threaded ),
  2220. * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
  2221. * 'recursive', 'page', 'fields', 'offset', 'order')
  2222. *
  2223. * Eg:
  2224. * {{{
  2225. * find('all', array(
  2226. * 'conditions' => array('name' => 'Thomas Anderson'),
  2227. * 'fields' => array('name', 'email'),
  2228. * 'order' => 'field3 DESC',
  2229. * 'recursive' => 2,
  2230. * 'group' => 'type'
  2231. * ));
  2232. * }}}
  2233. *
  2234. * In addition to the standard query keys above, you can provide Datasource, and behavior specific
  2235. * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
  2236. * joins that should be part of the query.
  2237. *
  2238. * {{{
  2239. * find('all', array(
  2240. * 'conditions' => array('name' => 'Thomas Anderson'),
  2241. * 'joins' => array(
  2242. * array(
  2243. * 'alias' => 'Thought',
  2244. * 'table' => 'thoughts',
  2245. * 'type' => 'LEFT',
  2246. * 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
  2247. * )
  2248. * )
  2249. * ));
  2250. * }}}
  2251. *
  2252. * Behaviors and find types can also define custom finder keys which are passed into find().
  2253. *
  2254. * Specifying 'fields' for notation 'list':
  2255. *
  2256. * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  2257. * - If a single field is specified, 'id' is used for key and specified field is used for value.
  2258. * - If three fields are specified, they are used (in order) for key, value and group.
  2259. * - Otherwise, first and second fields are used for key and value.
  2260. *
  2261. * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you
  2262. * have issues with database views.
  2263. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  2264. * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  2265. * @return array Array of records
  2266. * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall
  2267. */
  2268. public function find($type = 'first', $query = array()) {
  2269. $this->findQueryType = $type;
  2270. $this->id = $this->getID();
  2271. $query = $this->buildQuery($type, $query);
  2272. if (is_null($query)) {
  2273. return null;
  2274. }
  2275. $results = $this->getDataSource()->read($this, $query);
  2276. $this->resetAssociations();
  2277. if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
  2278. $results = $this->_filterResults($results);
  2279. }
  2280. $this->findQueryType = null;
  2281. if ($type === 'all') {
  2282. return $results;
  2283. } else {
  2284. if ($this->findMethods[$type] === true) {
  2285. return $this->{'_find' . ucfirst($type)}('after', $query, $results);
  2286. }
  2287. }
  2288. }
  2289. /**
  2290. * Builds the query array that is used by the data source to generate the query to fetch the data.
  2291. *
  2292. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  2293. * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  2294. * @return array Query array or null if it could not be build for some reasons
  2295. * @see Model::find()
  2296. */
  2297. public function buildQuery($type = 'first', $query = array()) {
  2298. $query = array_merge(
  2299. array(
  2300. 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
  2301. 'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true,
  2302. ),
  2303. (array)$query
  2304. );
  2305. if ($type !== 'all') {
  2306. if ($this->findMethods[$type] === true) {
  2307. $query = $this->{'_find' . ucfirst($type)}('before', $query);
  2308. }
  2309. }
  2310. if (!is_numeric($query['page']) || intval($query['page']) < 1) {
  2311. $query['page'] = 1;
  2312. }
  2313. if ($query['page'] > 1 && !empty($query['limit'])) {
  2314. $query['offset'] = ($query['page'] - 1) * $query['limit'];
  2315. }
  2316. if ($query['order'] === null && $this->order !== null) {
  2317. $query['order'] = $this->order;
  2318. }
  2319. $query['order'] = array($query['order']);
  2320. if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
  2321. $return = $this->Behaviors->trigger(
  2322. 'beforeFind',
  2323. array(&$this, $query),
  2324. array('break' => true, 'breakOn' => array(false, null), 'modParams' => 1)
  2325. );
  2326. $query = (is_array($return)) ? $return : $query;
  2327. if ($return === false) {
  2328. return null;
  2329. }
  2330. $return = $this->beforeFind($query);
  2331. $query = (is_array($return)) ? $return : $query;
  2332. if ($return === false) {
  2333. return null;
  2334. }
  2335. }
  2336. return $query;
  2337. }
  2338. /**
  2339. * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
  2340. *
  2341. * @param string $state Either "before" or "after"
  2342. * @param array $query
  2343. * @param array $results
  2344. * @return array
  2345. * @see Model::find()
  2346. */
  2347. protected function _findFirst($state, $query, $results = array()) {
  2348. if ($state === 'before') {
  2349. $query['limit'] = 1;
  2350. return $query;
  2351. } elseif ($state === 'after') {
  2352. if (empty($results[0])) {
  2353. return false;
  2354. }
  2355. return $results[0];
  2356. }
  2357. }
  2358. /**
  2359. * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
  2360. *
  2361. * @param string $state Either "before" or "after"
  2362. * @param array $query
  2363. * @param array $results
  2364. * @return integer The number of records found, or false
  2365. * @see Model::find()
  2366. */
  2367. protected function _findCount($state, $query, $results = array()) {
  2368. if ($state === 'before') {
  2369. $db = $this->getDataSource();
  2370. if (empty($query['fields'])) {
  2371. $query['fields'] = $db->calculate($this, 'count');
  2372. } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
  2373. $query['fields'] = $db->calculate($this, 'count', array(
  2374. $db->expression($query['fields']), 'count'
  2375. ));
  2376. }
  2377. $query['order'] = false;
  2378. return $query;
  2379. } elseif ($state === 'after') {
  2380. foreach (array(0, $this->alias) as $key) {
  2381. if (isset($results[0][$key]['count'])) {
  2382. if (($count = count($results)) > 1) {
  2383. return $count;
  2384. } else {
  2385. return intval($results[0][$key]['count']);
  2386. }
  2387. }
  2388. }
  2389. return false;
  2390. }
  2391. }
  2392. /**
  2393. * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
  2394. *
  2395. * @param string $state Either "before" or "after"
  2396. * @param array $query
  2397. * @param array $results
  2398. * @return array Key/value pairs of primary keys/display field values of all records found
  2399. * @see Model::find()
  2400. */
  2401. protected function _findList($state, $query, $results = array()) {
  2402. if ($state === 'before') {
  2403. if (empty($query['fields'])) {
  2404. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
  2405. $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
  2406. } else {
  2407. if (!is_array($query['fields'])) {
  2408. $query['fields'] = String::tokenize($query['fields']);
  2409. }
  2410. if (count($query['fields']) === 1) {
  2411. if (strpos($query['fields'][0], '.') === false) {
  2412. $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
  2413. }
  2414. $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
  2415. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
  2416. } elseif (count($query['fields']) === 3) {
  2417. for ($i = 0; $i < 3; $i++) {
  2418. if (strpos($query['fields'][$i], '.') === false) {
  2419. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2420. }
  2421. }
  2422. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
  2423. } else {
  2424. for ($i = 0; $i < 2; $i++) {
  2425. if (strpos($query['fields'][$i], '.') === false) {
  2426. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2427. }
  2428. }
  2429. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
  2430. }
  2431. }
  2432. if (!isset($query['recursive']) || $query['recursive'] === null) {
  2433. $query['recursive'] = -1;
  2434. }
  2435. list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
  2436. return $query;
  2437. } elseif ($state === 'after') {
  2438. if (empty($results)) {
  2439. return array();
  2440. }
  2441. $lst = $query['list'];
  2442. return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
  2443. }
  2444. }
  2445. /**
  2446. * Detects the previous field's value, then uses logic to find the 'wrapping'
  2447. * rows and return them.
  2448. *
  2449. * @param string $state Either "before" or "after"
  2450. * @param mixed $query
  2451. * @param array $results
  2452. * @return array
  2453. */
  2454. protected function _findNeighbors($state, $query, $results = array()) {
  2455. if ($state === 'before') {
  2456. extract($query);
  2457. $conditions = (array)$conditions;
  2458. if (isset($field) && isset($value)) {
  2459. if (strpos($field, '.') === false) {
  2460. $field = $this->alias . '.' . $field;
  2461. }
  2462. } else {
  2463. $field = $this->alias . '.' . $this->primaryKey;
  2464. $value = $this->id;
  2465. }
  2466. $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
  2467. $query['order'] = $field . ' DESC';
  2468. $query['limit'] = 1;
  2469. $query['field'] = $field;
  2470. $query['value'] = $value;
  2471. return $query;
  2472. } elseif ($state === 'after') {
  2473. extract($query);
  2474. unset($query['conditions'][$field . ' <']);
  2475. $return = array();
  2476. if (isset($results[0])) {
  2477. $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
  2478. $query['conditions'][$field . ' >='] = $prevVal[0];
  2479. $query['conditions'][$field . ' !='] = $value;
  2480. $query['limit'] = 2;
  2481. } else {
  2482. $return['prev'] = null;
  2483. $query['conditions'][$field . ' >'] = $value;
  2484. $query['limit'] = 1;
  2485. }
  2486. $query['order'] = $field . ' ASC';
  2487. $return2 = $this->find('all', $query);
  2488. if (!array_key_exists('prev', $return)) {
  2489. $return['prev'] = $return2[0];
  2490. }
  2491. if (count($return2) === 2) {
  2492. $return['next'] = $return2[1];
  2493. } elseif (count($return2) === 1 && !$return['prev']) {
  2494. $return['next'] = $return2[0];
  2495. } else {
  2496. $return['next'] = null;
  2497. }
  2498. return $return;
  2499. }
  2500. }
  2501. /**
  2502. * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
  2503. * top level results with different parent_ids to the first result will be dropped
  2504. *
  2505. * @param mixed $state
  2506. * @param mixed $query
  2507. * @param array $results
  2508. * @return array Threaded results
  2509. */
  2510. protected function _findThreaded($state, $query, $results = array()) {
  2511. if ($state === 'before') {
  2512. return $query;
  2513. } elseif ($state === 'after') {
  2514. $return = $idMap = array();
  2515. $ids = Set::extract($results, '{n}.' . $this->alias . '.' . $this->primaryKey);
  2516. foreach ($results as $result) {
  2517. $result['children'] = array();
  2518. $id = $result[$this->alias][$this->primaryKey];
  2519. $parentId = $result[$this->alias]['parent_id'];
  2520. if (isset($idMap[$id]['children'])) {
  2521. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  2522. } else {
  2523. $idMap[$id] = array_merge($result, array('children' => array()));
  2524. }
  2525. if (!$parentId || !in_array($parentId, $ids)) {
  2526. $return[] =& $idMap[$id];
  2527. } else {
  2528. $idMap[$parentId]['children'][] =& $idMap[$id];
  2529. }
  2530. }
  2531. if (count($return) > 1) {
  2532. $ids = array_unique(Set::extract('/' . $this->alias . '/parent_id', $return));
  2533. if (count($ids) > 1) {
  2534. $root = $return[0][$this->alias]['parent_id'];
  2535. foreach ($return as $key => $value) {
  2536. if ($value[$this->alias]['parent_id'] != $root) {
  2537. unset($return[$key]);
  2538. }
  2539. }
  2540. }
  2541. }
  2542. return $return;
  2543. }
  2544. }
  2545. /**
  2546. * Passes query results through model and behavior afterFilter() methods.
  2547. *
  2548. * @param array $results Results to filter
  2549. * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
  2550. * @return array Set of filtered results
  2551. */
  2552. protected function _filterResults($results, $primary = true) {
  2553. $return = $this->Behaviors->trigger(
  2554. 'afterFind',
  2555. array(&$this, $results, $primary),
  2556. array('modParams' => 1)
  2557. );
  2558. if ($return !== true) {
  2559. $results = $return;
  2560. }
  2561. return $this->afterFind($results, $primary);
  2562. }
  2563. /**
  2564. * This resets the association arrays for the model back
  2565. * to those originally defined in the model. Normally called at the end
  2566. * of each call to Model::find()
  2567. *
  2568. * @return boolean Success
  2569. */
  2570. public function resetAssociations() {
  2571. if (!empty($this->__backAssociation)) {
  2572. foreach ($this->_associations as $type) {
  2573. if (isset($this->__backAssociation[$type])) {
  2574. $this->{$type} = $this->__backAssociation[$type];
  2575. }
  2576. }
  2577. $this->__backAssociation = array();
  2578. }
  2579. foreach ($this->_associations as $type) {
  2580. foreach ($this->{$type} as $key => $name) {
  2581. if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) {
  2582. $this->{$key}->resetAssociations();
  2583. }
  2584. }
  2585. }
  2586. $this->__backAssociation = array();
  2587. return true;
  2588. }
  2589. /**
  2590. * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
  2591. *
  2592. * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
  2593. * @param boolean $or If false, all fields specified must match in order for a false return value
  2594. * @return boolean False if any records matching any fields are found
  2595. */
  2596. public function isUnique($fields, $or = true) {
  2597. if (!is_array($fields)) {
  2598. $fields = func_get_args();
  2599. if (is_bool($fields[count($fields) - 1])) {
  2600. $or = $fields[count($fields) - 1];
  2601. unset($fields[count($fields) - 1]);
  2602. }
  2603. }
  2604. foreach ($fields as $field => $value) {
  2605. if (is_numeric($field)) {
  2606. unset($fields[$field]);
  2607. $field = $value;
  2608. if (isset($this->data[$this->alias][$field])) {
  2609. $value = $this->data[$this->alias][$field];
  2610. } else {
  2611. $value = null;
  2612. }
  2613. }
  2614. if (strpos($field, '.') === false) {
  2615. unset($fields[$field]);
  2616. $fields[$this->alias . '.' . $field] = $value;
  2617. }
  2618. }
  2619. if ($or) {
  2620. $fields = array('or' => $fields);
  2621. }
  2622. if (!empty($this->id)) {
  2623. $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
  2624. }
  2625. return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
  2626. }
  2627. /**
  2628. * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
  2629. *
  2630. * @param string $sql,... SQL statement
  2631. * @return array Resultset
  2632. * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
  2633. */
  2634. public function query($sql) {
  2635. $params = func_get_args();
  2636. $db = $this->getDataSource();
  2637. return call_user_func_array(array(&$db, 'query'), $params);
  2638. }
  2639. /**
  2640. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  2641. * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.
  2642. *
  2643. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  2644. *
  2645. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2646. * @return boolean True if there are no errors
  2647. */
  2648. public function validates($options = array()) {
  2649. $errors = $this->invalidFields($options);
  2650. if (empty($errors) && $errors !== false) {
  2651. $errors = $this->_validateWithModels($options);
  2652. }
  2653. if (is_array($errors)) {
  2654. return count($errors) === 0;
  2655. }
  2656. return $errors;
  2657. }
  2658. /**
  2659. * Returns an array of fields that have failed validation. On the current model.
  2660. *
  2661. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2662. * @return array Array of invalid fields
  2663. * @see Model::validates()
  2664. */
  2665. public function invalidFields($options = array()) {
  2666. if (
  2667. !$this->Behaviors->trigger(
  2668. 'beforeValidate',
  2669. array(&$this, $options),
  2670. array('break' => true, 'breakOn' => false)
  2671. ) ||
  2672. $this->beforeValidate($options) === false
  2673. ) {
  2674. return false;
  2675. }
  2676. if (!isset($this->validate) || empty($this->validate)) {
  2677. return $this->validationErrors;
  2678. }
  2679. $data = $this->data;
  2680. $methods = array_map('strtolower', get_class_methods($this));
  2681. $behaviorMethods = array_keys($this->Behaviors->methods());
  2682. if (isset($data[$this->alias])) {
  2683. $data = $data[$this->alias];
  2684. } elseif (!is_array($data)) {
  2685. $data = array();
  2686. }
  2687. $exists = $this->exists();
  2688. $_validate = $this->validate;
  2689. $whitelist = $this->whitelist;
  2690. if (!empty($options['fieldList'])) {
  2691. $whitelist = $options['fieldList'];
  2692. }
  2693. if (!empty($whitelist)) {
  2694. $validate = array();
  2695. foreach ((array)$whitelist as $f) {
  2696. if (!empty($this->validate[$f])) {
  2697. $validate[$f] = $this->validate[$f];
  2698. }
  2699. }
  2700. $this->validate = $validate;
  2701. }
  2702. $validationDomain = $this->validationDomain;
  2703. if (empty($validationDomain)) {
  2704. $validationDomain = 'default';
  2705. }
  2706. foreach ($this->validate as $fieldName => $ruleSet) {
  2707. if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
  2708. $ruleSet = array($ruleSet);
  2709. }
  2710. $default = array(
  2711. 'allowEmpty' => null,
  2712. 'required' => null,
  2713. 'rule' => 'blank',
  2714. 'last' => true,
  2715. 'on' => null
  2716. );
  2717. foreach ($ruleSet as $index => $validator) {
  2718. if (!is_array($validator)) {
  2719. $validator = array('rule' => $validator);
  2720. }
  2721. $validator = array_merge($default, $validator);
  2722. if (
  2723. empty($validator['on']) || ($validator['on'] == 'create' &&
  2724. !$exists) || ($validator['on'] == 'update' && $exists
  2725. )) {
  2726. $valid = true;
  2727. $requiredFail = (
  2728. (!isset($data[$fieldName]) && $validator['required'] === true) ||
  2729. (
  2730. isset($data[$fieldName]) && (empty($data[$fieldName]) &&
  2731. !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false
  2732. )
  2733. );
  2734. if (!$requiredFail && array_key_exists($fieldName, $data)) {
  2735. if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
  2736. break;
  2737. }
  2738. if (is_array($validator['rule'])) {
  2739. $rule = $validator['rule'][0];
  2740. unset($validator['rule'][0]);
  2741. $ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
  2742. } else {
  2743. $rule = $validator['rule'];
  2744. $ruleParams = array($data[$fieldName]);
  2745. }
  2746. if (in_array(strtolower($rule), $methods)) {
  2747. $ruleParams[] = $validator;
  2748. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2749. $valid = $this->dispatchMethod($rule, $ruleParams);
  2750. } elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
  2751. $ruleParams[] = $validator;
  2752. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2753. $valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
  2754. } elseif (method_exists('Validation', $rule)) {
  2755. $valid = call_user_func_array(array('Validation', $rule), $ruleParams);
  2756. } elseif (!is_array($validator['rule'])) {
  2757. $valid = preg_match($rule, $data[$fieldName]);
  2758. } elseif (Configure::read('debug') > 0) {
  2759. trigger_error(__d('cake_dev', 'Could not find validation handler %s for %s', $rule, $fieldName), E_USER_WARNING);
  2760. }
  2761. }
  2762. if ($requiredFail || !$valid || (is_string($valid) && strlen($valid) > 0)) {
  2763. if (is_string($valid)) {
  2764. $message = $valid;
  2765. } elseif (isset($validator['message'])) {
  2766. $args = null;
  2767. if (is_array($validator['message'])) {
  2768. $message = $validator['message'][0];
  2769. $args = array_slice($validator['message'], 1);
  2770. } else {
  2771. $message = $validator['message'];
  2772. }
  2773. if (is_array($validator['rule']) && $args === null) {
  2774. $args = array_slice($ruleSet[$index]['rule'], 1);
  2775. }
  2776. $message = __d($validationDomain, $message, $args);
  2777. } elseif (is_string($index)) {
  2778. if (is_array($validator['rule'])) {
  2779. $args = array_slice($ruleSet[$index]['rule'], 1);
  2780. $message = __d($validationDomain, $index, $args);
  2781. } else {
  2782. $message = __d($validationDomain, $index);
  2783. }
  2784. } elseif (!$requiredFail && is_numeric($index) && count($ruleSet) > 1) {
  2785. $message = $index + 1;
  2786. } else {
  2787. $message = __d('cake_dev', 'This field cannot be left blank');
  2788. }
  2789. $this->invalidate($fieldName, $message);
  2790. if ($validator['last']) {
  2791. break;
  2792. }
  2793. }
  2794. }
  2795. }
  2796. }
  2797. $this->validate = $_validate;
  2798. return $this->validationErrors;
  2799. }
  2800. /**
  2801. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  2802. * set. And data in the set() data set.
  2803. *
  2804. * @param array $options Array of options to use on Validation of with models
  2805. * @return boolean Failure of validation on with models.
  2806. * @see Model::validates()
  2807. */
  2808. protected function _validateWithModels($options) {
  2809. $valid = true;
  2810. foreach ($this->hasAndBelongsToMany as $assoc => $association) {
  2811. if (empty($association['with']) || !isset($this->data[$assoc])) {
  2812. continue;
  2813. }
  2814. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  2815. $data = $this->data[$assoc];
  2816. $newData = array();
  2817. foreach ((array)$data as $row) {
  2818. if (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2819. $newData[] = $row;
  2820. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2821. $newData[] = $row[$join];
  2822. }
  2823. }
  2824. if (empty($newData)) {
  2825. continue;
  2826. }
  2827. foreach ($newData as $data) {
  2828. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $this->id;
  2829. $this->{$join}->create($data);
  2830. $valid = ($valid && $this->{$join}->validates($options));
  2831. }
  2832. }
  2833. return $valid;
  2834. }
  2835. /**
  2836. * Marks a field as invalid, optionally setting the name of validation
  2837. * rule (in case of multiple validation for field) that was broken.
  2838. *
  2839. * @param string $field The name of the field to invalidate
  2840. * @param mixed $value Name of validation rule that was not failed, or validation message to
  2841. * be returned. If no validation key is provided, defaults to true.
  2842. * @return void
  2843. */
  2844. public function invalidate($field, $value = true) {
  2845. if (!is_array($this->validationErrors)) {
  2846. $this->validationErrors = array();
  2847. }
  2848. $this->validationErrors[$field] []= $value;
  2849. }
  2850. /**
  2851. * Returns true if given field name is a foreign key in this model.
  2852. *
  2853. * @param string $field Returns true if the input string ends in "_id"
  2854. * @return boolean True if the field is a foreign key listed in the belongsTo array.
  2855. */
  2856. public function isForeignKey($field) {
  2857. $foreignKeys = array();
  2858. if (!empty($this->belongsTo)) {
  2859. foreach ($this->belongsTo as $assoc => $data) {
  2860. $foreignKeys[] = $data['foreignKey'];
  2861. }
  2862. }
  2863. return in_array($field, $foreignKeys);
  2864. }
  2865. /**
  2866. * Escapes the field name and prepends the model name. Escaping is done according to the
  2867. * current database driver's rules.
  2868. *
  2869. * @param string $field Field to escape (e.g: id)
  2870. * @param string $alias Alias for the model (e.g: Post)
  2871. * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
  2872. */
  2873. public function escapeField($field = null, $alias = null) {
  2874. if (empty($alias)) {
  2875. $alias = $this->alias;
  2876. }
  2877. if (empty($field)) {
  2878. $field = $this->primaryKey;
  2879. }
  2880. $db = $this->getDataSource();
  2881. if (strpos($field, $db->name($alias) . '.') === 0) {
  2882. return $field;
  2883. }
  2884. return $db->name($alias . '.' . $field);
  2885. }
  2886. /**
  2887. * Returns the current record's ID
  2888. *
  2889. * @param integer $list Index on which the composed ID is located
  2890. * @return mixed The ID of the current record, false if no ID
  2891. */
  2892. public function getID($list = 0) {
  2893. if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
  2894. return false;
  2895. }
  2896. if (!is_array($this->id)) {
  2897. return $this->id;
  2898. }
  2899. if (empty($this->id)) {
  2900. return false;
  2901. }
  2902. if (isset($this->id[$list]) && !empty($this->id[$list])) {
  2903. return $this->id[$list];
  2904. } elseif (isset($this->id[$list])) {
  2905. return false;
  2906. }
  2907. foreach ($this->id as $id) {
  2908. return $id;
  2909. }
  2910. return false;
  2911. }
  2912. /**
  2913. * Returns the ID of the last record this model inserted.
  2914. *
  2915. * @return mixed Last inserted ID
  2916. */
  2917. public function getLastInsertID() {
  2918. return $this->getInsertID();
  2919. }
  2920. /**
  2921. * Returns the ID of the last record this model inserted.
  2922. *
  2923. * @return mixed Last inserted ID
  2924. */
  2925. public function getInsertID() {
  2926. return $this->_insertID;
  2927. }
  2928. /**
  2929. * Sets the ID of the last record this model inserted
  2930. *
  2931. * @param mixed $id Last inserted ID
  2932. * @return void
  2933. */
  2934. public function setInsertID($id) {
  2935. $this->_insertID = $id;
  2936. }
  2937. /**
  2938. * Returns the number of rows returned from the last query.
  2939. *
  2940. * @return integer Number of rows
  2941. */
  2942. public function getNumRows() {
  2943. return $this->getDataSource()->lastNumRows();
  2944. }
  2945. /**
  2946. * Returns the number of rows affected by the last query.
  2947. *
  2948. * @return integer Number of rows
  2949. */
  2950. public function getAffectedRows() {
  2951. return $this->getDataSource()->lastAffected();
  2952. }
  2953. /**
  2954. * Sets the DataSource to which this model is bound.
  2955. *
  2956. * @param string $dataSource The name of the DataSource, as defined in app/Config/database.php
  2957. * @return boolean True on success
  2958. * @throws MissingConnectionException
  2959. */
  2960. public function setDataSource($dataSource = null) {
  2961. $oldConfig = $this->useDbConfig;
  2962. if ($dataSource != null) {
  2963. $this->useDbConfig = $dataSource;
  2964. }
  2965. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2966. if (!empty($oldConfig) && isset($db->config['prefix'])) {
  2967. $oldDb = ConnectionManager::getDataSource($oldConfig);
  2968. if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
  2969. $this->tablePrefix = $db->config['prefix'];
  2970. }
  2971. } elseif (isset($db->config['prefix'])) {
  2972. $this->tablePrefix = $db->config['prefix'];
  2973. }
  2974. if (empty($db) || !is_object($db)) {
  2975. throw new MissingConnectionException(array('class' => $this->name));
  2976. }
  2977. }
  2978. /**
  2979. * Gets the DataSource to which this model is bound.
  2980. *
  2981. * @return DataSource A DataSource object
  2982. */
  2983. public function getDataSource() {
  2984. if (!$this->_sourceConfigured && $this->useTable !== false) {
  2985. $this->_sourceConfigured = true;
  2986. $this->setSource($this->useTable);
  2987. }
  2988. return ConnectionManager::getDataSource($this->useDbConfig);
  2989. }
  2990. /**
  2991. * Get associations
  2992. *
  2993. * @return array
  2994. */
  2995. public function associations() {
  2996. return $this->_associations;
  2997. }
  2998. /**
  2999. * Gets all the models with which this model is associated.
  3000. *
  3001. * @param string $type Only result associations of this type
  3002. * @return array Associations
  3003. */
  3004. public function getAssociated($type = null) {
  3005. if ($type == null) {
  3006. $associated = array();
  3007. foreach ($this->_associations as $assoc) {
  3008. if (!empty($this->{$assoc})) {
  3009. $models = array_keys($this->{$assoc});
  3010. foreach ($models as $m) {
  3011. $associated[$m] = $assoc;
  3012. }
  3013. }
  3014. }
  3015. return $associated;
  3016. } elseif (in_array($type, $this->_associations)) {
  3017. if (empty($this->{$type})) {
  3018. return array();
  3019. }
  3020. return array_keys($this->{$type});
  3021. } else {
  3022. $assoc = array_merge(
  3023. $this->hasOne,
  3024. $this->hasMany,
  3025. $this->belongsTo,
  3026. $this->hasAndBelongsToMany
  3027. );
  3028. if (array_key_exists($type, $assoc)) {
  3029. foreach ($this->_associations as $a) {
  3030. if (isset($this->{$a}[$type])) {
  3031. $assoc[$type]['association'] = $a;
  3032. break;
  3033. }
  3034. }
  3035. return $assoc[$type];
  3036. }
  3037. return null;
  3038. }
  3039. }
  3040. /**
  3041. * Gets the name and fields to be used by a join model. This allows specifying join fields
  3042. * in the association definition.
  3043. *
  3044. * @param string|array $assoc The model to be joined
  3045. * @param array $keys Any join keys which must be merged with the keys queried
  3046. * @return array
  3047. */
  3048. public function joinModel($assoc, $keys = array()) {
  3049. if (is_string($assoc)) {
  3050. list(, $assoc) = pluginSplit($assoc);
  3051. return array($assoc, array_keys($this->{$assoc}->schema()));
  3052. } elseif (is_array($assoc)) {
  3053. $with = key($assoc);
  3054. return array($with, array_unique(array_merge($assoc[$with], $keys)));
  3055. }
  3056. trigger_error(
  3057. __d('cake_dev', 'Invalid join model settings in %s', $model->alias),
  3058. E_USER_WARNING
  3059. );
  3060. }
  3061. /**
  3062. * Called before each find operation. Return false if you want to halt the find
  3063. * call, otherwise return the (modified) query data.
  3064. *
  3065. * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
  3066. * @return mixed true if the operation should continue, false if it should abort; or, modified
  3067. * $queryData to continue with new $queryData
  3068. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeFind-1049
  3069. */
  3070. public function beforeFind($queryData) {
  3071. return true;
  3072. }
  3073. /**
  3074. * Called after each find operation. Can be used to modify any results returned by find().
  3075. * Return value should be the (modified) results.
  3076. *
  3077. * @param mixed $results The results of the find operation
  3078. * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
  3079. * @return mixed Result of the find operation
  3080. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterFind-1050
  3081. */
  3082. public function afterFind($results, $primary = false) {
  3083. return $results;
  3084. }
  3085. /**
  3086. * Called before each save operation, after validation. Return a non-true result
  3087. * to halt the save.
  3088. *
  3089. * @param array $options
  3090. * @return boolean True if the operation should continue, false if it should abort
  3091. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeSave-1052
  3092. */
  3093. public function beforeSave($options = array()) {
  3094. return true;
  3095. }
  3096. /**
  3097. * Called after each successful save operation.
  3098. *
  3099. * @param boolean $created True if this save created a new record
  3100. * @return void
  3101. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterSave-1053
  3102. */
  3103. public function afterSave($created) {
  3104. }
  3105. /**
  3106. * Called before every deletion operation.
  3107. *
  3108. * @param boolean $cascade If true records that depend on this record will also be deleted
  3109. * @return boolean True if the operation should continue, false if it should abort
  3110. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeDelete-1054
  3111. */
  3112. public function beforeDelete($cascade = true) {
  3113. return true;
  3114. }
  3115. /**
  3116. * Called after every deletion operation.
  3117. *
  3118. * @return void
  3119. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterDelete-1055
  3120. */
  3121. public function afterDelete() {
  3122. }
  3123. /**
  3124. * Called during validation operations, before validation. Please note that custom
  3125. * validation rules can be defined in $validate.
  3126. *
  3127. * @param array $options Options passed from model::save(), see $options of model::save().
  3128. * @return boolean True if validate operation should continue, false to abort
  3129. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeValidate-1051
  3130. */
  3131. public function beforeValidate($options = array()) {
  3132. return true;
  3133. }
  3134. /**
  3135. * Called when a DataSource-level error occurs.
  3136. *
  3137. * @return void
  3138. * @link http://book.cakephp.org/view/1048/Callback-Methods#onError-1056
  3139. */
  3140. public function onError() {
  3141. }
  3142. /**
  3143. * Clears cache for this model.
  3144. *
  3145. * @param string $type If null this deletes cached views if Cache.check is true
  3146. * Will be used to allow deleting query cache also
  3147. * @return boolean true on delete
  3148. * @todo
  3149. */
  3150. protected function _clearCache($type = null) {
  3151. if ($type === null) {
  3152. if (Configure::read('Cache.check') === true) {
  3153. $assoc[] = strtolower(Inflector::pluralize($this->alias));
  3154. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
  3155. foreach ($this->_associations as $key => $association) {
  3156. foreach ($this->$association as $key => $className) {
  3157. $check = strtolower(Inflector::pluralize($className['className']));
  3158. if (!in_array($check, $assoc)) {
  3159. $assoc[] = strtolower(Inflector::pluralize($className['className']));
  3160. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
  3161. }
  3162. }
  3163. }
  3164. clearCache($assoc);
  3165. return true;
  3166. }
  3167. } else {
  3168. //Will use for query cache deleting
  3169. }
  3170. }
  3171. }