Beispiel #1
0
 protected function getUser($value, $default = 0)
 {
     $currentAdmin = APIHelpers::getkey($_SESSION, 'mgrInternalKey', 0);
     $value = (int) $value;
     if (!empty($value)) {
         $by = $this->findUserBy($value);
         $exists = $this->managerUsers->exists(function ($key, $val) use($by, $value) {
             return $val->containsKey($by) && $val->get($by) === (string) $value;
         });
         if (!$exists) {
             $value = 0;
         }
     }
     if (empty($value)) {
         $value = empty($currentAdmin) ? $default : $currentAdmin;
     }
     return $value;
 }
Beispiel #2
0
 public function getCut()
 {
     return \APIHelpers::getkey($this->_cfg, 'cut', '<cut/>');
 }
        }
        return $url;
    }
}
$params = is_array($modx->event->params) ? $modx->event->params : array();
$out = $beforePage = $afterPage = '';
$display = (int) APIHelpers::getkey($params, 'display', '10');
$dateSource = APIHelpers::getkey($params, 'dateSource', 'content');
$dateField = APIHelpers::getkey($params, 'dateField', 'if(pub_date=0,createdon,pub_date)');
$tmp = date("Y-m-d H:i:s");
$currentDay = APIHelpers::getkey($params, 'currentDay', $tmp);
// Текущий день
if (!validateDate($currentDay)) {
    $currentDay = $tmp;
}
$start = (int) APIHelpers::getkey($_GET, 'start', '0');
$elements = array('offset' => $start);
//Если положительное значение, то нужы события предстоящие. Если отрицательное - прошедшее
$rule = $start >= 0 ? 'after' : 'before';
$noRule = $start >= 0 ? 'before' : 'after';
if ($start < 0) {
    $start = abs($start) > $display ? $start + $display : 0;
}
$d = $modx->db->escape($currentDay);
if ($dateSource == 'tv') {
    $params['tvSortType'] = 'TVDATETIME';
    $query = array('after' => "STR_TO_DATE(`dltv_" . $dateField . "_1`.`value`,'%d-%m-%Y %H:%i:%s') >= '" . $d . "'", 'before' => "STR_TO_DATE(`dltv_" . $dateField . "_1`.`value`,'%d-%m-%Y %H:%i:%s') < '" . $d . "'");
} else {
    $query = array('after' => "FROM_UNIXTIME(" . $dateField . ") >= '" . $d . "'", 'before' => "FROM_UNIXTIME(" . $dateField . ") < '" . $d . "'");
}
$sort = array('after' => 'ASC', 'before' => 'DESC');
 /**
  * Разбор строки фильтрации
  *
  * @param $filter строка фильтрации
  * @return bool результат разбора фильтра
  */
 protected function parseFilter($filter)
 {
     // first parse the give filter string
     $parsed = explode(':', $filter, 4);
     $this->field = APIHelpers::getkey($parsed, 1);
     $this->operator = APIHelpers::getkey($parsed, 2);
     $this->value = APIHelpers::getkey($parsed, 3);
     // exit if something is wrong
     return !(empty($this->field) || empty($this->operator) || is_null($this->value));
 }
Beispiel #5
0
 protected final function checkVersion($version, $dmi3yy = true)
 {
     $flag = false;
     $currentVer = $this->modx->getVersionData('version');
     if (is_array($currentVer)) {
         $currentVer = APIHelpers::getkey($currentVer, 'version', '');
     }
     $tmp = substr($currentVer, 0, strlen($version));
     if (version_compare($tmp, $version, '>=')) {
         $flag = true;
         if ($dmi3yy) {
             $flag = (bool) preg_match('/^' . $tmp . '(.*)\\-d/', $currentVer);
         }
     }
     return $flag;
 }
Beispiel #6
0
 /**
  * @todo set correct active placeholder if you work with other table. Because $item['id'] can differ of $modx->documentIdentifier (for other controller)
  * @todo set author placeholder (author name). Get id from Createdby OR editedby AND get info from extender user
  * @todo set filter placeholder with string filtering for insert URL
  */
 public function _render($tpl = '')
 {
     $out = '';
     if ($tpl == '') {
         $tpl = $this->getCFGDef('tpl', '@CODE:<a href="[+url+]">[+pagetitle+]</a><br />');
     }
     if ($tpl != '') {
         $date = $this->getCFGDef('dateSource', 'pub_date');
         $this->toPlaceholders(count($this->_docs), 1, "display");
         // [+display+] - сколько показано на странице.
         $i = 1;
         $sysPlh = $this->renameKeyArr($this->_plh, $this->getCFGDef("sysKey", "dl"));
         if (count($this->_docs) > 0) {
             /**
              * @var $extUser user_DL_Extender
              */
             if ($extUser = $this->getExtender('user')) {
                 $extUser->init($this, array('fields' => $this->getCFGDef("userFields", "")));
             }
             /**
              * @var $extSummary summary_DL_Extender
              */
             $extSummary = $this->getExtender('summary');
             /**
              * @var $extPrepare prepare_DL_Extender
              */
             $extPrepare = $this->getExtender('prepare');
             /**
              * @var $extJotCount jotcount_DL_Extender
              */
             $extJotCount = $this->getCFGdef('jotcount', 0) ? $this->getExtender('jotcount', true) : NULL;
             if ($extJotCount) {
                 $comments = $extJotCount->countComments(array_keys($this->_docs));
             }
             foreach ($this->_docs as $item) {
                 $this->renderTPL = $tpl;
                 if ($extUser) {
                     $item = $extUser->setUserData($item);
                     //[+user.id.createdby+], [+user.fullname.publishedby+], [+dl.user.publishedby+]....
                 }
                 $item['summary'] = $extSummary ? $this->getSummary($item, $extSummary, 'introtext', 'content') : '';
                 if ($extJotCount) {
                     $item['jotcount'] = APIHelpers::getkey($comments, $item['id'], 0);
                 }
                 $item = array_merge($item, $sysPlh);
                 //inside the chunks available all placeholders set via $modx->toPlaceholders with prefix id, and with prefix sysKey
                 $item['iteration'] = $i;
                 //[+iteration+] - Number element. Starting from zero
                 $item['title'] = $item['menutitle'] == '' ? $item['pagetitle'] : $item['menutitle'];
                 if ($this->getCFGDef('makeUrl', 1)) {
                     if ($item['type'] == 'reference') {
                         $item['url'] = is_numeric($item['content']) ? $this->modx->makeUrl($item['content'], '', '', $this->getCFGDef('urlScheme', '')) : $item['content'];
                     } else {
                         $item['url'] = $this->modx->makeUrl($item['id'], '', '', $this->getCFGDef('urlScheme', ''));
                     }
                 }
                 $item['date'] = isset($item[$date]) && $date != 'createdon' && $item[$date] != 0 && $item[$date] == (int) $item[$date] ? $item[$date] : $item['createdon'];
                 $item['date'] = $item['date'] + $this->modx->config['server_offset_time'];
                 if ($this->getCFGDef('dateFormat', '%d.%b.%y %H:%M') != '') {
                     $item['date'] = strftime($this->getCFGDef('dateFormat', '%d.%b.%y %H:%M'), $item['date']);
                 }
                 $findTpl = $this->renderTPL;
                 extract($this->uniformPrepare($item, $i), EXTR_SKIP);
                 if ($this->renderTPL == '') {
                     $this->renderTPL = $findTpl;
                 }
                 if ($extPrepare) {
                     $item = $extPrepare->init($this, array('data' => $item, 'nameParam' => 'prepare'));
                     if (is_bool($item) && $item === false) {
                         continue;
                     }
                 }
                 $tmp = $this->parseChunk($this->renderTPL, $item);
                 if ($this->getCFGDef('contentPlaceholder', 0) !== 0) {
                     $this->toPlaceholders($tmp, 1, "item[" . $i . "]");
                     // [+item[x]+] – individual placeholder for each iteration documents on this page
                 }
                 $out .= $tmp;
                 $i++;
             }
         } else {
             $noneTPL = $this->getCFGDef("noneTPL", "");
             $out = $noneTPL != '' ? $this->parseChunk($noneTPL, $sysPlh) : '';
         }
         $out = $this->renderWrap($out);
     } else {
         $out = 'no template';
     }
     return $this->toPlaceholders($out);
 }
 /**
  * Загрузка фильтра
  * @param string $filter срока с параметрами фильтрации
  * @return bool
  */
 protected function loadFilter($filter)
 {
     $this->debug->debug('Load filter ' . $this->debug->dumpData($filter), 'loadFilter', 2);
     $out = false;
     $fltr_params = explode(':', $filter, 2);
     $fltr = APIHelpers::getkey($fltr_params, 0, null);
     // check if the filter is implemented
     if (!is_null($fltr) && file_exists(dirname(__FILE__) . '/filter/' . $fltr . '.filter.php')) {
         require_once dirname(__FILE__) . '/filter/' . $fltr . '.filter.php';
         /**
          * @var tv_DL_filter|content_DL_filter $fltr_class
          */
         $fltr_class = $fltr . '_DL_filter';
         $this->totalFilters++;
         $fltr_obj = new $fltr_class();
         if ($fltr_obj->init($this, $filter)) {
             $out = $fltr_obj;
         } else {
             $this->debug->error("Wrong filter parameter: '{$this->debug->dumpData($filter)}'", 'Filter');
         }
     } else {
         $this->debug->error("Error load Filter: '{$this->debug->dumpData($filter)}'", 'Filter');
     }
     $this->debug->debugEnd("loadFilter");
     return $out;
 }
Beispiel #8
0
 /**
  * Редирект
  */
 public function moveTo($params)
 {
     $out = '';
     $id = (int) \APIHelpers::getkey($params, 'id', 0);
     $uri = \APIHelpers::getkey($params, 'url', '');
     if (empty($uri) && !empty($id) || !is_string($uri)) {
         $uri = $this->makeUrl($id);
     }
     $code = (int) \APIHelpers::getkey($params, 'code', 0);
     $addUrl = \APIHelpers::getkey($params, 'addUrl', '');
     if (is_scalar($addUrl) && $addUrl != '') {
         $uri .= "?" . $addUrl;
     }
     if (\APIHelpers::getkey($params, 'validate', false)) {
         if (isset($this->modx->snippetCache['getPageID'])) {
             $out = $this->modx->runSnippet('getPageID', compact('uri'));
             if (empty($out)) {
                 $uri = '';
             }
         } else {
             $uri = \DLTemplate::getInstance($this->modx)->sanitarTag($uri);
         }
     } else {
         //$modx->sendRedirect($url, 0, 'REDIRECT_HEADER', 'HTTP/1.1 307 Temporary Redirect');
         header("Location: " . $uri, true, $code > 0 ? $code : 307);
     }
     return $uri;
 }
Beispiel #9
0
<?php

include_once MODX_BASE_PATH . 'assets/snippets/DLUsers/src/Actions.php';
$params = is_array($modx->event->params) ? $modx->event->params : array();
$action = APIHelpers::getkey($params, 'action', '');
$lang = APIHelpers::getkey($params, 'lang', $modx->getConfig('manager_language'));
$userClass = APIHelpers::getkey($params, 'userClass', 'modUsers');
$DLUsers = \DLUsers\Actions::getInstance($modx, $lang, $userClass);
$out = '';
if (!empty($action) && method_exists($DLUsers, $action)) {
    $out = call_user_func_array(array($DLUsers, $action), array($params));
}
return $out;
 /**
  * Получение информации из конфига экстендера
  *
  * @param string $name имя параметра в конфиге экстендера
  * @param mixed $def значение по умолчанию, если в конфиге нет искомого параметра
  * @return mixed значение из конфига экстендера
  */
 protected function getCFGDef($name, $def)
 {
     return \APIHelpers::getkey($this->_cfg, $name, $def);
 }
Beispiel #11
0
if (is_null($activeReflect)) {
    if ($hasCurrentReflect && !$selectCurrentReflect || $appendCurrentReflect) {
        $outReflects->add($originalCurrentReflect);
    }
} else {
    $outReflects->add($activeReflect);
}
//Берем оставшее число позиций с правой стороны
$i = 0;
foreach ($rReflect as $item) {
    if (++$i > $showAfter) {
        break;
    }
    $outReflects->add($item['id']);
}
$sortDir = APIHelpers::getkey($params, 'sortDir', 'ASC');
//Сортируем результатирующий список
$outReflects = $outReflects->sort(function ($a, $b) use($sortDir, $dateFormat) {
    $aDate = DateTime::createFromFormat($dateFormat, $a);
    $bDate = DateTime::createFromFormat($dateFormat, $b);
    $out = false;
    switch ($sortDir) {
        case 'ASC':
            $out = $aDate->getTimestamp() - $bDate->getTimestamp();
            break;
        case 'DESC':
            $out = $bDate->getTimestamp() - $aDate->getTimestamp();
            break;
    }
    return $out;
})->reindex()->unique();
 /**
  * Возвращает результаты выполнения правил валидации
  * @param object $validator
  * @param array $rules
  * @param  array $fields
  * @return array
  */
 public function validate($validator, $rules, $fields)
 {
     if (empty($rules) || is_null($validator)) {
         return true;
     }
     //если правил нет, то не проверяем
     //применяем правила
     $errors = array();
     foreach ($rules as $field => $ruleSet) {
         $skipFlag = substr($field, 0, 1) == '!' ? true : false;
         if ($skipFlag) {
             $field = substr($field, 1);
         }
         $value = \APIHelpers::getkey($fields, $field);
         if ($skipFlag && empty($value)) {
             continue;
         }
         foreach ($ruleSet as $rule => $description) {
             $inverseFlag = substr($rule, 0, 1) == '!' ? true : false;
             if ($inverseFlag) {
                 $rule = substr($rule, 1);
             }
             $result = true;
             if (is_array($description)) {
                 if (isset($description['params'])) {
                     if (is_array($description['params'])) {
                         $params = $description['params'];
                         $params = array_merge(array($value), $params);
                     } else {
                         $params = array($value, $description['params']);
                     }
                 }
                 $message = isset($description['message']) ? $description['message'] : '';
             } else {
                 $params = array($value, $description);
                 $message = $description;
             }
             if (method_exists($validator, $rule)) {
                 $result = call_user_func_array(array($validator, $rule), $params);
             } else {
                 if (isset($description['function'])) {
                     $rule = $description['function'];
                     if (is_callable($rule)) {
                         array_unshift($params, $this);
                         $result = call_user_func_array($rule, $params);
                     }
                 }
             }
             if ($inverseFlag) {
                 $result = !$result;
             }
             if (!$result) {
                 $errors[] = array($field, $rule, $message);
                 break;
             }
         }
     }
     return $errors;
 }
    $currentReflect = APIHelpers::getkey($params, 'currentReflect', $tmp);
    if (!call_user_func($reflectValidator, $currentReflect)) {
        $currentReflect = $tmp;
    }
} else {
    $currentReflect = null;
}
/**
* activeReflect
*		Дата которую выбрал пользователь.
*
*		Если параметр не задан, то в качестве значения по умолчанию используется значение параметра currentReflect
*		При наличии ГЕТ параметра month/year, приоритет отдается ему
*/
$tmp = APIHelpers::getkey($params, 'activeReflect', $currentReflect);
$tmpGet = APIHelpers::getkey($_GET, $reflectType, $tmp);
if (!call_user_func($reflectValidator, $tmpGet)) {
    $activeReflect = $tmp;
    if (!call_user_func($reflectValidator, $activeReflect)) {
        $activeReflect = $currentReflect;
    }
} else {
    $activeReflect = $tmpGet;
}
if ($activeReflect) {
    $v = $modx->db->escape($activeReflect);
    if ($reflectSource == 'tv') {
        $params['tvSortType'] = 'TVDATETIME';
        $params['addWhereList'] = "DATE_FORMAT(STR_TO_DATE(`dltv_" . $reflectField . "_1`.`value`,'%d-%m-%Y %H:%i:%s'), '" . $sqlDateFormat . "')='" . $v . "'";
    } else {
        $params['addWhereList'] = "DATE_FORMAT(FROM_UNIXTIME(" . $reflectField . "), '" . $sqlDateFormat . "')='" . $v . "'";