Model.php 89 KB

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