Model.php 110 KB

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