Model.php 115 KB

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