Model.php 111 KB

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