Model.php 105 KB

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