Model.php 108 KB

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