Model.php 108 KB

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