Model.php 105 KB

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