Model.php 111 KB

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