/** * Get item from cache * * @param string $item May contain "/" symbols for cache structure, for example users/<i>user_id</i> * * @return bool|mixed Returns item on success of <b>false</b> on failure */ function get($item) { if (is_file(CACHE . "/{$item}") && is_readable(CACHE . "/{$item}") && ($cache = file_get_contents(CACHE . "/{$item}", FILE_BINARY))) { if (($cache = @_json_decode($cache)) !== false) { return $cache; } else { unlink(CACHE . "/{$item}"); return false; } } return false; }
/** * Get group data * * @param int $group * @param bool|string $item If <b>false</b> - array will be returned, if title|description|data - corresponding item * * @return array|bool|mixed */ function get($group, $item = false) { $group = (int) $group; if (!$group) { return false; } $group_data = $this->cache->get($group, function () use($group) { $group_data = $this->db()->qf("SELECT\n\t\t\t\t\t`id`,\n\t\t\t\t\t`title`,\n\t\t\t\t\t`description`,\n\t\t\t\t\t`data`\n\t\t\t\tFROM `[prefix]groups`\n\t\t\t\tWHERE `id` = '{$group}'\n\t\t\t\tLIMIT 1"); $group_data['data'] = _json_decode($group_data['data']); return $group_data; }); if ($item !== false) { if (isset($group_data[$item])) { return $group_data[$item]; } else { return false; } } else { return $group_data; } }
/** * Get stream * * @param int|int[] $id * * @return array|array[]|bool */ function get($id) { if (is_array($id)) { foreach ($id as &$i) { $i = $this->get($i); } return $id; } return $this->cache->get($id, function () use($id) { $data = $this->read_simple($id); if (!$data) { return false; } $data['images'] = _json_decode($data['images']); $data['id'] = (int) $data['id']; $data['precinct'] = (int) $data['precinct']; $data['user'] = (int) $data['user']; $data['date'] = (int) $data['date']; $data['status'] = (int) $data['status']; return $data; }); }
/** * JSON decode wrapper * - missing or broken in some php 5.x versions * * @param string $json * @param bool $assoc * @return mixed */ public static function json_decode($json, $assoc = false) { if (self::useJsonLibrary()) { return _json_decode($json, $assoc); } return json_decode($json, $assoc); }
/** * Test connection to the Storage * * @param array|bool|string $data Array or string in JSON format of connection parameters * * @return bool */ function test($data = false) { if (empty($data)) { return false; } elseif (is_array($data)) { if (isset($data[0])) { $storage = Config::instance()->storage[$data[0]]; } else { return false; } } else { $storage = _json_decode($data); } unset($data); if (is_array($storage)) { $connection_class = '\\cs\\Storage\\' . $storage['connection']; $test = new $connection_class($storage['url'], $storage['host'], $storage['user'], $storage['password']); return $test->connected(); } else { return false; } }
unset($districts, $district, $address, $location); } unset($regions, $region); $Precincts->db_prime()->q("INSERT INTO `[prefix]precincts` (`id`, `number`, `address_uk`, `address_en`, `address_ru`, `lat`, `lng`, `district`, `violations`) VALUES (NULL, '0', '01196, м.Київ, площа Лесі Українки, 1, 2-й поверх, хол прес-центру ЦВК', '1196, Kyiv, Lesi Ukrainky square 1, 2nd Floor, Hall Press Center CEC', '01196, г.Киев, площадь Леси Украинки, 1, 2-й этаж, холл пресс-центра ЦИК', '50.428073', '30.541399', '0', '0')"); } if (isset($_POST['update_addresses'])) { time_limit_pause(); $Precincts = Precincts::instance(); $all_precincts = $Precincts->get_all(); $cdb = $Precincts->db_prime(); foreach ($all_precincts as $p) { if ($cdb->qfs("SELECT `address_en` FROM `[prefix]precincts` WHERE `id` = {$p}")) { continue; } $p = $Precincts->get($p); $en_address = _json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($p['address']) . '&sensor=false&language=en')); if ($en_address['status'] == 'OK') { $cdb->q("UPDATE `[prefix]precincts`\n\t\t\t\tSET `address_en` = '%s'\n\t\t\t\tWHERE `id` = '%s'", $en_address['results'][0]['formatted_address'], $p['id']); } unset($en_address); $ru_address = _json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($p['address']) . '&sensor=false&language=ru')); if ($ru_address['status'] == 'OK') { $cdb->q("UPDATE `[prefix]precincts`\n\t\t\t\tSET `address_ru` = '%s'\n\t\t\t\tWHERE `id` = '%s'", $ru_address['results'][0]['formatted_address'], $p['id']); } unset($ru_address); } } $Index = Index::instance(); $Index->buttons = false; $Index->content(h::{'button[type=submit][name=update]'}('Оновити список дільниць з офіційного сайту виборів') . h::{'button[type=submit][name=update_districts]'}('Оновити список округів з офіційного сайту виборів') . h::{'button[type=submit][name=update_addresses]'}('Уточнити адреси дільниць російською та англійською')); Page::instance()->warning('Оновлення призведе до видалення дільниць, дані пов’язані з ними буде втрачено');
/** * Check key existence and/or getting of data stored with key. After this key will be deleted automatically. * * @param int $database Keys database * @param string $key 56 character [0-9a-z] key * @param bool $get_data If <b>true</d> - stored data will be returned on success, otherwise boolean result of key existence will be returned * * @return bool|mixed */ function get($database, $key, $get_data = false) { if (!preg_match('/^[a-z0-9]{56}$/', $key)) { return false; } if (!is_object($database)) { $database = DB::instance()->{$database}(); } $time = TIME; $result = $database->qf(["SELECT\n\t\t\t\t`id`,\n\t\t\t\t`data`\n\t\t\tFROM `[prefix]keys`\n\t\t\tWHERE\n\t\t\t\t(\n\t\t\t\t\t`key`\t= '{$key}'\n\t\t\t\t) AND\n\t\t\t\t`expire` >= {$time}\n\t\t\tORDER BY `id` DESC\n\t\t\tLIMIT 1"]); $this->del($database, $key); if (!$result || !is_array($result) || empty($result)) { return false; } elseif ($get_data) { return _json_decode($result['data']); } else { return true; } }
case 'getTheme': require_once("MultiLayerSearch.php"); $level=$_REQUEST['level']; $name=$_REQUEST['themeName']; $city_name=$_REQUEST['cityName']; $result=getTheme($name, $city_name, $level); print $result; break; //MultiLayerSearch.php ends //printPDF.php starts case 'printPDF': require_once("printPDF.php"); $json_pdf=$_REQUEST['json_PDF']; $pdfobj=_json_decode($json_pdf); $pdf_file_name=printFPDF($pdfobj); $pdf_URL=base_path() . 'pdf/' . $pdf_file_name; $json_arr=array(); $json_arr['pdf_url']=$pdf_URL; $json=json_encode($json_arr); print $json; break; //printPDF.php ends //search.php starts case 'getlayertablename': require_once("search.php"); $q=$_GET['layername']; $layer_names="'"; $layer_names.=str_replace(",", "','", $q);
/** * Loading of base system configuration, creating of missing directories */ protected function construct() { if (!file_exists(CONFIG . '/main.json')) { error_code(500); Page::instance()->error(h::p('Config file not found, is system installed properly?') . h::a('How to install CleverStyle CMS', ['href' => 'https://github.com/nazar-pc/CleverStyle-CMS/wiki/Installation'])); exit; } $this->config = file_get_json_nocomments(CONFIG . '/main.json'); _include_once(CONFIG . '/main.php', false); defined('DEBUG') || define('DEBUG', false); define('DOMAIN', $this->config['domain']); date_default_timezone_set($this->config['timezone']); if ($clangs = Cache::instance()->{'languages/clangs'}) { if (is_array($clangs) && !empty($clangs)) { $clang = explode('/', trim($_SERVER['REQUEST_URI'], '/'), 2)[0]; if (in_array($clang, $clangs)) { $this->set('language', array_flip($clangs)[$clang]); define('FIXED_LANGUAGE', true); } unset($clang); } } unset($clangs); if (!is_dir(STORAGE)) { @mkdir(STORAGE, 0755); file_put_contents(STORAGE . '/.htaccess', 'Allow From All'); } if (!is_dir(CACHE)) { @mkdir(CACHE, 0700); } if (!is_dir(PCACHE)) { @mkdir(PCACHE, 0755); file_put_contents(PCACHE . '/.htaccess', '<FilesMatch "\\.(css|js)$"> Allow From All </FilesMatch> <ifModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 month" </ifModule> <ifModule mod_headers.c> Header set Cache-Control "max-age=2592000, public" </ifModule> AddEncoding gzip .js AddEncoding gzip .css '); } if (!is_dir(LOGS)) { @mkdir(LOGS, 0700); } if (!is_dir(TEMP)) { @mkdir(TEMP, 0755); file_put_contents(TEMP . '/.htaccess', 'Allow From All'); } if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') === 0) { $_POST = _json_decode(@file_get_contents('php://input')) ?: []; $_REQUEST = array_merge($_REQUEST, $_POST); } elseif (in_array(strtolower($_SERVER['REQUEST_METHOD']), ['head', 'put', 'delete'])) { if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/x-www-form-urlencoded') === 0) { @parse_str(file_get_contents('php://input'), $_POST); $_REQUEST = array_merge($_REQUEST, $_POST); } } $this->constructed = true; }
if (isset($_POST['id'])) { $id = (int) $_POST['id']; if ($id != User::GUEST_ID && $id != User::ROOT_ID) { $User->set('status', User::STATUS_ACTIVE, $id); $Index->save(true); } } break; case 'permissions': if (isset($_POST['id'], $_POST['permission'])) { if ($_POST['id'] == User::ROOT_ID) { break; } $Index->save($User->set_permissions($_POST['permission'], $_POST['id'])); } break; case 'groups': if (isset($_POST['user'], $_POST['user']['id'], $_POST['user']['groups']) && $_POST['user']['groups']) { $user_id = (int) $_POST['user']['id']; if ($_POST['user']['id'] == User::ROOT_ID || in_array(User::BOT_GROUP_ID, (array) $User->get_groups($user_id))) { break; } $groups = _json_decode($_POST['user']['groups']); foreach ($groups as &$group) { $group = (int) substr($group, 5); } unset($group); $Index->save($User->set_groups($groups, $user_id)); } break; }
/** * Reads entire file into an array * * @see file() * * @param string $filename * @param int $flags * * @return array|bool */ function file($filename, $flags = null) { return _json_decode($this->request(['function' => __FUNCTION__, 'filename' => $filename, 'flags' => $flags])[1]); }
/** * RouteShutdown is the earliest event in the dispatch cycle, where a * fully routed request object is available */ public function routeShutdown(Zend_Controller_Request_Abstract $request) { if (isset($request->noListRedirect)) { return; } $ontoWiki = OntoWiki::getInstance(); // TODO: Refactor! The list helper is from an extension! Do not access extensions // from core code! if (!Zend_Controller_Action_HelperBroker::hasHelper('List')) { return; } $listHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('List'); // only once and only when possible if (!$this->_isSetup && $ontoWiki->selectedModel != null && (isset($request->init) || isset($request->instancesconfig) || isset($request->s) || isset($request->class) || isset($request->p) || isset($request->limit))) { $frontController = Zend_Controller_Front::getInstance(); $store = $ontoWiki->erfurt->getStore(); $resource = $ontoWiki->selectedResource; $session = $ontoWiki->session; // when switching to another class: // reset session vars (regarding the list) if (isset($request->init)) { //echo 'kill list session'; // reset the instances object unset($session->instances); //reset config from tag explorer unset($session->cloudproperties); } //react on m parameter to set the selected model if (isset($request->m)) { try { $model = $store->getModel($request->getParam('m', null, false)); $ontoWiki->selectedModel = $model; } catch (Erfurt_Store_Exception $e) { $model = null; $ontoWiki->selectedModel = null; } } $list = $listHelper->getLastList(); if (!isset($request->list) && $list == null || isset($request->init)) { // instantiate model, that selects all resources $list = new OntoWiki_Model_Instances($store, $ontoWiki->selectedModel, array()); } else { // use the object from the session if (isset($request->list) && $request->list != $listHelper->getLastListName()) { if ($listHelper->listExists($request->list)) { $list = $listHelper->getList($request->list); $ontoWiki->appendMessage(new OntoWiki_Message('reuse list')); } else { throw new OntoWiki_Exception('your trying to configure a list, but there is no list name specified'); } } $list->setStore($store); // store is not serialized in session! reset it } //local function :) function _json_decode($string) { /* PHP 5.3 DEPRECATED ; REMOVE IN PHP 6.0 */ if (get_magic_quotes_gpc()) { // add slashes for unicode chars in json $string = str_replace('\\u', '\\\\u', $string); //$string = str_replace('\\u000a','', $string); $string = stripslashes($string); } /* ---- */ return json_decode($string, true); } //a shortcut for search param if (isset($request->s)) { if (isset($request->instancesconfig)) { $config = _json_decode($request->instancesconfig); if (null === $config) { throw new OntoWiki_Exception('Invalid parameter instancesconfig (json_decode failed): ' . $this->_request->setup); } } else { $config = array(); } if (!isset($config['filter'])) { $config['filter'] = array(); } $config['filter'][] = array('action' => 'add', 'mode' => 'search', 'searchText' => $request->s); $request->setParam('instancesconfig', json_encode($config)); } //a shortcut for class param if (isset($request->class)) { if (isset($request->instancesconfig)) { $config = _json_decode($request->instancesconfig); if (null === $config) { throw new OntoWiki_Exception('Invalid parameter instancesconfig (json_decode failed): ' . $this->_request->setup); } } else { $config = array(); } if (!isset($config['filter'])) { $config['filter'] = array(); } $config['filter'][] = array('action' => 'add', 'mode' => 'rdfsclass', 'rdfsclass' => $request->class); $request->setParam('instancesconfig', json_encode($config)); } //check for change-requests if (isset($request->instancesconfig)) { $config = _json_decode($request->instancesconfig); if (null === $config) { throw new OntoWiki_Exception('Invalid parameter instancesconfig (json_decode failed)'); } // TODO is this a bug? why access sort->asc when it is null? if (isset($config['sort'])) { if ($config['sort'] == null) { $list->orderByUri($config['sort']['asc']); } else { $list->setOrderProperty($config['sort']['uri'], $config['sort']['asc']); } } if (isset($config['shownProperties'])) { foreach ($config['shownProperties'] as $prop) { if ($prop['action'] == 'add') { $list->addShownProperty($prop['uri'], $prop['label'], $prop['inverse']); } else { $list->removeShownProperty($prop['uri'], $prop['inverse']); } } } if (isset($config['filter'])) { foreach ($config['filter'] as $filter) { // set default value for action and mode if they're not assigned if (!isset($filter['action'])) { $filter['action'] = 'add'; } if (!isset($filter['mode'])) { $filter['mode'] = 'box'; } if ($filter['action'] == 'add') { if ($filter['mode'] == 'box') { $list->addFilter($filter['property'], isset($filter['isInverse']) ? $filter['isInverse'] : false, isset($filter['propertyLabel']) ? $filter['propertyLabel'] : 'defaultLabel', $filter['filter'], isset($filter['value1']) ? $filter['value1'] : null, isset($filter['value2']) ? $filter['value2'] : null, isset($filter['valuetype']) ? $filter['valuetype'] : 'literal', isset($filter['literaltype']) ? $filter['literaltype'] : null, isset($filter['hidden']) ? $filter['hidden'] : false, isset($filter['id']) ? $filter['id'] : null, isset($filter['negate']) ? $filter['negate'] : false); } else { if ($filter['mode'] == 'search') { $list->addSearchFilter($filter['searchText'], isset($filter['id']) ? $filter['id'] : null); } else { if ($filter['mode'] == 'rdfsclass') { $list->addTypeFilter($filter['rdfsclass'], isset($filter['id']) ? $filter['id'] : null); } else { if ($filter['mode'] == 'cnav') { $list->addTripleFilter(NavigationHelper::getInstancesTriples($filter['uri'], $filter['cnav']), isset($filter['id']) ? $filter['id'] : null); } else { if ($filter['mode'] == 'query') { try { //echo $filter->query." "; $query = Erfurt_Sparql_Query2::initFromString($filter['query']); // TODO what the hell is this?! if (!$query instanceof Exception) { $list->addTripleFilter($query->getWhere()->getElements(), isset($filter['id']) ? $filter['id'] : null); } //echo $query->getSparql(); } catch (Erfurt_Sparql_ParserException $e) { $ontoWiki->appendMessage('the query could not be parsed'); } } } } } } } else { $list->removeFilter($filter['id']); } } } if (isset($config['order'])) { foreach ($config['order'] as $prop) { if ($prop['action'] == 'set') { if ($prop['mode'] == 'var') { $list->setOrderVar($prop['var']); } else { $list->setOrderUri($prop['uri']); } } } } } if (isset($request->limit)) { // how many results per page $list->setLimit($request->limit); } else { $list->setLimit(10); } if (isset($request->p)) { // p is the page number $list->setOffset($request->p * $list->getLimit() - $list->getLimit()); } else { $list->setOffset(0); } //save to session $name = isset($request->list) ? $request->list : 'instances'; $listHelper->updateList($name, $list, true); // avoid setting up twice $this->_isSetup = true; // redirect normal requests if config-params are given to a param-free uri // (so a browser reload by user does nothing unwanted) if (!$request->isXmlHttpRequest()) { //strip of url parameters that modify the list $url = new OntoWiki_Url(array(), null, array('init', 'instancesconfig', 's', 'p', 'limit', 'class', 'list')); //redirect $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); $redirector->gotoUrl($url); } } }
/** * Delete data, stored with session * * @param string $item * @param null|string $session_id * * @return bool * */ function del_session_data($item, $session_id = null) { $session_id = $session_id ?: $this->current['session']; if (!is_md5($session_id)) { return false; } $data = $this->cache->get("sessions/data/{$session_id}", function () use($session_id) { return _json_decode($this->db()->qfs(["SELECT `data`\n\t\t\t\t\tFROM `[prefix]sessions`\n\t\t\t\t\tWHERE `id` = '%s'\n\t\t\t\t\tLIMIT 1", $session_id])) ?: false; }) ?: []; if (!isset($data[$item])) { return true; } unset($data[$item]); if ($this->db()->q("UPDATE `[prefix]sessions`\n\t\t\tSET `data` = '%s'\n\t\t\tWHERE `id` = '%s'\n\t\t\tLIMIT 1", _json_encode($data), $session_id)) { unset($this->cache->{"sessions/data/{$session_id}"}); return true; } return false; }
/** * Test connection to the DB * * @param array|string $data Array or string in JSON format of connection parameters * * @return bool */ function test($data) { $Core = Core::instance(); if (empty($data)) { return false; } elseif (is_array($data)) { $Config = Config::instance(); if (isset($data[1])) { $db = $Config->db[$data[0]]['mirrors'][$data[1]]; } elseif (isset($data[0])) { if ($data[0] == 0) { $db = ['type' => $Core->db_type, 'host' => $Core->db_host, 'name' => $Core->db_name, 'user' => $Core->db_user, 'password' => $Core->db_password, 'charset' => $Core->db_charset]; } else { $db = $Config->db[$data[0]]; } } else { return false; } } else { $db = _json_decode($data); } unset($data); if (is_array($db)) { errors_off(); $engine_class = '\\cs\\DB\\' . $db['type']; $test = new $engine_class($db['name'], $db['user'], $db['password'], $db['host'] ?: $Core->db_host, $db['charset'] ?: $Core->db_charset); errors_on(); return $test->connected(); } else { return false; } }
} } if (isset($_POST['users'])) { foreach ($_POST['users'] as $user => $value) { $result = $result && User::instance()->set_permissions([$permission => $value], $user); } } $a->save($result); } break; } } elseif (isset($_POST['edit_settings'])) { switch ($_POST['edit_settings']) { case 'apply': case 'save': $_POST['position'] = _json_decode($_POST['position']); if (is_array($_POST['position'])) { $blocks_array = []; foreach ($_POST['position'] as $position => $items) { foreach ($items as $item) { $item = (int) substr($item, 5); switch ($position) { default: $position = 'floating'; break; case 'top': case 'left': case 'floating': case 'right': case 'bottom': break;
* @subpackage HTTP Storage Engine backend * @author Nazar Mokrynskyi <*****@*****.**> * @copyright Copyright (c) 2011-2014, Nazar Mokrynskyi * @license MIT License, see license.txt * * Requires config.php file in current directory with specified global variables $STORAGE_USER and $STORAGE_PASSWORD */ header('Content-Type: text/html; charset=utf-8'); header('Connection: close'); require __DIR__ . '/core/thirdparty/upf.php'; define('STORAGE', __DIR__ . '/storage/public'); chdir(STORAGE); if ($_SERVER['HTTP_USER_AGENT'] == 'CleverStyle CMS' && file_exists(__DIR__ . '/config.php') && isset($_POST['data'])) { include __DIR__ . '/config.php'; global $STORAGE_USER, $STORAGE_PASSWORD; $data = _json_decode(urldecode($_POST['data'])); $KEY = substr($data['key'], 0, 32); unset($data['key']); if (md5(_json_encode($data) . $STORAGE_USER . $STORAGE_PASSWORD) !== $KEY) { exit; } unset($GLOBALS['STORAGE_USER'], $GLOBALS['STORAGE_PASSWORD'], $KEY); } else { exit; } switch ($data['function']) { default: exit; case 'get_files_list': exit(_json_encode(get_files_list($data['dir'], $data['mask'], $data['mode'], $data['prefix_path'], $data['subfolders'], $data['sort'], $data['exclusion'], $data['system_files'], null, $data['limit']))); case 'file':
function json_decode($json, $assoc = FALSE) { return _json_decode($json, $assoc); }
/** * _json_decode(file_get_contents()) * * @param string $filename Name of the file to read. * * @return mixed */ function file_get_json($filename) { return _json_decode(file_get_contents($filename)); }