Model.php 110 KB

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