예제 #1
0
 /**
  * @return callable|null
  */
 public function getValueConverter()
 {
     if (empty(parent::getValueConverter())) {
         switch ($this->getType()) {
             case self::TYPE_BOOL:
                 $this->setValueConverter(function ($value) {
                     return CmfConfig::transBase('.item_details.field.bool.' . ($value ? 'yes' : 'no'));
                 });
                 break;
             case self::TYPE_IMAGE:
                 $this->setValueConverter(function ($value, DbColumnConfig $columnConfig, array $record) {
                     if (!empty($value) && is_array($value) && !empty($value['url']) && is_array($value['url'])) {
                         if (count($value['url']) > 0) {
                             unset($value['url']['source']);
                         }
                         $images = [];
                         $translationPath = CmfConfig::getInstance()->custom_dictionary_name() . '.' . $columnConfig->getDbTableConfig()->getName() . '.item_details.field.' . $columnConfig->getName() . '_version.';
                         foreach ($value['url'] as $key => $url) {
                             $images[] = ['label' => trans($translationPath . $key), 'url' => $url];
                         }
                         return $images;
                     } else {
                         return [];
                     }
                 });
                 break;
         }
     }
     return parent::getValueConverter();
 }
예제 #2
0
파일: helpers.php 프로젝트: swayok/PeskyCMF
 /**
  * @param null|string $fallbackUrl
  * @param null|string $message
  * @return \PeskyCMF\Http\CmfJsonResponse
  */
 function cmfJsonResponseForHttp404($fallbackUrl = null, $message = null)
 {
     if (empty($message)) {
         $message = \PeskyCMF\Config\CmfConfig::transBase('.error.http404');
     }
     if (empty($fallbackUrl)) {
         $fallbackUrl = route('cmf_start_page');
     }
     return cmfServiceJsonResponse(\PeskyCMF\HttpCode::NOT_FOUND)->setMessage($message)->goBack($fallbackUrl);
 }
예제 #3
0
 /**
  * @param string $type
  * @return $this
  */
 public function setType($type)
 {
     parent::setType($type);
     switch ($this->type) {
         case self::TYPE_BOOL:
             $this->setValueConverter(function ($value) {
                 return CmfConfig::transBase('.datagrid.field.bool.' . ($value ? 'yes' : 'no'));
             });
             break;
     }
     return $this;
 }
예제 #4
0
 public function updateAdminProfile(Request $request)
 {
     $admin = $this->getAdmin();
     $updates = $this->validateAndGetAdminProfileUpdates($request, $admin);
     if (!is_array($updates)) {
         return $updates;
     } else {
         $admin->begin()->updateValues($updates);
         if (!empty(trim($request->data('new_password')))) {
             $admin->setPassword($request->data('new_password'));
         }
         if ($admin->commit()) {
             return cmfServiceJsonResponse()->setMessage(CmfConfig::transCustom('.page.profile.saved'))->reloadPage();
         } else {
             return cmfServiceJsonResponse(HttpCode::SERVER_ERROR)->setMessage(CmfConfig::transBase('.form.failed_to_save_resource_data'))->reloadPage();
         }
     }
 }
예제 #5
0
 protected function convertSomeExceptionsToJsonResponses(\Exception $exc)
 {
     switch (get_class($exc)) {
         case DbObjectValidationException::class:
             /** @var DbObjectValidationException $exc */
             return new JsonResponse(['_message' => CmfConfig::transBase('.error.invalid_data_received'), 'errors' => $exc->getValidationErrors()], HttpCode::INVALID);
         case NotFoundHttpException::class:
             return new JsonResponse(['_message' => CmfConfig::transBase('.error.http404')], HttpCode::NOT_FOUND);
         case HttpException::class:
             /** @var HttpException $exc */
             $data = json_decode($exc->getMessage(), true);
             if ($data === false) {
                 $data = ['_message' => $exc->getMessage()];
             }
             return new JsonResponse($data, $exc->getStatusCode());
         default:
             return $this->defaultConvertExceptionToResponse($exc);
     }
 }
예제 #6
0
 /**
  * Handle an incoming request.
  *
  * @param Request $request
  * @param \Closure $next
  * @return mixed
  */
 public function handle(Request $request, Closure $next)
 {
     if (!$request->ajax()) {
         abort(HttpCode::FORBIDDEN, 'Only ajax requests');
     }
     try {
         return $next($request);
     } catch (DbObjectValidationException $exc) {
         return new JsonResponse(['_message' => trans(CmfConfig::transBase('.error.invalid_data_received')), 'errors' => $exc->getValidationErrors()], HttpCode::INVALID);
     } catch (HttpException $exc) {
         if ($exc->getStatusCode() === HttpCode::INVALID) {
             $data = json_decode($exc->getMessage(), true);
             if (!empty($data) && !empty($data['_message'])) {
                 return new JsonResponse(['_message' => $data['_message'], 'errors' => empty($data['errors']) ? [] : $data['errors']], HttpCode::INVALID);
             }
         }
         throw $exc;
     }
 }
예제 #7
0
 /**
  * Request must be done via ajax
  * You can specify a fallback url OR 'route' with optional 'params' via 'fallback' key in route config:
  * Example:
  * Route::get('forgot_password/{param}', [
  *  'middleware' => AjaxOnly::class,
  *  'fallback' => '/some/url'
  *  // or
  *  'fallback' => '/some/url/{param}'
  *  // or
  *  'fallback' => [
  *      'route' => 'cmf_login',
  *      'params' => [] //< optional, can be array or boolean (by default === true: pass params from original url)
  *  ],
  *  ...
  * ]
  * If 'params' === true - all params retrieved from original URL will be passed to fallback route
  * If 'params' === false - all params retrieved from original URL will be passed to fallback route
  *
  * @param Request $request
  * @param \Closure $next
  * @return mixed
  * @throws \InvalidArgumentException
  */
 public function handle(Request $request, Closure $next)
 {
     if (!$request->ajax()) {
         // maybe there is a fallback?
         $fallback = array_get($request->route()->getAction(), 'fallback', []);
         if (!empty($fallback) && is_string($fallback)) {
             return new RedirectResponse(StringUtils::insert($fallback, $request->route()->parameters(), ['before' => '{', 'after' => '}']));
         } else {
             if (!empty($fallback['route'])) {
                 $params = array_get($fallback, 'params', true);
                 if ($params === true) {
                     $params = $request->route()->parameters();
                 } else {
                     if ($params instanceof \Closure) {
                         $params = call_user_func($params, $request->route()->parameters());
                     } else {
                         if ($params === false || !is_array($params)) {
                             $params = [];
                         }
                     }
                 }
                 return new RedirectResponse(route($fallback['route'], $params));
             } else {
                 abort(HttpCode::FORBIDDEN, 'Only ajax requests');
             }
         }
     }
     try {
         return $next($request);
     } catch (DbObjectValidationException $exc) {
         return new JsonResponse(['_message' => trans(CmfConfig::transBase('.error.invalid_data_received')), 'errors' => $exc->getValidationErrors()], HttpCode::INVALID);
     } catch (HttpException $exc) {
         if ($exc->getStatusCode() === HttpCode::INVALID) {
             $data = json_decode($exc->getMessage(), true);
             if (!empty($data) && !empty($data['_message'])) {
                 return new JsonResponse(['_message' => $data['_message'], 'errors' => empty($data['errors']) ? [] : $data['errors']], HttpCode::INVALID);
             }
         }
         throw $exc;
     }
 }
예제 #8
0
 /**
  * Abort with HTTP code 404
  */
 protected function sendRecordNotFoundResponse()
 {
     abort(HttpCode::NOT_FOUND, CmfConfig::transBase('.error.db_record_not_exists'));
 }
예제 #9
0
파일: bool.php 프로젝트: swayok/PeskyCMF
<?php

/**
 * @var \PeskyCMF\Scaffold\Form\InputRendererConfig $rendererConfig
 * @var \PeskyCMF\Scaffold\ItemDetails\ItemDetailsConfig $actionConfig
 * @var \PeskyCMF\Scaffold\ItemDetails\ItemDetailsFieldConfig $fieldConfig
 * @var array|null $options
 * @var \PeskyCMF\Db\CmfDbModel $model
 * @var string $translationPrefix
 */
if (empty($options)) {
    $options = [];
}
$yes = empty($options['yes']) ? \PeskyCMF\Config\CmfConfig::transBase('.item_details.field.bool.yes') : $options['yes'];
$no = empty($options['no']) ? \PeskyCMF\Config\CmfConfig::transBase('.item_details.field.bool.no') : $options['no'];
echo '{{? !!it.' . $fieldConfig->getName() . ' }}' . $yes . '{{??}}' . $no . '{{?}}';
예제 #10
0
 /**
  * @param CmfDbModel $model
  * @param null|string $message
  * @return $this
  */
 protected function sendItemNotFoundResponse(CmfDbModel $model, $message = null)
 {
     if (empty($message)) {
         $message = CmfConfig::transBase('.error.resource_item_not_found');
     }
     return cmfJsonResponseForHttp404(route('cmf_items_table', [$this->getTableNameForRoutes()]), $message);
 }
예제 #11
0
                            <?php 
    }
    ?>
                            <?php 
    if ($itemDetailsConfig->isEditAllowed()) {
        ?>
                                <?php 
        $editUrl = str_ireplace(':id:', "{{= it.{$model->getPkColumnName()} }}", route('cmf_item_edit_form', [$model->getTableName(), ':id:']));
        ?>
                                {{? !!it.___edit_allowed }}
                                <a class="btn btn-success" href="<?php 
        echo $editUrl;
        ?>
">
                                    <?php 
        echo \PeskyCMF\Config\CmfConfig::transBase('.item_details.toolbar.edit');
        ?>
                                </a>
                                {{?}}
                            <?php 
    }
    ?>
                        </div>
                    </div>
                </div>
            </div>
        </div></div>
    </div>
</script>
<?php 
} catch (Exception $exc) {
예제 #12
0
 protected function getValidationErrorsResponseMessage()
 {
     return CmfConfig::transBase('.error.invalid_data_received');
 }
예제 #13
0
파일: trigger.php 프로젝트: swayok/PeskyCMF
?>
" type="hidden" value="0">
    <label class="ib mr15 lh35" for="<?php 
echo $rendererConfig->getAttribute('id');
?>
"><?php 
echo $fieldConfig->getLabel();
?>
</label>
    <div class="ib">
        <input {{? !!it.isCreation }}<?php 
echo $attributesForCreate;
?>
{{??}}<?php 
echo $attributesForEdit;
?>
{{?}}
            {{? !!it.<?php 
echo $fieldConfig->getName();
?>
 }}checked{{?}}
            data-on-text="<?php 
echo \PeskyCMF\Config\CmfConfig::transBase('.form.field.bool.yes');
?>
"
            data-off-text="<?php 
echo \PeskyCMF\Config\CmfConfig::transBase('.form.field.bool.no');
?>
">
    </div>
</div>
예제 #14
0
 /**
  * @return DataGridFieldConfig
  */
 protected function getDataGridFieldConfigForRowActions()
 {
     return DataGridFieldConfig::create()->setIsDbField(false)->setName(static::ROW_ACTIONS_COLUMN_NAME)->setLabel(CmfConfig::transBase('.datagrid.actions.column_label'))->setType(DataGridFieldConfig::TYPE_STRING);
 }
예제 #15
0
    </section>
</aside>

<header class="main-header">
    <a href="{{ route('cmf_start_page', [], false, '/') }}" class="logo">
        <span class="logo-lg">
            {!! \PeskyCMF\Config\CmfConfig::getInstance()->sidebar_logo() !!}
        </span>
    </a>
</header>

<div class="content-wrapper" id="section-content">

</div>

@include(\PeskyCMF\Config\CmfConfig::getInstance()->footer_view())

<script type="application/javascript">
    GlobalVars.setLocalizationStrings(<?php 
echo json_encode(\PeskyCMF\Config\CmfConfig::transBase('.ui.js_component'), JSON_UNESCAPED_UNICODE);
?>
);
    $(document).ready(function () {
        $.AdminLTE.tree('.sidebar');
        setTimeout(function () {
            // without timeout it works not correctly
            $.AdminLTE.layout.fix();
            $.AdminLTE.layout.fixSidebar();
        }, 1);
    })
</script>
예제 #16
0
 /**
  * @param string $type
  * @param bool $canBeNull
  * @return $this
  * @throws ScaffoldException
  */
 public function setDataType($type, $canBeNull = false)
 {
     if (!array_key_exists($type, static::$dataTypeDefaultOperatorsGroup)) {
         throw new ScaffoldException("Unknown filter type: {$type}");
     }
     $this->dataType = $type;
     $this->operators = static::$operatorGroups[static::$dataTypeDefaultOperatorsGroup[$type]];
     if ($canBeNull) {
         $this->canBeNull();
     }
     $this->setInputType(static::$dataTypeToDefaultInputType[$type]);
     switch ($type) {
         case static::TYPE_BOOL:
             $this->setAllowedValues(['t' => CmfConfig::transBase('.datagrid.filter.bool.yes'), 'f' => CmfConfig::transBase('.datagrid.filter.bool.no')]);
             break;
         case static::TYPE_TIME:
             $this->setFormat('HH:mm');
             break;
         case static::TYPE_DATE:
         case static::TYPE_TIMESTAMP:
             $pluginConfig = ['locale' => app()->getLocale(), 'sideBySide' => false, 'useCurrent' => true, 'toolbarPlacement' => 'bottom', 'showTodayButton' => true, 'showClear' => false, 'showClose' => true, 'keepOpen' => false];
             if ($type === static::TYPE_DATE) {
                 $this->setFormat('YYYY-MM-DD');
             } else {
                 $this->setFormat('YYYY-MM-DD HH:mm');
                 $pluginConfig['sideBySide'] = true;
             }
             $pluginConfig['format'] = $this->getFormat();
             $this->setPlugin('datetimepicker')->setPluginConfig($pluginConfig);
             break;
     }
     return $this;
 }
예제 #17
0
 protected function getValidationErrorsResponseMessage()
 {
     return isset($this->errorMessage) ? trans($this->errorMessage) : CmfConfig::transBase('.error.invalid_data_received');
 }
예제 #18
0
 public function buildLinkToExternalRecord(DbColumnConfig $columnConfig, array $record, $linkLabel = null)
 {
     if (empty($record[$columnConfig->getName()])) {
         return '-';
     }
     $relationConfig = null;
     $relationAlias = null;
     foreach ($columnConfig->getRelations() as $alias => $relation) {
         if (in_array($relation->getType(), [DbRelationConfig::BELONGS_TO, DbRelationConfig::HAS_ONE])) {
             $relationConfig = $relation;
             $relationAlias = $alias;
             break;
         }
     }
     if (empty($relation)) {
         throw new ScaffoldFieldException($this, "Column [{$columnConfig->getName()}] has no fitting relation");
     }
     if (empty($record[$relationAlias]) || empty($record[$relationAlias][$relationConfig->getDisplayField()])) {
         return CmfConfig::transBase('.item_details.field.no_relation');
     } else {
         return Tag::a(empty($linkLabel) ? $record[$relationAlias][$relationConfig->getDisplayField()] : $linkLabel)->setHref(route('cmf_item_details', [$relationConfig->getForeignTable(), $record[$columnConfig->getName()]]))->build();
     }
 }
예제 #19
0
 protected function errorCodeToMessage($code, $parameters = [])
 {
     return CmfConfig::transBase('.error.' . $code, $parameters);
 }
예제 #20
0
파일: form.php 프로젝트: swayok/PeskyCMF
                            <?php 
    echo \PeskyCMF\Config\CmfConfig::transBase('.form.toolbar.delete');
    ?>
                        </a>
                        {{?}}
                    <?php 
}
?>
                <?php 
echo $endIf;
?>
                </div>
                <div class="col-xs-3 text-right">
                    <button type="submit" class="btn btn-success">
                        <?php 
echo \PeskyCMF\Config\CmfConfig::transBase('.form.toolbar.submit');
?>
                    </button>
                </div>
            </div>
            <?php 
$toolbarItems = $formConfig->getToolbarItems();
?>
            <?php 
if (count($toolbarItems) > 0) {
    ?>
                <div class="mt10 text-center">
                    <?php 
    foreach ($toolbarItems as $toolbarItem) {
        echo ' ' . preg_replace('%(:|\\%3A)([a-zA-Z0-9_]+)\\1%is', '{{= it.$2 }}', $toolbarItem) . ' ';
    }
 public static function sendItemNotFoundResponse(CmfDbModel $model)
 {
     return response()->json(['_message' => CmfConfig::transBase('.error.resource_item_not_found'), 'redirect' => 'back', 'redirect_fallback' => route('cmf_items_table', ['table_name' => $model->getTableName()])], 404);
 }
예제 #22
0
?>
        </div>
    </div>
<?php 
View::stopSection();
?>

<script type="text/html" id="item-details-tpl">
    {{? it._modal }}
        <div class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"
                        aria-label="<?php 
echo \PeskyCMF\Config\CmfConfig::transBase('.form.toolbar.close');
?>
">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title"><?php 
echo trans("{$translationPrefix}.item_details.header");
?>
</h4>
                    </div>
                    <div class="modal-body pn">
                        <?php 
echo View::yieldContent('item-detials-table');
?>
                    </div>
                    <div class="modal-footer">
예제 #23
0
        $filterConfig->setFilterLabel(trans($path));
    }
    $fitlers[] = $filterConfig->buildConfig();
}
?>
            var queryBuilderConfig = {
                filters: <?php 
echo json_encode($fitlers, JSON_UNESCAPED_UNICODE);
?>
,
                is_opened: <?php 
echo $dataGridConfig->isFilterShownByDefault() ? 'true' : 'false';
?>
            };
            DataGridSearchHelper.locale = <?php 
echo json_encode(\PeskyCMF\Config\CmfConfig::transBase('.datagrid.toolbar.filter'), JSON_UNESCAPED_UNICODE);
?>
;

            <?php 
if ($dataGridConfig->hasJsInitiator()) {
    ?>
                <?php 
    echo $dataGridConfig->getJsInitiator();
    ?>
.call($('#<?php 
    echo $dataGridId;
    ?>
'));
            <?php 
}
예제 #24
0
 /**
  * @return callable|null
  */
 public function getValueConverter()
 {
     if (empty($this->valueConverter)) {
         switch ($this->getType()) {
             case self::TYPE_BOOL:
                 return function ($value) {
                     if (!$this->isDbField()) {
                         if (!array_has($value, $this->getName())) {
                             return '-';
                         } else {
                             $value = (bool) $value[$this->getName()];
                         }
                     }
                     return CmfConfig::transBase('.datagrid.field.bool.' . ($value ? 'yes' : 'no'));
                 };
         }
     }
     return $this->valueConverter;
 }
예제 #25
0
 /**
  * @param Request $request
  * @param Admin $admin
  * @return array|\Illuminate\Http\JsonResponse
  */
 protected function validateAndGetAdminProfileUpdates(Request $request, Admin $admin)
 {
     $validationRules = ['old_password' => 'required', 'new_password' => 'min:6'];
     $fieldsToUpdate = [];
     if ($admin->_hasField('language')) {
         $validationRules['language'] = 'required|in:' . implode(CmfConfig::getInstance()->locales());
         $fieldsToUpdate[] = 'language';
     }
     if ($admin->_hasField('name')) {
         $validationRules['name'] = 'max:200';
         $fieldsToUpdate[] = 'name';
     }
     $usersTable = CmfConfig::getInstance()->users_table_name();
     $userLoginCol = CmfConfig::getInstance()->user_login_column();
     if ($admin->_hasField('email')) {
         if ($userLoginCol === 'email') {
             $validationRules['email'] = "required|email|unique:{$usersTable},email,{$admin->id},id";
         } else {
             $validationRules['email'] = "email";
         }
         $fieldsToUpdate[] = 'email';
     }
     if ($userLoginCol !== 'email') {
         $validationRules[$userLoginCol] = "required|alpha_dash|min:4|unique:{$usersTable},{$userLoginCol},{$admin->id},id";
         $fieldsToUpdate[] = $userLoginCol;
     }
     $validator = \Validator::make($request->data(), $validationRules, Set::flatten(CmfConfig::transCustom('.page.profile.errors')));
     $errors = [];
     if ($validator->fails()) {
         $errors = $validator->getMessageBag()->toArray();
     } else {
         if (!\Hash::check($request->data('old_password'), $admin->password)) {
             $errors['old_password'] = CmfConfig::transCustom('.page.profile.errors.old_password.match');
         }
     }
     if (!empty($errors)) {
         return response()->json(['errors' => $errors, 'message' => CmfConfig::transBase('.form.validation_errors')], HttpCode::INVALID);
     }
     return $request->only($fieldsToUpdate);
 }