Пример #1
0
 /**
  * Constructing cache object
  *
  * @param string $cache_link
  * @param string $class
  */
 public function __construct($cache_link = null, $class = null)
 {
     // if we need to use default link from application
     if (empty($cache_link)) {
         $cache_link = application::get(['flag', 'global', 'cache', 'default_cache_link']);
         if (empty($cache_link)) {
             throw new Exception('You must specify cache link and/or class!');
         }
     }
     // get object from factory
     $temp = factory::get(['cache', $cache_link]);
     // if we have class
     if (!empty($class) && !empty($cache_link)) {
         // replaces in case we have it as submodule
         $class = str_replace('.', '_', trim($class));
         // if we are replacing database connection with the same link we
         // need to manually close connection
         if (!empty($temp['object']) && $temp['class'] != $class) {
             $object = $temp['object'];
             $object->close();
             unset($this->object);
         }
         $this->object = new $class($cache_link);
         // putting every thing into factory
         factory::set(['cache', $cache_link], ['object' => $this->object, 'class' => $class]);
     } else {
         if (!empty($temp['object'])) {
             $this->object = $temp['object'];
         } else {
             throw new Exception('You must specify cache link and/or class!');
         }
     }
 }
Пример #2
0
 /**
  * Constructing crypt object
  *
  * @param string $db_link
  * @param string $class
  */
 public function __construct($crypt_link = null, $class = null, $options = [])
 {
     // if we need to use default link from application
     if ($crypt_link == null) {
         $crypt_link = application::get(['flag', 'global', 'crypt', 'default_crypt_link']);
         if (empty($crypt_link)) {
             throw new Exception('You must specify crypt link!');
         }
     }
     // get object from factory
     $temp = factory::get(['crypt', $crypt_link]);
     // if we have class
     if (!empty($class) && !empty($crypt_link)) {
         // replaces in case we have it as submodule
         $class = str_replace('.', '_', trim($class));
         // creating new class
         unset($this->object);
         $this->object = new $class($crypt_link, $options);
         factory::set(['crypt', $crypt_link], ['object' => $this->object, 'class' => $class]);
     } else {
         if (!empty($temp['object'])) {
             $this->object = $temp['object'];
         } else {
             throw new Exception('You must specify crypt link and/or class!');
         }
     }
 }
Пример #3
0
 /**
  * Get the unique cache instance
  *
  * @param array $cfg Config for the cache instance
  * @return cache_abstract The instance
  */
 public static function getInstance(array $cfg = array())
 {
     if (!self::$cfg) {
         self::$cfg = new config(factory::loadCfg(__CLASS__));
     }
     return factory::get('cache_' . self::$cfg->use, $cfg);
 }
Пример #4
0
	/**
	 * Get the response object according to the requested out
	 *
	 * @return response_abstract
	 */
	public static function getInstance() {
		if (self::$proxy)
			return self::$proxy;
		if (!self::$inst) {
			self::$inst = factory::get('response_'.request::getResponseName());
			self::$inst->setContentType(request::get('out'));
		}
		return self::$inst;
	}
Пример #5
0
 protected function afterInit()
 {
     parent::afterInit();
     $this->form = factory::get('form_db', array_merge($this->cfg->formOpts, array('table' => $this->cfg->table)));
     $this->replaceName = str_replace('[]', '', $this->name) . '_fields[' . $this->cfg->replaceKey . '][[name]]';
     foreach ($this->cfg->fields as $f) {
         $f['name'] = str_replace('[name]', $f['name'], $this->replaceName);
         $this->form->addFromField($f);
     }
     $this->prepareValuesForValid();
     $this->valid->getCfg()->setRef('value', $this->valuesForValid);
 }
Пример #6
0
 /**
  * Set up the valid object
  */
 protected function afterInit()
 {
     if (!$this->label && !is_bool($this->label)) {
         $this->label = ucfirst($this->name);
     }
     if (!is_object($this->cfg->value)) {
         $this->cfg->value = utils::htmlOut($this->cfg->value);
     }
     $this->id = $this->makeId($this->name);
     $val =& $this->cfg->getRef('value');
     $this->valid = factory::get($this->cfg->validType, array('value' => &$val, 'label' => $this->label, 'validEltArray' => $this->cfg->getInArray('valid', 'validEltArray')));
     $this->cfg->delInArray('valid', 'validEltArray');
     $this->initValid();
 }
Пример #7
0
 /**
  * Init the filter form
  */
 protected function initForm()
 {
     $this->form = factory::get('form_db', array_merge($this->cfg->formOpts, array('filter' => true, 'table' => $this->table, 'sectionName' => $this->cfg->formName, 'action' => request::uriDef(array('paramA' => array_merge(array_diff_key(request::get('paramA'), $this->cfg->actionPrmClear), $this->cfg->actionPrmForce))))));
     $this->form->setSubmitText($this->cfg->submitText);
     $this->form->setSubmitplus('<a href="' . $this->clearLink() . '">' . $this->cfg->clearText . '</a>');
     if (!empty($this->cfg->fields)) {
         foreach ($this->cfg->fields as $field) {
             if ($f = $this->table->getField($field)) {
                 $f['label'] = $this->getLabel($f['name']);
                 $f['link'] = $this->table->getLinked($f['name']);
                 $this->form->addFromFieldFilter($f);
             } else {
                 if ($r = $this->table->getRelated($field)) {
                     $r['label'] = $this->getLabel($r['table']);
                     $r['name'] = $r['tableLink'];
                     $this->form->addFromRelatedFilter($r);
                 } else {
                     if ($this->table->hasI18n() && db::isI18nName($field) && ($f = $this->table->getI18nTable()->getField(db::unI18nName($field)))) {
                         $name = db::unI18nName($field);
                         $f['name'] = $field;
                         $f['label'] = $this->getLabel($field);
                         $f['link'] = $this->table->getI18nTable()->getLinked($name);
                         $this->form->addFromFieldFilter($f);
                     }
                 }
             }
         }
     } else {
         // All fields
         foreach ($this->table->getField() as $f) {
             $f['label'] = $this->getLabel($f['name']);
             $f['link'] = $this->table->getLinked($f['name']);
             $this->form->addFromFieldFilter($f);
         }
         foreach ($this->table->getRelated() as $t => $r) {
             $r['name'] = $r['tableLink'];
             $r['label'] = $this->getLabel($r['table']);
             $this->form->addFromRelated($r);
         }
     }
     $this->fillValues();
 }
Пример #8
0
 /**
  * Constructing database object
  *
  * @param string $db_link
  * @param string $class
  */
 public function __construct($db_link = null, $class = null)
 {
     // if we need to use default link from application
     if (empty($db_link)) {
         $db_link = application::get(['flag', 'global', 'db', 'default_db_link']);
         if (empty($db_link)) {
             throw new Exception('You must specify database link and/or class!');
         }
     }
     // get object from factory
     $temp = factory::get(['db', $db_link]);
     // if we have class
     if (!empty($class) && !empty($db_link)) {
         // replaces in case we have it as submodule
         $class = str_replace('.', '_', trim($class));
         // if we are replacing database connection with the same link we
         // need to manually close database connection
         if (!empty($temp['object']) && $temp['class'] != $class) {
             $object = $temp['object'];
             $object->close();
             unset($this->object);
         }
         // creating new class
         $this->object = new $class($db_link);
         // determining ddl class & object
         $ddl_class = str_replace('_base_abc123', '_ddl', $class . '_abc123');
         $ddl_object = new $ddl_class();
         // backend
         $this->backend = str_replace(['numbers_backend_db_', '_base'], '', $class);
         // putting every thing into factory
         factory::set(['db', $db_link], ['object' => $this->object, 'class' => $class, 'backend' => $this->backend, 'ddl_class' => $ddl_class, 'ddl_object' => $ddl_object]);
     } else {
         if (!empty($temp['object'])) {
             $this->object =& $temp['object'];
             $this->backend = $temp['backend'];
         } else {
             throw new Exception('You must specify database link and/or class!');
         }
     }
 }
Пример #9
0
 protected function beforeInit()
 {
     $required = array_key_exists('required', $this->cfg->valid) && $this->cfg->getInArray('valid', 'required');
     $htVars = http_vars::getInstance();
     $this->keep = $htVars->getVar($this->name . 'NyroKeep');
     if ($this->keep) {
         $this->cfg->value = $this->keep;
     }
     $prm = array_merge($this->cfg->fileUploadedPrm, array('name' => $this->cfg->name, 'current' => $this->cfg->value, 'helper' => $this->cfg->helper, 'helperPrm' => $this->cfg->helperPrm, 'required' => $required));
     if ($this->cfg->dir) {
         $prm['dir'] = $this->cfg->dir;
     }
     if ($this->cfg->subdir) {
         $prm['subdir'] = $this->cfg->subdir;
     }
     $this->cfg->value = factory::get('form_fileUploaded', $prm);
     if ($this->cfg->autoDeleteOnGet && !$this->cfg->value->isSaved(true) && $htVars->getVar($this->name . 'NyroDel')) {
         $this->cfg->value->delete();
         $this->deleted = true;
     }
     $this->cfg->valid = array_merge($this->cfg->valid, array('callback' => array($this->cfg->value, 'isValid')));
 }
Пример #10
0
	/**
	 * Multiple delete action
	 *
	 * @param array $ids 
	 */
	protected function multipleDelete(array $ids) {
		$this->table->delete($this->table->getWhere(array(
			'clauses'=>factory::get('db_whereClause', array(
					'name'=>$this->table->getRawName().'.'.$this->table->getIdent(),
					'in'=>$ids
				))
		)));
	}
Пример #11
0
	/**
	 * Every called action must pass by this function
	 *
	 * @param null|string $prm Actopn Parameters
	 * @throws nException if wrong parameter or other errors
	 */
	final public function exec(array $prm=array()) {
		$this->prmExec = array_merge(array(
			'module'=>$this->getName(),
			'action'=>'index',
			'param'=>'',
			'paramA'=>null,
			'prefix'=>null),
			$prm);

		$this->prmExec['prefix'] = null;

		if (array_key_exists(NYROENV, $this->cfg->basicPrefixExec) &&
				in_array($this->prmExec['action'], $this->cfg->getInArray('basicPrefixExec', NYROENV)))
			$this->prmExec['prefix'] = ucfirst(NYROENV);
		else if ($this->cfg->prefixExec && !in_array($this->prmExec['action'], $this->cfg->noPrefixExec))
			$this->prmExec['prefix'] = $this->cfg->prefixExec;

		$this->beforeExec($prm);

		if (!$this->cfg->render)
			security::getInstance()->check($this->prmExec);

		$fctName = ($this->cfg->render? 'render' : 'exec').$this->prmExec['prefix'].ucfirst($this->prmExec['action']);
		if (!method_exists($this, $fctName))
			response::getInstance()->error();

		$this->setViewAction($this->prmExec['action']);

		$param = is_array($this->prmExec['paramA'])? $this->prmExec['paramA'] : request::parseParam($this->prmExec['param']);

		$tags = $this->cfg->cacheTags;
		$search = array('/', '<', '>');
		$replace = array('', '', '');
		if (is_array($this->prmExec['paramA']))
			foreach($this->prmExec['paramA'] as $k=>$v) {
				if (is_object($v)) {
					if (is_callable(array($v, '__toString')))
						$tags[] = $k.'='.$v;
					else
						$tags[] = $k.'='.get_class($v);
				} elseif (!is_numeric($k))
					$tags[] = $k.'='.str_replace($search, $replace, $v);
				else
					$tags[] = str_replace($search, $replace, $v);
			}

		$paramTpl = array();
		foreach($param as $k=>$v) {
			if (is_object($v)) {
				if (is_callable(array($v, '__toString')))
					$paramTpl[] = $k.'='.$v;
				else
					$paramTpl[] = $k.'='.get_class($v);
			} else
				$paramTpl[] = $k.':'.$v;
		}

		$conf = array(
			'layout'=>$this->cfg->layout,
			'module'=>$this->getName(),
			'action'=>$this->cfg->viewAction,
			'param'=>implode(',', $paramTpl),
			'cache'=>array_merge(array(
				'enabled'=>$this->isCacheEnabled(),
				'serialize'=>false,
				'tags'=>$tags,
				'request'=>array('uri'=>false, 'meth'=>array())
			), $this->cfg->cache)
		);
		$this->tpl = factory::get('tpl', array_merge_recursive($conf, $this->cfg->tplPrm));
		$this->tpl->getCfg()->layout = $this->cfg->layout;
		$this->tpl->getCfg()->module = $this->getName();
		$this->tpl->getCfg()->action = $this->cfg->viewAction;
		$this->tpl->getCfg()->default = $this->cfg->viewAction;
		
		$this->prmExec['callbackPrm'] = array(
			'fctName'=>$fctName,
			'fctNameParam'=>$param,
			'prm'=>$prm
		);
		$this->middleExec($prm);
	}
Пример #12
0
	protected function getForm() {
		$form = factory::get('form', array_merge(array(
			'sectionName'=>$this->myCfg['formName'],
			'action'=>$this->uri
		), $this->myCfg['formCfg']));
		
		$form->add('file', array(
			'name'=>'file',
			'subdir'=>$this->dir,
			'helper'=>$this->myCfg['helper'][$this->type]['name'],
			'helperPrm'=>$this->myCfg['helper'][$this->type]['prm'],
		));
		$form->get('file')->plupload(array_merge($this->myCfg['plupload'][$this->type], array(
			'multipart_params'=>array(
				'type'=>$this->type,
				'config'=>$this->config,
			),
			'onAllComplete'=>'function() {window.location.href = "'.$this->uri.'";}'
		)));
		
		return $form;
	}
Пример #13
0
	/**
	 * Get the unique session instance
	 *
	 * @param array $cfg Configuration array for the session
	 * @return session_abstract The instance
	 */
	public static function getInstance(array $cfg = array()) {
		self::initCfg();
		return factory::get('session_'.self::$cfg->use, $cfg);
	}
Пример #14
0
	public function logout($prm = null) {
		if ($this->isLogged()) {
			$this->session->del('cryptic');
			$this->logged = false;
			// Clear the cookie
			$cook = factory::get('http_cookie', $this->cfg->cookie);
			$cook->del();
		}
		$this->hook('logout');
		return $this->logged == false;
	}
Пример #15
0
	protected function afterInit() {
		$t = factory::get('tpl');
		$this->module = factory::getModule(request::get('module'));
		nReflection::callMethod($this->module, request::get('action').'Action', request::get('param'));
	}
Пример #16
0
 /**
  * Used when cloning the form to create new field element
  */
 public function __clone()
 {
     $this->cfg = new config($this->cfg->getAll());
     $bound = $this->isBound;
     foreach ($this->section as $kSection => $sectionName) {
         foreach ($this->elements[$kSection] as $name => $e) {
             $this->elements[$kSection][$name] = factory::get(get_class($e), unserialize(serialize($e->getCfg()->getAll())));
             if (!is_object($e->getValue())) {
                 $this->setValue($name, $e->getValue());
             }
         }
     }
     $this->isBound = $bound;
 }
Пример #17
0
 /**
  * Get a where object
  *
  * @param array $prm The configuration for the where object
  * @return db_where
  */
 public function getWhere(array $prm = array())
 {
     return factory::get('db_where', array_merge(array('db' => $this), $prm));
 }
Пример #18
0
 /**
  * Create the data Table out
  *
  * @param string $type Out type
  * @return string
  */
 public function to($type)
 {
     $tpl = factory::get('tpl', array('module' => $this->cfg->module, 'action' => $this->cfg->name, 'default' => 'dataTable', 'cache' => $this->cfg->cache, 'layout' => false));
     $data = $this->getData();
     if (count($data)) {
         if (empty($this->cfg->fields)) {
             $headersT = $data->getFields('flatReal');
             if ($keyRelated = array_search('related', $headersT)) {
                 unset($headersT[$keyRelated]);
             }
             foreach ($this->table->getI18nFields() as $f) {
                 $headersT[] = db::getCfg('i18n') . $f['name'];
             }
         } else {
             $headersT = $this->cfg->fields;
             if ($this->cfg->addIdentField && !in_array($this->table->getIdent(), $headersT)) {
                 array_unshift($headersT, $this->table->getIdent());
             }
         }
         $headers = array();
         $prmReplaceSortBy = '[sortBy]';
         $prmReplaceSortDir = '[sortDir]';
         $paramUrlA = request::get('paramA');
         unset($paramUrlA['page' . $this->cfg->nameParam]);
         $paramUrlA['sortBy' . $this->cfg->nameParam] = $prmReplaceSortBy;
         $paramUrlA['sortDir' . $this->cfg->nameParam] = $prmReplaceSortDir;
         $paramUrlA['page' . $this->cfg->nameParam] = 1;
         $tmpSortLink = request::uriDef(array('paramA' => $paramUrlA));
         foreach ($headersT as $k => $h) {
             $typeField = $this->table->getField($h, 'type');
             if ($typeField == 'file' && is_array($tmp = $this->table->getField($h, 'comment')) && array_key_exists(0, $tmp)) {
                 $typeField = $tmp[0];
             }
             $headers[$k] = array('label' => $this->table->getLabel($h), 'name' => $h, 'url' => str_replace(array($prmReplaceSortBy, $prmReplaceSortDir), array(db::isI18nName($h) ? $this->table->getI18nTable()->getName() . '_' . db::unI18nName($h) : $h, $this->cfg->sortBy == $h && $this->cfg->sortDir == 'asc' ? 'desc' : 'asc'), $tmpSortLink), 'type' => $typeField);
         }
         $actions = null;
         $actionsAlt = null;
         $actionsImg = null;
         if (is_array($this->cfg->actions) && !empty($this->cfg->actions)) {
             $actions = array();
             if (!$this->cfg->addIdentField) {
                 array_unshift($headersT, $this->table->getIdent());
             }
             array_walk($headersT, create_function('&$h', '$h = "[".$h."]";'));
             $dataK = null;
             $i = 0;
             foreach ($data as $d) {
                 $tmp = $this->getActions($d);
                 $tmpVals = $d->getValues('flatNoRelated');
                 $vals = array();
                 foreach ($headersT as $k => $v) {
                     $v = substr($v, 1, -1);
                     $vals[$k] = array_key_exists($v, $tmpVals) ? $tmpVals[$v] : null;
                 }
                 $curData = $d->getValues('data');
                 unset($curData['related']);
                 unset($curData['linked']);
                 if (is_null($dataK)) {
                     $dataK = array_keys($curData);
                     array_walk($dataK, create_function('&$h', '$h = "[".$h."]";'));
                 }
                 foreach ($tmp as &$t) {
                     $t = str_replace($dataK, $curData, $t);
                 }
                 $actions[$i] = $tmp;
                 $i++;
             }
             if (!empty($actions) && $this->cfg->actionsConfirmDelete) {
                 response::getInstance()->addJs('actionsConfirmDelete');
             }
             $actionsKey = array_keys($this->cfg->actions);
             $actionsAlt = $this->cfg->actionsAlt;
             if (!is_array($actionsAlt) || count($actionsAlt) < count($actionsKey)) {
                 foreach ($actionsKey as $v) {
                     if (!array_key_exists($v, $actionsAlt)) {
                         $actionsAlt[$v] = ucfirst($v);
                     }
                 }
             }
             $actionsImg = $this->cfg->actionsImg;
             foreach ($actionsKey as $v) {
                 if (!array_key_exists($v, $actionsImg)) {
                     $actionsImg[$v] = utils::getIcon(array('name' => $v, 'attr' => array('title' => $actionsAlt[$v]), 'alt' => $actionsAlt[$v], 'type' => $this->cfg->iconType));
                 }
             }
         }
         if ($this->cfg->sortBy) {
             $paramUrlA['sortBy' . $this->cfg->nameParam] = $this->cfg->sortBy;
             $paramUrlA['sortDir' . $this->cfg->nameParam] = $this->cfg->sortDir;
         } else {
             unset($paramUrlA['sortBy' . $this->cfg->nameParam]);
             unset($paramUrlA['sortDir' . $this->cfg->nameParam]);
         }
         $nbPage = $this->getNbPage();
         $pageLinks = array();
         $prmReplace = $this->cfg->pageLinkReplace;
         if (!$this->cfg->pageLinkTpl) {
             $paramUrlA['page' . $this->cfg->nameParam] = $prmReplace;
             $tmpPageLink = request::uriDef(array('paramA' => $paramUrlA));
         } else {
             $tmpPageLink = $this->cfg->pageLinkTpl;
         }
         for ($i = 1; $i <= $nbPage; $i++) {
             $pageLinks[$i] = str_replace($prmReplace, $i, $tmpPageLink);
         }
         if ($this->cfg->pageLinkTpl1) {
             $pageLinks[1] = $this->cfg->pageLinkTpl1;
         }
         $hasMultiple = count($this->cfg->multiple) > 0;
         if ($hasMultiple && $this->cfg->addCheckAllJs) {
             response::getInstance()->addJs('checkAll');
         }
         $tpl->setA(array_merge(array('headers' => $headers, 'list' => $data, 'nbPage' => $nbPage, 'currentPage' => $this->cfg->page, 'pageLinks' => $pageLinks, 'actions' => $actions, 'actionsImg' => $actionsImg, 'actionsAlt' => $actionsAlt, 'iconType' => $this->cfg->iconType, 'tblName' => $this->table->getName(), 'sortBy' => $this->cfg->sortBy, 'sortByReal' => $this->sortBy, 'sortDir' => $this->cfg->sortDir, 'hasMultiple' => $hasMultiple, 'multipleLabel' => $this->cfg->multipleLabel, 'multipleSubmit' => $this->cfg->multipleSubmit, 'multipleAction' => $this->cfg->multipleAction, 'multipleIdent' => $this->table->getIdent(), 'multiple' => $this->cfg->multiple), $this->cfg->tplVars));
     } else {
         // No data
         if ($this->cfg->page > 1) {
             $newPage = $this->cfg->page - 1;
             $uri = null;
             if ($newPage == 1 && $this->cfg->pageLinkTpl1) {
                 $uri = $this->cfg->pageLinkTpl1;
             }
             if (!$uri) {
                 $prmReplace = $this->cfg->pageLinkReplace;
                 if (!$this->cfg->pageLinkTpl) {
                     $paramUrlA = request::get('paramA');
                     unset($paramUrlA['page' . $this->cfg->nameParam]);
                     $prmReplaceSortBy = '[sortBy]';
                     $prmReplaceSortDir = '[sortDir]';
                     $paramUrlA['sortBy' . $this->cfg->nameParam] = $prmReplaceSortBy;
                     $paramUrlA['sortDir' . $this->cfg->nameParam] = $prmReplaceSortDir;
                     $paramUrlA['page' . $this->cfg->nameParam] = 1;
                     if ($this->cfg->sortBy) {
                         $paramUrlA['sortBy' . $this->cfg->nameParam] = $this->cfg->sortBy;
                         $paramUrlA['sortDir' . $this->cfg->nameParam] = $this->cfg->sortDir;
                     } else {
                         unset($paramUrlA['sortBy' . $this->cfg->nameParam]);
                         unset($paramUrlA['sortDir' . $this->cfg->nameParam]);
                     }
                     $paramUrlA['page' . $this->cfg->nameParam] = $prmReplace;
                     $tmpPageLink = request::uriDef(array('paramA' => $paramUrlA));
                 } else {
                     $tmpPageLink = $this->cfg->pageLinkTpl;
                 }
                 $uri = str_replace($prmReplace, $newPage, $tmpPageLink);
             }
             response::getInstance()->redirect($uri);
         }
         $tpl->set('noData', utils::htmlOut($this->cfg->noData));
         $tpl->set('list', null);
         $tpl->setA($this->cfg->tplVars);
     }
     return $tpl->fetch(array('tplExt' => $type));
 }
Пример #19
0
	/**
	 * Get the response proxy (used in the templates)
	 *
	 * @return response_proxy
	 */
	public function getProxy() {
		return factory::get('response_proxy');
	}
Пример #20
0
	/**
	 * Initialize the security instance parametred
	 */
	private static function init() {
		self::$cfg = new config(factory::loadCfg(__CLASS__));
		self::$instance = factory::get('security_'.self::$cfg->use);
	}
Пример #21
0
	/**
	 * Render a tpl element
	 *
	 * @param array $prm Array configuration, with at least the module and action keys
	 * @return string The rendered element
	 */
	public static function render(array $prm) {
		return factory::get('tpl', $prm)->render($prm);
	}
Пример #22
0
	/**
	 * Send The response
	 *
	 * @param bool $headerOnly Send only the header and exit
	 */
	public function send($headerOnly = false) {
		if (!headers_sent()) {
			$this->sendHeaders();
			$this->beforeOut();
			if ($headerOnly)
				exit(0);
		}

		$layout = request::isAjax()? $this->cfg->ajaxLayout : $this->cfg->layout;
		$ret = null;
		if (!$layout) {
			$ret = $this->content;
		} else {
			$tpl = factory::get('tpl', array(
				'module'=>'out',
				'action'=>$layout,
				'default'=>'layout',
				'layout'=>false,
				'cache'=>array('auto'=>false)
			));
			$tpl->set('content', $this->content);
			$ret = $tpl->fetch();
		}
		//if ($ret) $this->addHeader('Content-Length', strlen($ret), true);
		return $ret;
	}
Пример #23
0
 /**
  * Process models
  *
  * @param array $options
  * @return array
  */
 public static function process_models($options = [])
 {
     $result = ['success' => false, 'error' => [], 'hint' => [], 'data' => []];
     do {
         // we need to process all dependencies first
         $dep = self::process_deps_all($options);
         if (!$dep['success']) {
             $result = $dep;
             $result['error'][] = 'You must fix all dependency related errors first before processing models.';
             break;
         }
         // proccesing models
         if (empty($dep['data']['model_processed'])) {
             $result['error'][] = 'You do not have models to process!';
             break;
         }
         $object_attributes = [];
         $object_relations = [];
         $object_forms = [];
         $flag_relation = application::get('dep.submodule.numbers.data.relations') ? true : false;
         $object_documentation = [];
         $object_import = [];
         $ddl = new numbers_backend_db_class_ddl();
         // run 1 to deterine virtual tables
         $first = true;
         $virtual_models = $dep['data']['model_processed'];
         run_again:
         foreach ($virtual_models as $k => $v) {
             $k2 = str_replace('.', '_', $k);
             if ($v == 'object_table') {
                 $model = factory::model($k2, true);
                 foreach (['attributes', 'audit', 'addresses'] as $v0) {
                     if ($model->{$v0}) {
                         $v01 = $v0 . '_model';
                         $virtual_models[str_replace('_', '.', $model->{$v01})] = 'object_table';
                     }
                 }
             }
         }
         if ($first) {
             $first = false;
             goto run_again;
             // some widgets have attributes
         }
         $dep['data']['model_processed'] = array_merge_hard($dep['data']['model_processed'], $virtual_models);
         $domains = object_data_domains::get_static();
         // run 2
         foreach ($dep['data']['model_processed'] as $k => $v) {
             $k2 = str_replace('.', '_', $k);
             if ($v == 'object_table') {
                 $model = factory::model($k2, true);
                 $temp_result = $ddl->process_table_model($model);
                 if (!$temp_result['success']) {
                     array_merge3($result['error'], $temp_result['error']);
                 }
                 $object_documentation[$v][$k2] = $k2;
                 // relation
                 if ($flag_relation) {
                     if (!empty($model->relation)) {
                         $domain = $model->columns[$model->relation['field']]['domain'] ?? null;
                         if (!empty($domain)) {
                             $domain = str_replace('_sequence', '', $domain);
                             $type = $domains[$domain]['type'];
                         } else {
                             $type = $model->columns[$model->relation['field']]['type'];
                         }
                         $object_relations[$k2] = ['rn_relattr_code' => $model->relation['field'], 'rn_relattr_name' => $model->title, 'rn_relattr_model' => $k2, 'rn_relattr_domain' => $domain, 'rn_relattr_type' => $type, 'rn_relattr_inactive' => !empty($model->relation['inactive']) ? 1 : 0];
                     }
                     if (!empty($model->attributes)) {
                         $object_attributes[$k2] = ['rn_attrmdl_code' => $k2, 'rn_attrmdl_name' => $model->title, 'rn_attrmdl_inactive' => 0];
                     }
                 }
             } else {
                 if ($v == 'object_sequence') {
                     $temp_result = $ddl->process_sequence_model($k2);
                     if (!$temp_result['success']) {
                         array_merge3($result['error'], $temp_result['error']);
                     }
                     $object_documentation[$v][$k2] = $k2;
                 } else {
                     if ($v == 'object_function') {
                         $temp_result = $ddl->process_function_model($k2);
                         if (!$temp_result['success']) {
                             array_merge3($result['error'], $temp_result['error']);
                         }
                         $object_documentation[$v][$k2] = $k2;
                     } else {
                         if ($v == 'object_extension') {
                             $temp_result = $ddl->process_function_extension($k2);
                             if (!$temp_result['success']) {
                                 array_merge3($result['error'], $temp_result['error']);
                             }
                             $object_documentation[$v][$k2] = $k2;
                         } else {
                             if ($v == 'object_import') {
                                 $object_import[$k2] = ['model' => $k2];
                             }
                         }
                     }
                 }
             }
         }
         // if we have erros
         if (!empty($result['error'])) {
             break;
         }
         // db factory
         $db_factory = factory::get('db');
         // we load objects from database
         $loaded_objects = [];
         foreach ($ddl->db_links as $k => $v) {
             $ddl_object = $db_factory[$k]['ddl_object'];
             $temp_result = $ddl_object->load_schema($k);
             if (!$temp_result['success']) {
                 array_merge3($result['error'], $temp_result['error']);
             } else {
                 $loaded_objects[$k] = $temp_result['data'];
             }
         }
         // if we have erros
         if (!empty($result['error'])) {
             break;
         }
         // get a list of all db links
         $db_link_list = array_unique(array_merge(array_keys($ddl->objects), array_keys($loaded_objects)));
         // if we are dropping schema
         if ($options['mode'] == 'drop') {
             $ddl->objects = [];
         }
         // compare schemas per db link
         $schema_diff = [];
         $total_per_db_link = [];
         $total = 0;
         foreach ($db_link_list as $k) {
             // we need to have a back end for comparison
             $compare_options['backend'] = $db_factory[$k]['backend'];
             // comparing
             $temp_result = $ddl->compare_schemas(isset($ddl->objects[$k]) ? $ddl->objects[$k] : [], isset($loaded_objects[$k]) ? $loaded_objects[$k] : [], $compare_options);
             if (!$temp_result['success']) {
                 array_merge3($result['hint'], $temp_result['error']);
             } else {
                 $schema_diff[$k] = $temp_result['data'];
                 if (!isset($total_per_db_link[$k])) {
                     $total_per_db_link[$k] = 0;
                 }
                 $total_per_db_link[$k] += $temp_result['count'];
                 $total += $temp_result['count'];
             }
         }
         // if there's no schema changes
         if ($total == 0) {
             if ($options['mode'] == 'commit') {
                 goto import_data;
             } else {
                 $result['success'] = true;
             }
             break;
         }
         // we need to provide a list of changes
         foreach ($total_per_db_link as $k => $v) {
             $result['hint'][] = '';
             $result['hint'][] = "Db link {$k} requires {$v} changes!";
             // printing summary
             $result['hint'][] = ' * Link ' . $k . ': ';
             foreach ($schema_diff[$k] as $k2 => $v2) {
                 $result['hint'][] = '   * ' . $k2 . ': ';
                 foreach ($v2 as $k3 => $v3) {
                     $result['hint'][] = '    * ' . $k3 . ' - ' . $v3['type'];
                 }
             }
         }
         // if we are in no commit mode we exit
         if (!in_array($options['mode'], ['commit', 'drop'])) {
             break;
         }
         // generating sql
         foreach ($total_per_db_link as $k => $v) {
             if ($v == 0) {
                 continue;
             }
             $ddl_object = $db_factory[$k]['ddl_object'];
             foreach ($schema_diff[$k] as $k2 => $v2) {
                 foreach ($v2 as $k3 => $v3) {
                     // we need to make fk constraints last to sort MySQL issues
                     if ($k2 == 'new_constraints' && $v3['type'] == 'constraint_new' && $v3['data']['type'] == 'fk') {
                         $schema_diff[$k][$k2 . '_fks'][$k3]['sql'] = $ddl_object->render_sql($v3['type'], $v3);
                     } else {
                         $schema_diff[$k][$k2][$k3]['sql'] = $ddl_object->render_sql($v3['type'], $v3, ['mode' => $options['mode']]);
                     }
                 }
             }
         }
         //			print_r($schema_diff);
         //			exit;
         // executing sql
         foreach ($total_per_db_link as $k => $v) {
             if ($v == 0) {
                 continue;
             }
             $db_object = new db($k);
             // if we are dropping we need to disable foregn key checks
             if ($options['mode'] == 'drop') {
                 if ($db_object->backend == 'mysqli') {
                     $db_object->query('SET foreign_key_checks = 0;');
                     // we also need to unset sequences
                     unset($schema_diff[$k]['delete_sequences']);
                 }
             }
             foreach ($schema_diff[$k] as $k2 => $v2) {
                 foreach ($v2 as $k3 => $v3) {
                     if (empty($v3['sql'])) {
                         continue;
                     }
                     if (is_array($v3['sql'])) {
                         $temp = $v3['sql'];
                     } else {
                         $temp = [$v3['sql']];
                     }
                     foreach ($temp as $v4) {
                         $temp_result = $db_object->query($v4);
                         if (!$temp_result['success']) {
                             array_merge3($result['error'], $temp_result['error']);
                             goto error;
                         }
                     }
                 }
             }
         }
         // if we got here - we are ok
         $result['success'] = true;
     } while (0);
     import_data:
     // we need to import data
     if (!empty($object_import) && $options['mode'] == 'commit') {
         $result['hint'][] = '';
         foreach ($object_import as $k => $v) {
             $data_object = new $k();
             $data_result = $data_object->process();
             if (!$data_result['success']) {
                 throw new Exception(implode("\n", $data_result['error']));
             }
             $result['hint'] = array_merge($result['hint'], $data_result['hint']);
         }
     }
     // relation
     if ($flag_relation && $options['mode'] == 'commit') {
         $result['hint'][] = '';
         $model2 = factory::model('numbers_data_relations_model_relation_attributes');
         // insert new models
         if (!empty($object_relations)) {
             foreach ($object_relations as $k => $v) {
                 $result_insert = $model2->save($v, ['pk' => ['rn_relattr_code'], 'ignore_not_set_fields' => true]);
             }
             $result['hint'][] = ' * Imported relation models!';
         }
         // we need to process forms
         foreach ($dep['data']['submodule_dirs'] as $v) {
             $dir = $v . 'model/form/';
             if (!file_exists($dir)) {
                 continue;
             }
             $files = helper_file::iterate($dir, ['only_extensions' => ['php']]);
             foreach ($files as $v2) {
                 $model_name = str_replace(['../libraries/vendor/', '.php'], '', $v2);
                 $model_name = str_replace('/', '_', $model_name);
                 $model = new $model_name(['skip_processing' => true]);
                 if (empty($model->form_object->misc_settings['option_models'])) {
                     continue;
                 }
                 // loop though fields
                 foreach ($model->form_object->misc_settings['option_models'] as $k3 => $v3) {
                     $object_forms[$model_name . '::' . $k3] = ['rn_relfrmfld_form_code' => $model_name, 'rn_relfrmfld_form_name' => $model->title, 'rn_relfrmfld_field_code' => $k3, 'rn_relfrmfld_field_name' => $v3['field_name'], 'rn_relfrmfld_relattr_id' => $v3['model'], 'rn_relfrmfld_inactive' => 0];
                 }
             }
         }
         if (!empty($object_forms)) {
             // load all relation models
             $data = $model2->get(['pk' => ['rn_relattr_model']]);
             $model = factory::model('numbers_data_relations_model_relation_formfields');
             foreach ($object_forms as $k => $v) {
                 if (empty($data[$v['rn_relfrmfld_relattr_id']])) {
                     continue;
                 }
                 $v['rn_relfrmfld_relattr_id'] = $data[$v['rn_relfrmfld_relattr_id']]['rn_relattr_id'];
                 $result_insert = $model->save($v, ['pk' => ['rn_relfrmfld_form_code', 'rn_relfrmfld_field_code'], 'ignore_not_set_fields' => true]);
             }
             $result['hint'][] = ' * Imported relation form fields!';
         }
         // todo: import models
         //print_r2($object_attributes);
         if (!empty($object_attributes)) {
             $model = factory::model('numbers_data_relations_model_attribute_models');
             foreach ($object_attributes as $k => $v) {
                 $result_insert = $model->save($v, ['pk' => ['rn_attrmdl_code'], 'ignore_not_set_fields' => true]);
             }
             $result['hint'][] = ' * Imported attribute models!';
         }
     }
     // we need to generate documentation
     $system_documentation = application::get('system_documentation');
     if (!empty($system_documentation) && $options['mode'] == 'commit') {
         $model = factory::model($system_documentation['model']);
         /*
         print_r2($object_documentation);
         $documentation_result = $model->update($object_documentation, $system_documentation);
         if (!$documentation_result['success']) {
         	$result['error'] = array_merge($result['error'], $documentation_result['error']);
         }
         */
     }
     error:
     return $result;
 }
Пример #24
0
 /**
  * Get a db object
  *
  * @param string $type Element type (table, rowset or row)
  * @param db_table|string $table
  * @param array $prm Array parameter for the factory
  * @return db_table|db_rowset|db_row
  */
 public static function get($type, $table, array $prm = array())
 {
     if ($type == 'table' && array_key_exists($table, self::$tables)) {
         return self::$tables[$table];
     }
     self::init();
     if ($table instanceof db_table) {
         $tableName = $table->getName();
         if (!array_key_exists('table', $prm)) {
             $prm['table'] = $table;
         }
     } else {
         $tableName = $table;
         if ($type == 'table' && !array_key_exists('name', $prm)) {
             $prm['name'] = $table;
         } else {
             if ($type == 'row' && !array_key_exists('table', $prm)) {
                 $db = array_key_exists('db', $prm) ? $prm['db'] : self::getInstance();
                 $prm['table'] = self::get('table', $tableName, array('db' => $db));
             }
         }
     }
     if (!($className = self::$cfg->getInArray($type, $tableName)) && !factory::isCreable($className = 'db_' . $type . '_' . $tableName)) {
         $className = self::$cfg->get($type . 'Class');
     }
     if ($type == 'table') {
         self::$tables[$table] = factory::get($className, $prm);
         return self::$tables[$table];
     }
     return factory::get($className, $prm);
 }
Пример #25
0
application::run(['__run_only_bootstrap' => 1]);
// increase in memory and unlimited execution time
ini_set('memory_limit', '2048M');
set_time_limit(0);
// wrapping everything into try-catch block for system exceptions
try {
    // running proper class
    switch ($type) {
        case 'deploy':
            $result = system_deployments::deploy(['mode' => $mode]);
            break;
        case 'schema':
            $result = system_dependencies::process_models(['mode' => $mode]);
            // we need to reset all caches
            if ($mode == 'commit') {
                $cache = factory::get(['cache']);
                if (!empty($cache)) {
                    foreach ($cache as $k => $v) {
                        $object = $v['object'];
                        $object->gc(2);
                    }
                }
            }
            break;
        case 'dependency':
        default:
            $result = system_dependencies::process_deps_all(['mode' => $mode]);
    }
    // hint
    if (!empty($result['hint'])) {
        echo implode("\n", $result['hint']) . "\n";
Пример #26
0
 /**
  * Destroy everything
  */
 public static function destroy()
 {
     $__run_only_bootstrap = application::get(['flag', 'global', '__run_only_bootstrap']);
     // we need to set working directory again
     chdir(application::get(['application', 'path_full']));
     // error processing
     if (empty(error_base::$flag_error_already)) {
         $last_error = error_get_last();
         $flag_render = false;
         if (in_array($last_error['type'], [E_COMPILE_ERROR, E_PARSE, E_ERROR])) {
             error_base::error_handler($last_error['type'], $last_error['message'], $last_error['file'], $last_error['line']);
             error_base::$flag_error_already = true;
             $flag_render = true;
         }
         if ($flag_render || error_base::$flag_exception) {
             error_base::$flag_error_already = true;
             if ($__run_only_bootstrap) {
                 helper_ob::clean_all();
                 print_r(error_base::$errors);
             } else {
                 // set mvc + process
                 application::set_mvc('/error/_error/500');
                 application::process();
             }
         }
     }
     // write sessions
     session_write_close();
     // final benchmark
     if (debug::$debug) {
         debug::benchmark('application end');
     }
     // debugging toolbar last
     if (debug::$toolbar && !$__run_only_bootstrap) {
         echo str_replace('<!-- [numbers: debug toolbar] -->', debug::render(), helper_ob::clean());
     }
     // flush data to client
     flush();
     // closing caches before db
     $cache = factory::get(['cache']);
     if (!empty($cache)) {
         foreach ($cache as $k => $v) {
             $object = $v['object'];
             if (!empty(cache::$reset_caches[$k])) {
                 $object->gc(1, cache::$reset_caches[$k]);
             }
             $object->close();
         }
     }
     // destroy i18n
     if (i18n::$initialized) {
         i18n::destroy();
     }
     // close db connections
     $dbs = factory::get(['db']);
     if (!empty($dbs)) {
         foreach ($dbs as $k => $v) {
             $object = $v['object'];
             $object->close();
         }
     }
     // emails with erros
     if (debug::$debug && !empty(debug::$email)) {
         debug::send_errors_to_admin();
     }
 }
Пример #27
0
 /**
  * Process extension
  *
  * @param string $model_class
  * @return array
  */
 public function process_function_extension($model_class)
 {
     $result = ['success' => false, 'error' => []];
     do {
         // table model
         $model = new $model_class();
         $db = factory::get(['db', $model->db_link]);
         $ddl_object = $db['ddl_object'];
         $ddl_backend = $db['backend'];
         // if we do not have sql or its natively supported we exit
         if ($model->extension_submodule != $ddl_backend) {
             $result['success'] = true;
             break;
         }
         // process extension name and schema
         $this->object_add(['type' => 'extension', 'schema' => $model->schema, 'name' => $model->name], $model->db_link);
         // if we got here - we are ok
         $result['success'] = true;
     } while (0);
     return $result;
 }