Model.php 111 KB

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