예제 #1
0
 /**
  * 
  * Object constructor
  * @param t41\ObjectModel\DataObject|t41\ObjectModel\ObjectUri|string $val
  * @param array $params
  */
 public function __construct($val = null, array $params = null)
 {
     $this->_setParameterObjects();
     if (is_array($params)) {
         $this->_setParameters($params);
     }
     /* build data object and populate it if possible */
     if ($val instanceof DataObject) {
         if ($val->getClass() != get_class($this)) {
             throw new Exception("Provided Data Object is not build on class definition");
         }
         $this->_dataObject = $val;
     } else {
         if (!is_null($val)) {
             if (!$val instanceof ObjectUri) {
                 // provide backend if uri is partial
                 $backendUri = null;
                 //substr($val,0,1) != Backend::PREFIX ? ObjectModel::getObjectBackend(get_class($this)) : null;
                 $val = new ObjectUri($val, $backendUri);
                 $val->setClass(get_class($this));
             }
             $this->_dataObject = Core::_($val, get_class($this), ObjectModel::DATA);
         } else {
             $this->_dataObject = DataObject::factory(get_class($this));
         }
     }
     /* get object rules from config */
     $this->setRules();
 }
예제 #2
0
 /**
  * Execute the action and returns a result
  *
  * @return array
  */
 public function execute($params = null)
 {
     if ((!isset($params[$this->queryfield]) || empty($params[$this->queryfield])) && (!isset($params[$this->queryidfield]) || empty($params[$this->queryidfield]))) {
         return false;
     }
     if (isset($params['_offset'])) {
         $this->setParameter('offset', (int) $params['_offset']);
     }
     $extra = isset($params['extra']) ? (array) $params['extra'] : array();
     if (Core::getEnvData('cache_datasets') === true) {
         $hash = serialize($extra);
         $hash .= isset($params[$this->queryfield]) ? $params[$this->queryfield] : $params[$this->queryidfield];
         $md5 = md5($hash);
         //@todo check unicity, especially with hard-coded conditions having()
         $ckey = 'ds_ac_' . $this->_cachePrefix . '_' . $md5 . '_' . $this->getParameter('offset') . '_' . $this->getParameter('batch');
         if (($data = Core::cacheGet($ckey)) === false) {
             if (isset($params[$this->queryfield])) {
                 $data = $this->_getSuggestions(trim($params[$this->queryfield]), $extra);
             } else {
                 $data = $this->_getFromIdentifier(trim($params[$this->queryidfield]));
             }
             $data['cache-key'] = $ckey;
             Core::cacheSet($data, $ckey, true, array('tags' => array('view', 'ac', str_replace('\\', '_', $this->_obj->getClass()))));
         }
     } else {
         if (isset($params[$this->queryfield])) {
             $data = $this->_getSuggestions(trim($params[$this->queryfield]), $extra);
         } else {
             $data = $this->_getFromIdentifier(trim($params[$this->queryidfield]));
         }
     }
     return $data;
 }
예제 #3
0
 public static function getDownloadUrl(ObjectUri $uri)
 {
     $prefix = Core::getController('medias');
     if (!$prefix) {
         $prefix = '/t41/medias/';
     }
     return $prefix . 'download/obj/' . rawurlencode(base64_encode($uri->__toString()));
 }
예제 #4
0
 public function viewAction()
 {
     if (($cached = Core::cacheGet($this->_getParam('id'))) !== false) {
         echo '<pre>' . print_r($cached, true) . '<pre>';
     } else {
         throw new \Exception("Unable to find a cached object with this id: " . $this->_getParam('id'));
     }
     exit;
 }
예제 #5
0
파일: Session.php 프로젝트: crapougnax/t41
 /**
  * (non-PHPdoc)
  * @see \t41\ObjectModel\BaseObject::save()
  */
 public function save(Backend\Adapter\AbstractAdapter $backend = null)
 {
     if (is_null($backend)) {
         $this->setKey(Core::cacheSet($this, $this->getKey(), true, array('tags' => 'session')));
         return true;
     } else {
         return parent::save($backend);
     }
 }
예제 #6
0
파일: Loader.php 프로젝트: crapougnax/t41
 /**
  * Load a file into a Configuration Array
  * 
  * @param string $file
  * @param integer $realm
  * @param array $params
  * 
  * @return array|false Configuration Array or false if the file don't exists
  */
 public static function loadConfig($file, $realm = Config::REALM_CONFIGS, array $params = null)
 {
     // try to get cached version if configs caching is enabled
     if (Core::getEnvData('cache_configs') === true) {
         $ckey = self::getCacheKey($file, $realm);
         if (($cached = Core::cacheGet($ckey)) !== false) {
             Core::log(sprintf('[Config] Retrieved %s config file from cache', $file));
             return $cached;
         }
     }
     if (($filePath = self::findFile($file, $realm)) == null) {
         /* no matching file name in paths */
         Core::log(sprintf('[Config] Failed loading %s config file', $file), \Zend_Log::ERR);
         return false;
     }
     $type = substr($file, strrpos($file, '.') + 1);
     /* use existing adapter instance or create it */
     if (!isset(self::$_adapters[$type])) {
         $className = sprintf('\\t41\\Config\\Adapter\\%sAdapter', ucfirst(strtolower($type)));
         try {
             self::$_adapters[$type] = new $className($filePath, $params);
             if (!self::$_adapters[$type] instanceof Adapter\AbstractAdapter) {
                 throw new Exception("{$className} is not implementing AbstractAdapter.");
             }
         } catch (\Exception $e) {
             throw new Exception($e->getMessage());
         }
     } else {
         self::$_adapters[$type]->setPath($filePath);
     }
     $config = self::$_adapters[$type]->load();
     Core::log(sprintf('[Config] Successfully loaded %s config file', $file));
     /* if ckey is set, cache is activated but empty */
     if (isset($ckey)) {
         Core::cacheSet($config, $ckey, true, array('tags' => array('config')));
     }
     return $config;
 }
예제 #7
0
파일: Acl.php 프로젝트: crapougnax/t41
 /**
  * Detect all modules directories and try to get config for them
  * @param string $path
  */
 public static function init($path)
 {
     if (Core::getEnvData('cache_configs') !== false) {
         $ckey = 'configs_acl';
         if (($cached = Core::cacheGet($ckey)) !== false) {
             self::$_config = $cached;
             return;
         }
     }
     // load application acl configuration file
     $config = Config\Loader::loadConfig('acl.xml', Config::REALM_CONFIGS);
     $resources = array();
     // add all fragments coming from modules
     foreach (Core\Module::getConfig() as $vendorId => $vendorModules) {
         foreach ($vendorModules as $key => $module) {
             // module menus
             if (isset($module['controller']) && isset($module['controller']['items'])) {
                 // walk recursively through all module's items (menu elements)
                 $resources += self::_getAcl($module['controller']['base'], $module['controller']['items']);
             }
             // and optional menus extensions
             if (isset($module['controllers_extends'])) {
                 foreach ($module['controllers_extends'] as $controller => $data) {
                     $resources += self::_getAcl($module['controller']['base'], $data['items']);
                 }
             }
         }
     }
     if (!isset($config['acl']['resources'])) {
         $config['acl']['resources'] = array();
     }
     $config['acl']['resources'] += $resources;
     self::$_config = $config['acl'];
     if (isset($ckey)) {
         Core::cacheSet($config['acl'], $ckey, true, array('tags' => array('config', 'acl')));
     }
 }
예제 #8
0
 public function render()
 {
     // set correct name for field name value depending on 'mode' parameter value
     $name = $this->_obj->getId();
     $prefix = Core::getController('medias');
     if (!$prefix) {
         $prefix = '/t41/medias/';
     }
     $uri = $prefix . 'upload';
     View::addCoreLib(array('core.js', 'locale.js', 'view.js', 'uploader.css', 'view:action:upload.js'));
     View::addEvent(sprintf("t41.view.register('%s_ul', new t41.view.action.upload(jQuery('#%s_ul'),'%s'))", $name, $name, $uri), 'js');
     $html = '';
     // @todo code media deletion JS
     if ($this->_obj->getValue() != null) {
         $html .= sprintf('<span><a href="%s" target="_blank">%s %s</a> | <a href="#" onclick="t41.view.get(\'%s_ul\').reset(this)">%s</a></span>', MediaElement::getDownloadUrl($this->_obj->getValue()->getUri()), 'Télécharger', $this->_obj->getValue()->getLabel(), $name, 'Supprimer');
     }
     $html .= sprintf('<div id="%s_ul" class="qq-upload-list"></div>', $this->_nametoDomId($name));
     $html .= sprintf('<input type="hidden" name="%s" id="%s" value="%s" class="hiddenfilename"/>', $name, $this->_nametoDomId($name), $this->_obj->getValue() ? $this->_obj->getValue()->getIdentifier() : null);
     return $html;
     $action = new UploadAction($this->_obj);
     $deco = View\Decorator::factory($action);
     $deco->render();
     return $html . "\n";
 }
예제 #9
0
파일: Registry.php 프로젝트: crapougnax/t41
 public static function loadStore()
 {
     if (is_null(self::$_store)) {
         self::$_store = Core::cacheGet(self::$storeId);
     }
 }
예제 #10
0
 public function updateAction()
 {
     try {
         // populate status message if provided
         if (isset($this->_post['_status'])) {
             $this->_obj->status = new Status($this->_post['_status']);
         }
         // test object uri, if empty, object is new or faulty
         // @todo mix this with ObjectModel::populate()
         // walk through POST data
         foreach ($this->_post as $key => $val) {
             if (($property = $this->_obj->getProperty($key)) !== false) {
                 if ($property instanceof Property\ObjectProperty) {
                     if ($val) {
                         $class = $property->getParameter('instanceof');
                         if (substr($val, 0, 4) == 'obj_') {
                             // get object from cache
                             $property->setValue(Core::cacheGet($val));
                         } else {
                             $property->setValue(new $class($val));
                         }
                     } else {
                         $property->resetValue();
                     }
                 } else {
                     if ($property instanceof Property\CollectionProperty) {
                         $class = $property->getParameter('instanceof');
                         $keyprop = $property->getParameter('keyprop');
                         // val for a collection should come as an array of new/existing members
                         foreach ($val as $memberKey => $memberArray) {
                             if (!is_numeric($memberKey)) {
                                 $this->_status = "NOK";
                                 $this->_context['message'] = 'member-id is not a number';
                                 return false;
                             }
                             // action exists to update or remove member
                             if (isset($memberArray['action'])) {
                                 // get target member
                                 $object = $property->getValue()->getMember($memberKey, ObjectModel::MODEL);
                                 switch ($memberArray['action']) {
                                     case 'delete':
                                         if ($property->setValue($object, Collection::MEMBER_REMOVE) !== true) {
                                             $this->_status = "NOK";
                                             $this->_context['message'] = 'error removing member from collection';
                                             return false;
                                         }
                                         break;
                                     case 'update':
                                         foreach ($memberArray['props'] as $mApropN => $mApropV) {
                                             if (($mAprop = $object->getProperty($mApropN)) !== false) {
                                                 $mAprop->setValue($mApropV);
                                             }
                                         }
                                         // direct update of the member
                                         $object->save();
                                         break;
                                 }
                             } else {
                                 // no action, default is new member to add
                                 $member = new $class();
                                 // set keyprop property value
                                 $member->getProperty($member->getProperty($keyprop)->setValue($this->_obj));
                                 // walk through
                                 foreach ($memberArray as $memberPropKey => $memberPropVal) {
                                     $mprop = $member->getProperty($memberPropKey);
                                     if ($mprop instanceof Property\ObjectProperty) {
                                         $memberPropVal = Core\Registry::get($memberPropVal);
                                         if ($memberPropVal instanceof Property\AbstractProperty) {
                                             $mprop->setValue($memberPropVal->getValue());
                                         } else {
                                             $mprop->setValue($memberPropVal);
                                         }
                                     } else {
                                         $mprop->setValue($memberPropVal);
                                     }
                                 }
                                 // check if member was added successfully, break otherwise
                                 if ($property->setValue($member) === false) {
                                     $this->_status = "NOK";
                                     $this->_context['message'] = 'error adding member to collection';
                                     break;
                                 }
                             }
                         }
                     } else {
                         $property->setValue($val);
                     }
                 }
             }
         }
         // if record has no uri yet and an identifier value is present, inject it so backend will use it as primary key
         if (!$this->_obj->getUri() && isset($this->_post[ObjectUri::IDENTIFIER])) {
             $this->_obj->setUri($this->_post[ObjectUri::IDENTIFIER]);
         }
         $result = $this->_obj->save();
         if ($result === false) {
             $this->_context['message'] = Backend::getLastQuery();
             $this->_status = 'NOK';
         } else {
             $collections = isset($this->_post['_collections']) ? $this->_post['_collections'] : 1;
             $extprops = isset($this->_post['_extprops']) ? $this->_post['_extprops'] : [];
             $this->_data['object'] = $this->_obj->reduce(array('params' => array(), 'extprops' => $extprops, 'collections' => $collections));
             $this->_executeActions('ok');
             $this->_refreshCache = true;
         }
     } catch (\Exception $e) {
         $this->_context['err'] = $e->getMessage();
         if (Core::$env == Core::ENV_DEV) {
             $this->_context['trace'] = $e->getTraceAsString();
         }
         $this->_status = 'ERR';
     }
 }
예제 #11
0
 protected function _setResponse($status = 'OK', $data, $context = null, $format = 'json')
 {
     $response = array('status' => $status, 'data' => $data, 'context' => $context);
     switch ($format) {
         case 'json':
         default:
             $this->getResponse()->setHeader('Content-type', 'application/json')->setBody(\Zend_Json::encode($response));
             if (Core::getEnvData('cache_datasets') !== false) {
                 $this->getResponse()->setHeader('Expires', gmdate('D, d M Y H:i:s \\G\\M\\T', time() + 3600));
                 $this->getResponse()->clearHeader('Cache-Control');
                 $this->getResponse()->clearHeader('Pragma');
             }
             break;
     }
     $this->getResponse()->sendResponse();
     exit;
 }
예제 #12
0
파일: Module.php 프로젝트: crapougnax/t41
 public static function bind(array $config, $path, Layout\Menu $menu = null)
 {
     $store = $config['enabled'] == true ? 'enabled' : 'disabled';
     if ($store == 'disabled') {
         return;
     }
     Config::addPath($path . '/configs/', Config::REALM_CONFIGS);
     // if modules has model, declare path to the autoloader
     if (is_dir($path . '/models') && isset($config['namespace'])) {
         Core::addAutoloaderPrefix($config['namespace'], $path . '/models/');
         Config::addPath($path . '/models', Config::REALM_OBJECTS, null, $config['namespace']);
     }
     // Register views directory if it exists
     if (is_dir($path . '/views')) {
         //	Config::addPath($path . '/views', Config::REALM_TEMPLATES, Config::POSITION_TOP);
     }
 }
예제 #13
0
파일: View.php 프로젝트: crapougnax/t41
 public static function display($content = null, $error = null)
 {
     Core::setFancyExceptions(false);
     if (self::_isInstanciated()) {
         return self::$_display->display($content, $error);
     }
 }
예제 #14
0
파일: Core.php 프로젝트: crapougnax/t41
 public static function cacheGet($key)
 {
     $cache = self::cacheGetAdapter();
     $cached = $cache->load($key);
     Core::log(sprintf('[Cache] Retrieved %s as %s', $key, gettype($cached)));
     if (is_array($cached)) {
         if (isset($cached['_class'])) {
             try {
                 \Zend_Loader::loadClass($cached['_class']);
             } catch (Exception $e) {
                 return null;
             }
             return unserialize($cached['content']);
         } else {
             return $cached;
         }
     } else {
         return $cached;
     }
 }
예제 #15
0
 protected function _()
 {
     $template = file_get_contents($this->_template);
     // transform some characters
     $template = str_replace("\t", str_repeat("&nbsp;", 15), $template);
     $template = str_replace("\n", "<br/>", $template);
     $tagPattern = "/%([a-z0-9]+)\\:([a-z0-9.]*)\\{*([a-zA-Z0-9:,\\\"']*)\\}*%/";
     $tags = array();
     preg_match_all($tagPattern, $template, $tags, PREG_SET_ORDER);
     // PHASE 1
     foreach ($tags as $key => $tag) {
         $content = '';
         if ($tag[1] == 'env') {
             $content = \t41\Core::htmlEncode(\t41\View::getEnvData($tag[2]));
             unset($tag[$key]);
         }
         if (isset($tag[0])) {
             $template = str_replace($tag[0], $content, $template);
         }
     }
     $this->_document->writeHTML($template);
     // PHASE 2 - other tags
     foreach ($tags as $tag) {
         $content = '';
         switch ($tag[1]) {
             case 'container':
                 $elems = \t41\View::getObjects($tag[2]);
                 if (is_array($elems)) {
                     foreach ($elems as $elem) {
                         $object = $elem[0];
                         $params = $elem[1];
                         if (!is_object($object)) {
                             continue;
                         }
                         /* @var $object t41_Form_Abstract */
                         switch (get_class($object)) {
                             case 't41_Form_List':
                             case 't41_View_Table':
                             case 't41_View_Image':
                             case 't41_View_Component':
                             case 't41_View_Error':
                             case 't41_View_Spacer':
                                 $decorator = \t41\View\Decorator::factory($object, $params);
                                 $decorator->render($this->_document, $this->_width);
                                 break;
                             default:
                                 break;
                         }
                     }
                 }
                 break;
         }
     }
 }
예제 #16
0
 public function register()
 {
     $res = Core::cacheSet($this);
     if ($res !== false) {
         $this->_id = $res;
     }
     return $this->_id;
 }
예제 #17
0
 protected function _getConfigValue($var)
 {
     if (is_string($var)) {
         return $var;
     } else {
         return isset($var[\t41\Core::getEnvData('webEnv')]) ? $var[\t41\Core::getEnvData('webEnv')] : null;
     }
 }
예제 #18
0
 /**
  * (non-PHPdoc)
  * @see \t41\View\Adapter\AbstractAdapter::_renderComponents()
  */
 protected function _renderComponents($type, $params = null)
 {
     if (!isset($this->_component[$type])) {
         return '';
     }
     $components = $this->_component[$type];
     if (count($components) == 0) {
         return null;
     }
     if ($params) {
         // params come as a pseudo json string
         $params = \Zend_Json::decode('{' . $params . '}');
         $baseUrl = sprintf('http%s://%s', $_SERVER['SERVER_PORT'] == 443 ? 's' : null, $_SERVER['SERVER_NAME']);
     }
     $html = '';
     $cdn = Core::getEnvData('cdn');
     foreach ($components as $component) {
         if (isset($params['fullUrl']) && $params['fullUrl'] == true && substr($component, 0, 4) != 'http') {
             $component = $baseUrl . $component;
         }
         // use CDN url if provided
         if (!is_null($cdn)) {
             $component = '//' . $cdn . $component;
         }
         switch ($type) {
             case 'css':
                 $html .= sprintf('<link rel="stylesheet" href="%s" type="text/css" />' . "\n", $component);
                 break;
             case 'js':
                 $html .= sprintf('<script src="%s" type="text/javascript"></script>' . "\n", $component);
                 break;
         }
     }
     return $html;
 }
예제 #19
0
파일: Backend.php 프로젝트: crapougnax/t41
 /**
  * Execute a search on given backend with given t41\ObjectModel\Collection parameters
  * and returns an array of results (either t41\ObjectModel\ObjectUri, t41\ObjectModel/DataObject or t41\ObjectModel\BaseObject instances)
  * 
  * @param t41\ObjectModel\Collection $co
  * @param t41\Backend\Adapter\AbstractAdapter $backend
  * @param array|boolean $returnCount 
  * @throws t41\Backend\Exception
  * @return array
  */
 public static function find(ObjectModel\Collection $co, Backend\Adapter\AbstractAdapter $backend = null, $returnCount = false, $subOp = null)
 {
     /*
      * Backend to use in order of preferences
      * 
      * 1. current method backend argument if not null
      * 2. object default backend
      * 3. general default backend
      */
     if (is_null($backend)) {
         $backend = ObjectModel::getObjectBackend($co->getDataObject()->getClass());
         if (is_null($backend)) {
             // get default backend
             $backend = self::getDefaultBackend();
         }
     }
     if (!$backend) {
         throw new Backend\Exception("NO_AVAILABLE_BACKEND");
     }
     Core::log(sprintf('[Backend] executing find() on %s collection', $co->getClass()));
     return $backend->find($co, $returnCount, $subOp);
 }
예제 #20
0
 /**
  * Populate the given collection from the array of identifiers and the uri base
  * 
  * @param array $ids
  * @param \t41\ObjectModel\Collection $collection
  * @param \t41\ObjectModel\ObjectUri $uriBase
  */
 protected function _populateCollection(array $ids, ObjectModel\Collection $collection, ObjectModel\ObjectUri $uriBase)
 {
     if (count($ids) == 0) {
         return array();
     }
     if (count($ids[0]) > 1) {
         $do = clone $collection->getDataObject();
     }
     $class = $collection->getDataObject()->getClass();
     // populate array with relevant objects type
     $array = array();
     /**
      * If data object has been modified (meta property added) we need to use it to populate objects
      */
     if ($collection->getParameter('memberType') != ObjectModel::URI && $collection->getDataObject()->getDna('custom')) {
         $do = clone $collection->getDataObject();
     }
     foreach ($ids as $key => $id) {
         $uri = clone $uriBase;
         if (is_array($id)) {
             $uri->setUrl($uri->getUrl() . $id['id'])->setIdentifier($id['id']);
             unset($id['id']);
         } else {
             $uri->setUrl($uri->getUrl() . $id)->setIdentifier($id);
         }
         if (isset($do)) {
             $obj = clone $do;
             $obj->setUri($uri);
         } else {
             unset($obj);
         }
         switch ($collection->getParameter('memberType')) {
             case ObjectModel::URI:
                 $obj = $uri;
                 break;
             case ObjectModel::MODEL:
                 if (isset($obj) || is_array($ids)) {
                     Backend::read($obj, null, $id);
                 } else {
                     $obj = Core::_($uri, $class);
                 }
                 break;
             case ObjectModel::DATA:
             default:
                 if (isset($obj) || is_array($ids)) {
                     Backend::read($obj, null, $id);
                 } else {
                     $obj = Core::_($uri, $class);
                 }
                 $obj = $obj->getDataObject();
                 break;
         }
         $array[$key] = $obj;
     }
     return $array;
 }
예제 #21
0
 /**
  * Convert the given member to the given type
  * @param object $member
  * @param string $toType
  * @return \t41\ObjectModel\DataObject|\t41\ObjectModel\ObjectUri>|\t41\ObjectModel\BaseObject
  */
 protected function _castMember($member, $toType)
 {
     // Don't cast if it's already done
     if ($toType == ObjectModel::DATA && $member instanceof DataObject || $toType == ObjectModel::MODEL && $member instanceof BaseObject || $toType == ObjectModel::URI && $member instanceof ObjectUri) {
         return $member;
     }
     $class = $this->getClass();
     switch ($toType) {
         case ObjectModel::DATA:
             if ($member instanceof BaseObject) {
                 $member = $member->getDataObject();
             } else {
                 $member = Core::_($member)->getDataObject();
             }
             break;
         case ObjectModel::MODEL:
             if ($member instanceof DataObject) {
                 // careful with custom data objects !
                 $member = $member->getDna('custom') ? new $class($member) : Core::_($member->getUri());
             } else {
                 $member = Core::_($member);
             }
             break;
         case ObjectModel::URI:
             $member = $member->getUri();
             break;
     }
     return $member;
 }
예제 #22
0
 /**
  * Return the current value in the $param form
  * @see t41\ObjectModel\Property.AbstractProperty::getValue()
  * @param string $param define which format to use
  */
 public function getValue($param = null)
 {
     if (is_null($this->_value)) {
         return null;
     }
     /* if param is null, return the value in its current format */
     if (is_null($param)) {
         return $this->_value;
     }
     switch ($param) {
         case ObjectModel::MODEL:
             if ($this->_value instanceof ObjectModel\DataObject) {
                 $this->_value = Core::_($this->_value->getUri());
                 return $this->_value;
             } else {
                 if ($this->_value instanceof ObjectUri) {
                     /* object uri */
                     $this->_value = Core::_($this->_value);
                 }
             }
             return $this->_value;
             break;
         case ObjectModel::DATA:
             if ($this->_value instanceof ObjectUri) {
                 $this->_value = Core::_($this->_value);
                 return $this->_value->getDataObject();
             } else {
                 if ($this->_value instanceof DataObject) {
                     return $this->_value;
                 } else {
                     return $this->_value->getDataObject();
                 }
             }
             break;
         case ObjectModel::URI:
         default:
             if ($this->_value instanceof ObjectUri) {
                 return $this->_value;
             } else {
                 if ($this->_value instanceof DataObject) {
                     return $this->_value->getUri();
                 } else {
                     return $this->_value->getDataObject()->getUri();
                 }
             }
             break;
     }
 }
예제 #23
0
 /**
  * Populates a data object from a key/value array
  *
  * @param array $data
  * @param \t41\Backend\Mapper $mapper
  * @return \t41\ObjectModel\DataObject
  */
 public function populate(array $data, Backend\Mapper $mapper = null)
 {
     if ($mapper) {
         // @todo fix compatibility with metakeys in array
         $data = $mapper->toDataObject($data, $this->_class);
     }
     // then sent to data object properties
     foreach ($data as $key => $value) {
         // don't use empty() to check $value to avoid zero being ignored
         if (($property = $this->getProperty($key)) !== false && !is_null($value)) {
             if ($value == Property::EMPTY_VALUE) {
                 $property->resetValue();
                 continue;
             }
             if ($property instanceof ObjectProperty || $property instanceof MediaProperty) {
                 if ($property->getParameter('instanceof') == null) {
                     throw new DataObject\Exception("Parameter 'instanceof' for '{$key}' in class should contain a class name");
                 }
                 // Specific case of MediaObject()
                 if ($property->getParameter('instanceof') == 't41\\ObjectModel\\MediaObject') {
                     // new file case : value is a string prepended by  'tmp:'
                     if ($value && substr($value, 0, strlen(MediaObject::TMP_PREFIX)) == MediaObject::TMP_PREFIX) {
                         $parts = explode('|', substr($value, 4));
                         // 0 => hash, 1 => original file name
                         $file = '/tmp/' . $parts[0];
                         if (file_exists($file)) {
                             $media = new MediaObject();
                             $media->setUri(md5(rand() * microtime()));
                             $media->setLabel($parts[1]);
                             $finfo = finfo_open(FILEINFO_MIME_TYPE);
                             $mime = finfo_file($finfo, $file);
                             $media->setMedia($file);
                             // blob property
                             $media->setSize(filesize($file));
                             $media->setMime($mime);
                             $media->save();
                             $property->setValue($media);
                             // media property
                             unlink($file);
                         }
                         continue;
                         // don't go further in this case
                     }
                 }
                 if ($value && $value != Property::EMPTY_VALUE) {
                     if (is_object($value) && get_class($value) == $property->getParameter('instanceof')) {
                         $property->setValue($value);
                     } else {
                         if (substr($value, 0, 4) == 'obj_') {
                             // get object from cache
                             $property->setValue(Core::cacheGet($value));
                         } else {
                             if (substr($value, 0, 1) == Backend::PREFIX) {
                                 /* get & call object's backend to get a full configured object uri */
                                 $backend = ObjectModel::getObjectBackend($property->getParameter('instanceof'));
                                 $value = $backend->buildObjectUri($value, $property->getParameter('instanceof'));
                                 $property->setValue($value instanceof ObjectUri ? $value : new ObjectUri($value));
                             } else {
                                 //$class = $property->getParameter('instanceof');
                                 $backend = ObjectModel::getObjectBackend($property->getParameter('instanceof'));
                                 $value = $backend->buildObjectUri($value, $property->getParameter('instanceof'));
                                 $property->setValue($value);
                             }
                         }
                     }
                 } else {
                     $property->resetValue();
                 }
             } else {
                 if ($property instanceof Property\CollectionProperty) {
                     // @todo handle collection populating here
                 } else {
                     // if value is an array, it is most likely a set of multiple options
                     if (is_array($value)) {
                         $value = implode('|', $value);
                     }
                     $property->setValue($value);
                 }
             }
         }
     }
     return $this;
 }
예제 #24
0
 /**
  * Gets the latest session-saved environment and inject it in $_env
  * Returns true if $_env was modified, false otherwise
  * 
  * @return boolean
  */
 public function restoreSearchTerms()
 {
     if (count($this->getEnv()) == 0) {
         $env = Core::sessionGet('uri' . str_replace('/', '_', $this->_uriBase));
         if (is_array($env)) {
             $this->setEnv($env);
             return true;
         }
     }
     return false;
 }
예제 #25
0
 /**
  * Return current ObjecModel\Collection instance handled by current instance
  * instant instanciation is performed if $_value is null or $force is true
  * 
  *  @param boolean $force
  *  @return t41\ObjectModel\Collection
  */
 public function getValue($force = false)
 {
     if (is_null($this->_value) || $force === true) {
         /* set a new Collection based on instanceof parameter value */
         $this->_value = new ObjectModel\Collection($this->getParameter('instanceof'));
         $this->_value->setBoundaryBatch(-1);
         $this->_value->setParent($this->_parent);
         /* inject the condition that allows to find collection members */
         if ($this->getParameter('keyprop')) {
             $this->_value->having($this->getParameter('keyprop'))->equals($this->_parent);
         }
         /* inject any other defined condition */
         if ($this->getParameter('morekeyprop')) {
             foreach ($this->getParameter('morekeyprop') as $value) {
                 if (strstr(trim($value), ' ') !== false) {
                     // if value contains spaces, it's a pattern
                     $parts = explode(' ', $value);
                     if (count($parts) == 3) {
                         if ($parts[2] == 'novalue') {
                             $parts[2] = Condition::NO_VALUE;
                         }
                         if ($parts[2] == ObjectUri::IDENTIFIER) {
                             $parts[2] = $this->_parent->getUri();
                         }
                         if (substr($parts[2], 0, 1) == '%' && substr($parts[2], -1) == '%') {
                             $prop = substr($parts[2], 1, strlen($parts[2]) - 2);
                             if (($prop = $this->_parent->getProperty($prop)) !== false) {
                                 $parts[2] = $prop->getValue();
                             }
                         }
                         if (strstr($parts[2], ',') !== false) {
                             $parts[2] = explode(',', $parts[2]);
                         }
                         $this->_value->having($parts[0])->{$parts}[1]($parts[2]);
                     } else {
                         if ($parts[1] == 'novalue') {
                             $parts[1] = Condition::NO_VALUE;
                         }
                         if (substr($parts[1], 0, 1) == '%' && substr($parts[1], -1) == '%') {
                             $prop = substr($parts[1], 1, strlen($parts[1]) - 2);
                             if (($prop = $this->_parent->getProperty($prop)) !== false) {
                                 $parts[1] = $prop->getValue();
                             }
                         }
                         if (strstr($parts[1], ',') !== false) {
                             $parts[1] = explode(',', $parts[1]);
                         }
                         $this->_value->having($parts[0])->equals($parts[1]);
                     }
                 } else {
                     // default case, we expect the member to hold a property
                     // with the same name and value as the current object
                     if (($property = $this->_parent->getProperty($value)) === false) {
                         throw new Exception(sprintf("keyprop value '%s' doesn't match any property of class '%s'", $value, $this->_parent->getClass()));
                     }
                     $this->_value->having($value)->equals($property->getValue());
                 }
             }
         }
         // set sorting
         if ($this->getParameter('sorting')) {
             foreach ($this->getParameter('sorting') as $key => $val) {
                 if ($this->_value->getDataObject()->getRecursiveProperty($key) !== false) {
                     $this->_value->setSorting(array($key, $val));
                 } else {
                     Core::log(sprintf("Can't sort %s property with unknown property %s", $this->_id, $key), \Zend_Log::WARN);
                 }
             }
         }
         // DON'T POPULATE THERE, IT IS DONE IMPLICITELY IN Collection::getMembers()
         //$this->_value->debug();
     }
     return parent::getValue();
 }