Пример #1
0
 public function tearDown()
 {
     if (!is_null($this->prevValue)) {
         Cache::set($this->cacheVarName, $this->prevValue);
     } else {
         Cache::remove($this->cacheVarName);
     }
 }
Пример #2
0
 /**
  * prepare target db or create it from barebone
  * @return void
  */
 protected function prepareTargetDb()
 {
     $cfg = $this->cfg;
     if (!empty($cfg['importSql'])) {
         Cache::set('RUN_SETUP_CFG', $this->cfg);
         $options = array('core' => $cfg['core_name'], 'sql' => $cfg['importSql']);
         include $this->binDirectory . 'core_create.php';
     }
 }
Пример #3
0
 /**
  * connect to solr service
  *
  * @return Apache_Solr_Service handler to solr intance
  */
 public function connect()
 {
     if (!empty($this->solr_handler)) {
         return $this->solr_handler;
     }
     $cacheCoreName = 'solr_service_' . $this->core;
     //check cache
     $this->solr_handler = Cache::get($cacheCoreName);
     if (empty($this->solr_handler)) {
         if (!class_exists('\\Apache_Solr_Service', false)) {
             require_once $this->client;
         }
         $this->solr_handler = new \Apache_Solr_Service($this->host, $this->port, $this->core);
         if (!$this->solr_handler->ping()) {
             throw new \Exception('Solr_connection_error' . $this->debugInfo(), 1);
         }
         //setting handler in cache raise errors for atomic updates
         Cache::set($cacheCoreName, $this->solr_handler);
     }
     return $this->solr_handler;
 }
Пример #4
0
$coreName = empty($options['c']) ? @$options['core'] : $options['c'];
if (empty($coreName)) {
    die('no core specified or invalid options set.');
}
$sqlFile = empty($options['s']) ? @$options['sql'] : $options['s'];
if (empty($sqlFile)) {
    $ds = DIRECTORY_SEPARATOR;
    $sqlFile = $cbHome . "install{$ds}mysql{$ds}bare_bone_core.sql";
}
/*if (!defined('CB\INTERACTIVE_MODE')) {
    //define working mode
    define('CB\INTERACTIVE_MODE', empty($options['config']));
} */
if (!\CB\Cache::get('RUN_SETUP_INTERACTIVE_MODE')) {
    //define working mode
    \CB\Cache::set('RUN_SETUP_INTERACTIVE_MODE', !\CB\Cache::exist('RUN_SETUP_CFG'));
}
\CB\Install\defineBackupDir($cfg);
$dbName = (isset($cfg['prefix']) ? $cfg['prefix'] . '_' : \CB\PREFIX) . $coreName;
$dbUser = isset($cfg['su_db_user']) ? $cfg['su_db_user'] : $cfg['db_user'];
$dbPass = isset($cfg['su_db_pass']) ? $cfg['su_db_pass'] : $cfg['db_pass'];
$applyDump = true;
if (\CB\DB\dbQuery('use `' . $dbName . '`')) {
    if (confirm('overwrite_existing_core_db')) {
        if (\CB\Cache::get('RUN_SETUP_CREATE_BACKUPS') !== false) {
            echo 'Backuping .. ';
            backupDB($dbName, $dbUser, $dbPass);
            showMessage();
        }
    } else {
        $applyDump = false;
Пример #5
0
ini_set('max_execution_time', 0);
ini_set('allow_url_fopen', true);
error_reporting(E_ALL);
$scriptOptions = getOptions();
if (empty($scriptOptions['core'])) {
    die('no core specified or invalid options set.');
}
$_GET['core'] = $scriptOptions['core'];
$_SERVER['SERVER_NAME'] = $scriptOptions['core'];
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SESSION['user'] = array('id' => 1, 'name' => 'system');
$site_path = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'httpsdocs') . DIRECTORY_SEPARATOR;
register_shutdown_function('CB\\closeCron', $cron_id);
include $site_path . DIRECTORY_SEPARATOR . 'config.php';
require_once LIB_DIR . 'language.php';
\CB\Cache::set('scriptOptions', $scriptOptions);
$coreName = Config::get('core_name');
//L\initTranslations(); // would be called from inside crons that need translations
//--------------------------------------------------- functions
function getOptions()
{
    $rez = array();
    $options = getopt('c:alf', array('core', 'all', 'nolimit', 'force'));
    $rez['core'] = empty($options['c']) ? @$options['core'] : $options['c'];
    $rez['all'] = isset($options['a']) || isset($options['all']);
    $rez['nolimit'] = isset($options['l']) || isset($options['nolimit']);
    $rez['force'] = isset($options['f']) || isset($options['force']);
    return $rez;
}
function prepareCron($cron_id, $execution_timeout = 60, $info = '')
{
Пример #6
0
 /**
  * update object
  * @param  array   $p optional properties. If not specified then $this-data is used
  * @return boolean
  */
 public function update($p = false)
 {
     if ($p !== false) {
         $this->data = $p;
         unset($this->linearData);
         if (array_key_exists('id', $p)) {
             $this->id = $p['id'];
         }
         $this->template = null;
         if (!empty($this->data['template_id']) && $this->loadTemplate) {
             $this->template = \CB\Templates\SingletonCollection::getInstance()->getTemplate($this->data['template_id']);
         }
     }
     if (!is_numeric($this->id)) {
         throw new \Exception("No object id specified for update", 1);
     }
     //load current object from db into a variable to be passed to log and events
     $this->oldObject = clone $this;
     $this->oldObject->load($this->id);
     \CB\fireEvent('beforeNodeDbUpdate', $this);
     $p =& $this->data;
     if (empty($p['cid'])) {
         $p['cid'] = $_SESSION['user']['id'];
     }
     if (empty($p['oid'])) {
         $p['oid'] = $p['cid'];
     }
     $tableFields = array('pid', 'user_id', 'system', 'template_id', 'tag_id', 'target_id', 'name', 'date', 'date_end', 'size', 'cfg', 'oid', 'did', 'dstatus');
     $saveFields = array();
     $saveValues = array($this->id, $_SESSION['user']['id']);
     $params = array('`uid` = $2', '`udate` = CURRENT_TIMESTAMP', '`draft` = 0', 'updated = 1');
     $i = 3;
     foreach ($tableFields as $fieldName) {
         if (array_key_exists($fieldName, $p) && $p[$fieldName] !== 'id') {
             $saveFields[] = $fieldName;
             $saveValues[] = is_scalar($p[$fieldName]) || is_null($p[$fieldName]) ? $p[$fieldName] : Util\jsonEncode($p[$fieldName]);
             $params[] = "`{$fieldName}` = \${$i}";
             $i++;
         }
     }
     if (!empty($saveFields)) {
         DB\dbQuery('UPDATE tree
             SET ' . implode(',', $params) . '
             WHERE id = $1', $saveValues) or die(DB\dbQueryError());
     }
     DB\dbQuery('call `p_mark_all_child_drafts_as_active`($1)', $this->id) or die(DB\dbQueryError());
     $this->updateCustomData();
     // set/update this object to cache
     Cache::set('Objects[' . $this->id . ']', $this);
     \CB\fireEvent('nodeDbUpdate', $this);
     $this->logAction('update', array('old' => $this->oldObject));
     return true;
 }
Пример #7
0
 /**
  * get template type by its id
  * @param  int     $templateId
  * @return varchar
  */
 public function getType($templateId)
 {
     if (!is_numeric($templateId)) {
         return null;
     }
     // check if template has been loaded
     if (!empty($this->templates[$templateId])) {
         return $this->templates[$templateId]->getData()['type'];
     }
     $var_name = 'template_type' . $templateId;
     if (!\CB\Cache::exist($var_name)) {
         $res = DB\dbQuery('SELECT `type`
             FROM templates
             WHERE id = $1', $templateId) or die(DB\dbQueryError());
         if ($r = $res->fetch_assoc()) {
             \CB\Cache::set($var_name, $r['type']);
         }
         $res->close();
     }
     return \CB\Cache::get($var_name);
 }
Пример #8
0
 /**
  * connect to solr service
  *
  * @return Apache_Solr_Service handler to solr intance
  */
 public function connect()
 {
     if (!empty($this->solr_handler)) {
         return $this->solr_handler;
     }
     $cacheCoreName = 'solr_service_' . $this->core;
     //check cache
     $this->solr_handler = Cache::get($cacheCoreName);
     if (empty($this->solr_handler)) {
         if (!class_exists('\\Apache_Solr_Service', false)) {
             require_once 'Apache/Solr/Service.php';
         }
         if (!class_exists('\\Apache_Solr_Compatibility_Solr4CompatibilityLayer', false)) {
             require_once 'Apache/Solr/Compatibility/AddDocumentXmlCreator.php';
             require_once 'Apache/Solr/Compatibility/CompatibilityLayer.php';
             require_once 'Apache/Solr/Compatibility/Solr4CompatibilityLayer.php';
         }
         $layer = new \Apache_Solr_Compatibility_Solr4CompatibilityLayer();
         $this->solr_handler = new \Apache_Solr_Service($this->host, $this->port, $this->core, false, $layer);
         if (!$this->solr_handler->ping()) {
             throw new \Exception('Solr_connection_error' . $this->debugInfo(), 1);
         }
         //setting handler in cache raise errors for atomic updates
         Cache::set($cacheCoreName, $this->solr_handler);
     }
     return $this->solr_handler;
 }
Пример #9
0
 /**
  * Check if userId (or current loged user) is an administrator
  *
  * @param  int     $userId
  * @return boolean
  */
 public static function isAdmin($userId = false)
 {
     if ($userId == false) {
         $userId = User::getId();
     }
     $var_name = 'is_admin' . $userId;
     if (!Cache::exist($var_name)) {
         Cache::set($var_name, DM\Users::getIdByName('root') == $userId);
     }
     return Cache::get($var_name);
 }
Пример #10
0
    \CB\Cache::set('RUN_SETUP_CFG', $options['config']);
    if (isset($options['config']['overwrite_create_backups']) && $options['config']['overwrite_create_backups'] == 'n') {
        \CB\Cache::set('RUN_SETUP_CREATE_BACKUPS', false);
    } else {
        \CB\Cache::set('RUN_SETUP_CREATE_BACKUPS', true);
    }
} else {
    \CB\Cache::set('RUN_SETUP_CREATE_BACKUPS', true);
}
//define working mode
if (!empty($options['config'])) {
    // define('CB\\CB\Cache::get('RUN_SETUP_INTERACTIVE_MODE')', false);
    \CB\Cache::set('RUN_SETUP_INTERACTIVE_MODE', false);
    // $cfg = $options['config'];
} else {
    \CB\Cache::set('RUN_SETUP_INTERACTIVE_MODE', true);
}
require_once \CB\LIB_DIR . 'install_functions.php';
displaySystemNotices();
// initialize default values in cofig if not detected
$defaultValues = getDefaultConfigValues();
$cfg = $cfg + $defaultValues;
if (\CB\Util\getOS() != "WIN") {
    //ask for apache user and set ownership for some folders
    $cfg['apache_user'] = readParam('apache_user', $cfg['apache_user']);
    setOwnershipForApacheUser($cfg);
}
//init prefix
$cfg['prefix'] = readParam('prefix', $cfg['prefix']);
//init db config
do {
Пример #11
0
/**
 * function to set translations in Cache
 */
function initTranslations()
{
    $translations = \CB\Cache::get('translations', []);
    // if already defined translations then exit
    if (!empty($translations)) {
        return;
    }
    $languages = \CB\Config::get('languages');
    // or : \CB\USER_LANGUAGE;
    /* reading main translations table from casebox database*/
    $res = DB\dbQuery('SELECT name, ' . implode(',', $languages) . '
        FROM ' . \CB\PREFIX . '_casebox.translations
        WHERE `type` < 2');
    // if ($rez = $res->fetch_all(MYSQLI_ASSOC)) {
    // foreach ($rez as &$r) {
    while ($r = $res->fetch_assoc()) {
        reset($r);
        $name = current($r);
        while ($v = next($r)) {
            $translations[key($r)][$name] = $v;
        }
        // }
    }
    $res->close();
    /* reading specific translations of core */
    $res = DB\dbQuery('SELECT *
        FROM translations
        WHERE `type` < 2');
    // if ($rez = $res->fetch_all(MYSQLI_ASSOC)) {
    //     foreach ($rez as &$r) {
    while ($r = $res->fetch_assoc()) {
        foreach ($languages as $l) {
            if (!empty($r[$l])) {
                $translations[$l][$r['name']] = $r[$l];
            }
        }
        //  }
    }
    $res->close();
    \CB\Cache::set('translations', $translations);
}
Пример #12
0
 /**
  *  stores loaded nodes in 'DAVNodes' ary,
  *  later it's used in PropertyStoragePlugin to get 'creationdate'
  *  @param  [type] $ary [description]
  *  @return [type]      [description]
  */
 public static function cacheNodes($ary)
 {
     // initialize DAVNodes cache
     if (!\CB\Cache::exist('DAVNodes')) {
         \CB\Cache::set('DAVNodes', []);
     }
     $cachedNodes = \CB\Cache::get('DAVNodes');
     // store nodes in cache
     foreach ($ary as $id => $node) {
         // remove '/'
         $path = str_replace('\\', '/', $node['path']);
         $path = trim($path, '/');
         //  use only '/' as separator
         $cachedNodes[$path] = $node;
     }
     \CB\Cache::set('DAVNodes', $cachedNodes);
 }
Пример #13
0
/**
 * define backup_dir constant and create folder if doesnt exist
 * @param  array &$cfg
 * @return varchar
 */
function defineBackupDir(&$cfg)
{
    if (\CB\Cache::exist('RUN_INSTALL_BACKUP_DIR')) {
        return \CB\Cache::get('RUN_INSTALL_BACKUP_DIR');
    }
    $dir = empty($cfg['backup_dir']) ? \CB\APP_DIR . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR : $cfg['backup_dir'];
    \CB\Cache::set('RUN_INSTALL_BACKUP_DIR', $dir);
    if (!file_exists($dir)) {
        mkdir($dir, 0766, true);
    }
    return $dir;
}
Пример #14
0
 public function getChildren($p)
 {
     $rez = array();
     //unset restricted query params from user input
     unset($p['fq']);
     /* prepare params */
     $path = '/';
     if (!isset($p['path']) || strlen($p['path']) < 1) {
         if (!empty($p['pid'])) {
             $path = $p['pid'];
         }
     } else {
         $path = $p['path'];
     }
     $p['path'] = $path;
     //check if user have changed the row limit in grid
     if (!empty($p['setMaxRows']) && !empty($p['rows'])) {
         User::setGridMaxRows($p['rows']);
     }
     //the navigation goes from search results. We should get the real path of the node
     if (!empty($p['lastQuery']) && empty($p['query'])) {
         while (substr($path, -1) == '/') {
             $path = substr($path, 0, strlen($path) - 1);
         }
         $a = explode('/', $path);
         if (!empty($a) && is_numeric($a[sizeof($a) - 1])) {
             $p['path'] = @Path::getPath(array_pop($a))['path'];
         }
     }
     $this->showFoldersContent = isset($p['showFoldersContent']) ? $p['showFoldersContent'] : false;
     $this->requestParams = $p;
     /* end of prepare params */
     /* we should:
            1. load available plugins for the tree with their configs
            2. fire the on treeInitialize event
            3. call each plugin with received params
            4. join and sort received data
        */
     //detect tree nodes config,
     //but leave only SearchResults plugin when searching
     if (empty($p['search'])) {
         if (empty($p['query'])) {
             $this->treeNodeConfigs = Config::get('treeNodes');
         }
         // default is only DBNode if nothing defined in cofig
         if (empty($this->treeNodeConfigs)) {
             $this->treeNodeConfigs = array('Dbnode' => array());
         }
     } else {
         $this->treeNodeConfigs = array('SearchResults' => $p['search']);
         $path = Path::getGUID('SearchResults') . '-';
     }
     $params = array('params' => &$p, 'plugins' => &$this->treeNodeConfigs);
     fireEvent('treeInitialize', $params);
     // array of all available classes defined in treeNodes
     // used to check if any class should add its nodes based
     // on last node from current path
     $this->treeNodeClasses = Path::getNodeClasses($this->treeNodeConfigs);
     foreach ($this->treeNodeClasses as &$nodeClass) {
         $cfg = $nodeClass->getConfig();
         $this->treeNodeGUIDConfigs[$cfg['guid']] = $cfg;
     }
     $this->path = Path::createNodesPath($path, $this->treeNodeGUIDConfigs);
     //set path and input params for last node
     //because iterating each class and requesting children can
     //invoke a search that will use last node to get facets and DC
     if (!empty($this->path)) {
         $lastNode = $this->path[sizeof($path) - 1];
         $lastNode->path = $this->path;
         $lastNode->requestParams = $this->requestParams;
     }
     Cache::set('current_path', $this->path);
     $this->result = array('data' => array(), 'facets' => array(), 'pivot' => array(), 'search' => array(), 'view' => array(), 'sort' => array(), 'group' => array(), 'stats' => array(), 'DC' => array(), 'total' => 0);
     //get view config and apply to request params and for result
     $viewConfig = $this->detectViewConfig();
     $this->requestParams = array_merge($this->requestParams, $viewConfig);
     $this->result = array_merge($this->result, $viewConfig);
     $this->requestParams['facets'] = $this->detectFacets();
     $this->collectAllChildren();
     $this->prepareResult();
     $rez = array('success' => true, 'pathtext' => $this->getPathText($p), 'folderProperties' => $this->getPathProperties($p), 'page' => @$p['page'], 'data' => array());
     foreach ($this->result as $k => &$v) {
         if (!empty($this->result[$k])) {
             $rez[$k] =& $v;
         }
     }
     return $rez;
 }
Пример #15
0
 function dbQuery($query, $parameters = array(), $dbh = false)
 {
     if (empty($dbh)) {
         $dbh = \CB\Cache::get('dbh');
         if (empty($dbh)) {
             trigger_error('Error Database connections:' . __DIR__ . ' ' . __FILE__ . '(' . __LINE__ . ')', E_USER_ERROR);
         }
     }
     // Escape parameters as required & build parameters for callback function
     if (!is_array($parameters)) {
         $parameters = array($parameters);
     }
     foreach ($parameters as $k => $v) {
         if (!is_scalar($v) && !is_null($v)) {
             throw new \Exception("param error: " . print_r($parameters, 1) . "\n For SQL: {$query}", 1);
         }
         $parameters[$k] = is_int($v) ? $v : (null === $v ? 'NULL' : ($v == 'CURRENT_TIMESTAMP' ? $v : "'" . $dbh->real_escape_string($v) . "'"));
     }
     \CB\Cache::set('queryParameters', $parameters);
     // Call using mysqli_query
     $sql = preg_replace_callback('/\\$([0-9]+)/', __NAMESPACE__ . '\\dbQueryCallback', $query);
     \CB\Cache::set('lastSql', $sql);
     return $dbh->query($sql);
 }
Пример #16
0
 function dbQuery($query, $parameters = array(), $dbh = false)
 {
     if (empty($dbh)) {
         $dbh = \CB\Cache::get('dbh');
     }
     // Escape parameters as required & build parameters for callback function
     if (!is_array($parameters)) {
         $parameters = array($parameters);
     }
     foreach ($parameters as $k => $v) {
         if (!is_scalar($v) && !is_null($v)) {
             throw new \Exception("param error: " . print_r($parameters, 1) . "\n For SQL: {$query}", 1);
         }
         $parameters[$k] = is_int($v) ? $v : (null === $v ? 'NULL' : "'" . $dbh->real_escape_string($v) . "'");
     }
     \CB\Cache::set('queryParameters', $parameters);
     // Call using mysqli_query
     $sql = preg_replace_callback('/\\$([0-9]+)/', __NAMESPACE__ . '\\dbQueryCallback', $query);
     \CB\Cache::set('lastSql', $sql);
     return $dbh->query($sql);
 }
Пример #17
0
 /**
  * get template type of an object
  * @param  int          $objectId
  * @return varchar|null
  */
 public static function getType($objectId)
 {
     if (!is_numeric($objectId)) {
         return null;
     }
     $var_name = 'obj_template_type' . $objectId;
     if (!Cache::exist($var_name)) {
         $tc = Templates\SingletonCollection::getInstance();
         Cache::set($var_name, $tc->getType(self::getTemplateId($objectId)));
     }
     return Cache::get($var_name);
 }
Пример #18
0
 private function updateCronLastActionTime($cronId)
 {
     if (empty($cronId)) {
         return;
     }
     $cache_var_name = 'update_cron_' . $cronId;
     /* if less than 20 seconds have passed then skip updating db */
     if (\CB\Cache::exist($cache_var_name) && time() - \CB\Cache::get($cache_var_name) < 20) {
         return;
     }
     \CB\Cache::set($cache_var_name, time());
     $id = DM\Crons::toId($cronId, 'cron_id');
     if (empty($id)) {
         DM\Crons::create(array('cron_id' => $cronId, 'last_action' => 'CURRENT_TIMESTAMP'));
     } else {
         DM\Crons::update(array('id' => $id, 'last_action' => 'CURRENT_TIMESTAMP'));
     }
 }
Пример #19
0
 /**
  * get objects from cache or loads them and store in cache
  * @param  array $ids
  * @return array
  */
 public static function getCachedObjects($ids)
 {
     $ids = Util\toNumericArray($ids);
     $rez = array();
     $toLoad = array();
     foreach ($ids as $id) {
         //verify if already have cached result
         $var_name = 'Objects[' . $id . ']';
         if (\CB\Cache::exist($var_name)) {
             $rez[$id] = \CB\Cache::get($var_name);
         } else {
             $toLoad[] = $id;
         }
     }
     if (!empty($toLoad)) {
         $tc = Templates\SingletonCollection::getInstance();
         $data = DataModel\Objects::read($toLoad);
         foreach ($data as $objData) {
             $var_name = 'Objects[' . $objData['id'] . ']';
             $o = static::getCustomClassByType($tc->getType($objData['template_id']));
             if (!empty($o)) {
                 $o->setData($objData);
                 \CB\Cache::set($var_name, $o);
                 $rez[$objData['id']] = $o;
             }
         }
     }
     return $rez;
 }
Пример #20
0
 public static function getSolrLogConnection()
 {
     $rez = Cache::get('solr_log_connection');
     if (empty($rez)) {
         $cfg = Config::get('action_log');
         if (empty($cfg['core'])) {
             return;
         }
         $rez = new \CB\Search($cfg);
         Cache::set('solr_log_connection', $rez);
     }
     return $rez;
 }
Пример #21
0
 protected static function getMenuRules()
 {
     $rez = Cache::get('CreateMenuRules', array());
     if (!empty($rez)) {
         return $rez;
     }
     $s = new Search();
     $ids = array();
     $sr = $s->query(array('fl' => 'id', 'template_types' => 'menu', 'skipSecurity' => true));
     foreach ($sr['data'] as $r) {
         $ids[] = $r['id'];
     }
     $arr = Objects::getCachedObjects($ids);
     foreach ($arr as $o) {
         $d = $o->getData()['data'];
         $rez[] = array('nids' => empty($d['node_ids']) ? array() : Util\toNumericArray($d['node_ids']), 'ntids' => empty($d['template_ids']) ? array() : Util\toNumericArray($d['template_ids']), 'ugids' => empty($d['user_group_ids']) ? array() : Util\toNumericArray($d['user_group_ids']), 'menu' => $d['menu']);
     }
     Cache::set('CreateMenuRules', $rez);
     return $rez;
 }
Пример #22
0
 /**
  * formats a value for display according to it's field definition
  * @param  array | int $field array of field properties or field id
  * @param  variant     $value field value to be formated
  * @param  boolean     $html  default true - format for html, otherwise format for text display
  * @return varchar     formated value
  */
 public static function formatValueForDisplay($field, $value, $html = true)
 {
     $cacheVarName = '';
     if (is_numeric($field)) {
         $field = $this->data->fields[$field];
     }
     //condition is specified for values from search templates
     $condition = null;
     if (is_array($value)) {
         if (isset($value['cond'])) {
             $condition = Template::formatConditionForDisplay($field, $value['cond'], $html) . ' ';
         }
         if (isset($value['value'])) {
             $value = $value['value'];
         } else {
             $value = null;
         }
     }
     //we'll cache scalar by default, but will exclude textual fields
     $cacheValue = is_scalar($value);
     if ($cacheValue) {
         $fid = empty($field['id']) ? $field['name'] : $field['id'];
         $cacheVarName = 'dv' . $html . '_' . $fid . '_' . $value;
         //check if value is in cache and return
         if (Cache::exist($cacheVarName)) {
             return Cache::get($cacheVarName);
         }
     }
     /*check if field is not rezerved field for usernames (cid, oid, uid, did)*/
     if (!empty($field['name']) && in_array($field['name'], array('cid', 'oid', 'uid', 'did'))) {
         $value = Util\toNumericArray($value);
         for ($i = 0; $i < sizeof($value); $i++) {
             $value[$i] = User::getDisplayName($value[$i]);
         }
         $value = implode(', ', $value);
     } else {
         switch ($field['type']) {
             case 'boolean':
             case 'checkbox':
                 $value = empty($value) ? '' : ($value < 0 ? L\get('no') : L\get('yes'));
                 break;
             case '_sex':
                 switch ($value) {
                     case 'm':
                         $value = L\get('male');
                         break;
                     case 'f':
                         $value = L\get('female');
                         break;
                     default:
                         $value = '';
                 }
                 break;
             case '_language':
                 @($value = @\CB\Config::get('language_settings')[\CB\Config::get('languages')[$value - 1]][0]);
                 break;
             case 'combo':
             case '_objects':
                 if (empty($value)) {
                     $value = '';
                     break;
                 }
                 $ids = Util\toNumericArray($value);
                 if (empty($ids)) {
                     if (empty($field['cfg']['source']) || !is_array($field['cfg']['source'])) {
                         $value = '';
                     }
                     break;
                 }
                 $value = array();
                 if (in_array(@$field['cfg']['source'], array('users', 'groups', 'usersgroups'))) {
                     $udp = UsersGroups::getDisplayData($ids);
                     foreach ($ids as $id) {
                         if (empty($udp[$id])) {
                             continue;
                         }
                         $r =& $udp[$id];
                         $label = @htmlspecialchars(Util\coalesce($r['title'], $r['name']), ENT_COMPAT);
                         if ($html) {
                             switch (@$field['cfg']['renderer']) {
                                 case 'listGreenIcons':
                                     $label = '<li class="icon-padding icon-element">' . $label . '</li>';
                                     break;
                                     // case 'listObjIcons':
                                 // case 'listObjIcons':
                                 default:
                                     $icon = empty($r['iconCls']) ? 'icon-none' : $r['iconCls'];
                                     $label = '<li class="icon-padding ' . $icon . '">' . $label . '</li>';
                                     break;
                             }
                         }
                         $value[] = $label;
                     }
                 } else {
                     $objects = \CB\Objects::getCachedObjects($ids);
                     foreach ($ids as $id) {
                         if (empty($objects[$id])) {
                             continue;
                         }
                         $obj =& $objects[$id];
                         $d = $obj->getData();
                         $label = $obj->getHtmlSafeName();
                         $pids = $d['pids'];
                         if ($html && !empty($pids)) {
                             $pids = str_replace(',', '/', $pids);
                             $linkType = empty($field['cfg']['linkType']) ? '' : 'link-type-' . $field['cfg']['linkType'];
                             $label = '<a class="click ' . $linkType . '" template_id="' . $d['template_id'] . '" path="' . $pids . '" nid="' . $id . '">' . $label . '</a>';
                         }
                         switch (@$field['cfg']['renderer']) {
                             case 'listGreenIcons':
                                 $value[] = $html ? '<li class="icon-padding icon-element">' . $label . '</li>' : $label;
                                 break;
                                 // case 'listObjIcons':
                             // case 'listObjIcons':
                             default:
                                 $icon = \CB\Browser::getIcon($d);
                                 if (empty($icon)) {
                                     $icon = 'icon-none';
                                 }
                                 $value[] = $html ? '<li class="icon-padding ' . $icon . '">' . $label . '</li>' : $label;
                                 break;
                         }
                     }
                 }
                 $value = $html ? '<ul class="clean">' . implode('', $value) . '</ul>' : implode(', ', $value);
                 break;
             case '_fieldTypesCombo':
                 $value = L\get(@static::$fieldTypeNames[$value]);
                 break;
             case 'date':
                 $value = Util\formatMysqlDate(Util\dateISOToMysql($value));
                 break;
             case 'datetime':
                 $value = Util\UTCTimeToUserTimezone($value);
                 break;
             case 'time':
                 if (empty($value)) {
                     continue;
                 }
                 $format = empty($field['format']) ? 'H:i' : $field['format'];
                 if (is_numeric($value)) {
                     $s = $value % 60;
                     $value = floor($value / 60);
                     $m = $value % 60;
                     $value = floor($value / 60);
                     if (strlen($value) < 2) {
                         $value = '0' . $value;
                     }
                     if (strlen($m) < 2) {
                         $m = '0' . $m;
                     }
                     $value .= ':' . $m;
                     if (!empty($s)) {
                         if (strlen($s) < 2) {
                             $s = '0' . $s;
                         }
                         $value .= ':' . $s;
                     }
                 } else {
                     $date = \DateTime::createFromFormat($format, $value);
                     if (is_object($date)) {
                         $value = $date->format($format);
                     }
                 }
                 break;
             case 'html':
                 $cacheValue = false;
                 // $value = trim(strip_tags($value));
                 // $value = nl2br($value);
                 break;
             case 'varchar':
             case 'memo':
             case 'text':
                 $cacheValue = false;
                 $renderers = '';
                 if (!empty($field['cfg']['linkRenderers'])) {
                     $renderers = $field['cfg']['linkRenderers'];
                 } elseif (!empty($field['cfg']['text_renderer'])) {
                     $renderers = $field['cfg']['text_renderer'];
                 }
                 $value = empty($renderers) ? nl2br(htmlspecialchars($value, ENT_COMPAT)) : nl2br(Comment::processAndFormatMessage($value), $renderers);
                 break;
             default:
                 if (is_array($value)) {
                     $cacheValue = false;
                     $value = Util\jsonEncode($value);
                 } else {
                     $value = htmlspecialchars($value, ENT_COMPAT);
                 }
         }
     }
     if ($cacheValue) {
         Cache::set($cacheVarName, $condition . $value);
     }
     return $condition . $value;
 }
Пример #23
0
 /**
  * update object
  * @param  array   $p optional properties. If not specified then $this-data is used
  * @return boolean
  */
 public function update($p = false)
 {
     if ($p !== false) {
         $this->data = $p;
         unset($this->linearData);
         if (array_key_exists('id', $p)) {
             $this->id = $p['id'];
         }
         $this->template = null;
         if (!empty($this->data['template_id']) && $this->loadTemplate) {
             $this->template = \CB\Templates\SingletonCollection::getInstance()->getTemplate($this->data['template_id']);
         }
     }
     if (!is_numeric($this->id)) {
         throw new \Exception("No object id specified for update", 1);
     }
     //load current object from db into a variable to be passed to log and events
     $this->oldObject = clone $this;
     $od = $this->oldObject->load($this->id);
     $wasDraft = !empty($od['draft']);
     \CB\fireEvent('beforeNodeDbUpdate', $this);
     $p =& $this->data;
     $tableFields = array('pid', 'user_id', 'system', 'template_id', 'tag_id', 'target_id', 'name', 'date', 'date_end', 'size', 'cfg', 'oid', 'did', 'dstatus');
     $data = $this->collectModelData($p);
     $data = array_merge($data, array('draft' => 0, 'uid' => User::getId(), 'udate' => 'CURRENT_TIMESTAMP'));
     DM\Tree::update($data);
     DM\Tree::activateChildDrafts($this->id);
     $this->updateCustomData();
     // set/update this object to cache
     Cache::set('Objects[' . $this->id . ']', $this);
     \CB\fireEvent('nodeDbUpdate', $this);
     if ($wasDraft) {
         $this->logAction('create', array('mentioned' => $this->lastMentionedUserIds));
     } else {
         $this->logAction('update', array('old' => $this->oldObject, 'mentioned' => $this->lastMentionedUserIds));
     }
     return true;
 }
Пример #24
0
 /**
  * get display data for given ids
  * @param  varchar|array $ids
  * @return associative   array of users display data
  */
 public static function getDisplayData($ids)
 {
     $rez = array();
     $ids = Util\toNumericArray($ids);
     if (!empty($ids)) {
         $cdd = array();
         if (Cache::exist('UsersGroupsDisplayData')) {
             $cdd = Cache::get('UsersGroupsDisplayData');
         } else {
             $cdd = DataModel\UsersGroups::getDisplayData();
             Cache::set('UsersGroupsDisplayData', $cdd);
         }
         $rez = array_intersect_key($cdd, array_flip($ids));
     }
     return $rez;
 }
Пример #25
0
 /**
  * method to get multiple object properties from solr
  * Multilanguage plugin works also
  *
  * @param  array | string $ids
  * @param  string         $fieldList
  * @return array          associative array of properties per id
  */
 public static function getObjects($ids, $fieldList = 'id,name')
 {
     $rez = array();
     $ids = Util\toNumericArray($ids);
     if (!empty($ids)) {
         $chunks = array_chunk($ids, 200);
         //connect or get solr service connection
         $conn = Cache::get('solr_service');
         if (empty($conn)) {
             $conn = new Solr\Service();
             Cache::set('solr_service', $conn);
         }
         //execute search
         try {
             foreach ($chunks as $chunk) {
                 $params = array('defType' => 'dismax', 'q.alt' => '*:*', 'fl' => $fieldList, 'fq' => array('id:(' . implode(' OR ', $chunk) . ')'));
                 $inputParams = array('ids' => $chunk);
                 $eventParams = array('params' => &$params, 'inputParams' => &$inputParams);
                 \CB\fireEvent('beforeSolrQuery', $eventParams);
                 $searchRez = $conn->search('', 0, 200, $params);
                 if (!empty($searchRez->response->docs)) {
                     foreach ($searchRez->response->docs as $d) {
                         $rd = array();
                         foreach ($d as $fn => $fv) {
                             $rd[$fn] = $fv;
                         }
                         $rez[$d->id] = $rd;
                     }
                 }
                 $eventParams['result'] = array('data' => &$rez);
                 \CB\fireEvent('solrQuery', $eventParams);
             }
         } catch (\Exception $e) {
             throw new \Exception("An error occured in getObjects: \n\n {$e->__toString()}");
         }
     }
     return $rez;
 }
Пример #26
0
 /**
  *
  * @param type $corename
  */
 public static function prepareInstance($corename = DEFAULT_TEST_CORENAME)
 {
     try {
         require_once CB_ROOT_PATH . 'httpsdocs/config_platform.php';
     } catch (\Exception $e) {
         //config.ini could not exist
         //we don't need to do anything here because this script will create confing.ini in result
         //we just use values form config.ini as defaults, if it exists
     }
     require_once \CB\LIB_DIR . 'install_functions.php';
     $config_filename = static::getConfigFilename();
     $config_filename_tpl = static::getConfigFilenameTPL();
     if (!file_exists($config_filename)) {
         if (file_exists($config_filename_tpl)) {
             $test_cfg = parse_ini_file($config_filename_tpl);
             Cache::set('RUN_SETUP_INTERACTIVE_MODE', true);
             $test_cfg['backup_dir'] = CB_ROOT_PATH . 'backup' . DIRECTORY_SEPARATOR;
             //$test_cfg['server_name']     = Install\readParam('server_name', $test_cfg['server_name']);
             $test_hostname = preg_replace('/^http(s)?:\\/\\//si', '', $test_cfg['server_name']);
             $tests_solr_path = CB_ROOT_PATH . 'tests/server/solr/solr-5.2.0/server/';
             if (file_exists($tests_solr_path)) {
                 $test_cfg['solr_home'] = CB_ROOT_PATH . 'tests/server/solr/solr-5.2.0/server/';
             }
             $test_cfg['admin_email'] = 'admin@' . $test_hostname;
             $test_cfg['sender_email'] = 'sender@' . $test_hostname;
             $test_cfg['comments_email'] = 'comments@' . $test_hostname;
             $test_cfg['core_root_email'] = 'root@' . $test_hostname;
             if (!\CB\IS_WINDOWS) {
                 //ask for apache user and set ownership for some folders
                 // $test_cfg['apache_user'] = Install\readParam('apache_user', $test_cfg['apache_user']);
             }
             /* $test_cfg['db_user']     = Install\readParam('db_user', $test_cfg['db_user']);
                             $test_cfg['db_pass']     = Install\readParam('db_pass');
             
                             $test_cfg['su_db_user'] = Install\readParam('su_db_user', $test_cfg['su_db_user']);
                             $test_cfg['su_db_pass'] = Install\readParam('su_db_pass'); */
             echo 'writing autoconfig file to:' . $config_filename . PHP_EOL;
             Install\putIniFile($config_filename, $test_cfg);
             if (!\CB\IS_WINDOWS) {
                 //     shell_exec('chown ' . $test_cfg['apache_user'].' "' . $config_filename . '"');
             }
             Cache::set('RUN_SETUP_INTERACTIVE_MODE', false);
         }
     }
     if (file_exists($config_filename)) {
         $options = array('file' => $config_filename);
         include CB_ROOT_PATH . 'bin/install.php';
     } else {
         $error_msg = ' Please create cofig file : ' . $config_filename . PHP_EOL . ' ' . ' You can use file: ' . TEST_PATH . 'auto_install_config.ini as template ' . PHP_EOL . PHP_EOL;
         trigger_error($error_msg, E_USER_ERROR);
     }
 }
Пример #27
0
 private function updateCronLastActionTime($cron_id)
 {
     if (empty($cron_id)) {
         return;
     }
     $cache_var_name = 'update_cron_' . $cron_id;
     /* if less than 20 seconds have passed then skip updating db */
     if (\CB\Cache::exist($cache_var_name) && time() - \CB\Cache::get($cache_var_name) < 20) {
         return;
     }
     \CB\Cache::set($cache_var_name, time());
     DB\dbQuery('UPDATE crons
         SET last_action = CURRENT_TIMESTAMP
         WHERE cron_id = $1', $cron_id) or die('error updating crons last action');
 }
Пример #28
0
/**
 * load config from CLI parameters and set respective FLAGS for install
 * @param array $options
 */
function cliLoadConfig($options = null)
{
    $cfg = null;
    if (empty($options)) {
        $options = cliGetAllOptions();
    }
    $configFile = cliGetConfigFile($options);
    if (!empty($configFile) && file_exists($configFile)) {
        $cfg = \CB\Config::loadConfigFile($configFile);
        if (count($cfg)) {
            \CB\Cache::set('RUN_SETUP_INTERACTIVE_MODE', false);
        }
        \CB\Cache::set('RUN_SETUP_CFG', $cfg);
        if (isset($cfg['overwrite_create_backups']) && $cfg['overwrite_create_backups'] == 'n') {
            \CB\Cache::set('RUN_SETUP_CREATE_BACKUPS', false);
        } else {
            \CB\Cache::set('RUN_SETUP_CREATE_BACKUPS', true);
        }
    } else {
        \CB\Cache::set('RUN_SETUP_CREATE_BACKUPS', true);
    }
    //define working mode
    if (!empty($cfg)) {
        // define('CB\\CB\Cache::get('RUN_SETUP_INTERACTIVE_MODE')', false);
        \CB\Cache::set('RUN_SETUP_INTERACTIVE_MODE', false);
        // $cfg = $cfg + $options['config'];
    } else {
        \CB\Cache::set('RUN_SETUP_INTERACTIVE_MODE', true);
    }
    // initialize default values in cofig if not detected
    $defaultValues = getDefaultConfigValues();
    if (is_array($cfg)) {
        $cfg = $cfg + $defaultValues;
    } else {
        $cfg = $defaultValues;
    }
    if (\CB\Util\checkKeyExists(array_keys($options), getParamPhrase())) {
        foreach ($options as $OptKey => $OptValue) {
            $cfg[$OptKey] = $OptValue;
        }
    }
    return $cfg;
}
Пример #29
0
 /**
  * get photo param to be added for photo urls
  * @param  $idOrData
  * @return varchar
  */
 public static function getPhotoParam($idOrData = false)
 {
     $data = array();
     if ($idOrData === false) {
         //use current logged users
         $id = static::getId();
     } elseif (is_numeric($idOrData)) {
         //id specified
         $id = $idOrData;
     } elseif (is_array($idOrData) && !empty($idOrData['id']) && is_numeric($idOrData['id'])) {
         $id = $idOrData['id'];
         $data = $idOrData;
     } else {
         return '';
     }
     $var_name = 'users[' . $id . "]['photoParam']";
     if (!Cache::exist($var_name)) {
         if (empty($data)) {
             $data = DM\Users::read($id);
         }
         $rez = '';
         $photosPath = Config::get('photos_path');
         $photoFile = $photosPath . $data['photo'];
         if (file_exists($photoFile)) {
             $rez = date('ynjGis', filemtime($photoFile));
         }
         Cache::set($var_name, $rez);
     }
     return Cache::get($var_name);
 }
Пример #30
0
 /**
  * get param for this node
  *
  * @param  varchar $param for now using to get 'facets' or 'DC'
  * @return array
  */
 public function getNodeParam($param = 'facets')
 {
     $rez = false;
     $from = $this->getId();
     //check if cached
     $cacheParam = 'nodeParam_' . $param . '_' . $from;
     if (Cache::exist($cacheParam)) {
         return Cache::get($cacheParam);
     }
     //select configs from tree and template of the current node
     $sql = 'SELECT t.cfg, t.template_id, tt.cfg `templateCfg`
         FROM tree t
         LEFT JOIN templates tt
             ON (t.template_id = tt.id)
                 OR ((tt.id = $2) AND (t.template_id IS NULL))
         WHERE t.id = $1';
     //if template_id specified in config then select directly from templates table
     if (empty($from) && !empty($this->config['template_id'])) {
         $from = 'template_' . $this->config['template_id'];
         $sql = 'SELECT null `cfg`, t.id template_id, t.cfg `templateCfg`
             FROM templates t
             WHERE t.id = $2';
     }
     //check node configuration and/or its template for facets definitions
     $res = DB\dbQuery($sql, array($this->id, @$this->config['template_id'])) or die(DB\dbQueryError());
     if ($r = $res->fetch_assoc()) {
         $cfg = Util\toJSONArray($r['cfg']);
         if (isset($cfg[$param])) {
             $rez = $cfg[$param];
         } else {
             $cfg = Util\toJSONArray($r['templateCfg']);
             if (isset($cfg[$param])) {
                 $rez = $cfg[$param];
                 $from = 'template_' . $r['template_id'];
             }
         }
         //add grouping param for DC
         if ($param == 'DC' && $rez !== false) {
             if (!empty($cfg['view']['group'])) {
                 $rez['group'] = $cfg['view']['group'];
             } elseif (!empty($cfg['group'])) {
                 $rez['group'] = $cfg['group'];
             }
         }
     }
     $res->close();
     if ($rez === false) {
         $rez = parent::getNodeParam($param);
     } else {
         $rez = array('from' => $from, 'data' => $rez);
     }
     Cache::set($cacheParam, $rez);
     return $rez;
 }