/**
  * Deletes a group.
  */
 public function actionDeleteGroup()
 {
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     $groupId = craft()->request->getRequiredPost('id');
     $success = sproutForms()->groups->deleteGroupById($groupId);
     craft()->userSession->setNotice(Craft::t('Group deleted.'));
     $this->returnJson(array('success' => $success));
 }
 /**
  * Returns this element type's sources.
  *
  * @param string|null $context
  * @return array|false
  */
 public function getSources($context = null)
 {
     $sources = array('*' => array('label' => Craft::t('All Forms')));
     $groups = sproutForms()->groups->getAllFormGroups();
     foreach ($groups as $group) {
         $key = 'group:' . $group->id;
         $sources[$key] = array('label' => $group->name, 'data' => array('id' => $group->id), 'criteria' => array('groupId' => $group->id));
     }
     return $sources;
 }
 /**
  * Save a Form Field
  * 
  * @param  SproutForms_FormModel $form
  * @param  FieldModel            $field
  * @param  boolean               $validate
  * @throws \Exception
  * @return boolean               true/false
  */
 public function saveField(SproutForms_FormModel $form, FieldModel $field, $validate = true)
 {
     if (!$validate || craft()->fields->validateField($field)) {
         $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
         try {
             if ($field->id) {
                 $fieldLayoutFields = array();
                 $sortOrder = 0;
                 // Save a new field layout with all form fields
                 // to make sure we capture the required setting
                 $sortOrder++;
                 foreach ($form->getFields() as $oldField) {
                     if ($oldField->id == $field->id) {
                         $fieldLayoutFields[] = array('fieldId' => $field->id, 'required' => $field->required, 'sortOrder' => $sortOrder);
                     } else {
                         $fieldLayoutFields[] = array('fieldId' => $oldField->id, 'required' => $oldField->required, 'sortOrder' => $sortOrder);
                     }
                 }
                 $fieldLayout = new FieldLayoutModel();
                 $fieldLayout->type = 'SproutForms_Form';
                 $fieldLayout->setFields($fieldLayoutFields);
                 // Update the form model & record with our new field layout ID
                 $form->setFieldLayout($fieldLayout);
             } else {
                 // Save the new field
                 craft()->fields->saveField($field);
                 // Save a new field layout with all form fields
                 $fieldLayoutFields = array();
                 $sortOrder = 0;
                 foreach ($form->getFields() as $oldField) {
                     $sortOrder++;
                     $fieldLayoutFields[] = array('fieldId' => $oldField->id, 'required' => $oldField->required, 'sortOrder' => $sortOrder);
                 }
                 $sortOrder++;
                 $fieldLayoutFields[] = array('fieldId' => $field->id, 'required' => $field->required, 'sortOrder' => $sortOrder);
                 $fieldLayout = new FieldLayoutModel();
                 $fieldLayout->type = 'SproutForms_Form';
                 $fieldLayout->setFields($fieldLayoutFields);
                 $form->setFieldLayout($fieldLayout);
             }
             sproutForms()->forms->saveForm($form);
             if ($transaction !== null) {
                 $transaction->commit();
             }
         } catch (\Exception $e) {
             if ($transaction !== null) {
                 $transaction->rollback();
             }
             throw $e;
         }
         return true;
     } else {
         return false;
     }
 }
 /**
  * Save Plugin Settings
  * 
  * @return void
  */
 public function actionSaveSettings()
 {
     $this->requirePostRequest();
     $settings = craft()->request->getPost('settings');
     if (sproutForms()->settings->saveSettings($settings)) {
         craft()->userSession->setNotice(Craft::t('Settings saved.'));
         $this->redirectToPostedUrl();
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save settings.'));
         // Send the settings back to the template
         craft()->urlManager->setRouteVariables(array('settings' => $settings));
     }
 }
 /**
  * Before Validate
  *
  */
 protected function beforeValidate()
 {
     // Validate the name and handle fields when the record is save as new
     if (isset($_POST["saveAsNew"])) {
         if ($_POST['saveAsNew']) {
             if (sproutForms()->forms->getFieldValue('name', $this->name)) {
                 $this->name = $this->getFieldAsNew('name', $this->name);
             }
             if (sproutForms()->forms->getFieldValue('handle', $this->handle)) {
                 $this->handle = $this->getFieldAsNew('handle', $this->handle);
             }
         }
     }
     return true;
 }
 /**
  * Updates the query command, criteria, and select fields when a source is available
  *
  * @param DbCommand            $query
  * @param ElementCriteriaModel $criteria
  * @param string               $select
  */
 protected function joinContentTableAndAddContentSelects(DbCommand &$query, ElementCriteriaModel &$criteria, &$select)
 {
     // Do we have a source selected in the sidebar?
     // If so, we have a form id and we can use that to fetch the content table
     if ($criteria->formId) {
         $form = sproutForms()->forms->getFormById($criteria->formId);
         if ($form) {
             $content = "{$form->handle}.title";
             $select = empty($select) ? $content : $select . ', ' . $content;
             $query->join($form->getContentTable() . ' ' . $form->handle, 'entries.formId = ' . $form->id);
         }
     }
 }
 /**
  * Install example data
  * 
  * @return void
  */
 private function _installExampleData()
 {
     try {
         // Create Example Forms
         // ------------------------------------------------------------
         $formSettings = array(array('name' => 'Contact Form', 'handle' => 'contact', 'titleFormat' => "{dateCreated|date('Y-m-d')} – {fullName} – {message|slice(0,22)}...", 'redirectUri' => 'sproutforms/examples/contact-form?message=thank-you', 'displaySectionTitles' => false), array('name' => 'Basic Fields Form', 'handle' => 'basic', 'titleFormat' => "{plainText} – {dropdown}{% if object.textarea %} – {{ object.textarea|slice(0,15) }}{% endif %}", 'redirectUri' => 'sproutforms/examples/basic-fields?message=thank-you', 'displaySectionTitles' => true));
         $fieldSettings = array('contact' => array('Default' => array(array('name' => 'Full Name', 'handle' => 'fullName', 'type' => 'PlainText', 'required' => 1, 'settings' => array('placeholder' => '', 'maxLength' => '', 'multiline' => '', 'initialRows' => 4)), array('name' => 'Email', 'handle' => 'email', 'type' => 'PlainText', 'required' => 1, 'settings' => array('placeholder' => '', 'maxLength' => '', 'multiline' => '', 'initialRows' => 4)), array('name' => 'Message', 'handle' => 'message', 'type' => 'PlainText', 'required' => 1, 'settings' => array('placeholder' => '', 'maxLength' => '', 'multiline' => 1, 'initialRows' => 4)))), 'basic' => array('Section One' => array(array('name' => 'Plain Text Field', 'handle' => 'plainText', 'type' => 'PlainText', 'required' => 1, 'settings' => array('placeholder' => '', 'maxLength' => '', 'multiline' => 0, 'initialRows' => 4)), array('name' => 'Dropdown Field', 'handle' => 'dropdown', 'type' => 'Dropdown', 'required' => 1, 'settings' => array('options' => array(array('label' => 'Option 1', 'value' => 'option1', 'default' => ''), array('label' => 'Option 2', 'value' => 'option2', 'default' => ''), array('label' => 'Option 3', 'value' => 'option3', 'default' => '')))), array('name' => 'Number Field', 'handle' => 'number', 'type' => 'Number', 'required' => 0, 'settings' => array('min' => 0, 'max' => '', 'decimals' => ''))), 'Section Two' => array(array('name' => 'Radio Buttons Field', 'handle' => 'radioButtons', 'type' => 'RadioButtons', 'required' => 0, 'settings' => array('options' => array(array('label' => 'Option 1', 'value' => 'option1', 'default' => ''), array('label' => 'Option 2', 'value' => 'option2', 'default' => ''), array('label' => 'Option 3', 'value' => 'option3', 'default' => '')))), array('name' => 'Checkboxes Field', 'handle' => 'checkboxes', 'type' => 'Checkboxes', 'required' => 0, 'settings' => array('options' => array(array('label' => 'Option 1', 'value' => 'option1', 'default' => ''), array('label' => 'Option 2', 'value' => 'option2', 'default' => ''), array('label' => 'Option 3', 'value' => 'option3', 'default' => '')))), array('name' => 'Multi-select Field', 'handle' => 'multiSelect', 'type' => 'MultiSelect', 'required' => 0, 'settings' => array('options' => array(array('label' => 'Option 1', 'value' => 'option1', 'default' => ''), array('label' => 'Option 2', 'value' => 'option2', 'default' => ''), array('label' => 'Option 3', 'value' => 'option3', 'default' => '')))), array('name' => 'Textarea Field', 'handle' => 'textarea', 'type' => 'PlainText', 'required' => 0, 'settings' => array('placeholder' => '', 'maxLength' => '', 'multiline' => 1, 'initialRows' => 4)))));
         // Create Forms and their Content Tables
         foreach ($formSettings as $settings) {
             $form = new SproutForms_FormModel();
             // Assign our form settings
             $form->name = $settings['name'];
             $form->handle = $settings['handle'];
             $form->titleFormat = $settings['titleFormat'];
             $form->redirectUri = $settings['redirectUri'];
             $form->displaySectionTitles = $settings['displaySectionTitles'];
             // Create the Form
             sproutForms()->forms->saveForm($form);
             // Set our field context
             craft()->content->fieldContext = $form->getFieldContext();
             craft()->content->contentTable = $form->getContentTable();
             //------------------------------------------------------------
             // Do we have a new field that doesn't exist yet?
             // If so, save it and grab the id.
             $fieldLayout = array();
             $requiredFields = array();
             $tabs = $fieldSettings[$form->handle];
             foreach ($tabs as $tabName => $newFields) {
                 foreach ($newFields as $newField) {
                     $field = new FieldModel();
                     $field->name = $newField['name'];
                     $field->handle = $newField['handle'];
                     $field->type = $newField['type'];
                     $field->required = $newField['required'];
                     $field->settings = $newField['settings'];
                     // Save our field
                     craft()->fields->saveField($field);
                     $fieldLayout[$tabName][] = $field->id;
                     if ($field->required) {
                         $requiredFields[] = $field->id;
                     }
                 }
             }
             // Set the field layout
             $fieldLayout = craft()->fields->assembleLayout($fieldLayout, $requiredFields);
             $fieldLayout->type = 'SproutForms_Form';
             $form->setFieldLayout($fieldLayout);
             // Save our form again with a layouts
             sproutForms()->forms->saveForm($form);
         }
     } catch (\Exception $e) {
         $this->_handleError($e);
     }
 }
 /**
  * Returns the name of the table this element's content is stored in.
  *
  * @return string
  */
 public function getContentTable()
 {
     return sproutForms()->forms->getContentTableName($this);
 }
 /**
  * @throws \Exception
  */
 public function onBeforeUninstall()
 {
     $forms = sproutForms()->forms->getAllForms();
     foreach ($forms as $form) {
         sproutForms()->forms->deleteForm($form);
     }
 }
 /**
  * Delete a form.
  *
  * @return void
  */
 public function actionDeleteForm()
 {
     $this->requirePostRequest();
     // Get the Form these fields are related to
     $formId = craft()->request->getRequiredPost('id');
     $form = sproutForms()->forms->getFormById($formId);
     // @TODO - handle errors
     $success = sproutForms()->forms->deleteForm($form);
     $this->redirectToPostedUrl($form);
 }
 /**
  * Reorder a field
  * 
  * @return json
  */
 public function actionReorderFields()
 {
     craft()->userSession->requireAdmin();
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     $fieldIds = JsonHelper::decode(craft()->request->getRequiredPost('ids'));
     sproutForms()->fields->reorderFields($fieldIds);
     $this->returnJson(array('success' => true));
 }
 /**
  * Builds FieldType dropdown by grouping fields into to basic and advanced
  *
  * 1) Basic fields we can output by default
  * 2) Advanced fields that need some love before outputting
  *
  * @param  array $fieldTypes
  * @return array
  */
 public function prepareFieldTypesDropdown($fieldTypes)
 {
     return sproutForms()->fields->prepareFieldTypesDropdown($fieldTypes);
 }
 /**
  * Returns an array of forms suitable for use in checkbox field
  *
  * @return array
  */
 protected function getAllForms()
 {
     $result = sproutForms()->forms->getAllForms();
     $options = array();
     foreach ($result as $key => $forms) {
         array_push($options, array('label' => $forms->name, 'value' => $forms->id));
     }
     return $options;
 }
 /**
  * Route Controller for Edit Entry Template
  *
  * @param array $variables
  *
  * @throws HttpException
  * @throws Exception
  */
 public function actionEditEntryTemplate(array $variables = array())
 {
     $entryId = craft()->request->getSegment(4);
     if (sproutForms()->forms->activeCpEntry) {
         $entry = sproutForms()->forms->activeCpEntry;
     } else {
         $entry = sproutForms()->entries->getEntryById($entryId);
     }
     $form = sproutForms()->forms->getFormById($entry->formId);
     $variables['form'] = $form;
     $variables['entryId'] = $entryId;
     // This is our element, so we know where to get the field values
     $variables['entry'] = $entry;
     // Get the fields for this entry
     $fieldLayoutTabs = $entry->getFieldLayout()->getTabs();
     foreach ($fieldLayoutTabs as $tab) {
         $tabs[$tab->id]['label'] = $tab->name;
         $tabs[$tab->id]['url'] = '#tab' . $tab->sortOrder;
     }
     $variables['tabs'] = $tabs;
     $variables['fieldLayoutTabs'] = $fieldLayoutTabs;
     $this->renderTemplate('sproutforms/entries/_edit', $variables);
 }
 /**
  * Returns an active or new entry model
  *
  * @param SproutForms_FormModel $form
  *
  * @return SproutForms_EntryModel
  */
 public function getEntryModel(SproutForms_FormModel $form)
 {
     if (isset(sproutForms()->forms->activeEntries[$form->handle])) {
         return sproutForms()->forms->activeEntries[$form->handle];
     }
     $entry = new SproutForms_EntryModel();
     $entry->setAttribute('formId', $form->id);
     return $entry;
 }
 /**
  * Returns the form model associated with this entry
  *
  * @return SproutForms_FormModel
  */
 public function getForm()
 {
     if (!isset($this->form)) {
         $this->form = sproutForms()->forms->getFormById($this->formId);
     }
     return $this->form;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     $oldTable = 'sproutforms_forms_old';
     $newTable = 'sproutforms_forms';
     // ------------------------------------------------------------
     // Loop through each form in the old table and migrate it to the new table
     SproutFormsPlugin::log("Gathering all forms from the `{$oldTable}` table.", LogLevel::Info, true);
     $oldForms = craft()->db->createCommand()->select('*')->from($oldTable)->queryAll();
     $user = craft()->userSession->getUser();
     $email = isset($user->email) && $user->email != "" ? $user->email : "";
     foreach ($oldForms as $oldForm) {
         SproutFormsPlugin::log("Build SproutForms_FormModel for " . $oldForm['name'] . " Form", LogLevel::Info, true);
         // Map any values from the old form to their
         // new column names to save to the new form
         $newForm = new SproutForms_FormModel();
         $newForm->name = $oldForm['name'];
         $newForm->handle = $oldForm['handle'];
         $newForm->submitButtonText = $oldForm['submitButtonText'];
         $newForm->redirectUri = $oldForm['redirectUri'];
         $newForm->handle = $oldForm['handle'];
         $newForm->titleFormat = "Form submission on " . "{dateCreated|date('D, d M Y H:i:s')}";
         $newForm->displaySectionTitles = 0;
         $newForm->notificationRecipients = $oldForm['email_distribution_list'];
         $newForm->notificationSubject = $oldForm['notification_subject'];
         $newForm->notificationSenderName = craft()->getSiteName();
         $newForm->notificationSenderEmail = $email;
         $newForm->notificationReplyToEmail = $oldForm['notification_reply_to'];
         // Save the Form
         // Create a new content table
         sproutForms()->forms->saveForm($newForm);
         SproutFormsPlugin::log($newForm->name . " Form saved anew. Form ID: " . $newForm->id, LogLevel::Info, true);
         // Set our field context
         craft()->content->fieldContext = $newForm->getFieldContext();
         craft()->content->contentTable = $newForm->getContentTable();
         SproutFormsPlugin::log($newForm->name . " Form fieldContext: " . craft()->content->fieldContext, LogLevel::Info, true);
         SproutFormsPlugin::log($newForm->name . " Form contentTable: " . craft()->content->contentTable, LogLevel::Info, true);
         SproutFormsPlugin::log("Grab all fields for " . $newForm->name . " Form", LogLevel::Info, true);
         // Get the Form Fields
         $oldFormFields = craft()->db->createCommand()->select('*')->from('sproutforms_fields')->where('formId=:formId', array(':formId' => $oldForm['id']))->queryAll();
         // Prepare a couple variables to help save our fields and layout
         $fieldLayout = array();
         $requiredFields = array();
         $fieldMap = array();
         foreach ($oldFormFields as $oldFormField) {
             $newFieldHandle = str_replace("formId" . $oldForm['id'] . "_", "", $oldFormField['handle']);
             // Determine if we have a Number field
             // Might need to update teh Settings object to have the correct values min/max...
             if (strpos($oldFormField['validation'], 'numerical') !== FALSE) {
                 $oldFormField['type'] = 'Number';
                 $oldFormField['settings'] = '{"min":"0","max":"","decimals":"0"}';
             }
             // Build a field map of our old field handles and our new ones
             // so we can more easily match things up when inserting fields later
             $fieldMap[$oldFormField['handle']] = array('type' => $oldFormField['type'], 'newHandle' => $newFieldHandle);
             //------------------------------------------------------------
             SproutFormsPlugin::log("Build FieldModel for " . $oldFormField['name'] . " Field", LogLevel::Info, true);
             // SproutFormsPlugin::log("The Fieldtype " . $newFieldType . " for the "  . $oldFormField['name'] ." Field", LogLevel::Info, true);
             $newField = new FieldModel();
             $newField->name = $oldFormField['name'];
             $newField->handle = $newFieldHandle;
             $newField->instructions = $oldFormField['instructions'];
             $newField->type = $oldFormField['type'];
             $newField->required = strpos($oldFormField['validation'], 'required') !== FALSE;
             $newField->settings = $oldFormField['settings'];
             // Save our field
             craft()->fields->saveField($newField);
             SproutFormsPlugin::log($oldFormField['name'] . " Field saved.", LogLevel::Info, true);
             $fieldLayout['Form'][] = $newField->id;
             if ($newField->required) {
                 $requiredFields[] = $newField->id;
             }
         }
         // Set the field layout
         $fieldLayout = craft()->fields->assembleLayout($fieldLayout, $requiredFields);
         $fieldLayout->type = 'SproutForms_Form';
         $newForm->setFieldLayout($fieldLayout);
         // Save our form again with a layouts
         sproutForms()->forms->saveForm($newForm);
         SproutFormsPlugin::log("Form saved again with fieldLayout", LogLevel::Info, true);
         // Migrate the Entries Content
         SproutFormsPlugin::log("Grab Form Entries for " . $oldForm['name'] . " Form", LogLevel::Info, true);
         // Get the Form Entries
         $oldFormEntries = craft()->db->createCommand()->select('*')->from('sproutforms_content')->where('formId=:formId', array(':formId' => $oldForm['id']))->queryAll();
         foreach ($oldFormEntries as $oldFormEntry) {
             SproutFormsPlugin::log("Build SproutForms_EntryModel for Form Entry ID " . $oldFormEntry['id'], LogLevel::Info, true);
             $newFormEntry = new SproutForms_EntryModel();
             SproutFormsPlugin::log("Server data: " . $oldFormEntry['serverData'], LogLevel::Info, true);
             $oldEntryServerData = json_decode($oldFormEntry['serverData']);
             $newFormEntry->formId = $newForm->id;
             if (isset($oldEntryServerData)) {
                 $newFormEntry->ipAddress = $oldEntryServerData->ipAddress;
                 $newFormEntry->userAgent = $oldEntryServerData->userAgent;
                 $newFormEntry->dateCreated = $oldFormEntry['dateCreated'];
                 $newFormEntry->dateUpdated = $oldFormEntry['dateUpdated'];
             } else {
                 // Add null values if we don't have data for some reason
                 $newFormEntry->ipAddress = NULL;
                 $newFormEntry->userAgent = NULL;
             }
             $newFormFields = array();
             // Loop through our field map
             foreach ($fieldMap as $oldHandle => $fieldInfo) {
                 // If any columns in our current Form Entry match a
                 // field in our field map, add that field to be saved
                 if ($oldFormEntry[$oldHandle]) {
                     $newFormFields[$fieldInfo['newHandle']] = $oldFormEntry[$oldHandle];
                 }
             }
             $_POST['fields'] = $newFormFields;
             $fieldsLocation = 'fields';
             $newFormEntry->setContentFromPost($fieldsLocation);
             $newFormEntry->setContentPostLocation($fieldsLocation);
             SproutFormsPlugin::log("Try to Save Old Form Entry ID " . $oldFormEntry['id'], LogLevel::Info, true);
             sproutForms()->entries->saveEntry($newFormEntry);
             SproutFormsPlugin::log("Save New Form Entry ID " . $newFormEntry->id, LogLevel::Info, true);
         }
     }
     // Drop old field table
     if (craft()->db->tableExists('sproutforms_fields')) {
         SproutFormsPlugin::log("Dropping the 'sproutforms_fields' table.", LogLevel::Info, true);
         craft()->db->createCommand()->dropTable('sproutforms_fields');
         SproutFormsPlugin::log("'sproutforms_fields' table dropped.", LogLevel::Info, true);
     }
     // Drop old entries table
     if (craft()->db->tableExists('sproutforms_content')) {
         SproutFormsPlugin::log("Dropping the 'sproutforms_content' table.", LogLevel::Info, true);
         craft()->db->createCommand()->dropTable('sproutforms_content');
         SproutFormsPlugin::log("'sproutforms_content' table dropped.", LogLevel::Info, true);
     }
     // Drop old forms table
     if (craft()->db->tableExists($oldTable)) {
         SproutFormsPlugin::log("Dropping the old `{$oldTable}` table.", LogLevel::Info, true);
         craft()->db->createCommand('SET FOREIGN_KEY_CHECKS = 0;')->execute();
         // Need to drop this after we drop the fields table because fields has a fk
         craft()->db->createCommand()->dropTable($oldTable);
         craft()->db->createCommand('SET FOREIGN_KEY_CHECKS = 1;')->execute();
         SproutFormsPlugin::log("`{$oldTable}` table dropped.", LogLevel::Info, true);
     }
     return true;
 }