PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/craft/plugins/sproutforms/services/SproutForms_EntriesService.php

https://bitbucket.org/graphicactivity/rollingstills
PHP | 624 lines | 399 code | 111 blank | 114 comment | 35 complexity | bb0ea5dc32f39c46123eff20619588dd MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.1, MIT
  1. <?php
  2. namespace Craft;
  3. use Guzzle\Http\Client;
  4. class SproutForms_EntriesService extends BaseApplicationComponent
  5. {
  6. public $fakeIt = false;
  7. protected $entryRecord;
  8. /**
  9. * @param object $entryRecord
  10. */
  11. public function __construct($entryRecord = null)
  12. {
  13. $this->entryRecord = $entryRecord;
  14. if (is_null($this->entryRecord))
  15. {
  16. $this->entryRecord = SproutForms_EntryRecord::model();
  17. }
  18. }
  19. /**
  20. * Returns a criteria model for SproutForms_Entry elements
  21. *
  22. * @param array $attributes
  23. *
  24. * @return ElementCriteriaModel
  25. * @throws Exception
  26. */
  27. public function getCriteria(array $attributes = array())
  28. {
  29. return craft()->elements->getCriteria('SproutForms_Entry', $attributes);
  30. }
  31. /**
  32. * @param SproutForms_EntryModel $entry
  33. *
  34. * @throws \Exception
  35. * @return bool
  36. */
  37. public function forwardEntry(SproutForms_EntryModel &$entry)
  38. {
  39. if (!$entry->validate())
  40. {
  41. sproutForms()->log($entry->getErrors());
  42. return false;
  43. }
  44. // Setting the title explicitly to perform field validation
  45. $entry->getContent()->setAttribute('title', sha1(time()));
  46. $fields = $entry->getPayloadFields();
  47. $endpoint = $entry->form->submitAction;
  48. if (empty($endpoint) || !filter_var($endpoint, FILTER_VALIDATE_URL))
  49. {
  50. sproutForms()->log('{form} has no submit action or submit action is an invalid URL', array('form' => $entry->formName));
  51. return false;
  52. }
  53. $client = new Client();
  54. // Annoying context switching
  55. $oldFieldContext = craft()->content->fieldContext;
  56. $oldContentTable = craft()->content->contentTable;
  57. craft()->content->fieldContext = $entry->getFieldContext();
  58. craft()->content->contentTable = $entry->getContentTable();
  59. $success = craft()->content->validateContent($entry);
  60. craft()->content->fieldContext = $oldFieldContext;
  61. craft()->content->contentTable = $oldContentTable;
  62. if (!$success)
  63. {
  64. $entry->addErrors($entry->getContent()->getErrors());
  65. sproutForms()->log($entry->getErrors());
  66. return false;
  67. }
  68. try
  69. {
  70. sproutForms()->log($fields);
  71. $response = $client->post($endpoint, null, $fields)->send();
  72. sproutForms()->log($response->getBody());
  73. return true;
  74. }
  75. catch (\Exception $e)
  76. {
  77. $entry->addError('general', $e->getMessage());
  78. return false;
  79. }
  80. }
  81. /**
  82. * @param SproutForms_EntryModel $entry
  83. *
  84. * @throws \Exception
  85. * @return bool
  86. */
  87. public function saveEntry(SproutForms_EntryModel &$entry)
  88. {
  89. $isNewEntry = !$entry->id;
  90. if ($entry->id)
  91. {
  92. $entryRecord = SproutForms_EntryRecord::model()->findById($entry->id);
  93. if (!$entryRecord)
  94. {
  95. throw new Exception(Craft::t('No entry exists with id “{id}”', array('id' => $entry->id)));
  96. }
  97. }
  98. else
  99. {
  100. $entryRecord = new SproutForms_EntryRecord();
  101. }
  102. $entryRecord->formId = $entry->formId;
  103. $entryRecord->ipAddress = $entry->ipAddress;
  104. $entryRecord->userAgent = $entry->userAgent;
  105. $entryRecord->statusId = $entry->statusId != null ? $entry->statusId : $this->getDefaultEntryStatusId();
  106. $entryRecord->validate();
  107. $entry->addErrors($entryRecord->getErrors());
  108. Craft::import('plugins.sproutforms.events.SproutForms_OnBeforeSaveEntryEvent');
  109. $event = new SproutForms_OnBeforeSaveEntryEvent(
  110. $this, array(
  111. 'entry' => $entry,
  112. 'isNewEntry' => $isNewEntry
  113. )
  114. );
  115. craft()->sproutForms->onBeforeSaveEntry($event);
  116. if (!$entry->hasErrors())
  117. {
  118. try
  119. {
  120. $form = sproutForms()->forms->getFormById($entry->formId);
  121. $entry->getContent()->title = craft()->templates->renderObjectTemplate($form->titleFormat, $entry);
  122. $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
  123. if ($event->isValid)
  124. {
  125. $oldFieldContext = craft()->content->fieldContext;
  126. $oldContentTable = craft()->content->contentTable;
  127. craft()->content->fieldContext = $entry->getFieldContext();
  128. craft()->content->contentTable = $entry->getContentTable();
  129. SproutFormsPlugin::log('Transaction: Event is Valid');
  130. $success = craft()->elements->saveElement($entry);
  131. if ($success)
  132. {
  133. SproutFormsPlugin::log('Element Saved: ' . $success);
  134. // Now that we have an element ID, save it on the other stuff
  135. if ($isNewEntry)
  136. {
  137. $entryRecord->id = $entry->id;
  138. }
  139. // Save our Entry Settings
  140. $entryRecord->save(false);
  141. if ($transaction !== null)
  142. {
  143. $transaction->commit();
  144. SproutFormsPlugin::log('Transaction committed');
  145. }
  146. // Reset our field context and content table to what they were previously
  147. craft()->content->fieldContext = $oldFieldContext;
  148. craft()->content->contentTable = $oldContentTable;
  149. $this->callOnSaveEntryEvent($entry, $isNewEntry);
  150. return true;
  151. }
  152. else
  153. {
  154. SproutFormsPlugin::log("Couldn’t save Element on saveEntry service.", LogLevel::Error, true);
  155. }
  156. craft()->content->fieldContext = $oldFieldContext;
  157. craft()->content->contentTable = $oldContentTable;
  158. }
  159. else
  160. {
  161. SproutFormsPlugin::log('OnBeforeSaveEntryEvent is not valid', LogLevel::Error);
  162. if ($event->fakeIt)
  163. {
  164. sproutForms()->entries->fakeIt = true;
  165. }
  166. }
  167. }
  168. catch (\Exception $e)
  169. {
  170. SproutFormsPlugin::log('Failed to save element: '.$e->getMessage());
  171. return false;
  172. throw $e;
  173. }
  174. }
  175. else
  176. {
  177. SproutFormsPlugin::log('Service returns false');
  178. return false;
  179. }
  180. }
  181. public function callOnSaveEntryEvent($entry, $isNewEntry)
  182. {
  183. Craft::import('plugins.sproutforms.events.SproutForms_OnSaveEntryEvent');
  184. $event = new SproutForms_OnSaveEntryEvent(
  185. $this, array(
  186. 'entry' => $entry,
  187. 'isNewEntry' => $isNewEntry,
  188. 'event' => 'saveEntry',
  189. 'entity' => $entry,
  190. )
  191. );
  192. craft()->sproutForms->onSaveEntry($event);
  193. }
  194. /**
  195. * Deletes an entry
  196. *
  197. * @param SproutForms_EntryModel $entry
  198. *
  199. * @throws \CDbException
  200. * @throws \Exception
  201. *
  202. * @return bool
  203. */
  204. public function deleteEntry(SproutForms_EntryModel $entry)
  205. {
  206. $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
  207. try
  208. {
  209. // Delete the Element and Entry
  210. craft()->elements->deleteElementById($entry->id);
  211. if ($transaction !== null)
  212. {
  213. $transaction->commit();
  214. }
  215. return true;
  216. }
  217. catch (\Exception $e)
  218. {
  219. if ($transaction !== null)
  220. {
  221. $transaction->rollback();
  222. }
  223. throw $e;
  224. }
  225. }
  226. /**
  227. * Returns an array of models for entries found in the database
  228. *
  229. * @return SproutForms_EntryModel|array|null
  230. */
  231. public function getAllEntries()
  232. {
  233. $attributes = array('order' => 'forms.name');
  234. return $this->getCriteria($attributes)->find();
  235. }
  236. /**
  237. * Returns a form entry model if one is found in the database by id
  238. *
  239. * @param int $entryId
  240. *
  241. * @return null|SproutForms_EntryModel
  242. */
  243. public function getEntryById($entryId)
  244. {
  245. return $this->getCriteria(array('limit' => 1, 'id' => $entryId))->first();
  246. }
  247. /**
  248. * Returns an active or new entry model
  249. *
  250. * @param SproutForms_FormModel $form
  251. *
  252. * @return SproutForms_EntryModel
  253. */
  254. public function getEntryModel(SproutForms_FormModel $form)
  255. {
  256. if (isset(sproutForms()->forms->activeEntries[$form->handle]))
  257. {
  258. return sproutForms()->forms->activeEntries[$form->handle];
  259. }
  260. $entry = new SproutForms_EntryModel;
  261. $entry->setAttribute('formId', $form->id);
  262. return $entry;
  263. }
  264. /**
  265. * Updates previous title formats
  266. *
  267. * @param Mixed $contentRow
  268. * @param String $newFormat
  269. * @param String $contentTable
  270. *
  271. * @return boolean
  272. */
  273. public function updateTitleFormat($contentRow, $newFormat, $contentTable)
  274. {
  275. try
  276. {
  277. // get the entry
  278. $entry = sproutForms()->entries->getEntryById($contentRow['elementId']);
  279. // update the title with the new format
  280. $newTitle = craft()->templates->renderObjectTemplate($newFormat, $entry);
  281. $tablePrefix = Craft()->db->tablePrefix;
  282. // update single entry
  283. Craft()->db->createCommand("UPDATE {$tablePrefix}{$contentTable} SET title =:newTitle WHERE id=:contentId")
  284. ->bindValues(array(':contentId' => $contentRow['id'], ':newTitle' => $newTitle))
  285. ->execute();
  286. }
  287. catch (Exception $e)
  288. {
  289. SproutFormsPlugin::log('An error has occurred: ' . $e->getMessage(), LogLevel::Info, true);
  290. return false;
  291. }
  292. return true;
  293. }
  294. /**
  295. * Get Content Entries
  296. *
  297. * @param String $contentTable
  298. *
  299. * @return boolean
  300. */
  301. public function getContentEntries($contentTable)
  302. {
  303. $entries = Craft()->db->createCommand()
  304. ->select('id, elementId')
  305. ->from($contentTable)
  306. ->queryAll();
  307. return $entries;
  308. }
  309. public function installDefaultEntryStatuses()
  310. {
  311. $defaultEntryStatuses = array(
  312. 0 => array(
  313. 'name' => 'Unread',
  314. 'handle' => 'unread',
  315. 'color' => 'blue',
  316. 'sortOrder' => 1,
  317. 'isDefault' => 1
  318. ),
  319. 1 => array(
  320. 'name' => 'Read',
  321. 'handle' => 'read',
  322. 'color' => 'grey',
  323. 'sortOrder' => 2,
  324. 'isDefault' => 0
  325. )
  326. );
  327. foreach ($defaultEntryStatuses as $entryStatus)
  328. {
  329. craft()->db->createCommand()->insert('sproutforms_entrystatuses', array(
  330. 'name' => $entryStatus['name'],
  331. 'handle' => $entryStatus['handle'],
  332. 'color' => $entryStatus['color'],
  333. 'sortOrder' => $entryStatus['sortOrder'],
  334. 'isDefault' => $entryStatus['isDefault']
  335. ));
  336. }
  337. }
  338. /**
  339. * @return array
  340. */
  341. public function getAllEntryStatuses()
  342. {
  343. $entryStatuses = craft()->db->createCommand()
  344. ->select('*')
  345. ->from('sproutforms_entrystatuses')
  346. ->order('sortOrder asc')
  347. ->queryAll();
  348. return SproutForms_EntryStatusModel::populateModels($entryStatuses);
  349. }
  350. /**
  351. * @param $entryStatusId
  352. *
  353. * @return BaseModel
  354. */
  355. public function getEntryStatusById($entryStatusId)
  356. {
  357. $entryStatus = craft()->db->createCommand()
  358. ->select('*')
  359. ->from('sproutforms_entrystatuses')
  360. ->where('id=:id', array(':id' => $entryStatusId))
  361. ->queryRow();
  362. return $entryStatus != null ? SproutForms_EntryStatusModel::populateModel($entryStatus) : null;
  363. }
  364. /**
  365. * @param SproutForms_EntryStatusModel $entryStatus
  366. *
  367. * @return bool
  368. * @throws Exception
  369. * @throws \CDbException
  370. * @throws \Exception
  371. */
  372. public function saveEntryStatus(SproutForms_EntryStatusModel $entryStatus)
  373. {
  374. $record = new SproutForms_EntryStatusRecord;
  375. if ($entryStatus->id)
  376. {
  377. $record = SproutForms_EntryStatusRecord::model()->findByPk($entryStatus->id);
  378. if (!$record)
  379. {
  380. throw new Exception(Craft::t('No Entry Status exists with the id of “{id}”', array('id' => $entryStatus->id)));
  381. }
  382. }
  383. $record->setAttributes($entryStatus->getAttributes(), false);
  384. $record->sortOrder = $entryStatus->sortOrder ? $entryStatus->sortOrder : 999;
  385. $record->validate();
  386. $entryStatus->addErrors($record->getErrors());
  387. if (!$entryStatus->hasErrors())
  388. {
  389. $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
  390. try
  391. {
  392. if ($record->isDefault)
  393. {
  394. SproutForms_EntryStatusRecord::model()->updateAll(array('isDefault' => 0));
  395. }
  396. $record->save(false);
  397. if (!$entryStatus->id)
  398. {
  399. $entryStatus->id = $record->id;
  400. }
  401. if ($transaction !== null)
  402. {
  403. $transaction->commit();
  404. }
  405. }
  406. catch (\Exception $e)
  407. {
  408. if ($transaction !== null)
  409. {
  410. $transaction->rollback();
  411. }
  412. throw $e;
  413. }
  414. return true;
  415. }
  416. return false;
  417. }
  418. /**
  419. * @param int
  420. *
  421. * @return bool
  422. */
  423. public function deleteEntryStatusById($id)
  424. {
  425. $statuses = $this->getAllEntryStatuses();
  426. $criteria = craft()->elements->getCriteria('SproutForms_Entry');
  427. $criteria->statusId = $id;
  428. $order = $criteria->first();
  429. if ($order)
  430. {
  431. return false;
  432. }
  433. if (count($statuses) >= 2)
  434. {
  435. SproutForms_EntryStatusRecord::model()->deleteByPk($id);
  436. return true;
  437. }
  438. return false;
  439. }
  440. /**
  441. * Reorders Entry Statuses
  442. *
  443. * @param array $entryStatusIds
  444. *
  445. * @throws \Exception
  446. * @return bool
  447. */
  448. public function reorderEntryStatuses($entryStatusIds)
  449. {
  450. $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
  451. try
  452. {
  453. foreach ($entryStatusIds as $entryStatus => $entryStatusId)
  454. {
  455. $entryStatusRecord = $this->_getEntryStatusRecordById($entryStatusId);
  456. $entryStatusRecord->sortOrder = $entryStatus + 1;
  457. $entryStatusRecord->save();
  458. }
  459. if ($transaction !== null)
  460. {
  461. $transaction->commit();
  462. }
  463. }
  464. catch (\Exception $e)
  465. {
  466. if ($transaction !== null)
  467. {
  468. $transaction->rollback();
  469. }
  470. throw $e;
  471. }
  472. return true;
  473. }
  474. public function getDefaultEntryStatusId()
  475. {
  476. $entryStatus = SproutForms_EntryStatusRecord::model()->find(array('order'=>'isDefault DESC'));
  477. return $entryStatus != null ? $entryStatus->id : null;
  478. }
  479. public function isDataSaved($form)
  480. {
  481. $settings = craft()->plugins->getPlugin('sproutforms')->getSettings();
  482. $saveData = $settings['enableSaveData'];
  483. if (($settings['enableSaveDataPerFormBasis'] && $saveData) || $form->submitAction)
  484. {
  485. $saveData = $form->saveData;
  486. }
  487. return $saveData;
  488. }
  489. /**
  490. * Gets an Entry Status's record.
  491. *
  492. * @param int $sourceId
  493. *
  494. * @throws Exception
  495. * @return AssetSourceRecord
  496. */
  497. private function _getEntryStatusRecordById($entryStatusId = null)
  498. {
  499. if ($entryStatusId)
  500. {
  501. $entryStatusRecord = SproutForms_EntryStatusRecord::model()->findById($entryStatusId);
  502. if (!$entryStatusRecord)
  503. {
  504. throw new Exception(Craft::t('No Entry Status exists with the ID “{id}”.', array('id' => $entryStatusId)));
  505. }
  506. }
  507. else
  508. {
  509. $entryStatusRecord = new SproutForms_EntryStatusRecord();
  510. }
  511. return $entryStatusRecord;
  512. }
  513. }