Model.php 107 KB

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