function getCMSFields()
 {
     $subsites = Subsite::accessible_sites("CMS_ACCESS_CMSMain");
     if (!$subsites) {
         $subsites = new DataObjectSet();
     }
     if (Subsite::hasMainSitePermission(null, array("CMS_ACCESS_CMSMain"))) {
         $subsites->push(new ArrayData(array('Title' => 'Main site', "\"ID\"" => 0)));
     }
     if ($subsites->Count()) {
         $subsiteSelectionField = new DropdownField("CopyContentFromID_SubsiteID", "Subsite", $subsites->toDropdownMap('ID', 'Title'), $this->CopyContentFromID ? $this->CopyContentFrom()->SubsiteID : Session::get('SubsiteID'));
     }
     // Setup the linking to the original page.
     $pageSelectionField = new SubsitesTreeDropdownField("RelatedPageID", _t('VirtualPage.CHOOSE', "Choose a page to link to"), "SiteTree", "ID", "MenuTitle");
     if (isset($_GET['RelatedPageID_SubsiteID'])) {
         $pageSelectionField->setSubsiteID($_GET['RelatedPageID_SubsiteID']);
     }
     $pageSelectionField->setFilterFunction(create_function('$item', 'return $item->ClassName != "VirtualPage";'));
     if ($subsites->Count()) {
         $fields = new FieldSet($subsiteSelectionField, $pageSelectionField);
     } else {
         $fields = new FieldSet($pageSelectionField);
     }
     return $fields;
 }
 /**
  * Returns a DataObjectSet of all the members that can publish pages
  * on this site by default
  */
 public function PublisherMembers()
 {
     if ($this->owner->CanPublishType == 'OnlyTheseUsers') {
         $groups = $this->owner->PublisherGroups();
         $members = new DataObjectSet();
         if ($groups) {
             foreach ($groups as $group) {
                 $members->merge($group->Members());
             }
         }
         // Default to ADMINs, if something goes wrong
         if (!$members->Count()) {
             $group = Permission::get_groups_by_permission('ADMIN')->first();
             $members = $group->Members();
         }
         return $members;
     } else {
         if ($this->owner->CanPublishType == 'LoggedInUsers') {
             // We don't want to return every user in the CMS....
             return Permission::get_members_by_permission('CMS_ACCESS_CMSMain');
         } else {
             $group = Permission::get_groups_by_permission('ADMIN')->first();
             return $group->Members();
         }
     }
 }
 /**
  * Returns a DataObjectSet of all the members that can publish this page
  */
 public function PublisherMembers()
 {
     if ($this->owner->CanPublishType == 'OnlyTheseUsers') {
         $groups = $this->owner->PublisherGroups();
         $members = new DataObjectSet();
         if ($groups) {
             foreach ($groups as $group) {
                 $members->merge($group->Members());
             }
         }
         // Default to ADMINs, if something goes wrong
         if (!$members->Count()) {
             $group = Permission::get_groups_by_permission('ADMIN')->first();
             $members = $group->Members();
         }
         return $members;
     } elseif ($this->owner->CanPublishType == 'Inherit') {
         if ($this->owner->Parent()->Exists()) {
             return $this->owner->Parent()->PublisherMembers();
         } else {
             return SiteConfig::current_site_config()->PublisherMembers();
         }
     } elseif ($this->owner->CanPublishType == 'LoggedInUsers') {
         return Permission::get_members_by_permission('CMS_ACCESS_CMSMain');
     } else {
         $group = Permission::get_groups_by_permission('ADMIN')->first();
         return $group->Members();
     }
 }
 /**
  * Helper method for processing batch actions.
  * Returns a set of status-updating JavaScript to return to the CMS.
  *
  * @param $pages The DataObjectSet of SiteTree objects to perform this batch action
  * on.
  * @param $helperMethod The method to call on each of those objects.
  * @return JSON encoded map in the following format:
  *  {
  *     'modified': {
  *       3: {'TreeTitle': 'Page3'},
  *       5: {'TreeTitle': 'Page5'}
  *     },
  *     'deleted': {
  *       // all deleted pages
  *     }
  *  }
  */
 public function batchaction(DataObjectSet $pages, $helperMethod, $successMessage, $arguments = array())
 {
     $status = array('modified' => array(), 'error' => array());
     foreach ($pages as $page) {
         // Perform the action
         if (!call_user_func_array(array($page, $helperMethod), $arguments)) {
             $status['error'][$page->ID] = '';
         }
         // Now make sure the tree title is appropriately updated
         $publishedRecord = DataObject::get_by_id('SiteTree', $page->ID);
         if ($publishedRecord) {
             $status['modified'][$publishedRecord->ID] = array('TreeTitle' => $publishedRecord->TreeTitle);
         }
         $page->destroy();
         unset($page);
     }
     $response = Controller::curr()->getResponse();
     if ($response) {
         $response->setStatusCode(200, sprintf($successMessage, $pages->Count(), count($status['error'])));
     }
     return Convert::raw2json($status);
 }
 /**
  * Run the update.
  *
  * Things it needs to do:
  * 		- Port the Settings on Individual Fields
  *		- Create the new class for multiple options
  *		- Port Email To to New Email_Recipients
  * 
  * @param HTTPRequest
  */
 function run($request)
 {
     // load the forms
     $forms = DataObject::get('UserDefinedForm');
     if (!$forms) {
         $forms = new DataObjectSet();
     }
     // set debugging / useful test
     $this->dryRun = isset($_GET['dryRun']) ? true : false;
     if ($this->dryRun) {
         echo "Will be running this test as a dry run. No data will be added or removed.<br />";
     }
     // if they want to import just 1 form - eg for testing
     if (isset($_GET['formID'])) {
         $id = Convert::raw2sql($_GET['formID']);
         $forms->push(DataObject::get_by_id('UserDefinedForm', $id));
     }
     if (!$forms) {
         echo "No UserForms Found on Database";
         return;
     }
     echo "Proceeding to update " . $forms->Count() . " Forms<br />";
     foreach ($forms as $form) {
         echo " -- Updating  {$form->URLSegment} <br />";
         // easy step first port over email data from the structure
         if ($form->EmailOnSubmit && $form->EmailTo) {
             // EmailTo can be a comma separated list so we need to explode that
             $emails = explode(",", $form->EmailTo);
             if ($emails) {
                 foreach ($emails as $email) {
                     $emailTo = new UserDefinedForm_EmailRecipient();
                     $emailTo->EmailAddress = trim($email);
                     $emailTo->EmailSubject = $form ? $form->Title : _t('UserFormsMigrationTask.DEFAULTSUBMISSIONTITLE', "Submission Data");
                     $emailTo->EmailFrom = Email::getAdminEmail();
                     $emailTo->FormID = $form->ID;
                     echo " -- -- Created new Email Recipient  {$email}<br />";
                     if (!$this->dryRun) {
                         $emailTo->write();
                     }
                 }
             }
         }
         // now fix all the fields
         if ($form->Fields()) {
             foreach ($form->Fields() as $field) {
                 switch ($field->ClassName) {
                     case 'EditableDropdown':
                     case 'EditableRadioField':
                     case 'EditableCheckboxGroupField':
                         $optionClass = "EditableDropdownOption";
                         if ($field->ClassName == "EditableRadioField") {
                             $optionClass = "EditableRadioOption";
                         } else {
                             if ($field->ClassName == "EditableCheckboxGroupField") {
                                 $optionClass = "EditableCheckboxOption";
                             }
                         }
                         $query = DB::query("SELECT * FROM \"{$optionClass}\" WHERE \"ParentID\" = '{$field->ID}'");
                         $result = $query->first();
                         if ($result) {
                             do {
                                 $this->createOption($result, $optionClass);
                             } while ($result = $query->next());
                         }
                         break;
                     case 'EditableTextField':
                         $database = $this->findDatabaseTableName('EditableTextField');
                         // get the data from the table
                         $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                         if ($result) {
                             $field->setSettings(array('Size' => $result['Size'], 'MinLength' => $result['MinLength'], 'MaxLength' => $result['MaxLength'], 'Rows' => $result['Rows']));
                         }
                         break;
                     case 'EditableLiteralField':
                         if ($field->Content) {
                             // find what table to use
                             $database = $this->findDatabaseTableName('EditableLiteralField');
                             // get the data from the table
                             $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                             if ($result) {
                                 $field->setSettings(array('Content' => $result['Content']));
                             }
                         }
                         break;
                     case 'EditableMemberListField':
                         if ($field->GroupID) {
                             // find what table to use
                             $database = $this->findDatabaseTableName('EditableMemberListField');
                             // get the data from the table
                             $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                             if ($result) {
                                 $field->setSettings(array('GroupID' => $result['GroupID']));
                             }
                         }
                         break;
                     case 'EditableCheckbox':
                         if ($field->Checked) {
                             // find what table to use
                             $database = $this->findDatabaseTableName('EditableCheckbox');
                             // get the data from the table
                             $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                             if ($result) {
                                 $field->setSettings(array('Default' => $result['Checked']));
                             }
                         }
                         break;
                     case 'EditableEmailField':
                         $database = $this->findDatabaseTableName('EditableEmailField');
                         $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                         if ($result && isset($result['SendCopy']) && $result['SendCopy'] == true) {
                             // we do not store send copy on email field anymore. This has been wrapped into
                             // the email recipients
                             $emailTo = new UserDefinedForm_EmailRecipient();
                             $emailTo->EmailSubject = $form ? $form->Title : _t('UserFormsMigrationTask.DEFAULTSUBMISSIONTITLE', "Submission Data");
                             $emailTo->EmailFrom = Email::getAdminEmail();
                             $emailTo->FormID = $form->ID;
                             $emailTo->SendEmailToFieldID = $field->ID;
                             $emailTo->EmailBody = $form->EmailMessageToSubmitter;
                             if (!$this->dryRun) {
                                 $emailTo->write();
                             }
                         }
                         break;
                 }
                 if (!$this->dryRun) {
                     $field->write();
                 }
             }
         }
     }
     echo "<h3>Migration Complete</h3>";
 }
Example #6
0
 function Field()
 {
     Requirements::css(SAPPHIRE_DIR . '/css/CheckboxSetField.css');
     Requirements::javascript(SAPPHIRE_DIR . '/javascript/PermissionCheckboxSetField.js');
     $uninheritedCodes = array();
     $inheritedCodes = array();
     $records = $this->records ? $this->records : new ArrayList();
     // Get existing values from the form record (assuming the formfield name is a join field on the record)
     if (is_object($this->form)) {
         $record = $this->form->getRecord();
         if ($record && (is_a($record, 'Group') || is_a($record, 'PermissionRole')) && !$records->find('ID', $record->ID)) {
             $records->push($record);
         }
     }
     // Get all 'inherited' codes not directly assigned to the group (which is stored in $values)
     foreach ($records as $record) {
         // Get all uninherited permissions
         $relationMethod = $this->name;
         foreach ($record->{$relationMethod}() as $permission) {
             if (!isset($uninheritedCodes[$permission->Code])) {
                 $uninheritedCodes[$permission->Code] = array();
             }
             $uninheritedCodes[$permission->Code][] = sprintf(_t('PermissionCheckboxSetField.AssignedTo', 'assigned to "%s"'), $record->Title);
         }
         // Special case for Group records (not PermissionRole):
         // Determine inherited assignments
         if (is_a($record, 'Group')) {
             // Get all permissions from roles
             if ($record->Roles()->Count()) {
                 foreach ($record->Roles() as $role) {
                     foreach ($role->Codes() as $code) {
                         if (!isset($inheritedCodes[$code->Code])) {
                             $inheritedCodes[$code->Code] = array();
                         }
                         $inheritedCodes[$code->Code][] = sprintf(_t('PermissionCheckboxSetField.FromRole', 'inherited from role "%s"', PR_MEDIUM, 'A permission inherited from a certain permission role'), $role->Title);
                     }
                 }
             }
             // Get from parent groups
             $parentGroups = $record->getAncestors();
             if ($parentGroups) {
                 foreach ($parentGroups as $parent) {
                     if (!$parent->Roles()->Count()) {
                         continue;
                     }
                     foreach ($parent->Roles() as $role) {
                         if ($role->Codes()) {
                             foreach ($role->Codes() as $code) {
                                 if (!isset($inheritedCodes[$code->Code])) {
                                     $inheritedCodes[$code->Code] = array();
                                 }
                                 $inheritedCodes[$code->Code][] = sprintf(_t('PermissionCheckboxSetField.FromRoleOnGroup', 'inherited from role "%s" on group "%s"', PR_MEDIUM, 'A permission inherited from a role on a certain group'), $role->Title, $parent->Title);
                             }
                         }
                     }
                     if ($parent->Permissions()->Count()) {
                         foreach ($parent->Permissions() as $permission) {
                             if (!isset($inheritedCodes[$permission->Code])) {
                                 $inheritedCodes[$permission->Code] = array();
                             }
                             $inheritedCodes[$permission->Code][] = sprintf(_t('PermissionCheckboxSetField.FromGroup', 'inherited from group "%s"', PR_MEDIUM, 'A permission inherited from a certain group'), $parent->Title);
                         }
                     }
                 }
             }
         }
     }
     $odd = 0;
     $options = '';
     if ($this->source) {
         // loop through all available categorized permissions and see if they're assigned for the given groups
         foreach ($this->source as $categoryName => $permissions) {
             $options .= "<li><h5>{$categoryName}</h5></li>";
             foreach ($permissions as $code => $permission) {
                 if (in_array($code, $this->hiddenPermissions)) {
                     continue;
                 }
                 if (in_array($code, Permission::$hidden_permissions)) {
                     continue;
                 }
                 $value = $permission['name'];
                 $odd = ($odd + 1) % 2;
                 $extraClass = $odd ? 'odd' : 'even';
                 $extraClass .= ' val' . str_replace(' ', '', $code);
                 $itemID = $this->id() . '_' . ereg_replace('[^a-zA-Z0-9]+', '', $code);
                 $checked = $disabled = $inheritMessage = '';
                 $checked = isset($uninheritedCodes[$code]) || isset($inheritedCodes[$code]) ? ' checked="checked"' : '';
                 $title = $permission['help'] ? 'title="' . htmlentities($permission['help'], ENT_COMPAT, 'UTF-8') . '" ' : '';
                 if (isset($inheritedCodes[$code])) {
                     // disable inherited codes, as any saving logic would be too complicate to express in this interface
                     $disabled = ' disabled="true"';
                     $inheritMessage = ' (' . join(', ', $inheritedCodes[$code]) . ')';
                 } elseif ($this->records && $this->records->Count() > 1 && isset($uninheritedCodes[$code])) {
                     // If code assignments are collected from more than one "source group",
                     // show its origin automatically
                     $inheritMessage = ' (' . join(', ', $uninheritedCodes[$code]) . ')';
                 }
                 // If the field is readonly, always mark as "disabled"
                 if ($this->readonly) {
                     $disabled = ' disabled="true"';
                 }
                 $inheritMessage = '<small>' . $inheritMessage . '</small>';
                 $options .= "<li class=\"{$extraClass}\">" . "<input id=\"{$itemID}\"{$disabled} name=\"{$this->name}[{$code}]\" type=\"checkbox\" value=\"{$code}\"{$checked} class=\"checkbox\" />" . "<label {$title}for=\"{$itemID}\">{$value}{$inheritMessage}</label>" . "</li>\n";
             }
         }
     }
     return "<ul id=\"{$this->id()}\" class=\"optionset checkboxsetfield{$this->extraClass()}\">\n{$options}</ul>\n";
 }
 function run(DataObjectSet $pages)
 {
     $failures = 0;
     foreach ($pages as $page) {
         $id = $page->ID;
         // Perform the action
         if ($page->canDelete()) {
             $page->delete();
         } else {
             $failures++;
         }
         // check to see if the record exists on the live site, if it doesn't remove the tree node
         $liveRecord = Versioned::get_one_by_stage('SiteTree', 'Live', "\"SiteTree\".\"ID\"={$id}");
         if ($liveRecord) {
             $liveRecord->IsDeletedFromStage = true;
             $title = Convert::raw2js($liveRecord->TreeTitle());
             FormResponse::add("\$('sitetree').setNodeTitle({$id}, '{$title}');");
             FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$id});");
         } else {
             FormResponse::add("var node = \$('sitetree').getTreeNodeByIdx('{$id}');");
             FormResponse::add("if(node && node.parentTreeNode)\tnode.parentTreeNode.removeTreeNode(node);");
             FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$id});");
         }
         $page->destroy();
         unset($page);
     }
     $message = sprintf(_t('CMSBatchActions.DELETED_DRAFT_PAGES', 'Deleted %d pages from the draft site, %d failures'), $pages->Count() - $failures, $failures);
     FormResponse::add('statusMessage("' . $message . '","good");');
     return FormResponse::respond();
 }
Example #8
0
 public function getNextRecurringEvents($event_obj, $datetime_obj, $limit = null)
 {
     $counter = new sfDate($datetime_obj->StartDate);
     if ($event = $datetime_obj->Event()->DateTimes()->First()) {
         $end_date = strtotime($event->EndDate);
     } else {
         $end_date = false;
     }
     $counter->tomorrow();
     $dates = new DataObjectSet();
     while ($dates->Count() != $this->OtherDatesCount) {
         // check the end date
         if ($end_date) {
             if ($end_date > 0 && $end_date <= $counter->get()) {
                 break;
             }
         }
         if ($event_obj->recursionHappensOn($counter->get())) {
             $dates->push($this->newRecursionDateTime($datetime_obj, $counter->date()));
         }
         $counter->tomorrow();
     }
     return $dates;
 }
 function NormalRelated()
 {
     $return = new DataObjectSet();
     $links = DataObject::get('RelatedPageLink', '"MasterPageID" = ' . $this->owner->ID);
     if ($links) {
         foreach ($links as $link) {
             if ($link->RelatedPage()->exists()) {
                 $return->push($link->RelatedPage());
             }
         }
     }
     return $return->Count() > 0 ? $return : false;
 }
 function testRemoveDuplicates()
 {
     // Note that PageComment and DataObjectSetTest_TeamComment are both descendants of DataObject, and don't
     // share an inheritance relationship below that.
     $pageComments = DataObject::get('DataObjectSetTest_TeamComment');
     $teamComments = DataObject::get('DataObjectSetTest_TeamComment');
     /* Test default functionality (remove by ID). We'd expect to loose all our
      * team comments as they have the same IDs as the first three page comments */
     $allComments = new DataObjectSet();
     $allComments->merge($pageComments);
     $allComments->merge($teamComments);
     $this->assertEquals($allComments->Count(), 6);
     $allComments->removeDuplicates();
     $this->assertEquals($allComments->Count(), 3, 'Standard functionality is to remove duplicate base class/IDs');
     /* Now test removing duplicates based on a common field. In this case we shall
      * use 'Name', so we can get all the unique commentators */
     $comment = new DataObjectSetTest_TeamComment();
     $comment->Name = "Bob";
     $allComments->push($comment);
     $this->assertEquals($allComments->Count(), 4);
     $allComments->removeDuplicates('Name');
     $this->assertEquals($allComments->Count(), 3, 'There are 3 uniquely named commentators');
     // Ensure that duplicates are removed where the base data class is the same.
     $mixedSet = new DataObjectSet();
     $mixedSet->push(new SiteTree(array('ID' => 1)));
     $mixedSet->push(new Page(array('ID' => 1)));
     // dup: same base class and ID
     $mixedSet->push(new Page(array('ID' => 1)));
     // dup: more than one dup of the same object
     $mixedSet->push(new Page(array('ID' => 2)));
     // not dup: same type again, but different
     $mixedSet->push(new SiteTree(array('ID' => 1)));
     // dup: another dup, not consequetive.
     $mixedSet->removeDuplicates('ID');
     $this->assertEquals($mixedSet->Count(), 2, 'There are 3 unique data objects in a very mixed set');
 }