Model.php 111 KB

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