Model.php 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192
  1. <?php
  2. /**
  3. * Object-relational mapper.
  4. *
  5. * DBO-backed object data model, for mapping database tables to Cake objects.
  6. *
  7. * PHP versions 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.Model
  18. * @since CakePHP(tm) v 0.10.0.0
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. /**
  22. * Included libs
  23. */
  24. App::uses('ClassRegistry', 'Utility');
  25. App::uses('Validation', 'Utility');
  26. App::uses('String', 'Utility');
  27. App::uses('BehaviorCollection', 'Model');
  28. App::uses('ModelBehavior', 'Model');
  29. App::uses('ConnectionManager', 'Model');
  30. App::uses('Xml', 'Utility');
  31. /**
  32. * Object-relational mapper.
  33. *
  34. * DBO-backed object data model.
  35. * Automatically selects a database table name based on a pluralized lowercase object class name
  36. * (i.e. class 'User' => table 'users'; class 'Man' => table 'men')
  37. * The table is required to have at least 'id auto_increment' primary key.
  38. *
  39. * @package Cake.Model
  40. * @link http://book.cakephp.org/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. * Name 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. public 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. public 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. public 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. public 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. private 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. private 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. if ($plugin) {
  634. $plugin .= '.';
  635. }
  636. $model = array('class' => $plugin . $className, 'alias' => $assoc);
  637. $this->{$assoc} = ClassRegistry::init($model);
  638. if ($plugin) {
  639. ClassRegistry::addObject($plugin . $className, $this->{$assoc});
  640. }
  641. if ($assoc) {
  642. $this->tableToModel[$this->{$assoc}->table] = $assoc;
  643. }
  644. }
  645. }
  646. /**
  647. * Build an array-based association from string.
  648. *
  649. * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  650. * @param string $assocKey
  651. * @return void
  652. * @access private
  653. */
  654. private function __generateAssociation($type, $assocKey) {
  655. $class = $assocKey;
  656. $dynamicWith = false;
  657. foreach ($this->__associationKeys[$type] as $key) {
  658. if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) {
  659. $data = '';
  660. switch ($key) {
  661. case 'fields':
  662. $data = '';
  663. break;
  664. case 'foreignKey':
  665. $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id';
  666. break;
  667. case 'associationForeignKey':
  668. $data = Inflector::singularize($this->{$class}->table) . '_id';
  669. break;
  670. case 'with':
  671. $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable']));
  672. $dynamicWith = true;
  673. break;
  674. case 'joinTable':
  675. $tables = array($this->table, $this->{$class}->table);
  676. sort ($tables);
  677. $data = $tables[0] . '_' . $tables[1];
  678. break;
  679. case 'className':
  680. $data = $class;
  681. break;
  682. case 'unique':
  683. $data = true;
  684. break;
  685. }
  686. $this->{$type}[$assocKey][$key] = $data;
  687. }
  688. if ($dynamicWith) {
  689. $this->{$type}[$assocKey]['dynamicWith'] = true;
  690. }
  691. }
  692. }
  693. /**
  694. * Sets a custom table for your controller class. Used by your controller to select a database table.
  695. *
  696. * @param string $tableName Name of the custom table
  697. * @throws MissingTableException when database table $tableName is not found on data source
  698. * @return void
  699. */
  700. public function setSource($tableName) {
  701. $this->setDataSource($this->useDbConfig);
  702. $db = ConnectionManager::getDataSource($this->useDbConfig);
  703. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  704. if (method_exists($db, 'listSources')) {
  705. $sources = $db->listSources();
  706. if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) {
  707. throw new MissingTableException(array(
  708. 'table' => $this->tablePrefix . $tableName,
  709. 'class' => $this->alias
  710. ));
  711. }
  712. $this->_schema = null;
  713. }
  714. $this->table = $this->useTable = $tableName;
  715. $this->tableToModel[$this->table] = $this->alias;
  716. }
  717. /**
  718. * This function does two things:
  719. *
  720. * 1. it scans the array $one for the primary key,
  721. * and if that's found, it sets the current id to the value of $one[id].
  722. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object.
  723. * 2. Returns an array with all of $one's keys and values.
  724. * (Alternative indata: two strings, which are mangled to
  725. * a one-item, two-dimensional array using $one for a key and $two as its value.)
  726. *
  727. * @param mixed $one Array or string of data
  728. * @param string $two Value string for the alternative indata method
  729. * @return array Data with all of $one's keys and values
  730. * @access public
  731. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  732. */
  733. public function set($one, $two = null) {
  734. if (!$one) {
  735. return;
  736. }
  737. if (is_object($one)) {
  738. if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) {
  739. $one = $this->_normalizeXmlData(Xml::toArray($one));
  740. } else {
  741. $one = Set::reverse($one);
  742. }
  743. }
  744. if (is_array($one)) {
  745. $data = $one;
  746. if (empty($one[$this->alias])) {
  747. if ($this->getAssociated(key($one)) === null) {
  748. $data = array($this->alias => $one);
  749. }
  750. }
  751. } else {
  752. $data = array($this->alias => array($one => $two));
  753. }
  754. foreach ($data as $modelName => $fieldSet) {
  755. if (is_array($fieldSet)) {
  756. foreach ($fieldSet as $fieldName => $fieldValue) {
  757. if (isset($this->validationErrors[$fieldName])) {
  758. unset ($this->validationErrors[$fieldName]);
  759. }
  760. if ($modelName === $this->alias) {
  761. if ($fieldName === $this->primaryKey) {
  762. $this->id = $fieldValue;
  763. }
  764. }
  765. if (is_array($fieldValue) || is_object($fieldValue)) {
  766. $fieldValue = $this->deconstruct($fieldName, $fieldValue);
  767. }
  768. $this->data[$modelName][$fieldName] = $fieldValue;
  769. }
  770. }
  771. }
  772. return $data;
  773. }
  774. /**
  775. * Normalize Xml::toArray() to use in Model::save()
  776. *
  777. * @param array $xml XML as array
  778. * @return array
  779. */
  780. protected function _normalizeXmlData(array $xml) {
  781. $return = array();
  782. foreach ($xml as $key => $value) {
  783. if (is_array($value)) {
  784. $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value);
  785. } elseif ($key[0] === '@') {
  786. $return[substr($key, 1)] = $value;
  787. } else {
  788. $return[$key] = $value;
  789. }
  790. }
  791. return $return;
  792. }
  793. /**
  794. * Deconstructs a complex data type (array or object) into a single field value.
  795. *
  796. * @param string $field The name of the field to be deconstructed
  797. * @param mixed $data An array or object to be deconstructed into a field
  798. * @return mixed The resulting data that should be assigned to a field
  799. */
  800. public function deconstruct($field, $data) {
  801. if (!is_array($data)) {
  802. return $data;
  803. }
  804. $copy = $data;
  805. $type = $this->getColumnType($field);
  806. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  807. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  808. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  809. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  810. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  811. $date = array();
  812. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
  813. $data['hour'] = $data['hour'] + 12;
  814. }
  815. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  816. $data['hour'] = '00';
  817. }
  818. if ($type == 'time') {
  819. foreach ($timeFields as $key => $val) {
  820. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  821. $data[$val] = '00';
  822. } elseif ($data[$val] === '') {
  823. $data[$val] = '';
  824. } else {
  825. $data[$val] = sprintf('%02d', $data[$val]);
  826. }
  827. if (!empty($data[$val])) {
  828. $date[$key] = $data[$val];
  829. } else {
  830. return null;
  831. }
  832. }
  833. }
  834. if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') {
  835. foreach ($dateFields as $key => $val) {
  836. if ($val == 'hour' || $val == 'min' || $val == 'sec') {
  837. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  838. $data[$val] = '00';
  839. } else {
  840. $data[$val] = sprintf('%02d', $data[$val]);
  841. }
  842. }
  843. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  844. return null;
  845. }
  846. if (isset($data[$val]) && !empty($data[$val])) {
  847. $date[$key] = $data[$val];
  848. }
  849. }
  850. }
  851. $format = $this->getDataSource()->columns[$type]['format'];
  852. $day = empty($date['Y']) ? null : $date['Y'] . '-' . $date['m'] . '-' . $date['d'] . ' ';
  853. $hour = empty($date['H']) ? null : $date['H'] . ':' . $date['i'] . ':' . $date['s'];
  854. $date = new DateTime($day . $hour);
  855. if ($useNewDate && !empty($date)) {
  856. return $date->format($format);
  857. }
  858. }
  859. return $data;
  860. }
  861. /**
  862. * Returns an array of table metadata (column names and types) from the database.
  863. * $field => keys(type, null, default, key, length, extra)
  864. *
  865. * @param mixed $field Set to true to reload schema, or a string to return a specific field
  866. * @return array Array of table metadata
  867. */
  868. public function schema($field = false) {
  869. if (!is_array($this->_schema) || $field === true) {
  870. $db = $this->getDataSource();
  871. $db->cacheSources = ($this->cacheSources && $db->cacheSources);
  872. if (method_exists($db, 'describe') && $this->useTable !== false) {
  873. $this->_schema = $db->describe($this);
  874. } elseif ($this->useTable === false) {
  875. $this->_schema = array();
  876. }
  877. }
  878. if (is_string($field)) {
  879. if (isset($this->_schema[$field])) {
  880. return $this->_schema[$field];
  881. } else {
  882. return null;
  883. }
  884. }
  885. return $this->_schema;
  886. }
  887. /**
  888. * Returns an associative array of field names and column types.
  889. *
  890. * @return array Field types indexed by field name
  891. */
  892. public function getColumnTypes() {
  893. $columns = $this->schema();
  894. if (empty($columns)) {
  895. 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);
  896. }
  897. $cols = array();
  898. foreach ($columns as $field => $values) {
  899. $cols[$field] = $values['type'];
  900. }
  901. return $cols;
  902. }
  903. /**
  904. * Returns the column type of a column in the model.
  905. *
  906. * @param string $column The name of the model column
  907. * @return string Column type
  908. */
  909. public function getColumnType($column) {
  910. $db = $this->getDataSource();
  911. $cols = $this->schema();
  912. $model = null;
  913. $column = str_replace(array($db->startQuote, $db->endQuote), '', $column);
  914. if (strpos($column, '.')) {
  915. list($model, $column) = explode('.', $column);
  916. }
  917. if ($model != $this->alias && isset($this->{$model})) {
  918. return $this->{$model}->getColumnType($column);
  919. }
  920. if (isset($cols[$column]) && isset($cols[$column]['type'])) {
  921. return $cols[$column]['type'];
  922. }
  923. return null;
  924. }
  925. /**
  926. * Returns true if the supplied field exists in the model's database table.
  927. *
  928. * @param mixed $name Name of field to look for, or an array of names
  929. * @param boolean $checkVirtual checks if the field is declared as virtual
  930. * @return mixed If $name is a string, returns a boolean indicating whether the field exists.
  931. * If $name is an array of field names, returns the first field that exists,
  932. * or false if none exist.
  933. */
  934. public function hasField($name, $checkVirtual = false) {
  935. if (is_array($name)) {
  936. foreach ($name as $n) {
  937. if ($this->hasField($n, $checkVirtual)) {
  938. return $n;
  939. }
  940. }
  941. return false;
  942. }
  943. if ($checkVirtual && !empty($this->virtualFields)) {
  944. if ($this->isVirtualField($name)) {
  945. return true;
  946. }
  947. }
  948. if (empty($this->_schema)) {
  949. $this->schema();
  950. }
  951. if ($this->_schema != null) {
  952. return isset($this->_schema[$name]);
  953. }
  954. return false;
  955. }
  956. /**
  957. * Check that a method is callable on a model. This will check both the model's own methods, its
  958. * inherited methods and methods that could be callable through behaviors.
  959. *
  960. * @param string $method The method to be called.
  961. * @return boolean True on method being callable.
  962. */
  963. public function hasMethod($method) {
  964. if (method_exists($this, $method)) {
  965. return true;
  966. }
  967. if ($this->Behaviors->hasMethod($method)) {
  968. return true;
  969. }
  970. return false;
  971. }
  972. /**
  973. * Returns true if the supplied field is a model Virtual Field
  974. *
  975. * @param mixed $name Name of field to look for
  976. * @return boolean indicating whether the field exists as a model virtual field.
  977. */
  978. public function isVirtualField($field) {
  979. if (empty($this->virtualFields) || !is_string($field)) {
  980. return false;
  981. }
  982. if (isset($this->virtualFields[$field])) {
  983. return true;
  984. }
  985. if (strpos($field, '.') !== false) {
  986. list($model, $field) = explode('.', $field);
  987. if (isset($this->virtualFields[$field])) {
  988. return true;
  989. }
  990. }
  991. return false;
  992. }
  993. /**
  994. * Returns the expression for a model virtual field
  995. *
  996. * @param mixed $name Name of field to look for
  997. * @return mixed If $field is string expression bound to virtual field $field
  998. * If $field is null, returns an array of all model virtual fields
  999. * or false if none $field exist.
  1000. */
  1001. public function getVirtualField($field = null) {
  1002. if ($field == null) {
  1003. return empty($this->virtualFields) ? false : $this->virtualFields;
  1004. }
  1005. if ($this->isVirtualField($field)) {
  1006. if (strpos($field, '.') !== false) {
  1007. list($model, $field) = explode('.', $field);
  1008. }
  1009. return $this->virtualFields[$field];
  1010. }
  1011. return false;
  1012. }
  1013. /**
  1014. * Initializes the model for writing a new record, loading the default values
  1015. * for those fields that are not defined in $data, and clearing previous validation errors.
  1016. * Especially helpful for saving data in loops.
  1017. *
  1018. * @param mixed $data Optional data array to assign to the model after it is created. If null or false,
  1019. * schema data defaults are not merged.
  1020. * @param boolean $filterKey If true, overwrites any primary key input with an empty value
  1021. * @return array The current Model::data; after merging $data and/or defaults from database
  1022. * @access public
  1023. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1024. */
  1025. public function create($data = array(), $filterKey = false) {
  1026. $defaults = array();
  1027. $this->id = false;
  1028. $this->data = array();
  1029. $this->validationErrors = array();
  1030. if ($data !== null && $data !== false) {
  1031. foreach ($this->schema() as $field => $properties) {
  1032. if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') {
  1033. $defaults[$field] = $properties['default'];
  1034. }
  1035. }
  1036. $this->set($defaults);
  1037. $this->set($data);
  1038. }
  1039. if ($filterKey) {
  1040. $this->set($this->primaryKey, false);
  1041. }
  1042. return $this->data;
  1043. }
  1044. /**
  1045. * Returns a list of fields from the database, and sets the current model
  1046. * data (Model::$data) with the record found.
  1047. *
  1048. * @param mixed $fields String of single fieldname, or an array of fieldnames.
  1049. * @param mixed $id The ID of the record to read
  1050. * @return array Array of database fields, or false if not found
  1051. * @access public
  1052. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#read-1029
  1053. */
  1054. public function read($fields = null, $id = null) {
  1055. $this->validationErrors = array();
  1056. if ($id != null) {
  1057. $this->id = $id;
  1058. }
  1059. $id = $this->id;
  1060. if (is_array($this->id)) {
  1061. $id = $this->id[0];
  1062. }
  1063. if ($id !== null && $id !== false) {
  1064. $this->data = $this->find('first', array(
  1065. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
  1066. 'fields' => $fields
  1067. ));
  1068. return $this->data;
  1069. } else {
  1070. return false;
  1071. }
  1072. }
  1073. /**
  1074. * Returns the contents of a single field given the supplied conditions, in the
  1075. * supplied order.
  1076. *
  1077. * @param string $name Name of field to get
  1078. * @param array $conditions SQL conditions (defaults to NULL)
  1079. * @param string $order SQL ORDER BY fragment
  1080. * @return string field contents, or false if not found
  1081. * @access public
  1082. * @link http://book.cakephp.org/view/1017/Retrieving-Your-Data#field-1028
  1083. */
  1084. public function field($name, $conditions = null, $order = null) {
  1085. if ($conditions === null && $this->id !== false) {
  1086. $conditions = array($this->alias . '.' . $this->primaryKey => $this->id);
  1087. }
  1088. if ($this->recursive >= 1) {
  1089. $recursive = -1;
  1090. } else {
  1091. $recursive = $this->recursive;
  1092. }
  1093. $fields = $name;
  1094. if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) {
  1095. if (strpos($name, '.') === false) {
  1096. if (isset($data[$this->alias][$name])) {
  1097. return $data[$this->alias][$name];
  1098. }
  1099. } else {
  1100. $name = explode('.', $name);
  1101. if (isset($data[$name[0]][$name[1]])) {
  1102. return $data[$name[0]][$name[1]];
  1103. }
  1104. }
  1105. if (isset($data[0]) && count($data[0]) > 0) {
  1106. return array_shift($data[0]);
  1107. }
  1108. } else {
  1109. return false;
  1110. }
  1111. }
  1112. /**
  1113. * Saves the value of a single field to the database, based on the current
  1114. * model ID.
  1115. *
  1116. * @param string $name Name of the table field
  1117. * @param mixed $value Value of the field
  1118. * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed
  1119. * @return boolean See Model::save()
  1120. * @access public
  1121. * @see Model::save()
  1122. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1123. */
  1124. public function saveField($name, $value, $validate = false) {
  1125. $id = $this->id;
  1126. $this->create(false);
  1127. if (is_array($validate)) {
  1128. $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate);
  1129. } else {
  1130. $options = array('validate' => $validate, 'fieldList' => array($name));
  1131. }
  1132. return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options);
  1133. }
  1134. /**
  1135. * Saves model data (based on white-list, if supplied) to the database. By
  1136. * default, validation occurs before save.
  1137. *
  1138. * @param array $data Data to save.
  1139. * @param mixed $validate Either a boolean, or an array.
  1140. * If a boolean, indicates whether or not to validate before saving.
  1141. * If an array, allows control of validate, callbacks, and fieldList
  1142. * @param array $fieldList List of fields to allow to be written
  1143. * @return mixed On success Model::$data if its not empty or true, false on failure
  1144. * @access public
  1145. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1146. */
  1147. public function save($data = null, $validate = true, $fieldList = array()) {
  1148. $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true);
  1149. $_whitelist = $this->whitelist;
  1150. $fields = array();
  1151. if (!is_array($validate)) {
  1152. $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks'));
  1153. } else {
  1154. $options = array_merge($defaults, $validate);
  1155. }
  1156. if (!empty($options['fieldList'])) {
  1157. $this->whitelist = $options['fieldList'];
  1158. } elseif ($options['fieldList'] === null) {
  1159. $this->whitelist = array();
  1160. }
  1161. $this->set($data);
  1162. if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) {
  1163. return false;
  1164. }
  1165. foreach (array('created', 'updated', 'modified') as $field) {
  1166. $keyPresentAndEmpty = (
  1167. isset($this->data[$this->alias]) &&
  1168. array_key_exists($field, $this->data[$this->alias]) &&
  1169. $this->data[$this->alias][$field] === null
  1170. );
  1171. if ($keyPresentAndEmpty) {
  1172. unset($this->data[$this->alias][$field]);
  1173. }
  1174. }
  1175. $exists = $this->exists();
  1176. $dateFields = array('modified', 'updated');
  1177. if (!$exists) {
  1178. $dateFields[] = 'created';
  1179. }
  1180. if (isset($this->data[$this->alias])) {
  1181. $fields = array_keys($this->data[$this->alias]);
  1182. }
  1183. if ($options['validate'] && !$this->validates($options)) {
  1184. $this->whitelist = $_whitelist;
  1185. return false;
  1186. }
  1187. $db = $this->getDataSource();
  1188. foreach ($dateFields as $updateCol) {
  1189. if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {
  1190. $default = array('formatter' => 'date');
  1191. $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]);
  1192. if (!array_key_exists('format', $colType)) {
  1193. $time = strtotime('now');
  1194. } else {
  1195. $time = $colType['formatter']($colType['format']);
  1196. }
  1197. if (!empty($this->whitelist)) {
  1198. $this->whitelist[] = $updateCol;
  1199. }
  1200. $this->set($updateCol, $time);
  1201. }
  1202. }
  1203. if ($options['callbacks'] === true || $options['callbacks'] === 'before') {
  1204. $result = $this->Behaviors->trigger('beforeSave', array(&$this, $options), array(
  1205. 'break' => true, 'breakOn' => array(false, null)
  1206. ));
  1207. if (!$result || !$this->beforeSave($options)) {
  1208. $this->whitelist = $_whitelist;
  1209. return false;
  1210. }
  1211. }
  1212. if (empty($this->data[$this->alias][$this->primaryKey])) {
  1213. unset($this->data[$this->alias][$this->primaryKey]);
  1214. }
  1215. $fields = $values = array();
  1216. foreach ($this->data as $n => $v) {
  1217. if (isset($this->hasAndBelongsToMany[$n])) {
  1218. if (isset($v[$n])) {
  1219. $v = $v[$n];
  1220. }
  1221. $joined[$n] = $v;
  1222. } else {
  1223. if ($n === $this->alias) {
  1224. foreach (array('created', 'updated', 'modified') as $field) {
  1225. if (array_key_exists($field, $v) && empty($v[$field])) {
  1226. unset($v[$field]);
  1227. }
  1228. }
  1229. foreach ($v as $x => $y) {
  1230. if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) {
  1231. list($fields[], $values[]) = array($x, $y);
  1232. }
  1233. }
  1234. }
  1235. }
  1236. }
  1237. $count = count($fields);
  1238. if (!$exists && $count > 0) {
  1239. $this->id = false;
  1240. }
  1241. $success = true;
  1242. $created = false;
  1243. if ($count > 0) {
  1244. $cache = $this->_prepareUpdateFields(array_combine($fields, $values));
  1245. if (!empty($this->id)) {
  1246. $success = (bool)$db->update($this, $fields, $values);
  1247. } else {
  1248. $fInfo = $this->schema($this->primaryKey);
  1249. $isUUID = ($fInfo['length'] == 36 &&
  1250. ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
  1251. );
  1252. if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
  1253. if (array_key_exists($this->primaryKey, $this->data[$this->alias])) {
  1254. $j = array_search($this->primaryKey, $fields);
  1255. $values[$j] = String::uuid();
  1256. } else {
  1257. list($fields[], $values[]) = array($this->primaryKey, String::uuid());
  1258. }
  1259. }
  1260. if (!$db->create($this, $fields, $values)) {
  1261. $success = $created = false;
  1262. } else {
  1263. $created = true;
  1264. }
  1265. }
  1266. if ($success && !empty($this->belongsTo)) {
  1267. $this->updateCounterCache($cache, $created);
  1268. }
  1269. }
  1270. if (!empty($joined) && $success === true) {
  1271. $this->__saveMulti($joined, $this->id, $db);
  1272. }
  1273. if ($success && $count > 0) {
  1274. if (!empty($this->data)) {
  1275. $success = $this->data;
  1276. if ($created) {
  1277. $this->data[$this->alias][$this->primaryKey] = $this->id;
  1278. }
  1279. }
  1280. if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
  1281. $this->Behaviors->trigger('afterSave', array(&$this, $created, $options));
  1282. $this->afterSave($created);
  1283. }
  1284. if (!empty($this->data)) {
  1285. $success = Set::merge($success, $this->data);
  1286. }
  1287. $this->data = false;
  1288. $this->_clearCache();
  1289. $this->validationErrors = array();
  1290. }
  1291. $this->whitelist = $_whitelist;
  1292. return $success;
  1293. }
  1294. /**
  1295. * Saves model hasAndBelongsToMany data to the database.
  1296. *
  1297. * @param array $joined Data to save
  1298. * @param mixed $id ID of record in this model
  1299. * @access private
  1300. */
  1301. private function __saveMulti($joined, $id, $db) {
  1302. foreach ($joined as $assoc => $data) {
  1303. if (isset($this->hasAndBelongsToMany[$assoc])) {
  1304. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  1305. $keyInfo = $this->{$join}->schema($this->{$join}->primaryKey);
  1306. $isUUID = !empty($this->{$join}->primaryKey) && (
  1307. $keyInfo['length'] == 36 && (
  1308. $keyInfo['type'] === 'string' ||
  1309. $keyInfo['type'] === 'binary'
  1310. )
  1311. );
  1312. $newData = $newValues = array();
  1313. $primaryAdded = false;
  1314. $fields = array(
  1315. $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']),
  1316. $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey'])
  1317. );
  1318. $idField = $db->name($this->{$join}->primaryKey);
  1319. if ($isUUID && !in_array($idField, $fields)) {
  1320. $fields[] = $idField;
  1321. $primaryAdded = true;
  1322. }
  1323. foreach ((array)$data as $row) {
  1324. if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
  1325. $values = array($id, $row);
  1326. if ($isUUID && $primaryAdded) {
  1327. $values[] = String::uuid();
  1328. }
  1329. $newValues[] = $values;
  1330. unset($values);
  1331. } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1332. $newData[] = $row;
  1333. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  1334. $newData[] = $row[$join];
  1335. }
  1336. }
  1337. if ($this->hasAndBelongsToMany[$assoc]['unique']) {
  1338. $conditions = array(
  1339. $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id
  1340. );
  1341. if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) {
  1342. $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']);
  1343. }
  1344. $links = $this->{$join}->find('all', array(
  1345. 'conditions' => $conditions,
  1346. 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0,
  1347. 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey']
  1348. ));
  1349. $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey'];
  1350. $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
  1351. if (!empty($oldLinks)) {
  1352. $conditions[$associationForeignKey] = $oldLinks;
  1353. $db->delete($this->{$join}, $conditions);
  1354. }
  1355. }
  1356. if (!empty($newData)) {
  1357. foreach ($newData as $data) {
  1358. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id;
  1359. $this->{$join}->create($data);
  1360. $this->{$join}->save();
  1361. }
  1362. }
  1363. if (!empty($newValues)) {
  1364. $db->insertMulti($this->{$join}, $fields, $newValues);
  1365. }
  1366. }
  1367. }
  1368. }
  1369. /**
  1370. * Updates the counter cache of belongsTo associations after a save or delete operation
  1371. *
  1372. * @param array $keys Optional foreign key data, defaults to the information $this->data
  1373. * @param boolean $created True if a new record was created, otherwise only associations with
  1374. * 'counterScope' defined get updated
  1375. * @return void
  1376. */
  1377. public function updateCounterCache($keys = array(), $created = false) {
  1378. $keys = empty($keys) ? $this->data[$this->alias] : $keys;
  1379. $keys['old'] = isset($keys['old']) ? $keys['old'] : array();
  1380. foreach ($this->belongsTo as $parent => $assoc) {
  1381. $foreignKey = $assoc['foreignKey'];
  1382. $fkQuoted = $this->escapeField($assoc['foreignKey']);
  1383. if (!empty($assoc['counterCache'])) {
  1384. if ($assoc['counterCache'] === true) {
  1385. $assoc['counterCache'] = Inflector::underscore($this->alias) . '_count';
  1386. }
  1387. if (!$this->{$parent}->hasField($assoc['counterCache'])) {
  1388. continue;
  1389. }
  1390. if (!array_key_exists($foreignKey, $keys)) {
  1391. $keys[$foreignKey] = $this->field($foreignKey);
  1392. }
  1393. $recursive = (isset($assoc['counterScope']) ? 1 : -1);
  1394. $conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
  1395. if (isset($keys['old'][$foreignKey])) {
  1396. if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
  1397. $conditions[$fkQuoted] = $keys['old'][$foreignKey];
  1398. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1399. $this->{$parent}->updateAll(
  1400. array($assoc['counterCache'] => $count),
  1401. array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
  1402. );
  1403. }
  1404. }
  1405. $conditions[$fkQuoted] = $keys[$foreignKey];
  1406. if ($recursive == 1) {
  1407. $conditions = array_merge($conditions, (array)$assoc['counterScope']);
  1408. }
  1409. $count = intval($this->find('count', compact('conditions', 'recursive')));
  1410. $this->{$parent}->updateAll(
  1411. array($assoc['counterCache'] => $count),
  1412. array($this->{$parent}->escapeField() => $keys[$foreignKey])
  1413. );
  1414. }
  1415. }
  1416. }
  1417. /**
  1418. * Helper method for Model::updateCounterCache(). Checks the fields to be updated for
  1419. *
  1420. * @param array $data The fields of the record that will be updated
  1421. * @return array Returns updated foreign key values, along with an 'old' key containing the old
  1422. * values, or empty if no foreign keys are updated.
  1423. */
  1424. protected function _prepareUpdateFields($data) {
  1425. $foreignKeys = array();
  1426. foreach ($this->belongsTo as $assoc => $info) {
  1427. if ($info['counterCache']) {
  1428. $foreignKeys[$assoc] = $info['foreignKey'];
  1429. }
  1430. }
  1431. $included = array_intersect($foreignKeys, array_keys($data));
  1432. if (empty($included) || empty($this->id)) {
  1433. return array();
  1434. }
  1435. $old = $this->find('first', array(
  1436. 'conditions' => array($this->primaryKey => $this->id),
  1437. 'fields' => array_values($included),
  1438. 'recursive' => -1
  1439. ));
  1440. return array_merge($data, array('old' => $old[$this->alias]));
  1441. }
  1442. /**
  1443. * Backwards compatible passtrough method for:
  1444. * saveMany(), validateMany(), saveAssociated() and validateAssociated()
  1445. *
  1446. * Saves multiple individual records for a single model; Also works with a single record, as well as
  1447. * all its associated records.
  1448. *
  1449. * #### Options
  1450. *
  1451. * - validate: Set to false to disable validation, true to validate each record before saving,
  1452. * 'first' to validate *all* records before any are saved (default),
  1453. * or 'only' to only validate the records, but not save them.
  1454. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1455. * Should be set to false if database/table does not support transactions.
  1456. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1457. *
  1458. * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple
  1459. * records of the same type), or an array indexed by association name.
  1460. * @param array $options Options to use when saving record data, See $options above.
  1461. * @return mixed If atomic: True on success, or false on failure.
  1462. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1463. * depending on whether each record saved successfully.
  1464. * @access public
  1465. * @link http://book.cakephp.org/view/1032/Saving-Related-Model-Data-hasOne-hasMany-belongsTo
  1466. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1467. */
  1468. public function saveAll($data = null, $options = array()) {
  1469. $options = array_merge(array('validate' => 'first'), $options);
  1470. if (Set::numeric(array_keys($data))) {
  1471. if ($options['validate'] === 'only') {
  1472. return $this->validateMany($data, $options);
  1473. }
  1474. return $this->saveMany($data, $options);
  1475. }
  1476. if ($options['validate'] === 'only') {
  1477. $validatesAssoc = $this->validateAssociated($data, $options);
  1478. if (isset($this->validationErrors[$this->alias]) && $this->validationErrors[$this->alias] === false) {
  1479. return false;
  1480. }
  1481. return $validatesAssoc;
  1482. }
  1483. return $this->saveAssociated($data, $options);
  1484. }
  1485. /**
  1486. * Saves multiple individual records for a single model
  1487. *
  1488. * #### Options
  1489. *
  1490. * - validate: Set to false to disable validation, true to validate each record before saving,
  1491. * 'first' to validate *all* records before any are saved (default),
  1492. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1493. * Should be set to false if database/table does not support transactions.
  1494. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1495. *
  1496. * @param array $data Record data to save. This should be a numerically-indexed array
  1497. * @param array $options Options to use when saving record data, See $options above.
  1498. * @return mixed If atomic: True on success, or false on failure.
  1499. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1500. * depending on whether each record saved successfully.
  1501. * @access public
  1502. */
  1503. public function saveMany($data = null, $options = array()) {
  1504. if (empty($data)) {
  1505. $data = $this->data;
  1506. }
  1507. $options = array_merge(array('validate' => 'first', 'atomic' => true), $options);
  1508. $this->validationErrors = $validationErrors = array();
  1509. if (empty($data) && $options['validate'] !== false) {
  1510. $result = $this->save($data, $options);
  1511. return !empty($result);
  1512. }
  1513. if ($options['validate'] === 'first') {
  1514. $validates = $this->validateMany($data, $options);
  1515. if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
  1516. return $validates;
  1517. }
  1518. }
  1519. if ($options['atomic']) {
  1520. $db = $this->getDataSource();
  1521. $transactionBegun = $db->begin($this);
  1522. }
  1523. $return = array();
  1524. foreach ($data as $key => $record) {
  1525. $validates = ($this->create(null) !== null && $this->save($record, $options));
  1526. if (!$validates) {
  1527. $validationErrors[$key] = $this->validationErrors;
  1528. }
  1529. if (!$options['atomic']) {
  1530. $return[] = $validates;
  1531. } elseif (!$validates) {
  1532. break;
  1533. }
  1534. }
  1535. $this->validationErrors = $validationErrors;
  1536. if (!$options['atomic']) {
  1537. return $return;
  1538. }
  1539. if ($validates) {
  1540. if ($transactionBegun) {
  1541. return $db->commit($this) !== false;
  1542. } else {
  1543. return true;
  1544. }
  1545. }
  1546. $db->rollback($this);
  1547. return false;
  1548. }
  1549. /**
  1550. * Validates multiple individual records for a single model
  1551. *
  1552. * #### Options
  1553. *
  1554. * - atomic: If true (default), returns boolean. If false returns array.
  1555. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1556. *
  1557. * @param array $data Record data to validate. This should be a numerically-indexed array
  1558. * @param array $options Options to use when validating record data (see above), See also $options of validates().
  1559. * @return boolean True on success, or false on failure.
  1560. * @return mixed If atomic: True on success, or false on failure.
  1561. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1562. * depending on whether each record validated successfully.
  1563. * @access public
  1564. */
  1565. public function validateMany($data, $options = array()) {
  1566. $options = array_merge(array('atomic' => true), $options);
  1567. $this->validationErrors = $validationErrors = $return = array();
  1568. foreach ($data as $key => $record) {
  1569. $validates = $this->create($record) && $this->validates($options);
  1570. if (!$validates) {
  1571. $validationErrors[$key] = $this->validationErrors;
  1572. }
  1573. $return[] = $validates;
  1574. }
  1575. $this->validationErrors = $validationErrors;
  1576. if (!$options['atomic']) {
  1577. return $return;
  1578. }
  1579. if (empty($this->validationErrors)) {
  1580. return true;
  1581. }
  1582. return false;
  1583. }
  1584. /**
  1585. * Saves a single record, as well as all its directly associated records.
  1586. *
  1587. * #### Options
  1588. *
  1589. * - validate: Set to false to disable validation, true to validate each record before saving,
  1590. * 'first' to validate *all* records before any are saved (default),
  1591. * - atomic: If true (default), will attempt to save all records in a single transaction.
  1592. * Should be set to false if database/table does not support transactions.
  1593. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1594. *
  1595. * @param array $data Record data to save. This should be an array indexed by association name.
  1596. * @param array $options Options to use when saving record data, See $options above.
  1597. * @return mixed If atomic: True on success, or false on failure.
  1598. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1599. * depending on whether each record saved successfully.
  1600. * @access public
  1601. */
  1602. public function saveAssociated($data = null, $options = array()) {
  1603. if (empty($data)) {
  1604. $data = $this->data;
  1605. }
  1606. $options = array_merge(array('validate' => true, 'atomic' => true), $options);
  1607. $this->validationErrors = $validationErrors = array();
  1608. if (empty($data) && $options['validate'] !== false) {
  1609. $result = $this->save($data, $options);
  1610. return !empty($result);
  1611. }
  1612. if ($options['validate'] === 'first') {
  1613. $validates = $this->validateAssociated($data, $options);
  1614. if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) {
  1615. return $validates;
  1616. }
  1617. }
  1618. if ($options['atomic']) {
  1619. $db = $this->getDataSource();
  1620. $transactionBegun = $db->begin($this);
  1621. }
  1622. $associations = $this->getAssociated();
  1623. $return = array();
  1624. $validates = true;
  1625. foreach ($data as $association => $values) {
  1626. if (isset($associations[$association]) && $associations[$association] === 'belongsTo') {
  1627. if ($this->{$association}->create(null) !== null && $this->{$association}->save($values, $options)) {
  1628. $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
  1629. } else {
  1630. $validationErrors[$association] = $this->{$association}->validationErrors;
  1631. $validates = false;
  1632. }
  1633. $return[$association][] = $validates;
  1634. }
  1635. }
  1636. if ($validates && !($this->create(null) !== null && $this->save($data, $options))) {
  1637. $validationErrors[$this->alias] = $this->validationErrors;
  1638. $validates = false;
  1639. }
  1640. $return[$this->alias] = $validates;
  1641. foreach ($data as $association => $values) {
  1642. if (!$validates) {
  1643. break;
  1644. }
  1645. if (isset($associations[$association])) {
  1646. $type = $associations[$association];
  1647. switch ($type) {
  1648. case 'hasOne':
  1649. $values[$this->{$type}[$association]['foreignKey']] = $this->id;
  1650. if (!($this->{$association}->create(null) !== null && $this->{$association}->save($values, $options))) {
  1651. $validationErrors[$association] = $this->{$association}->validationErrors;
  1652. $validates = false;
  1653. }
  1654. $return[$association][] = $validates;
  1655. break;
  1656. case 'hasMany':
  1657. foreach ($values as $i => $value) {
  1658. $values[$i][$this->{$type}[$association]['foreignKey']] = $this->id;
  1659. }
  1660. $_return = $this->{$association}->saveMany($values, array_merge($options, array('atomic' => false)));
  1661. if (in_array(false, $_return, true)) {
  1662. $validationErrors[$association] = $this->{$association}->validationErrors;
  1663. $validates = false;
  1664. }
  1665. $return[$association] = $_return;
  1666. break;
  1667. }
  1668. }
  1669. }
  1670. $this->validationErrors = $validationErrors;
  1671. if (isset($validationErrors[$this->alias])) {
  1672. $this->validationErrors = $validationErrors[$this->alias];
  1673. }
  1674. if (!$options['atomic']) {
  1675. return $return;
  1676. }
  1677. if ($validates) {
  1678. if ($transactionBegun) {
  1679. return $db->commit($this) !== false;
  1680. } else {
  1681. return true;
  1682. }
  1683. }
  1684. $db->rollback($this);
  1685. return false;
  1686. }
  1687. /**
  1688. * Validates a single record, as well as all its directly associated records.
  1689. *
  1690. * #### Options
  1691. *
  1692. * - atomic: If true (default), returns boolean. If false returns array.
  1693. * - fieldList: Equivalent to the $fieldList parameter in Model::save()
  1694. *
  1695. * @param array $data Record data to validate. This should be an array indexed by association name.
  1696. * @param array Options to use when validating record data (see above), See also $options of validates().
  1697. * @return mixed If atomic: True on success, or false on failure.
  1698. * Otherwise: array similar to the $data array passed, but values are set to true/false
  1699. * depending on whether each record validated successfully.
  1700. * @access public
  1701. */
  1702. public function validateAssociated($data, $options = array()) {
  1703. $options = array_merge(array('atomic' => true), $options);
  1704. $this->validationErrors = $validationErrors = $return = array();
  1705. if (!($this->create($data) && $this->validates($options))) {
  1706. $validationErrors[$this->alias] = $this->validationErrors;
  1707. $return[$this->alias] = false;
  1708. } else {
  1709. $return[$this->alias] = true;
  1710. }
  1711. $associations = $this->getAssociated();
  1712. $validates = true;
  1713. foreach ($data as $association => $values) {
  1714. if (isset($associations[$association])) {
  1715. if (in_array($associations[$association], array('belongsTo', 'hasOne'))) {
  1716. $validates = $this->{$association}->create($values) && $this->{$association}->validates($options);
  1717. $return[$association][] = $validates;
  1718. } elseif($associations[$association] === 'hasMany') {
  1719. $validates = $this->{$association}->validateMany($values, $options);
  1720. $return[$association] = $validates;
  1721. }
  1722. if (!$validates || (is_array($validates) && in_array(false, $validates, true))) {
  1723. $validationErrors[$association] = $this->{$association}->validationErrors;
  1724. }
  1725. }
  1726. }
  1727. $this->validationErrors = $validationErrors;
  1728. if (isset($validationErrors[$this->alias])) {
  1729. $this->validationErrors = $validationErrors[$this->alias];
  1730. }
  1731. if (!$options['atomic']) {
  1732. return $return;
  1733. }
  1734. if ($return[$this->alias] === false || !empty($this->validationErrors)) {
  1735. return false;
  1736. }
  1737. return true;
  1738. }
  1739. /**
  1740. * Updates multiple model records based on a set of conditions.
  1741. *
  1742. * @param array $fields Set of fields and values, indexed by fields.
  1743. * Fields are treated as SQL snippets, to insert literal values manually escape your data.
  1744. * @param mixed $conditions Conditions to match, true for all records
  1745. * @return boolean True on success, false on failure
  1746. * @access public
  1747. * @link http://book.cakephp.org/view/1031/Saving-Your-Data
  1748. */
  1749. public function updateAll($fields, $conditions = true) {
  1750. return $this->getDataSource()->update($this, $fields, null, $conditions);
  1751. }
  1752. /**
  1753. * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
  1754. *
  1755. * @param mixed $id ID of record to delete
  1756. * @param boolean $cascade Set to true to delete records that depend on this record
  1757. * @return boolean True on success
  1758. * @access public
  1759. * @link http://book.cakephp.org/view/1036/delete
  1760. */
  1761. public function delete($id = null, $cascade = true) {
  1762. if (!empty($id)) {
  1763. $this->id = $id;
  1764. }
  1765. $id = $this->id;
  1766. if ($this->beforeDelete($cascade)) {
  1767. $filters = $this->Behaviors->trigger(
  1768. 'beforeDelete',
  1769. array(&$this, $cascade),
  1770. array('break' => true, 'breakOn' => array(false, null))
  1771. );
  1772. if (!$filters || !$this->exists()) {
  1773. return false;
  1774. }
  1775. $db = $this->getDataSource();
  1776. $this->_deleteDependent($id, $cascade);
  1777. $this->_deleteLinks($id);
  1778. $this->id = $id;
  1779. if (!empty($this->belongsTo)) {
  1780. $keys = $this->find('first', array(
  1781. 'fields' => $this->__collectForeignKeys(),
  1782. 'conditions' => array($this->alias . '.' . $this->primaryKey => $id)
  1783. ));
  1784. }
  1785. if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
  1786. if (!empty($this->belongsTo)) {
  1787. $this->updateCounterCache($keys[$this->alias]);
  1788. }
  1789. $this->Behaviors->trigger('afterDelete', array(&$this));
  1790. $this->afterDelete();
  1791. $this->_clearCache();
  1792. $this->id = false;
  1793. return true;
  1794. }
  1795. }
  1796. return false;
  1797. }
  1798. /**
  1799. * Cascades model deletes through associated hasMany and hasOne child records.
  1800. *
  1801. * @param string $id ID of record that was deleted
  1802. * @param boolean $cascade Set to true to delete records that depend on this record
  1803. * @return void
  1804. */
  1805. protected function _deleteDependent($id, $cascade) {
  1806. if (!empty($this->__backAssociation)) {
  1807. $savedAssociatons = $this->__backAssociation;
  1808. $this->__backAssociation = array();
  1809. }
  1810. foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) {
  1811. if ($data['dependent'] === true && $cascade === true) {
  1812. $model = $this->{$assoc};
  1813. $conditions = array($model->escapeField($data['foreignKey']) => $id);
  1814. if ($data['conditions']) {
  1815. $conditions = array_merge((array)$data['conditions'], $conditions);
  1816. }
  1817. $model->recursive = -1;
  1818. if (isset($data['exclusive']) && $data['exclusive']) {
  1819. $model->deleteAll($conditions);
  1820. } else {
  1821. $records = $model->find('all', array(
  1822. 'conditions' => $conditions, 'fields' => $model->primaryKey
  1823. ));
  1824. if (!empty($records)) {
  1825. foreach ($records as $record) {
  1826. $model->delete($record[$model->alias][$model->primaryKey]);
  1827. }
  1828. }
  1829. }
  1830. }
  1831. }
  1832. if (isset($savedAssociatons)) {
  1833. $this->__backAssociation = $savedAssociatons;
  1834. }
  1835. }
  1836. /**
  1837. * Cascades model deletes through HABTM join keys.
  1838. *
  1839. * @param string $id ID of record that was deleted
  1840. * @return void
  1841. */
  1842. protected function _deleteLinks($id) {
  1843. foreach ($this->hasAndBelongsToMany as $assoc => $data) {
  1844. list($plugin, $joinModel) = pluginSplit($data['with']);
  1845. $records = $this->{$joinModel}->find('all', array(
  1846. 'conditions' => array_merge(array($this->{$joinModel}->escapeField($data['foreignKey']) => $id)),
  1847. 'fields' => $this->{$joinModel}->primaryKey,
  1848. 'recursive' => -1
  1849. ));
  1850. if (!empty($records)) {
  1851. foreach ($records as $record) {
  1852. $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]);
  1853. }
  1854. }
  1855. }
  1856. }
  1857. /**
  1858. * Deletes multiple model records based on a set of conditions.
  1859. *
  1860. * @param mixed $conditions Conditions to match
  1861. * @param boolean $cascade Set to true to delete records that depend on this record
  1862. * @param boolean $callbacks Run callbacks
  1863. * @return boolean True on success, false on failure
  1864. * @access public
  1865. * @link http://book.cakephp.org/view/1038/deleteAll
  1866. */
  1867. public function deleteAll($conditions, $cascade = true, $callbacks = false) {
  1868. if (empty($conditions)) {
  1869. return false;
  1870. }
  1871. $db = $this->getDataSource();
  1872. if (!$cascade && !$callbacks) {
  1873. return $db->delete($this, $conditions);
  1874. } else {
  1875. $ids = $this->find('all', array_merge(array(
  1876. 'fields' => "{$this->alias}.{$this->primaryKey}",
  1877. 'recursive' => 0), compact('conditions'))
  1878. );
  1879. if ($ids === false) {
  1880. return false;
  1881. }
  1882. $ids = Set::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
  1883. if (empty($ids)) {
  1884. return true;
  1885. }
  1886. if ($callbacks) {
  1887. $_id = $this->id;
  1888. $result = true;
  1889. foreach ($ids as $id) {
  1890. $result = ($result && $this->delete($id, $cascade));
  1891. }
  1892. $this->id = $_id;
  1893. return $result;
  1894. } else {
  1895. foreach ($ids as $id) {
  1896. $this->_deleteLinks($id);
  1897. if ($cascade) {
  1898. $this->_deleteDependent($id, $cascade);
  1899. }
  1900. }
  1901. return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids));
  1902. }
  1903. }
  1904. }
  1905. /**
  1906. * Collects foreign keys from associations.
  1907. *
  1908. * @return array
  1909. * @access private
  1910. */
  1911. private function __collectForeignKeys($type = 'belongsTo') {
  1912. $result = array();
  1913. foreach ($this->{$type} as $assoc => $data) {
  1914. if (isset($data['foreignKey']) && is_string($data['foreignKey'])) {
  1915. $result[$assoc] = $data['foreignKey'];
  1916. }
  1917. }
  1918. return $result;
  1919. }
  1920. /**
  1921. * Returns true if a record with the currently set ID exists.
  1922. *
  1923. * Internally calls Model::getID() to obtain the current record ID to verify,
  1924. * and then performs a Model::find('count') on the currently configured datasource
  1925. * to ascertain the existence of the record in persistent storage.
  1926. *
  1927. * @return boolean True if such a record exists
  1928. */
  1929. public function exists() {
  1930. if ($this->getID() === false) {
  1931. return false;
  1932. }
  1933. $conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
  1934. $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false);
  1935. return ($this->find('count', $query) > 0);
  1936. }
  1937. /**
  1938. * Returns true if a record that meets given conditions exists.
  1939. *
  1940. * @param array $conditions SQL conditions array
  1941. * @return boolean True if such a record exists
  1942. */
  1943. public function hasAny($conditions = null) {
  1944. return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
  1945. }
  1946. /**
  1947. * Queries the datasource and returns a result set array.
  1948. *
  1949. * Also used to perform notation finds, where the first argument is type of find operation to perform
  1950. * (all / first / count / neighbors / list / threaded ),
  1951. * second parameter options for finding ( indexed array, including: 'conditions', 'limit',
  1952. * 'recursive', 'page', 'fields', 'offset', 'order')
  1953. *
  1954. * Eg:
  1955. * {{{
  1956. * find('all', array(
  1957. * 'conditions' => array('name' => 'Thomas Anderson'),
  1958. * 'fields' => array('name', 'email'),
  1959. * 'order' => 'field3 DESC',
  1960. * 'recursive' => 2,
  1961. * 'group' => 'type'
  1962. * ));
  1963. * }}}
  1964. *
  1965. * In addition to the standard query keys above, you can provide Datasource, and behavior specific
  1966. * keys. For example, when using a SQL based datasource you can use the joins key to specify additional
  1967. * joins that should be part of the query.
  1968. *
  1969. * {{{
  1970. * find('all', array(
  1971. * 'conditions' => array('name' => 'Thomas Anderson'),
  1972. * 'joins' => array(
  1973. * array(
  1974. * 'alias' => 'Thought',
  1975. * 'table' => 'thoughts',
  1976. * 'type' => 'LEFT',
  1977. * 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
  1978. * )
  1979. * )
  1980. * ));
  1981. * }}}
  1982. *
  1983. * Behaviors and find types can also define custom finder keys which are passed into find().
  1984. *
  1985. * Specifying 'fields' for notation 'list':
  1986. *
  1987. * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  1988. * - If a single field is specified, 'id' is used for key and specified field is used for value.
  1989. * - If three fields are specified, they are used (in order) for key, value and group.
  1990. * - Otherwise, first and second fields are used for key and value.
  1991. *
  1992. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  1993. * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  1994. * @return array Array of records
  1995. * @link http://book.cakephp.org/view/1018/find
  1996. */
  1997. public function find($type = 'first', $query = array()) {
  1998. $this->findQueryType = $type;
  1999. $this->id = $this->getID();
  2000. $query = $this->buildQuery($type, $query);
  2001. if (is_null($query)) {
  2002. return null;
  2003. }
  2004. $results = $this->getDataSource()->read($this, $query);
  2005. $this->resetAssociations();
  2006. if ($query['callbacks'] === true || $query['callbacks'] === 'after') {
  2007. $results = $this->_filterResults($results);
  2008. }
  2009. $this->findQueryType = null;
  2010. if ($type === 'all') {
  2011. return $results;
  2012. } else {
  2013. if ($this->findMethods[$type] === true) {
  2014. return $this->{'_find' . ucfirst($type)}('after', $query, $results);
  2015. }
  2016. }
  2017. }
  2018. /**
  2019. * Builds the query array that is used by the data source to generate the query to fetch the data.
  2020. *
  2021. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
  2022. * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
  2023. * @return array Query array or null if it could not be build for some reasons
  2024. * @see Model::find()
  2025. */
  2026. public function buildQuery($type = 'first', $query = array()) {
  2027. $query = array_merge(
  2028. array(
  2029. 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null,
  2030. 'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true,
  2031. ),
  2032. (array)$query
  2033. );
  2034. if ($type !== 'all') {
  2035. if ($this->findMethods[$type] === true) {
  2036. $query = $this->{'_find' . ucfirst($type)}('before', $query);
  2037. }
  2038. }
  2039. if (!is_numeric($query['page']) || intval($query['page']) < 1) {
  2040. $query['page'] = 1;
  2041. }
  2042. if ($query['page'] > 1 && !empty($query['limit'])) {
  2043. $query['offset'] = ($query['page'] - 1) * $query['limit'];
  2044. }
  2045. if ($query['order'] === null && $this->order !== null) {
  2046. $query['order'] = $this->order;
  2047. }
  2048. $query['order'] = array($query['order']);
  2049. if ($query['callbacks'] === true || $query['callbacks'] === 'before') {
  2050. $return = $this->Behaviors->trigger(
  2051. 'beforeFind',
  2052. array(&$this, $query),
  2053. array('break' => true, 'breakOn' => array(false, null), 'modParams' => 1)
  2054. );
  2055. $query = (is_array($return)) ? $return : $query;
  2056. if ($return === false) {
  2057. return null;
  2058. }
  2059. $return = $this->beforeFind($query);
  2060. $query = (is_array($return)) ? $return : $query;
  2061. if ($return === false) {
  2062. return null;
  2063. }
  2064. }
  2065. return $query;
  2066. }
  2067. /**
  2068. * Handles the before/after filter logic for find('first') operations. Only called by Model::find().
  2069. *
  2070. * @param string $state Either "before" or "after"
  2071. * @param array $query
  2072. * @param array $data
  2073. * @return array
  2074. * @see Model::find()
  2075. */
  2076. protected function _findFirst($state, $query, $results = array()) {
  2077. if ($state === 'before') {
  2078. $query['limit'] = 1;
  2079. return $query;
  2080. } elseif ($state === 'after') {
  2081. if (empty($results[0])) {
  2082. return false;
  2083. }
  2084. return $results[0];
  2085. }
  2086. }
  2087. /**
  2088. * Handles the before/after filter logic for find('count') operations. Only called by Model::find().
  2089. *
  2090. * @param string $state Either "before" or "after"
  2091. * @param array $query
  2092. * @param array $data
  2093. * @return int The number of records found, or false
  2094. * @see Model::find()
  2095. */
  2096. protected function _findCount($state, $query, $results = array()) {
  2097. if ($state === 'before') {
  2098. $db = $this->getDataSource();
  2099. if (empty($query['fields'])) {
  2100. $query['fields'] = $db->calculate($this, 'count');
  2101. } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) {
  2102. $query['fields'] = $db->calculate($this, 'count', array(
  2103. $db->expression($query['fields']), 'count'
  2104. ));
  2105. }
  2106. $query['order'] = false;
  2107. return $query;
  2108. } elseif ($state === 'after') {
  2109. foreach (array(0, $this->alias) as $key) {
  2110. if (isset($results[0][$key]['count'])) {
  2111. if (count($results) > 1) {
  2112. return intval(array_sum(Set::extract('/' . $key . '/count', $results)));
  2113. } else {
  2114. return intval($results[0][$key]['count']);
  2115. }
  2116. }
  2117. }
  2118. return false;
  2119. }
  2120. }
  2121. /**
  2122. * Handles the before/after filter logic for find('list') operations. Only called by Model::find().
  2123. *
  2124. * @param string $state Either "before" or "after"
  2125. * @param array $query
  2126. * @param array $data
  2127. * @return array Key/value pairs of primary keys/display field values of all records found
  2128. * @see Model::find()
  2129. */
  2130. protected function _findList($state, $query, $results = array()) {
  2131. if ($state === 'before') {
  2132. if (empty($query['fields'])) {
  2133. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}");
  2134. $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null);
  2135. } else {
  2136. if (!is_array($query['fields'])) {
  2137. $query['fields'] = String::tokenize($query['fields']);
  2138. }
  2139. if (count($query['fields']) === 1) {
  2140. if (strpos($query['fields'][0], '.') === false) {
  2141. $query['fields'][0] = $this->alias . '.' . $query['fields'][0];
  2142. }
  2143. $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null);
  2144. $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]);
  2145. } elseif (count($query['fields']) === 3) {
  2146. for ($i = 0; $i < 3; $i++) {
  2147. if (strpos($query['fields'][$i], '.') === false) {
  2148. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2149. }
  2150. }
  2151. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]);
  2152. } else {
  2153. for ($i = 0; $i < 2; $i++) {
  2154. if (strpos($query['fields'][$i], '.') === false) {
  2155. $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i];
  2156. }
  2157. }
  2158. $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null);
  2159. }
  2160. }
  2161. if (!isset($query['recursive']) || $query['recursive'] === null) {
  2162. $query['recursive'] = -1;
  2163. }
  2164. list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list;
  2165. return $query;
  2166. } elseif ($state === 'after') {
  2167. if (empty($results)) {
  2168. return array();
  2169. }
  2170. $lst = $query['list'];
  2171. return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
  2172. }
  2173. }
  2174. /**
  2175. * Detects the previous field's value, then uses logic to find the 'wrapping'
  2176. * rows and return them.
  2177. *
  2178. * @param string $state Either "before" or "after"
  2179. * @param mixed $query
  2180. * @param array $results
  2181. * @return array
  2182. */
  2183. protected function _findNeighbors($state, $query, $results = array()) {
  2184. if ($state === 'before') {
  2185. extract($query);
  2186. $conditions = (array)$conditions;
  2187. if (isset($field) && isset($value)) {
  2188. if (strpos($field, '.') === false) {
  2189. $field = $this->alias . '.' . $field;
  2190. }
  2191. } else {
  2192. $field = $this->alias . '.' . $this->primaryKey;
  2193. $value = $this->id;
  2194. }
  2195. $query['conditions'] = array_merge($conditions, array($field . ' <' => $value));
  2196. $query['order'] = $field . ' DESC';
  2197. $query['limit'] = 1;
  2198. $query['field'] = $field;
  2199. $query['value'] = $value;
  2200. return $query;
  2201. } elseif ($state === 'after') {
  2202. extract($query);
  2203. unset($query['conditions'][$field . ' <']);
  2204. $return = array();
  2205. if (isset($results[0])) {
  2206. $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]);
  2207. $query['conditions'][$field . ' >='] = $prevVal[0];
  2208. $query['conditions'][$field . ' !='] = $value;
  2209. $query['limit'] = 2;
  2210. } else {
  2211. $return['prev'] = null;
  2212. $query['conditions'][$field . ' >'] = $value;
  2213. $query['limit'] = 1;
  2214. }
  2215. $query['order'] = $field . ' ASC';
  2216. $return2 = $this->find('all', $query);
  2217. if (!array_key_exists('prev', $return)) {
  2218. $return['prev'] = $return2[0];
  2219. }
  2220. if (count($return2) === 2) {
  2221. $return['next'] = $return2[1];
  2222. } elseif (count($return2) === 1 && !$return['prev']) {
  2223. $return['next'] = $return2[0];
  2224. } else {
  2225. $return['next'] = null;
  2226. }
  2227. return $return;
  2228. }
  2229. }
  2230. /**
  2231. * In the event of ambiguous results returned (multiple top level results, with different parent_ids)
  2232. * top level results with different parent_ids to the first result will be dropped
  2233. *
  2234. * @param mixed $state
  2235. * @param mixed $query
  2236. * @param array $results
  2237. * @return array Threaded results
  2238. */
  2239. protected function _findThreaded($state, $query, $results = array()) {
  2240. if ($state === 'before') {
  2241. return $query;
  2242. } elseif ($state === 'after') {
  2243. $return = $idMap = array();
  2244. $ids = Set::extract($results, '{n}.' . $this->alias . '.' . $this->primaryKey);
  2245. foreach ($results as $result) {
  2246. $result['children'] = array();
  2247. $id = $result[$this->alias][$this->primaryKey];
  2248. $parentId = $result[$this->alias]['parent_id'];
  2249. if (isset($idMap[$id]['children'])) {
  2250. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  2251. } else {
  2252. $idMap[$id] = array_merge($result, array('children' => array()));
  2253. }
  2254. if (!$parentId || !in_array($parentId, $ids)) {
  2255. $return[] =& $idMap[$id];
  2256. } else {
  2257. $idMap[$parentId]['children'][] =& $idMap[$id];
  2258. }
  2259. }
  2260. if (count($return) > 1) {
  2261. $ids = array_unique(Set::extract('/' . $this->alias . '/parent_id', $return));
  2262. if (count($ids) > 1) {
  2263. $root = $return[0][$this->alias]['parent_id'];
  2264. foreach ($return as $key => $value) {
  2265. if ($value[$this->alias]['parent_id'] != $root) {
  2266. unset($return[$key]);
  2267. }
  2268. }
  2269. }
  2270. }
  2271. return $return;
  2272. }
  2273. }
  2274. /**
  2275. * Passes query results through model and behavior afterFilter() methods.
  2276. *
  2277. * @param array Results to filter
  2278. * @param boolean $primary If this is the primary model results (results from model where the find operation was performed)
  2279. * @return array Set of filtered results
  2280. */
  2281. protected function _filterResults($results, $primary = true) {
  2282. $return = $this->Behaviors->trigger(
  2283. 'afterFind',
  2284. array(&$this, $results, $primary),
  2285. array('modParams' => 1)
  2286. );
  2287. if ($return !== true) {
  2288. $results = $return;
  2289. }
  2290. return $this->afterFind($results, $primary);
  2291. }
  2292. /**
  2293. * This resets the association arrays for the model back
  2294. * to those originally defined in the model. Normally called at the end
  2295. * of each call to Model::find()
  2296. *
  2297. * @return boolean Success
  2298. */
  2299. public function resetAssociations() {
  2300. if (!empty($this->__backAssociation)) {
  2301. foreach ($this->__associations as $type) {
  2302. if (isset($this->__backAssociation[$type])) {
  2303. $this->{$type} = $this->__backAssociation[$type];
  2304. }
  2305. }
  2306. $this->__backAssociation = array();
  2307. }
  2308. foreach ($this->__associations as $type) {
  2309. foreach ($this->{$type} as $key => $name) {
  2310. if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) {
  2311. $this->{$key}->resetAssociations();
  2312. }
  2313. }
  2314. }
  2315. $this->__backAssociation = array();
  2316. return true;
  2317. }
  2318. /**
  2319. * Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
  2320. *
  2321. * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data)
  2322. * @param boolean $or If false, all fields specified must match in order for a false return value
  2323. * @return boolean False if any records matching any fields are found
  2324. */
  2325. public function isUnique($fields, $or = true) {
  2326. if (!is_array($fields)) {
  2327. $fields = func_get_args();
  2328. if (is_bool($fields[count($fields) - 1])) {
  2329. $or = $fields[count($fields) - 1];
  2330. unset($fields[count($fields) - 1]);
  2331. }
  2332. }
  2333. foreach ($fields as $field => $value) {
  2334. if (is_numeric($field)) {
  2335. unset($fields[$field]);
  2336. $field = $value;
  2337. if (isset($this->data[$this->alias][$field])) {
  2338. $value = $this->data[$this->alias][$field];
  2339. } else {
  2340. $value = null;
  2341. }
  2342. }
  2343. if (strpos($field, '.') === false) {
  2344. unset($fields[$field]);
  2345. $fields[$this->alias . '.' . $field] = $value;
  2346. }
  2347. }
  2348. if ($or) {
  2349. $fields = array('or' => $fields);
  2350. }
  2351. if (!empty($this->id)) {
  2352. $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
  2353. }
  2354. return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
  2355. }
  2356. /**
  2357. * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
  2358. *
  2359. * @param string $sql SQL statement
  2360. * @return array Resultset
  2361. * @access public
  2362. * @link http://book.cakephp.org/view/1027/query
  2363. */
  2364. public function query() {
  2365. $params = func_get_args();
  2366. $db = $this->getDataSource();
  2367. return call_user_func_array(array(&$db, 'query'), $params);
  2368. }
  2369. /**
  2370. * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations
  2371. * that use the 'with' key as well. Since __saveMulti is incapable of exiting a save operation.
  2372. *
  2373. * Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
  2374. *
  2375. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2376. * @return boolean True if there are no errors
  2377. * @access public
  2378. * @link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller
  2379. */
  2380. public function validates($options = array()) {
  2381. $errors = $this->invalidFields($options);
  2382. if (empty($errors) && $errors !== false) {
  2383. $errors = $this->__validateWithModels($options);
  2384. }
  2385. if (is_array($errors)) {
  2386. return count($errors) === 0;
  2387. }
  2388. return $errors;
  2389. }
  2390. /**
  2391. * Returns an array of fields that have failed validation. On the current model.
  2392. *
  2393. * @param string $options An optional array of custom options to be made available in the beforeValidate callback
  2394. * @return array Array of invalid fields
  2395. * @see Model::validates()
  2396. * @access public
  2397. * @link http://book.cakephp.org/view/1182/Validating-Data-from-the-Controller
  2398. */
  2399. public function invalidFields($options = array()) {
  2400. if (
  2401. !$this->Behaviors->trigger(
  2402. 'beforeValidate',
  2403. array(&$this, $options),
  2404. array('break' => true, 'breakOn' => false)
  2405. ) ||
  2406. $this->beforeValidate($options) === false
  2407. ) {
  2408. return false;
  2409. }
  2410. if (!isset($this->validate) || empty($this->validate)) {
  2411. return $this->validationErrors;
  2412. }
  2413. $data = $this->data;
  2414. $methods = array_map('strtolower', get_class_methods($this));
  2415. $behaviorMethods = array_keys($this->Behaviors->methods());
  2416. if (isset($data[$this->alias])) {
  2417. $data = $data[$this->alias];
  2418. } elseif (!is_array($data)) {
  2419. $data = array();
  2420. }
  2421. $exists = $this->exists();
  2422. $_validate = $this->validate;
  2423. $whitelist = $this->whitelist;
  2424. if (!empty($options['fieldList'])) {
  2425. $whitelist = $options['fieldList'];
  2426. }
  2427. if (!empty($whitelist)) {
  2428. $validate = array();
  2429. foreach ((array)$whitelist as $f) {
  2430. if (!empty($this->validate[$f])) {
  2431. $validate[$f] = $this->validate[$f];
  2432. }
  2433. }
  2434. $this->validate = $validate;
  2435. }
  2436. foreach ($this->validate as $fieldName => $ruleSet) {
  2437. if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) {
  2438. $ruleSet = array($ruleSet);
  2439. }
  2440. $default = array(
  2441. 'allowEmpty' => null,
  2442. 'required' => null,
  2443. 'rule' => 'blank',
  2444. 'last' => true,
  2445. 'on' => null
  2446. );
  2447. foreach ($ruleSet as $index => $validator) {
  2448. if (!is_array($validator)) {
  2449. $validator = array('rule' => $validator);
  2450. }
  2451. $validator = array_merge($default, $validator);
  2452. $validationDomain = $this->validationDomain;
  2453. if (empty($validationDomain)) {
  2454. $validationDomain = 'default';
  2455. }
  2456. if (isset($validator['message'])) {
  2457. $message = $validator['message'];
  2458. } else {
  2459. $message = __d('cake_dev', 'This field cannot be left blank');
  2460. }
  2461. if (
  2462. empty($validator['on']) || ($validator['on'] == 'create' &&
  2463. !$exists) || ($validator['on'] == 'update' && $exists
  2464. )) {
  2465. $required = (
  2466. (!isset($data[$fieldName]) && $validator['required'] === true) ||
  2467. (
  2468. isset($data[$fieldName]) && (empty($data[$fieldName]) &&
  2469. !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false
  2470. )
  2471. );
  2472. if ($required) {
  2473. $this->invalidate($fieldName, __d($validationDomain, $message));
  2474. if ($validator['last']) {
  2475. break;
  2476. }
  2477. } elseif (array_key_exists($fieldName, $data)) {
  2478. if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) {
  2479. break;
  2480. }
  2481. if (is_array($validator['rule'])) {
  2482. $rule = $validator['rule'][0];
  2483. unset($validator['rule'][0]);
  2484. $ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule']));
  2485. } else {
  2486. $rule = $validator['rule'];
  2487. $ruleParams = array($data[$fieldName]);
  2488. }
  2489. $valid = true;
  2490. if (in_array(strtolower($rule), $methods)) {
  2491. $ruleParams[] = $validator;
  2492. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2493. $valid = $this->dispatchMethod($rule, $ruleParams);
  2494. } elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) {
  2495. $ruleParams[] = $validator;
  2496. $ruleParams[0] = array($fieldName => $ruleParams[0]);
  2497. $valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams);
  2498. } elseif (method_exists('Validation', $rule)) {
  2499. $valid = call_user_func_array(array('Validation', $rule), $ruleParams);
  2500. } elseif (!is_array($validator['rule'])) {
  2501. $valid = preg_match($rule, $data[$fieldName]);
  2502. } elseif (Configure::read('debug') > 0) {
  2503. trigger_error(__d('cake_dev', 'Could not find validation handler %s for %s', $rule, $fieldName), E_USER_WARNING);
  2504. }
  2505. if (!$valid || (is_string($valid) && strlen($valid) > 0)) {
  2506. if (is_string($valid) && strlen($valid) > 0) {
  2507. $validator['message'] = $valid;
  2508. } elseif (!isset($validator['message'])) {
  2509. if (is_string($index)) {
  2510. $validator['message'] = $index;
  2511. } elseif (is_numeric($index) && count($ruleSet) > 1) {
  2512. $validator['message'] = $index + 1;
  2513. } else {
  2514. $validator['message'] = __d($validationDomain, $message);
  2515. }
  2516. } elseif (is_array($validator['message'])) {
  2517. if (count($validator['message']) > 1) {
  2518. $args = array_slice($validator['message'], 1);
  2519. } else {
  2520. $args = $validator['rule'];
  2521. }
  2522. $validator['message'] = __d($validationDomain, $validator['message'][0], $args);
  2523. }
  2524. $this->invalidate($fieldName, $validator['message']);
  2525. if ($validator['last']) {
  2526. break;
  2527. }
  2528. }
  2529. }
  2530. }
  2531. }
  2532. }
  2533. $this->validate = $_validate;
  2534. return $this->validationErrors;
  2535. }
  2536. /**
  2537. * Runs validation for hasAndBelongsToMany associations that have 'with' keys
  2538. * set. And data in the set() data set.
  2539. *
  2540. * @param array $options Array of options to use on Valdation of with models
  2541. * @return boolean Failure of validation on with models.
  2542. * @access private
  2543. * @see Model::validates()
  2544. */
  2545. private function __validateWithModels($options) {
  2546. $valid = true;
  2547. foreach ($this->hasAndBelongsToMany as $assoc => $association) {
  2548. if (empty($association['with']) || !isset($this->data[$assoc])) {
  2549. continue;
  2550. }
  2551. list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']);
  2552. $data = $this->data[$assoc];
  2553. $newData = array();
  2554. foreach ((array)$data as $row) {
  2555. if (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2556. $newData[] = $row;
  2557. } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
  2558. $newData[] = $row[$join];
  2559. }
  2560. }
  2561. if (empty($newData)) {
  2562. continue;
  2563. }
  2564. foreach ($newData as $data) {
  2565. $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $this->id;
  2566. $this->{$join}->create($data);
  2567. $valid = ($valid && $this->{$join}->validates($options));
  2568. }
  2569. }
  2570. return $valid;
  2571. }
  2572. /**
  2573. * Marks a field as invalid, optionally setting the name of validation
  2574. * rule (in case of multiple validation for field) that was broken.
  2575. *
  2576. * @param string $field The name of the field to invalidate
  2577. * @param mixed $value Name of validation rule that was not failed, or validation message to
  2578. * be returned. If no validation key is provided, defaults to true.
  2579. */
  2580. public function invalidate($field, $value = true) {
  2581. if (!is_array($this->validationErrors)) {
  2582. $this->validationErrors = array();
  2583. }
  2584. $this->validationErrors[$field] []= $value;
  2585. }
  2586. /**
  2587. * Returns true if given field name is a foreign key in this model.
  2588. *
  2589. * @param string $field Returns true if the input string ends in "_id"
  2590. * @return boolean True if the field is a foreign key listed in the belongsTo array.
  2591. */
  2592. public function isForeignKey($field) {
  2593. $foreignKeys = array();
  2594. if (!empty($this->belongsTo)) {
  2595. foreach ($this->belongsTo as $assoc => $data) {
  2596. $foreignKeys[] = $data['foreignKey'];
  2597. }
  2598. }
  2599. return in_array($field, $foreignKeys);
  2600. }
  2601. /**
  2602. * Escapes the field name and prepends the model name. Escaping is done according to the
  2603. * current database driver's rules.
  2604. *
  2605. * @param string $field Field to escape (e.g: id)
  2606. * @param string $alias Alias for the model (e.g: Post)
  2607. * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`).
  2608. */
  2609. public function escapeField($field = null, $alias = null) {
  2610. if (empty($alias)) {
  2611. $alias = $this->alias;
  2612. }
  2613. if (empty($field)) {
  2614. $field = $this->primaryKey;
  2615. }
  2616. $db = $this->getDataSource();
  2617. if (strpos($field, $db->name($alias) . '.') === 0) {
  2618. return $field;
  2619. }
  2620. return $db->name($alias . '.' . $field);
  2621. }
  2622. /**
  2623. * Returns the current record's ID
  2624. *
  2625. * @param integer $list Index on which the composed ID is located
  2626. * @return mixed The ID of the current record, false if no ID
  2627. */
  2628. public function getID($list = 0) {
  2629. if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) {
  2630. return false;
  2631. }
  2632. if (!is_array($this->id)) {
  2633. return $this->id;
  2634. }
  2635. if (empty($this->id)) {
  2636. return false;
  2637. }
  2638. if (isset($this->id[$list]) && !empty($this->id[$list])) {
  2639. return $this->id[$list];
  2640. } elseif (isset($this->id[$list])) {
  2641. return false;
  2642. }
  2643. foreach ($this->id as $id) {
  2644. return $id;
  2645. }
  2646. return false;
  2647. }
  2648. /**
  2649. * Returns the ID of the last record this model inserted.
  2650. *
  2651. * @return mixed Last inserted ID
  2652. */
  2653. public function getLastInsertID() {
  2654. return $this->getInsertID();
  2655. }
  2656. /**
  2657. * Returns the ID of the last record this model inserted.
  2658. *
  2659. * @return mixed Last inserted ID
  2660. */
  2661. public function getInsertID() {
  2662. return $this->__insertID;
  2663. }
  2664. /**
  2665. * Sets the ID of the last record this model inserted
  2666. *
  2667. * @param mixed Last inserted ID
  2668. */
  2669. public function setInsertID($id) {
  2670. $this->__insertID = $id;
  2671. }
  2672. /**
  2673. * Returns the number of rows returned from the last query.
  2674. *
  2675. * @return int Number of rows
  2676. */
  2677. public function getNumRows() {
  2678. return $this->getDataSource()->lastNumRows();
  2679. }
  2680. /**
  2681. * Returns the number of rows affected by the last query.
  2682. *
  2683. * @return int Number of rows
  2684. */
  2685. public function getAffectedRows() {
  2686. return $this->getDataSource()->lastAffected();
  2687. }
  2688. /**
  2689. * Sets the DataSource to which this model is bound.
  2690. *
  2691. * @param string $dataSource The name of the DataSource, as defined in app/Config/database.php
  2692. * @return boolean True on success
  2693. */
  2694. public function setDataSource($dataSource = null) {
  2695. $oldConfig = $this->useDbConfig;
  2696. if ($dataSource != null) {
  2697. $this->useDbConfig = $dataSource;
  2698. }
  2699. $db = ConnectionManager::getDataSource($this->useDbConfig);
  2700. if (!empty($oldConfig) && isset($db->config['prefix'])) {
  2701. $oldDb = ConnectionManager::getDataSource($oldConfig);
  2702. if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) {
  2703. $this->tablePrefix = $db->config['prefix'];
  2704. }
  2705. } elseif (isset($db->config['prefix'])) {
  2706. $this->tablePrefix = $db->config['prefix'];
  2707. }
  2708. if (empty($db) || !is_object($db)) {
  2709. throw new MissingConnectionException(array('class' => $this->name));
  2710. }
  2711. }
  2712. /**
  2713. * Gets the DataSource to which this model is bound.
  2714. *
  2715. * @return object A DataSource object
  2716. */
  2717. public function getDataSource() {
  2718. if (!$this->__sourceConfigured && $this->useTable !== false) {
  2719. $this->__sourceConfigured = true;
  2720. $this->setSource($this->useTable);
  2721. }
  2722. return ConnectionManager::getDataSource($this->useDbConfig);
  2723. }
  2724. /**
  2725. * Get associations
  2726. *
  2727. * @return array
  2728. */
  2729. public function associations() {
  2730. return $this->__associations;
  2731. }
  2732. /**
  2733. * Gets all the models with which this model is associated.
  2734. *
  2735. * @param string $type Only result associations of this type
  2736. * @return array Associations
  2737. */
  2738. public function getAssociated($type = null) {
  2739. if ($type == null) {
  2740. $associated = array();
  2741. foreach ($this->__associations as $assoc) {
  2742. if (!empty($this->{$assoc})) {
  2743. $models = array_keys($this->{$assoc});
  2744. foreach ($models as $m) {
  2745. $associated[$m] = $assoc;
  2746. }
  2747. }
  2748. }
  2749. return $associated;
  2750. } elseif (in_array($type, $this->__associations)) {
  2751. if (empty($this->{$type})) {
  2752. return array();
  2753. }
  2754. return array_keys($this->{$type});
  2755. } else {
  2756. $assoc = array_merge(
  2757. $this->hasOne,
  2758. $this->hasMany,
  2759. $this->belongsTo,
  2760. $this->hasAndBelongsToMany
  2761. );
  2762. if (array_key_exists($type, $assoc)) {
  2763. foreach ($this->__associations as $a) {
  2764. if (isset($this->{$a}[$type])) {
  2765. $assoc[$type]['association'] = $a;
  2766. break;
  2767. }
  2768. }
  2769. return $assoc[$type];
  2770. }
  2771. return null;
  2772. }
  2773. }
  2774. /**
  2775. * Gets the name and fields to be used by a join model. This allows specifying join fields
  2776. * in the association definition.
  2777. *
  2778. * @param object $model The model to be joined
  2779. * @param mixed $with The 'with' key of the model association
  2780. * @param array $keys Any join keys which must be merged with the keys queried
  2781. * @return array
  2782. */
  2783. public function joinModel($assoc, $keys = array()) {
  2784. if (is_string($assoc)) {
  2785. list(, $assoc) = pluginSplit($assoc);
  2786. return array($assoc, array_keys($this->{$assoc}->schema()));
  2787. } elseif (is_array($assoc)) {
  2788. $with = key($assoc);
  2789. return array($with, array_unique(array_merge($assoc[$with], $keys)));
  2790. }
  2791. trigger_error(
  2792. __d('cake_dev', 'Invalid join model settings in %s', $model->alias),
  2793. E_USER_WARNING
  2794. );
  2795. }
  2796. /**
  2797. * Called before each find operation. Return false if you want to halt the find
  2798. * call, otherwise return the (modified) query data.
  2799. *
  2800. * @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
  2801. * @return mixed true if the operation should continue, false if it should abort; or, modified
  2802. * $queryData to continue with new $queryData
  2803. * @access public
  2804. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeFind-1049
  2805. */
  2806. public function beforeFind($queryData) {
  2807. return true;
  2808. }
  2809. /**
  2810. * Called after each find operation. Can be used to modify any results returned by find().
  2811. * Return value should be the (modified) results.
  2812. *
  2813. * @param mixed $results The results of the find operation
  2814. * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association)
  2815. * @return mixed Result of the find operation
  2816. * @access public
  2817. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterFind-1050
  2818. */
  2819. public function afterFind($results, $primary = false) {
  2820. return $results;
  2821. }
  2822. /**
  2823. * Called before each save operation, after validation. Return a non-true result
  2824. * to halt the save.
  2825. *
  2826. * @return boolean True if the operation should continue, false if it should abort
  2827. * @access public
  2828. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeSave-1052
  2829. */
  2830. public function beforeSave($options = array()) {
  2831. return true;
  2832. }
  2833. /**
  2834. * Called after each successful save operation.
  2835. *
  2836. * @param boolean $created True if this save created a new record
  2837. * @access public
  2838. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterSave-1053
  2839. */
  2840. public function afterSave($created) {
  2841. }
  2842. /**
  2843. * Called before every deletion operation.
  2844. *
  2845. * @param boolean $cascade If true records that depend on this record will also be deleted
  2846. * @return boolean True if the operation should continue, false if it should abort
  2847. * @access public
  2848. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeDelete-1054
  2849. */
  2850. public function beforeDelete($cascade = true) {
  2851. return true;
  2852. }
  2853. /**
  2854. * Called after every deletion operation.
  2855. *
  2856. * @access public
  2857. * @link http://book.cakephp.org/view/1048/Callback-Methods#afterDelete-1055
  2858. */
  2859. public function afterDelete() {
  2860. }
  2861. /**
  2862. * Called during validation operations, before validation. Please note that custom
  2863. * validation rules can be defined in $validate.
  2864. *
  2865. * @return boolean True if validate operation should continue, false to abort
  2866. * @param $options array Options passed from model::save(), see $options of model::save().
  2867. * @access public
  2868. * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeValidate-1051
  2869. */
  2870. public function beforeValidate($options = array()) {
  2871. return true;
  2872. }
  2873. /**
  2874. * Called when a DataSource-level error occurs.
  2875. *
  2876. * @access public
  2877. * @link http://book.cakephp.org/view/1048/Callback-Methods#onError-1056
  2878. */
  2879. public function onError() {
  2880. }
  2881. /**
  2882. * Private method. Clears cache for this model.
  2883. *
  2884. * @param string $type If null this deletes cached views if Cache.check is true
  2885. * Will be used to allow deleting query cache also
  2886. * @return boolean true on delete
  2887. * @access protected
  2888. * @todo
  2889. */
  2890. protected function _clearCache($type = null) {
  2891. if ($type === null) {
  2892. if (Configure::read('Cache.check') === true) {
  2893. $assoc[] = strtolower(Inflector::pluralize($this->alias));
  2894. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias)));
  2895. foreach ($this->__associations as $key => $association) {
  2896. foreach ($this->$association as $key => $className) {
  2897. $check = strtolower(Inflector::pluralize($className['className']));
  2898. if (!in_array($check, $assoc)) {
  2899. $assoc[] = strtolower(Inflector::pluralize($className['className']));
  2900. $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className'])));
  2901. }
  2902. }
  2903. }
  2904. clearCache($assoc);
  2905. return true;
  2906. }
  2907. } else {
  2908. //Will use for query cache deleting
  2909. }
  2910. }
  2911. }