Esempio n. 1
0
 public function dumpData($data, $wrap = '', $charset = 'UTF-8')
 {
     $out = \APIHelpers::sanitarTag(print_r($data, 1), $charset);
     if (!empty($wrap) && is_string($wrap)) {
         $out = "<{$wrap}>{$out}</{$wrap}>";
     }
     return $out;
 }
Esempio n. 2
0
    static function insertUpdateInfo($conn, $old_version, $new_version, $name, $description, $userid)
    {
        try {
            $stmt = $conn->prepare('
					INSERT INTO updates(from_version, version, name, result, description, userid, datetime_update) 
					VALUES(?,?,?,?,?,?,NOW())
			');
            $stmt->execute(array($old_version, $new_version, $name, 'updated', $description, $userid));
        } catch (PDOException $e) {
            APIHelpers::showerror(1010, $e->getMessage());
        }
    }
Esempio n. 3
0
 static function loadUserProfile($conn)
 {
     try {
         $profile = array();
         $inserts = array();
         $defaults = array();
         $defaults['template'] = 'base';
         $defaults['country'] = '?';
         $defaults['city'] = '?';
         $defaults['university'] = '?';
         $defaults['game'] = '0';
         $defaults['lasteventid'] = '0';
         $query = 'SELECT * FROM users_profile WHERE userid = ?';
         $stmt = $conn->prepare($query);
         $stmt->execute(array(APISecurity::userid()));
         while ($row = $stmt->fetch()) {
             $name = $row['name'];
             $value = $row['value'];
             $profile[$name] = $value;
         }
         foreach ($defaults as $k => $v) {
             if (!isset($profile[$k])) {
                 $inserts[$k] = $v;
                 // default value
                 $profile[$k] = $v;
                 // default value
             }
         }
         foreach ($profile as $k => $v) {
             $_SESSION['user']['profile'][$k] = $v;
         }
         $stmt2 = $conn->prepare('INSERT INTO users_profile(userid,name,value,date_change) VALUES(?,?,?,NOW());');
         foreach ($inserts as $k => $v) {
             $stmt2->execute(array(APISecurity::userid(), $k, $v));
         }
     } catch (PDOException $e) {
         APIHelpers::showerror(1195, $e->getMessage());
     }
 }
Esempio n. 4
0
include_once $curdir_events_count . "/../../config/config.php";
$response = APIHelpers::startpage($config);
$conn = APIHelpers::createConnection($config);
if (!APIHelpers::issetParam('id')) {
    APIHelpers::showerror(1225, 'Not found parameter "id"');
}
$type = APIHelpers::getParam('type', '');
$id = APIHelpers::getParam('id', 0);
if (!is_numeric($id)) {
    APIHelpers::showerror(1226, 'id must be integer');
}
try {
    $params = array();
    $params[] = $id;
    $query = 'SELECT count(*) as cnt FROM public_events WHERE id > ?';
    if ($type != '') {
        $query .= ' AND type = ?';
        $params[] = $type;
    }
    $stmt = $conn->prepare($query);
    $stmt->execute($params);
    if ($row = $stmt->fetch()) {
        $count = $row['cnt'];
        $response['data']['count'] = $count;
        $response['result'] = 'ok';
    }
} catch (PDOException $e) {
    APIHelpers::showerror(1227, $e->getMessage());
}
APIHelpers::endpage($response);
 /**
  * Разбор строки фильтрации
  *
  * @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));
 }
Esempio n. 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);
 }
Esempio n. 7
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;
 }
Esempio n. 8
0
<?php

$conn = null;
$token = null;
$issetToken = APIHelpers::issetParam('token');
if ($issetToken) {
    $conn = APIHelpers::createConnection($config);
    $token = APIHelpers::getParam('token', '');
    APISecurity::loadByToken($conn, $token);
}
Esempio n. 9
0
}
$zip->open($zipname, ZIPARCHIVE::CREATE);
try {
    $stmt2 = $conn->prepare('
			SELECT
				*
			FROM
				users
			ORDER BY
				id ASC
	');
    $stmt2->execute();
    while ($row2 = $stmt2->fetch()) {
        $userid = $row2['id'];
        $uuid = $row2['uuid'];
        $oldlogoname = $curdir_users_export . '/../../' . $row2['logo'];
        if (file_exists($oldlogoname) && $uuid) {
            $newlogoname = 'files/users/' . $uuid . '.png';
            $zip->addFile($oldlogoname, $newlogoname);
        } else {
            $newlogoname = $row2['logo'];
        }
        $userarr = ['uuid' => $row2['uuid'], 'email' => $row2['email'], 'pass' => $row2['pass'], 'role' => $row2['role'], 'nick' => $row2['nick'], 'logo' => $newlogoname, 'last_ip' => $row2['last_ip'], 'dt_create' => $row2['dt_create'], 'dt_last_login' => $row2['dt_last_login'], 'status' => $row2['status']];
        $zip->addFromString($uuid . '.json', json_encode($userarr));
    }
} catch (PDOException $e) {
    APIHelpers::showerror(1296, $e->getMessage());
}
$result['data']['filename'] = $zipname;
$zip->close();
echo json_encode($result);
Esempio n. 10
0
				dt_last_login
			FROM
				users
			WHERE 
				(email LIKE ? OR nick LIKE ?)
				AND (role LIKE ?)
				AND (status LIKE ?)
			ORDER BY
				dt_last_login DESC
			LIMIT ' . $start . ',' . $onpage . '
	');
    $stmt2->execute(array($search, $search, $role, $status));
    $i = 0;
    while ($row2 = $stmt2->fetch()) {
        $userid = $row2['id'];
        $result['data'][$i] = array('userid' => $userid, 'email' => $row2['email'], 'role' => $row2['role'], 'nick' => $row2['nick'], 'logo' => $row2['logo'], 'dt_last_login' => $row2['dt_last_login'], 'status' => $row2['status']);
        $i++;
    }
} catch (PDOException $e) {
    APIHelpers::showerror(1093, $e->getMessage());
}
$dir = $curdir_users_list . "/../../files/dumps/";
$dh = opendir($dir);
$result['dumps'] = array();
while (false !== ($filename = readdir($dh))) {
    if (preg_match('/^users\\_.*\\.zip$/', $filename)) {
        $result['dumps'][] = $filename;
    }
    sort($result['dumps']);
}
echo json_encode($result);
Esempio n. 11
0
 static function removeByToken($conn, $token)
 {
     try {
         $query = 'DELETE FROM users_tokens WHERE token = ?';
         $params = array($token);
         $stmt = $conn->prepare($query);
         $stmt->execute($params);
     } catch (PDOException $e) {
         APIHelpers::showerror(1199, $e->getMessage());
     }
 }
Esempio n. 12
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();
Esempio n. 13
0
File: list.php Progetto: KaDeaT/fhq
function getCountStatBy($conn, $table, $questid, $passed)
{
    $res = 0;
    try {
        $stmt = $conn->prepare('
				select 
					count(t0.id) as cnt 
				from 
					' . $table . ' t0
				inner join users t1 on t1.id = t0.iduser
				where 
					t0.idquest = ?
					and t0.passed = ?
					and t1.role = ?
		');
        $stmt->execute(array(intval($questid), $passed, 'user'));
        if ($row = $stmt->fetch()) {
            $res = $row['cnt'];
        }
    } catch (PDOException $e) {
        APIHelpers::showerror(1079, $e->getMessage());
    }
    return $res;
}
Esempio n. 14
0
}
$uuid = APIHelpers::getParam('uuid', APIHelpers::gen_guid());
$logo = APIHelpers::getParam('logo', 'files/users/0.png');
$email = APIHelpers::getParam('email', '1');
$role = APIHelpers::getParam('role', 'user');
$nick = APIHelpers::getParam('nick', '1');
$password = APIHelpers::getParam('password', '1');
$status = APIHelpers::getParam('status', 'activated');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    APIHelpers::showerror(1036, 'Invalid e-mail address.');
}
$stmt = $conn->prepare('select count(*) as cnt from users where email = ?');
$stmt->execute(array($email));
if ($row = $stmt->fetch()) {
    if (intval($row['cnt']) >= 1) {
        APIHelpers::showerror(1037, 'This e-mail was already registered.');
    }
}
// same code exists in api/security/registration.php
$email = strtolower($email);
$password_hash = APISecurity::generatePassword2($email, $password);
$stmt_insert = $conn->prepare('
	INSERT INTO users(
		uuid,
		pass,
		status,
		email,
		nick,
		role,
		logo,
		last_ip,
 /**
  * Возвращает результаты выполнения правил валидации
  * @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;
 }
Esempio n. 16
0
		status,
		email,
		nick,
		role,
		logo,
		dt_last_login,
		dt_create
	)
	VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, NOW());
');
$stmt_insert->execute(array($uuid, $password_hash, 'activated', $email, $nick, 'user', 'files/users/0.png', '0000-00-00 00:00:00'));
if (!APISecurity::login($conn, $email, $password_hash)) {
    APIEvents::addPublicEvents($conn, 'errors', 'Alert! Admin, registration is broken!');
    APIHelpers::showerror(1287, '[Registration] Sorry registration is broken. Please send report to the admin about this.');
} else {
    APISecurity::insertLastIp($conn, APIHelpers::getParam('client', 'none'));
    APIUser::loadUserProfile($conn);
    APISecurity::logout();
}
$email_subject = "Registration on FreeHackQuest.";
$email_message = '
	Registration:

	If you was not tried registering on ' . $httpname . ' just remove this email.

	Welcome to FreeHackQuest!

	Your login: '******'
	Your password: '******' (You must change it)
	Link: ' . $httpname . 'index.php
';
Esempio n. 17
0
    APIHelpers::showerror(1108, 'Not found parameter "userid"');
}
$userid = APIHelpers::getParam('userid', 0);
if (!is_numeric($userid)) {
    APIHelpers::showerror(1109, 'userid must be numeric');
}
$nick = '';
// check user
try {
    $stmt = $conn->prepare('SELECT id, nick FROM users WHERE id = ?');
    $stmt->execute(array($userid));
    if ($row = $stmt->fetch()) {
        $nick = $row['nick'];
    } else {
        APIHelpers::showerror(1111, 'Userid did not found');
    }
} catch (PDOException $e) {
    APIHelpers::showerror(1110, $e->getMessage());
}
try {
    $params = array($userid);
    $conn->prepare('DELETE FROM users WHERE id = ?')->execute($params);
    $conn->prepare('DELETE FROM users_games WHERE userid = ?')->execute($params);
    $conn->prepare('DELETE FROM feedback WHERE userid = ?')->execute($params);
    $conn->prepare('DELETE FROM feedback_msg WHERE userid = ?')->execute($params);
    $result['result'] = 'ok';
} catch (PDOException $e) {
    APIHelpers::showerror(1147, $e->getMessage());
}
APIEvents::addPublicEvents($conn, 'users', 'User #' . $userid . ' {' . htmlspecialchars($nick) . '} was removed by admin!');
echo json_encode($result);
Esempio n. 18
0
 /**
  * Получение информации из конфига экстендера
  *
  * @param string $name имя параметра в конфиге экстендера
  * @param mixed $def значение по умолчанию, если в конфиге нет искомого параметра
  * @return mixed значение из конфига экстендера
  */
 protected function getCFGDef($name, $def)
 {
     return \APIHelpers::getkey($this->_cfg, $name, $def);
 }
Esempio n. 19
0
        foreach ($columns as $k) {
            $info[$k] = $row[$k];
        }
        $oldlogoname = $curdir_games_export . '/../../' . $row['logo'];
        if (file_exists($oldlogoname)) {
            $newlogoname = $row['uuid'] . '.png';
            $zip->addFile($oldlogoname, $newlogoname);
            $info['logo'] = $row['uuid'] . '.png';
        } else {
            $info['logo'] = "";
        }
    } else {
        APIHelpers::showerror(1336, 'Does not found game with this id');
    }
} catch (PDOException $e) {
    APIHelpers::showerror(1332, $e->getMessage());
}
// normalize filename
$title = preg_replace("([^A-Za-z0-9])", '', $info['title']);
$filename = 'game_' . $title . '_' . $info['uuid'] . '.zip';
$zip->addFromString($info['uuid'] . '.json', json_encode($info));
$zip->close();
header_remove('Content-Type');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
header("Content-Transfer-Encoding: binary");
Esempio n. 20
0
<?php

header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
/*
 * API_NAME: Logout
 * API_DESCRIPTION: Methods for logout from system
 * API_ACCESS: authorized users
 * API_INPUT: token - string, access token for user
 */
$curdir_logout = dirname(__FILE__);
include_once $curdir_logout . "/../api.lib/api.base.php";
include_once $curdir_logout . "/../api.lib/api.helpers.php";
include_once $curdir_logout . "/../api.lib/api.security.php";
include $curdir_logout . "/../../config/config.php";
$result = array('result' => 'ok', 'data' => array());
if (APIHelpers::issetParam('token')) {
    $token = APIHelpers::getParam('token', '');
    $conn = APIHelpers::createConnection($config);
    APISecurity::removeByToken($conn, $token);
}
APISecurity::logout();
echo json_encode($result);
Esempio n. 21
0
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
/*
 * API_NAME: Remove dump of users
 * API_DESCRIPTION: Method will be remove zip-archive
 * API_ACCESS: admin only
 * API_INPUT: filename - string, filename for removing
 * API_OKRESPONSE: { "result":"ok", "data" : { "filename" : "files/dumps/users_XXXX.zip" } }
 */
$curdir_users_export_remove = dirname(__FILE__);
include_once $curdir_users_export_remove . "/../api.lib/api.base.php";
include_once $curdir_users_export_remove . "/../api.lib/api.game.php";
include_once $curdir_users_export_remove . "/../../config/config.php";
APIHelpers::checkAuth();
$message = '';
if (!APISecurity::isAdmin()) {
    APIHelpers::showerror(1297, 'This function allowed only for admin');
}
$result = array('result' => 'fail', 'data' => array());
$result['result'] = 'ok';
if (!APIHelpers::issetParam('filename')) {
    APIHelpers::showerror(1298, 'Parameter filename did not found');
}
$filename = $curdir_users_export_remove . '/../../files/dumps/' . APIHelpers::getParam('filename', '');
if (!file_exists($filename)) {
    APIHelpers::showerror(1299, 'File did not found');
}
unlink($filename);
$result['result'] = 'ok';
$result['data']['filename'] = $filename;
echo json_encode($result);
Esempio n. 22
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;
Esempio n. 23
0
        }
        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');
Esempio n. 24
0
 /**
  * Загрузка фильтра
  * @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;
 }
Esempio n. 25
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;
 }
Esempio n. 26
0
 protected static function loadLang($lang)
 {
     $file = dirname(dirname(__FILE__)) . '/lang/' . $lang . '.php';
     if (!\Helpers\FS::getInstance()->checkFile($file)) {
         $file = false;
     }
     if (!empty($lang) && !isset(static::$langDic[$lang]) && !empty($file)) {
         static::$langDic[$lang] = (include_once $file);
         if (is_array(static::$langDic[$lang])) {
             static::$langDic[$lang] = \APIHelpers::renameKeyArr(static::$langDic[$lang], $lang);
         } else {
             static::$langDic[$lang] = array();
         }
     }
     return !(empty($lang) || empty(static::$langDic[$lang]));
 }
Esempio n. 27
0
 function LogClean($string)
 {
     $string = preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&\$1;", $string);
     $string = APIHelpers::sanitarTag($string);
     return $string;
 }
Esempio n. 28
0
 static function startpage($config)
 {
     header("Access-Control-Allow-Origin: *");
     header('Content-Type: application/json');
     APIHelpers::$TIMESTART = microtime(true);
     $issetToken = APIHelpers::issetParam('token');
     if ($issetToken) {
         APIHelpers::$TOKEN = APIHelpers::getParam('token', '');
         $conn = APIHelpers::createConnection($config);
         try {
             $stmt = $conn->prepare('SELECT data FROM users_tokens WHERE token = ? AND status = ? AND end_date > NOW()');
             $stmt->execute(array(APIHelpers::$TOKEN, 'active'));
             if ($row = $stmt->fetch()) {
                 APIHelpers::$FHQSESSION = json_decode($row['data'], true);
                 APIHelpers::$FHQSESSION_ORIG = json_decode($row['data'], true);
             }
         } catch (PDOException $e) {
             APIHelpers::showerror(1188, $e->getMessage());
         }
     } else {
         APIHelpers::$FHQSESSION = $_SESSION;
         APIHelpers::$FHQSESSION_ORIG = $_SESSION;
     }
     $response = array('result' => 'fail', 'lead_time_sec' => 0, 'data' => array());
     return $response;
 }
Esempio n. 29
0
 public function getCut()
 {
     return \APIHelpers::getkey($this->_cfg, 'cut', '<cut/>');
 }
Esempio n. 30
0
    $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 . "'";