Model.php 110 KB

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