public function entityCommand($categoryName, $entityName, $commandKey, $instanceId, Request $request) { // Find Entity config (from sharp CMS config file) $entity = SharpCmsConfig::findEntity($categoryName, $entityName); // Have to manage access auth here, because it can be managed from the config $granted = SharpAccessManager::granted('entity', $entity->commands->entity->{$commandKey}->auth ?: "update", $entity->key); if (!$granted) { return redirect("/"); } $commandForm = $this->commandsManager->getEntityCommandForm($entity, $commandKey); $error = false; if ($commandForm) { // There's a form attached to the command: if (!$request->has("sharp_form_valued")) { // Return the view of the form // to make the user fill parameters before send the command return view("sharp::cms.partials.list.commandForm", ['fields' => $commandForm, 'url' => route('cms.entityCommand', array_merge([$categoryName, $entityName, $commandKey, $instanceId], $request->all()))]); } // Form posted: call the command with the values of the form try { $commandReturn = $this->commandsManager->executeEntityCommand($entity, $commandKey, $instanceId, $request->only(array_keys($commandForm))); } catch (CommandValidationException $ex) { $commandReturn = $ex->getMessage(); $error = true; } } else { $commandReturn = $this->commandsManager->executeEntityCommand($entity, $commandKey, $instanceId); } return $this->handleCommandReturn($entity->commands->entity->{$commandKey}, $commandReturn, $categoryName, $entityName, $request->except(array_merge(["_token", "sharp_form_valued"], $commandForm ? array_keys($commandForm) : [])), $error); }
public function entityCommand($categoryName, $entityName, $commandKey, $instanceId) { // Find Entity config (from sharp CMS config file) $entity = SharpCmsConfig::findEntity($categoryName, $entityName); // Have to manage access auth here, because it can be managed from the config $granted = SharpAccessManager::granted('entity', $entity->commands->entity->{$commandKey}->auth ?: "update", $entity->key); if (!$granted) { return redirect("/"); } $commandReturn = $this->commandsManager->executeEntityCommand($entity, $commandKey, $instanceId); return $this->handleCommandReturn($entity->commands->entity->{$commandKey}, $commandReturn, $categoryName, $entityName); }
public function __construct($data, $parent) { parent::__construct($data, $parent); if (isset($this->data['extends']) && $this->data['extends']) { // This Entity is configured to extend another entity config list($cat, $ent) = explode(".", $this->data['extends']); $extendedEntity = SharpCmsConfig::findEntity($cat, $ent, false); if (!$extendedEntity) { throw new EntityConfigurationNotFoundException("Extended entity [" . $this->data['extends'] . "] configuration not found"); } $entendedEntityData = $extendedEntity->getData(); $this->data = array_merge($entendedEntityData, $this->data); } }
/** * The actual HTML creation of the field. * @return string * @throws MandatoryClassNotFoundException * @throws \Dvlpp\Sharp\Exceptions\EntityConfigurationNotFoundException * @throws \Dvlpp\Sharp\Exceptions\MandatoryEntityAttributeNotFoundException */ function make() { $this->_checkMandatoryAttributes(['listitem_template', 'result_template', 'id_attribute']); $this->addData("template", $this->field->listitem_template); $this->addData("idattr", $this->field->id_attribute); if ($this->field->min_char) { $this->addData("minchar", $this->field->min_char); } $modalTitle = $this->field->modal_title ?: trans("sharp::ui.form_customSearchField_modalTitle"); $this->addData("remote", route("cms.customSearchField", [$this->field->getCategoryKey(), $this->field->getEntityKey(), $this->fieldName])); if (!$this->instance && $this->isListItem) { // No data and part of a list item: this field is meant to be in the template item. // In this case, we don't set the "sharp-file" class which will trigger the JS code for // the file upload component creation $this->addClass('sharp-customSearch-template'); } else { $this->addClass('sharp-customSearch'); } // Render the valuated view $valuated = false; $strValuatedView = ""; if ($this->fieldValue || $this->isRepopulated()) { // Instantiate entity repository $entity = SharpCmsConfig::findEntity($this->field->getCategoryKey(), $this->field->getEntityKey()); $repo = app($entity->repository); if (!$repo instanceof SharpHasCustomSearch) { throw new MandatoryClassNotFoundException("Repository [{$entity->repository}] must implement the " . 'Dvlpp\\Sharp\\Repositories\\SharpHasCustomSearch' . " interface"); } $value = $this->fieldValue ?: $this->getOldValue(); $result = $repo->getCustomSearchResult($value); $strValuatedView = $this->wrapIntoPanel(view($this->field->result_template, $result)->render()); $valuated = true; } $strTemplateView = $this->wrapIntoPanel(view($this->field->result_template)->render(), true); // Render the result modal (where results will be displayed) $strModal = view('sharp::cms.partials.fields.customsearchfield_modal', ["field" => $this->fieldName, "title" => $modalTitle])->render(); return '<div class="search ' . ($valuated ? "hidden" : "") . '">' . Form::text("__customSearchBox__" . $this->fieldName, "", $this->attributes) . '</div>' . Form::hidden($this->fieldName, $this->fieldValue, ["autocomplete" => "off"]) . $strValuatedView . $strTemplateView . $strModal; }
/** * Updates the field value (in db). * * @param $instance * @param $data * @param $configFieldAttr * @param $dataAttribute * @param null $listKey * @throws \InvalidArgumentException */ public function updateField($instance, $data, $configFieldAttr, $dataAttribute, $listKey = null) { // First test if there is a special hook method on the controller // that takes the precedence. Method name should be : // "update[$dataAttribute]Attribute" for a normal field // "update[$listKey]List[$dataAttribute]Attribute" for an list item field. // For example : updateBooksListTitleAttribute $methodName = "update" . ($listKey ? ucFirst(Str::camel($listKey)) . "List" : "") . ucFirst(Str::camel(str_replace("~", "_", $dataAttribute))) . "Attribute"; if (method_exists($this->sharpRepository, $methodName)) { // Method exists, we call it if (!$this->sharpRepository->{$methodName}($instance, $data[$dataAttribute])) { // Returns false: we are done with this attribute. return; } } // Otherwise, we have to manage this attribute ourselves... $value = $data[$dataAttribute]; // These vars are used to store old values of $dataAttribute and $entity // in case of modification by singleRelationCase (below) $baseInstance = null; $baseAttribute = null; $isSingleRelationCase = strpos($dataAttribute, "~"); if ($isSingleRelationCase) { // If there's a "~" in the field $key, this means we are in a single relation case // (One-To-One or Belongs To). The ~ separates the relation name and the value. // For instance : boss~name indicate that the instance as a single "boss" relation, // which has a "name" attribute. list($relationKey, $relationAttribute) = explode("~", $dataAttribute); $relationObject = $instance->{$relationKey}; if (!$relationObject) { if (array_key_exists($relationKey, $this->singleRelationOneToOneObjects)) { $relationObject = $this->singleRelationOneToOneObjects[$relationKey]; } elseif (array_key_exists($relationKey, $this->singleRelationBelongsToObjects)) { $relationObject = $this->singleRelationBelongsToObjects[$relationKey]; } } if (!$relationObject) { // Related object has to be created. // If value is null, we won't create the related instance if (!$value) { return; } // We create the related object $relationObject = $instance->{$relationKey}()->getRelated()->newInstance([]); // Unset the relation to be sure that other attribute of the same relation will // use the created related object (otherwise, relation is cached to null by Laravel) unset($instance->{$relationKey}); } // Then, we have to save the related object in order to persist it at the end of the update process // We can't save it right now because of potential mandatory attributes which will be treated later // in the process, and for the OneToOne case because we can't be sure that the current instance // has an ID to provide // if($configFieldAttr->type != "list") // { if ($instance->{$relationKey}() instanceof BelongsTo) { // BelongsTo: foreign key is on the instance object side $this->singleRelationBelongsToObjects[$relationKey] = $relationObject; } else { // One-to-one or morphOne: foreign key is on the related object side $this->singleRelationOneToOneObjects[$relationKey] = $relationObject; } // } // Finally, we translate attributes to the related object $baseAttribute = $dataAttribute; $dataAttribute = $relationAttribute; $instance = $relationObject; } $valuator = null; switch ($configFieldAttr->type) { case "text": case "ref": case "refSublistItem": case "check": case "choose": case "textarea": case "password": case "markdown": case "customSearch": $valuator = new SimpleValuator($instance, $dataAttribute, $value); break; case "date": $valuator = new DateValuator($instance, $dataAttribute, $value); break; case "file": $cropValues = isset($data["__filecrop__" . $dataAttribute]) ? $data["__filecrop__" . $dataAttribute] : null; $valuator = new FileValuator($instance, $dataAttribute, $value, $this->sharpRepository, $cropValues); break; case "list": // Find list config $listFieldConfig = $this->findListConfig($baseAttribute ?: $dataAttribute); $valuator = new ListValuator($instance, $dataAttribute, $value, $listFieldConfig, $this->sharpRepository, $this); break; case "pivot": // Find pivot config $pivotConfig = $this->findPivotConfig($baseAttribute ?: $dataAttribute, $listKey); $valuator = new PivotTagValuator($instance, $dataAttribute, $value, $pivotConfig, $this->sharpRepository); break; case "embed": $embedConfig = SharpCmsConfig::findEntity($configFieldAttr->entity_category, $configFieldAttr->entity); $valuator = new EmbedValuator($instance, $dataAttribute, $value, $embedConfig, $this->sharpRepository); break; case "embed_list": $embedConfig = SharpCmsConfig::findEntity($configFieldAttr->entity_category, $configFieldAttr->entity); $valuator = new EmbedListValuator($instance, $dataAttribute, $value, $configFieldAttr, $embedConfig, $this->sharpRepository); break; case "label": // Nothing to do... return; default: throw new InvalidArgumentException("Config type [" . $configFieldAttr->type . "] is invalid."); } $valuator->valuate(); }
/** * @param $masterCategoryKey * @param $masterEntityKey * @param $masterFieldKey * @param $embeddedCategoryKey * @param $embeddedEntityKey * @param $id * @param bool $creation * @return mixed */ private function save($masterCategoryKey, $masterEntityKey, $masterFieldKey, $embeddedCategoryKey, $embeddedEntityKey, $id, $creation = false) { $data = Input::all(); // Find Entity config (from sharp CMS config file) $entity = SharpCmsConfig::findEntity($embeddedCategoryKey, $embeddedEntityKey); try { // First : validation if ($entity->validator) { $validator = App::make($entity->validator); $validator->validate($data, !$creation ? $id : null); } // Data is valid, we are going back to the master form. Let's restore the master form data... $masterInstanceData = sharp_decode_embedded_entity_data($data['masterInstanceData']); // ... add the embedded form data... $embeddedInstanceData = sharp_encode_embedded_entity_data(Input::except(["_method", "_token", "masterInstanceData", "masterInstanceId", "masterEntityLabel"])); if (strpos($masterFieldKey, ".") !== false) { // Embedded instance in part of a list item list($listKey, $itemId, $fieldKey) = explode(".", $masterFieldKey); $masterInstanceData[$listKey][$itemId][$fieldKey] = $embeddedInstanceData; } else { $masterInstanceData[$masterFieldKey] = $embeddedInstanceData; } Session::flash('masterInstanceData', serialize($masterInstanceData)); // ... and redirect back to the master entity form return $this->redirectToMaster($masterCategoryKey, $masterEntityKey, $data['masterInstanceId']); } catch (ValidationException $e) { return Redirect::back()->withInput()->withErrors($e->getErrors()); } }
/** * @return string * @throws \Dvlpp\Sharp\Exceptions\EntityConfigurationNotFoundException */ private function initValue() { // First time we display the embed field. We have to valuate its __embed_data field, // in order to post the current value of the embedded object $embeddedEntityConfig = SharpCmsConfig::findEntity($this->field->entity_category, $this->field->entity); $std = []; foreach ($embeddedEntityConfig->data["form_fields"] as $fieldKey => $configField) { $std[$fieldKey] = $this->initValueFormField($fieldKey, $configField, $this->fieldValue); } $std["__sharp_duplication"] = $this->instance->__sharp_duplication; // Add Id $std[$embeddedEntityConfig->id_attribute] = $this->fieldValue->{$embeddedEntityConfig->id_attribute}; $initialVal = sharp_encode_embedded_entity_data($std); return $initialVal; }
Route::post('/admin/cms/{category}/{entity}/{id}/activate', ["as" => "cms.activate", "uses" => '\\Dvlpp\\Sharp\\Http\\CmsController@ax_activateEntity', "before" => "sharp_access_granted:entity update *entity"]); Route::post('/admin/cms/{category}/{entity}/{id}/deactivate', ["as" => "cms.deactivate", "uses" => '\\Dvlpp\\Sharp\\Http\\CmsController@ax_deactivateEntity', "before" => "sharp_access_granted:entity update *entity"]); Route::post('/admin/cms/{category}/{entity}/reorder', ["as" => "cms.reorder", "uses" => '\\Dvlpp\\Sharp\\Http\\CmsController@ax_reorderEntities', "before" => "sharp_access_granted:entity update *entity"]); Route::post('/admin/cms/{category}/{entity}/{field}/customSearchField', ["as" => "cms.customSearchField", "uses" => '\\Dvlpp\\Sharp\\Http\\CmsController@ax_customSearchField', "before" => "sharp_access_granted:entity update *entity"]); Route::post('/admin/upload', ["as" => "upload", "uses" => '\\Dvlpp\\Sharp\\Http\\UploadController@upload']); Route::post('/admin/uploadWithThumbnail', ["as" => "uploadWithThumbnail", "uses" => '\\Dvlpp\\Sharp\\Http\\UploadController@uploadWithThumbnail']); Route::get('/admin/download/{file?}', ["as" => "download", "uses" => '\\Dvlpp\\Sharp\\Http\\UploadController@download'])->where('file', '(.*)'); Route::get('/admin/logout', ["as" => "logout", "uses" => '\\Dvlpp\\Sharp\\Http\\AuthController@logout']); }); Route::group(['before' => 'sharp_guest'], function () { Route::get('/admin/login', '\\Dvlpp\\Sharp\\Http\\AuthController@index'); Route::post('/admin/login', ["as" => "login", "uses" => '\\Dvlpp\\Sharp\\Http\\AuthController@login']); }); View::composer(['sharp::cms.cmslayout'], function ($view) { // Load categories $categories = SharpCmsConfig::listCategories(); $view->with('cmsCategories', $categories); // Get current language $language = Session::get("sharp_lang"); $languages = SharpSiteConfig::getLanguages(); if ($languages) { if (!$language || !array_key_exists($language, $languages)) { $language = array_values($languages)[0]; } else { $language = $languages[$language]; } } $view->with('language', $language); // Get sharp version $view->with('sharpVersion', File::get(__DIR__ . "/../version.txt")); });
/** * @param $categoryName * @param $entityName * @param Request $request * @param $id * @return mixed * @throws \Dvlpp\Sharp\Exceptions\EntityConfigurationNotFoundException */ private function save($categoryName, $entityName, Request $request, $id) { $creation = $id === null; $data = $request->all(); // Find Entity config (from sharp CMS config file) $entity = SharpCmsConfig::findEntity($categoryName, $entityName); // Instantiate the entity repository $repo = app($entity->repository); try { // First : validation if ($entity->validator) { $validator = app($entity->validator); $validator->validate($data, $id); } // Then : update (calling repo) if ($creation) { $repo->create($data); } else { $repo->update($id, $data); } // And redirect return redirect()->route("cms.list", [$categoryName, $entityName]); } catch (ValidationException $e) { return redirect()->back()->withInput()->withErrors($e->getErrors()); } }
/** * @param $categoryName * @param $entityName * @param $id * @return mixed */ private function save($categoryName, $entityName, $id) { $creation = $id === null; $data = Input::all(); // Find Entity config (from sharp CMS config file) $entity = SharpCmsConfig::findEntity($categoryName, $entityName); // Instantiate the entity repository $repo = App::make($entity->repository); // if duplicate / changing lang, set the new lang to repo if (isset($data['lang'])) { $repo->lang = $data['lang']; } try { // First : validation if ($entity->validator) { $validator = App::make($entity->validator); $validator->validate($data, $id); } // Then : update (calling repo) if ($creation) { $repo->create($data); } else { $repo->update($id, $data); } // And redirect return redirect()->route("cms.list", [$categoryName, $entityName]); } catch (ValidationException $e) { return redirect()->back()->withInput()->withErrors($e->getErrors()); } }