Model.php 90 KB

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