public function transition($request)
 {
     if (!Member::currentUserID()) {
         return Security::permissionFailure($this, _t('AdvancedWorkflowActionController.ACTION_ERROR', "You must be logged in"));
     }
     $id = $this->request->requestVar('id');
     $transition = $this->request->requestVar('transition');
     $instance = DataObject::get_by_id('WorkflowInstance', (int) $id);
     if ($instance && $instance->canEdit()) {
         $transition = DataObject::get_by_id('WorkflowTransition', (int) $transition);
         if ($transition) {
             if ($this->request->requestVar('comments')) {
                 $action = $instance->CurrentAction();
                 $action->Comment = $this->request->requestVar('comments');
                 $action->write();
             }
             singleton('WorkflowService')->executeTransition($instance->getTarget(), $transition->ID);
             $result = array('success' => true, 'link' => $instance->getTarget()->AbsoluteLink());
             if (Director::is_ajax()) {
                 return Convert::raw2json($result);
             } else {
                 return $this->redirect($instance->getTarget()->Link());
             }
         }
     }
     if (Director::is_ajax()) {
         $result = array('success' => false);
         return Convert::raw2json($result);
     } else {
         $this->redirect($instance->getTarget()->Link());
     }
 }
 public function Field($properties = array())
 {
     $config = array('timeformat' => $this->getConfig('timeformat'));
     $config = array_filter($config);
     $this->addExtraClass(Convert::raw2json($config));
     return parent::Field($properties);
 }
 /**
  * Out of the box, the handler "CurrentForm" value, which will return the rendered form.  
  * Non-Ajax calls will redirect back.
  * 
  * @param SS_HTTPRequest $request 
  * @param array $extraCallbacks List of anonymous functions or callables returning either a string
  * or SS_HTTPResponse, keyed by their fragment identifier. The 'default' key can
  * be used as a fallback for non-ajax responses.
  * @param array $fragmentOverride Change the response fragments.
  * @return SS_HTTPResponse
  */
 public function respond(SS_HTTPRequest $request, $extraCallbacks = array())
 {
     // Prepare the default options and combine with the others
     $callbacks = array_merge($this->callbacks, $extraCallbacks);
     $response = $this->getResponse();
     $responseParts = array();
     if (isset($this->fragmentOverride)) {
         $fragments = $this->fragmentOverride;
     } elseif ($fragmentStr = $request->getHeader('X-Pjax')) {
         $fragments = explode(',', $fragmentStr);
     } else {
         if ($request->isAjax()) {
             throw new SS_HTTPResponse_Exception("Ajax requests to this URL require an X-Pjax header.", 400);
         }
         $response->setBody(call_user_func($callbacks['default']));
         return $response;
     }
     // Execute the fragment callbacks and build the response.
     foreach ($fragments as $fragment) {
         if (isset($callbacks[$fragment])) {
             $responseParts[$fragment] = call_user_func($callbacks[$fragment]);
         } else {
             throw new SS_HTTPResponse_Exception("X-Pjax = '{$fragment}' not supported for this URL.", 400);
         }
     }
     $response->setBody(Convert::raw2json($responseParts));
     $response->addHeader('Content-Type', 'text/json');
     return $response;
 }
 /**
  * Action to handle upload of a single file
  *
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse
  * @return SS_HTTPResponse
  */
 public function upload(SS_HTTPRequest $request)
 {
     if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
         return $this->httpError(403);
     }
     // Protect against CSRF on destructive action
     $token = $this->getForm()->getSecurityToken();
     if (!$token->checkRequest($request)) {
         return $this->httpError(400);
     }
     // Get form details
     $name = $this->getName();
     $postVars = $request->postVar($name);
     // Save the temporary file into a File object
     $uploadedFiles = $this->extractUploadedFileData($postVars);
     $firstFile = reset($uploadedFiles);
     $file = $this->saveTemporaryFile($firstFile, $error);
     if (empty($file)) {
         $return = array('error' => $error);
     } else {
         $return = $this->encodeFileAttributes($file);
     }
     // Format response with json
     $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
     $response->addHeader('Content-Type', 'text/plain');
     if (!empty($return['error'])) {
         $response->setStatusCode(200);
     }
     return $response;
 }
 public function convert(DataObject $object)
 {
     if ($object->hasMethod('toFilteredMap')) {
         return Convert::raw2json($object->toFilteredMap());
     }
     return Convert::raw2json($object->toMap());
 }
示例#6
0
 function FieldHolder()
 {
     $config = array('datetimeorder' => $this->getConfig('datetimeorder'));
     $config = array_filter($config);
     $this->addExtraClass(Convert::raw2json($config));
     return parent::FieldHolder();
 }
 public function Field($properties = array())
 {
     Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js');
     Requirements::javascript(DYNAMICLIST_MODULE . '/javascript/DependentDynamicListDropdownField.js');
     $listItems = array();
     if (is_string($this->dependentLists)) {
         $list = DynamicList::get_dynamic_list($this->dependentLists);
         if ($list) {
             $this->dependentLists = $list->Items()->map('Title', 'Title')->toArray();
         }
     }
     if (!is_array($this->dependentLists)) {
         $this->dependentLists = array();
     }
     foreach ($this->dependentLists as $k => $v) {
         $list = DynamicList::get_dynamic_list($k);
         if ($list) {
             $listItems[$k] = $list->Items()->map('Title', 'Title')->toArray();
         }
     }
     $this->setAttribute('data-listoptions', Convert::raw2json($listItems));
     $this->setAttribute('data-dependentOn', $this->dependentOn);
     if ($this->value) {
         $this->setAttribute('data-initialvalue', $this->value);
     }
     return parent::Field();
 }
 /**
  * @return string
  */
 public function tree($request)
 {
     $data = array();
     $class = $request->getVar('class');
     $id = $request->getVar('id');
     if ($id == 0) {
         $items = singleton('WorkflowService')->getDefinitions();
         $type = 'WorkflowDefinition';
     } elseif ($class == 'WorkflowDefinition') {
         $items = DataObject::get('WorkflowAction', '"WorkflowDefID" = ' . (int) $id);
         $type = 'WorkflowAction';
     } else {
         $items = DataObject::get('WorkflowTransition', '"ActionID" = ' . (int) $id);
         $type = 'WorkflowTransition';
     }
     if ($items) {
         foreach ($items as $item) {
             $new = array('data' => array('title' => $item->Title, 'attr' => array('href' => $this->Link("{$type}/{$item->ID}/edit")), 'icon' => $item->stat('icon')), 'attr' => array('id' => "{$type}_{$item->ID}", 'title' => Convert::raw2att($item->Title), 'data-id' => $item->ID, 'data-type' => $type, 'data-class' => $item->class));
             if ($item->numChildren() > 0) {
                 $new['state'] = 'closed';
             }
             $data[] = $new;
         }
     }
     return Convert::raw2json($data);
 }
示例#9
0
	/**
	 * Helper method for processing batch actions.
	 * Returns a set of status-updating JavaScript to return to the CMS.
	 *
	 * @param $objs The SS_List of 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(SS_List $objs, $helperMethod, $successMessage, $arguments = array()) {
		$status = array('modified' => array(), 'error' => array());
		
		foreach($objs as $obj) {
			
			// Perform the action
			if (!call_user_func_array(array($obj, $helperMethod), $arguments)) {
				$status['error'][$obj->ID] = '';
			}
			
			// Now make sure the tree title is appropriately updated
			$publishedRecord = DataObject::get_by_id($this->managedClass, $obj->ID);
			if ($publishedRecord) {
				$status['modified'][$publishedRecord->ID] = array(
					'TreeTitle' => $publishedRecord->TreeTitle,
				);
			}
			$obj->destroy();
			unset($obj);
		}

		$response = Controller::curr()->getResponse();
		if($response) {
			$response->setStatusCode(
				200, 
				sprintf($successMessage, $objs->Count(), count($status['error']))
			);
		}

		return Convert::raw2json($status);
	}
    /**
     * This basically merges HtmlEditorField::include_js() and HTMLEditorConfig::generateJS() to output all
     * configuration sets to a customTinyMceConfigs javascript array.
     * This is output in addition to the standard ssTinyMceConfig because a) we can't stop the default output
     * with extensions; and b) the default setting is still used for any HTMLEditorField that doesn't specify
     * it's own config.
     *
     * Calls Requirements::javascript() to load the scripts.
     */
    public static function include_js()
    {
        require_once 'tinymce/tiny_mce_gzip.php';
        $availableConfigs = HtmlEditorConfig::get_available_configs_map();
        $pluginsForTag = array();
        $languages = array();
        //$allConfigs = array();
        $settingsJS = '';
        $externalPluginsForJS = array();
        $activeConfig = HtmlEditorConfig::get_active();
        foreach ($availableConfigs as $identifier => $friendlyName) {
            $configObj = CustomHtmlEditorConfig::get($identifier);
            $internalPluginsForJS = array();
            $configObj->getConfig()->setOption('language', i18n::get_tinymce_lang());
            if (!$configObj->getConfig()->getOption('content_css')) {
                $configObj->getConfig()->setOption('content_css', $activeConfig->getOption('content_css'));
            }
            $settings = $configObj->getSettings();
            foreach ($configObj->getPlugins() as $plugin => $path) {
                if (!$path) {
                    $pluginsForTag[$plugin] = $plugin;
                    $internalPluginsForJS[$plugin] = $plugin;
                } else {
                    $internalPluginsForJS[$plugin] = '-' . $plugin;
                    $externalPluginsForJS[$plugin] = sprintf('tinymce.PluginManager.load("%s", "%s");' . "\n", $plugin, $path);
                }
            }
            $language = $configObj->getConfig()->getOption('language');
            if ($language) {
                $languages[$language] = $language;
            }
            $settings['plugins'] = implode(',', $internalPluginsForJS);
            $buttons = $configObj->getButtons();
            foreach ($buttons as $i => $buttons) {
                $settings['theme_advanced_buttons' . $i] = implode(',', $buttons);
            }
            $settingsJS .= "customTinyMceConfigs['" . $identifier . "'] = " . Convert::raw2json($settings) . ";\n";
        }
        if (Config::inst()->get('HtmlEditorField', 'use_gzip')) {
            $tag = TinyMCE_Compressor::renderTag(array('url' => THIRDPARTY_DIR . '/tinymce/tiny_mce_gzip.php', 'plugins' => implode(',', $pluginsForTag), 'themes' => 'advanced', 'languages' => implode(',', $languages)), true);
            preg_match('/src="([^"]*)"/', $tag, $matches);
            Requirements::javascript($matches[1]);
        } else {
            Requirements::javascript(MCE_ROOT . 'tiny_mce_src.js');
        }
        $externalPluginsJS = implode('', $externalPluginsForJS);
        $script = <<<JS
\t\t\tif((typeof tinyMCE != 'undefined')) {
\t\t\t\t{$externalPluginsJS}

\t\t\t\tif (typeof customTinyMceConfigs == 'undefined') {
\t\t\t\t\tvar customTinyMceConfigs = [];
\t\t\t\t}
\t\t\t\t{$settingsJS}
\t\t\t}

JS;
        Requirements::customScript($script, 'htmlEditorConfigs');
    }
 /**
  * Request nodes from the server
  *
  * @param SS_HTTPRequest $request
  * @return JSONString
  */
 public function childnodes($request)
 {
     $data = array();
     $rootObjectType = 'SiteTree';
     if ($request->param('ID')) {
         $rootObjectType = $request->param('ID');
     }
     if ($request->getVar('search')) {
         return $this->performSearch($request->getVar('search'), $rootObjectType);
     }
     $parentId = $request->getVar('id');
     if (!$parentId) {
         $parentId = $rootObjectType . '-0';
     }
     $selectable = null;
     if ($request->param('OtherID')) {
         $selectable = explode(',', $request->param('OtherID'));
     }
     list($type, $id) = explode('-', $parentId);
     if (!$type || $id < 0) {
         $data = array(0 => array('data' => 'An error has occurred'));
     } else {
         $children = null;
         if ($id == 0) {
             $children = DataObject::get($rootObjectType, 'ParentID = 0');
         } else {
             $object = DataObject::get_by_id($type, $id);
             $children = $this->childrenOfNode($object);
         }
         $data = array();
         if ($children && count($children)) {
             foreach ($children as $child) {
                 if ($child->ID < 0) {
                     continue;
                 }
                 $haskids = $child->numChildren() > 0;
                 $nodeData = array('title' => isset($child->MenuTitle) ? $child->MenuTitle : $child->Title);
                 if ($selectable && !in_array($child->ClassName, $selectable)) {
                     $nodeData['clickable'] = false;
                 }
                 $thumbs = null;
                 if ($child->ClassName == 'Image') {
                     $thumbs = $this->generateThumbnails($child);
                     $nodeData['icon'] = $thumbs['x16'];
                 } else {
                     if (!$haskids) {
                         $nodeData['icon'] = 'frontend-editing/images/page.png';
                     }
                 }
                 $nodeEntry = array('attributes' => array('id' => $child->ClassName . '-' . $child->ID, 'title' => Convert::raw2att($nodeData['title']), 'link' => $child->RelativeLink()), 'data' => $nodeData, 'state' => $haskids ? 'closed' : 'open');
                 if ($thumbs) {
                     $nodeEntry['thumbs'] = $thumbs;
                 }
                 $data[] = $nodeEntry;
             }
         }
     }
     return Convert::raw2json($data);
 }
 function WidgetSetupJSON()
 {
     $settings = $this->WidgetSetup();
     $settings['type'] = $this->type;
     $settings['title'] = $this->FavesTitle;
     $settings['subject'] = $this->FavesSubject;
     return Convert::raw2json($settings);
 }
 /**
  * Unlink the selected records passed from the unlink bulk action.
  * 
  * @param SS_HTTPRequest $request
  *
  * @return SS_HTTPResponse List of affected records ID
  */
 public function unLink(SS_HTTPRequest $request)
 {
     $ids = $this->getRecordIDList();
     $this->gridField->list->removeMany($ids);
     $response = new SS_HTTPResponse(Convert::raw2json(array('done' => true, 'records' => $ids)));
     $response->addHeader('Content-Type', 'text/json');
     return $response;
 }
 public function FieldHolder($properties = array())
 {
     $config = array('datetimeorder' => $this->getConfig('datetimeorder'));
     $config = array_filter($config);
     $this->addExtraClass('fieldgroup');
     $this->addExtraClass(Convert::raw2json($config));
     return parent::FieldHolder($properties);
 }
 function WidgetSetupJSON()
 {
     $settings = $this->WidgetSetup();
     $settings['type'] = $this->type;
     $settings['title'] = $this->SearchTitle;
     $settings['search'] = $this->SearchPhrase;
     $settings['subject'] = $this->SearchSubject;
     return Convert::raw2json($settings);
 }
 /**
  * Handles returning a JSON response, makes sure Content-Type header is set
  *
  * @param array $array
  * @param bool $isJson Is the passed string already a json string
  * @return SS_HTTPResponse
  */
 public function jsonResponse($array, $isJson = false)
 {
     $json = $array;
     if (!$isJson) {
         $json = Convert::raw2json($array);
     }
     $response = new SS_HTTPResponse($json);
     $response->addHeader('Content-Type', 'application/json');
     $response->addHeader('Vary', 'Accept');
     return $response;
 }
 /**
  * Delete the selected records passed from the delete bulk action.
  * 
  * @param SS_HTTPRequest $request
  *
  * @return SS_HTTPResponse List of deleted records ID
  */
 public function delete(SS_HTTPRequest $request)
 {
     $ids = array();
     foreach ($this->getRecords() as $record) {
         array_push($ids, $record->ID);
         $record->delete();
     }
     $response = new SS_HTTPResponse(Convert::raw2json(array('done' => true, 'records' => $ids)));
     $response->addHeader('Content-Type', 'text/json');
     return $response;
 }
 public function handleAssignBulkAction($gridField, $request)
 {
     $entity_id = $request->param('EntityID');
     $controller = $gridField->getForm()->Controller();
     $this->gridField = $gridField;
     $ids = $this->getRecordIDList();
     $this->processRecordIds($ids, $entity_id, $gridField, $request);
     $response = new SS_HTTPResponse(Convert::raw2json(array('done' => true, 'records' => $ids)));
     $response->addHeader('Content-Type', 'text/json');
     $response->setStatusCode(200);
     return $response;
 }
 /**
  * Unpublish the selected records passed from the unpublish bulk action
  *
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse List of published record IDs
  */
 public function unpublish(SS_HTTPRequest $request)
 {
     $ids = array();
     foreach ($this->getRecords() as $record) {
         if ($record->hasExtension('Versioned')) {
             array_push($ids, $record->ID);
             $record->deleteFromStage(Versioned::get_live_stage());
         }
     }
     $response = new SS_HTTPResponse(Convert::raw2json(array('done' => true, 'records' => $ids)));
     $response->addHeader('Content-Type', 'text/json');
     return $response;
 }
 public function toJson()
 {
     $res = false;
     if ($this->owner->exists()) {
         // I could not seem to find a way to access the protected data propery of Oembed_Result
         // This works.... seems a little hacky
         $reflection = new ReflectionClass($this->owner);
         $property = $reflection->getProperty("data");
         $property->setAccessible(true);
         $res = Convert::raw2json($property->getValue($this->owner));
     }
     return $res;
 }
示例#21
0
 /**
  *
  * @return SS_HTTPResponse
  */
 protected function getAPIResponse($output)
 {
     $response = $this->getResponse();
     if ($this->respondWithText()) {
         $body = print_r($output, true);
         $response->addHeader('Content-Type', 'text/plain');
     } else {
         $body = Convert::raw2json($output);
         $response->addHeader('Content-Type', 'application/json');
     }
     $response->setBody($body);
     return $response;
 }
 /**
  * Upload the given file, and import or start preview.
  * @param  SS_HTTPRequest $request
  * @return string
  */
 public function upload(SS_HTTPRequest $request)
 {
     $field = $this->getUploadField();
     $uploadResponse = $field->upload($request);
     //decode response body. ugly hack ;o
     $body = Convert::json2array($uploadResponse->getBody());
     $body = array_shift($body);
     //add extra data
     $body['import_url'] = Controller::join_links($this->Link('preview'), $body['id'], "?BackURL=" . $this->getBackURL($request));
     //don't return buttons at all
     unset($body['buttons']);
     //re-encode
     $response = new SS_HTTPResponse(Convert::raw2json(array($body)));
     return $response;
 }
	function suggest($request) {
		if(!$request->getVar('value')) return $this->httpError(405);
		$page = $this->getPage();

		// Same logic as SiteTree->onBeforeWrite
		$page->URLSegment = $page->generateURLSegment($request->getVar('value'));
		$count = 2;
		while(!$page->validURLSegment()) {
			$page->URLSegment = preg_replace('/-[0-9]+$/', null, $page->URLSegment) . '-' . $count;
			$count++;
		}
		
		Controller::curr()->getResponse()->addHeader('Content-Type', 'application/json');
		return Convert::raw2json(array('value' => $page->URLSegment));
	}
 /**
  * action for rating an object
  * @return JSON
  **/
 public function rate($request)
 {
     $class = $request->param('ObjectClassName');
     $id = (int) $request->param('ObjectID');
     $score = (int) $request->getVar('score');
     // check we have all the params
     if (!class_exists($class) || !$id || !$score || !($object = $class::get()->byID($id))) {
         return Convert::raw2json(array('status' => 'error', 'message' => _t('RateableController.ERRORMESSAGE', 'Sorry, there was an error rating this item')));
     }
     // check the object exists
     if (!$object || !$object->checkRatingsEnabled()) {
         return Convert::raw2json(array('status' => 'error', 'message' => _t('RateableController.ERRORNOTFOUNT', 'Sorry, the item you are trying to rate could not be found')));
     }
     // check the user can rate the object
     $ratingRecord = $this->rateableService->userGetRating($class, $id);
     if ($ratingRecord) {
         if (!$object->canChangeRating()) {
             return Convert::raw2json(array('status' => 'error', 'message' => _t('RateableController.ERRORALREADYRATED', 'Sorry, You have already rated this item')));
         }
         // If clicked same score as before, remove rating
         if ($score == $ratingRecord->Score) {
             // Remove rating
             $ratingRecord->delete();
             // Success
             return Convert::raw2json(array('status' => 'success', 'isremovingrating' => 1, 'averagescore' => $object->getAverageScore(), 'numberofratings' => $object->getNumberOfRatings(), 'message' => _t('RateableController.RATINGREMOVED', 'Your rating has been removed!')));
         }
     }
     // check if score is valid
     $isScoreValid = false;
     $scoreOptions = $object->getRatingOptions();
     if ($scoreOptions) {
         foreach ($scoreOptions as $scoreOption) {
             $isScoreValid = $isScoreValid || $score == $scoreOption->Score;
         }
     }
     if (!$isScoreValid) {
         return Convert::raw2json(array('status' => 'error', 'message' => _t('RateableController.ERRORINVALIDRATING', 'You sent an invalid rating.')));
     }
     // create the rating
     $isRatingNew = !$ratingRecord;
     if (!$ratingRecord) {
         $ratingRecord = Rating::create(array('ObjectID' => $id, 'ObjectClass' => $class));
     }
     $ratingRecord->Score = $score;
     $ratingRecord->write();
     // success
     return Convert::raw2json(array('status' => 'success', 'isnew' => $isRatingNew, 'averagescore' => $object->getAverageScore(), 'numberofratings' => $object->getNumberOfRatings(), 'message' => $isRatingNew ? _t('RateableController.THANKYOUMESSAGE', 'Thanks for rating!') : _t('RateableController.CHANGEMESSAGE', 'Your rating has been changed!')));
 }
 public function convert($set)
 {
     $ret = new stdClass();
     $ret->items = array();
     foreach ($set as $item) {
         if ($item instanceof Object && $item->hasMethod('toFilteredMap')) {
             $ret->items[] = $item->toFilteredMap();
         } else {
             if (method_exists($item, 'toMap')) {
                 $ret->items[] = $item->toMap();
             } else {
                 $ret->items[] = $item;
             }
         }
     }
     return Convert::raw2json($ret);
 }
 /**
  * Creates and return the editing interface
  * 
  * @return string Form's HTML
  */
 public function index()
 {
     $form = $this->listForm();
     $form->setTemplate('LeftAndMain_EditForm');
     $form->addExtraClass('center cms-content');
     $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
     if ($this->request->isAjax()) {
         $response = new SS_HTTPResponse(Convert::raw2json(array('Content' => $form->forAjaxTemplate()->getValue())));
         $response->addHeader('X-Pjax', 'Content');
         $response->addHeader('Content-Type', 'text/json');
         $response->addHeader('X-Title', 'SilverStripe - Bulk ' . $this->gridField->list->dataClass . ' Editing');
         return $response;
     } else {
         $controller = $this->getToplevelController();
         return $controller->customise(array('Content' => $form));
     }
 }
 /**
  * Helper method for responding to a back action request
  * @param $successMessage string - The message to return as a notification.
  * Can have up to two %d's in it. The first will be replaced by the number of successful
  * changes, the second by the number of failures
  * @param $status array - A status array like batchactions builds. Should be
  * key => value pairs, the key can be any string: "error" indicates errors, anything
  * else indicates a type of success. The value is an array. We don't care what's in it,
  * we just use count($value) to find the number of items that succeeded or failed
  */
 public function response($successMessage, $status)
 {
     $count = 0;
     $errors = 0;
     foreach ($status as $k => $v) {
         if ($k == 'errors') {
             $errors = count($v);
         } else {
             $count += count($v);
         }
     }
     $response = Controller::curr()->getResponse();
     if ($response) {
         $response->setStatusCode(200, sprintf($successMessage, $count, $errors));
     }
     return Convert::raw2json($status);
 }
 /**
  * Unlink the selected records by setting the foreign key to zero
  * in both Stage and Live tables.
  *
  * @param SS_HTTPRequest $request
  * @return SS_HTTPResponse List of published record IDs
  */
 public function versionedunlink(SS_HTTPRequest $request)
 {
     $ids = $this->getRecordIDList();
     // remove the selected entries from Stage.
     $this->gridField->list->removeMany($ids);
     // Unpublish the unlinked records.
     // This is potentially destructive, but there's no other "good" way to do this.
     // When a unlinked record gets added to another page, the only way to "activate" the
     // record is to publish it.. so the published version will be overwritten anyway!
     foreach ($this->getRecords() as $record) {
         if ($record->hasExtension('Versioned')) {
             $record->deleteFromStage(Versioned::get_live_stage());
         }
     }
     $response = new SS_HTTPResponse(Convert::raw2json(array('done' => true, 'records' => $ids)));
     $response->addHeader('Content-Type', 'text/json');
     return $response;
 }
示例#29
0
 public function Field($properties = array())
 {
     $record = $this->getRecord();
     $name = $this->getName();
     // if there is a has_one relation with that name on the record and
     // allowedMaxFileNumber has not been set, it's wanted to be 1
     if ($record && $record->exists() && $record->has_one($name) && !$this->getConfig('allowedMaxFileNumber')) {
         $this->setConfig('allowedMaxFileNumber', 1);
     }
     Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery-ui.js');
     Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js');
     Requirements::javascript(FRAMEWORK_DIR . '/javascript/i18n.js');
     Requirements::javascript(FRAMEWORK_ADMIN_DIR . '/javascript/ssui.core.js');
     Requirements::combine_files('uploadfield.js', array(THIRDPARTY_DIR . '/javascript-templates/tmpl.js', THIRDPARTY_DIR . '/javascript-loadimage/load-image.js', THIRDPARTY_DIR . '/jquery-fileupload/jquery.iframe-transport.js', THIRDPARTY_DIR . '/jquery-fileupload/cors/jquery.xdr-transport.js', THIRDPARTY_DIR . '/jquery-fileupload/jquery.fileupload.js', THIRDPARTY_DIR . '/jquery-fileupload/jquery.fileupload-ui.js', FRAMEWORK_DIR . '/javascript/UploadField_uploadtemplate.js', FRAMEWORK_DIR . '/javascript/UploadField_downloadtemplate.js', FRAMEWORK_DIR . '/javascript/UploadField.js'));
     Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
     // Requirements::javascript('gallery/javascript/GalleryUploadField.js');
     Requirements::css(THIRDPARTY_DIR . '/jquery-ui-themes/smoothness/jquery-ui.css');
     // TODO hmmm, remove it?
     Requirements::css(FRAMEWORK_DIR . '/css/UploadField.css');
     // Requirements::css('gallery/css/GalleryUploadField.css');
     $allowedMaxFileNumber = $this->getAllowedMaxFileNumber();
     $config = array('url' => $this->Link('upload'), 'urlSelectDialog' => $this->Link('select'), 'urlAttach' => $this->Link('attach'), 'urlSort' => $this->Link('sort'), 'urlFileExists' => $this->link('fileexists'), 'acceptFileTypes' => '.+$', 'maxNumberOfFiles' => $allowedMaxFileNumber ? $allowedMaxFileNumber - count($this->getItemIDs()) : null);
     if (count($this->getValidator()->getAllowedExtensions())) {
         $allowedExtensions = $this->getValidator()->getAllowedExtensions();
         $config['acceptFileTypes'] = '(\\.|\\/)(' . implode('|', $allowedExtensions) . ')$';
         $config['errorMessages']['acceptFileTypes'] = _t('File.INVALIDEXTENSIONSHORT', 'Extension is not allowed');
     }
     if ($this->getValidator()->getAllowedMaxFileSize()) {
         $config['maxFileSize'] = $this->getValidator()->getAllowedMaxFileSize();
         $config['errorMessages']['maxFileSize'] = _t('File.TOOLARGESHORT', 'Filesize exceeds {size}', array('size' => File::format_size($config['maxFileSize'])));
     }
     if ($config['maxNumberOfFiles'] > 1) {
         $config['errorMessages']['maxNumberOfFiles'] = _t('UploadField.MAXNUMBEROFFILESSHORT', 'Can only upload {count} files', array('count' => $config['maxNumberOfFiles']));
     }
     $configOverwrite = array();
     if (is_numeric($config['maxNumberOfFiles']) && $this->getItems()->count()) {
         $configOverwrite['maxNumberOfFiles'] = $config['maxNumberOfFiles'] - $this->getItems()->count();
     }
     $config = array_merge($config, $this->ufConfig, $configOverwrite);
     return $this->customise(array('configString' => str_replace('"', "&quot;", Convert::raw2json($config)), 'config' => new ArrayData($config), 'multiple' => $config['maxNumberOfFiles'] !== 1, 'displayInput' => !isset($configOverwrite['maxNumberOfFiles']) || $configOverwrite['maxNumberOfFiles']))->renderWith($this->getTemplates());
 }
 /**
  * Helper method for responding to a back action request
  * @param string $successMessage The message to return as a notification.
  * Can have up to two %d's in it. The first will be replaced by the number of successful
  * changes, the second by the number of failures
  * @param array $status A status array like batchactions builds. Should be
  * key => value pairs, the key can be any string: "error" indicates errors, anything
  * else indicates a type of success. The value is an array. We don't care what's in it,
  * we just use count($value) to find the number of items that succeeded or failed
  * @return string
  */
 public function response($successMessage, $status)
 {
     $count = 0;
     $errors = 0;
     foreach ($status as $k => $v) {
         switch ($k) {
             case 'error':
                 $errors += count($v);
                 break;
             case 'success':
                 $count += count($v);
                 break;
         }
     }
     $response = Controller::curr()->getResponse();
     if ($response) {
         $response->setStatusCode(200, sprintf($successMessage, $count, $errors));
     }
     return Convert::raw2json($status);
 }