Base for a static organization website

Model.php 114KB

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