Model.php 106 KB

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