ficus/db/s2dao/S2DaoComponentFactory.php100644 1751 144 6312 10645132217 13622 ISHITOYA Kentaro * @version $Id: S2DaoComponentFactory.php 2 2007-07-11 10:37:48Z ishitoya $ * * S2Dao component factory */ require_once("ficus/io/File.php"); require_once("ficus/config/Registry.php"); /** * @class Ficus_S2DaoComponentFactory */ class Ficus_S2DaoComponentFactory extends Ficus_S2ContainerComponentFactory{ const KEY_FACTORY = "ModelFactory"; const KEY_MANAGEr = "S2DaoManager"; /** * dicon file name registry key */ const REGISTRY_DICON_FILENAME = "s2dao.dicon"; /** * dicon namespace registry key */ const REGISTRY_DICON_NAMESPACE = "s2dao.namespace"; /** * Default dicon file name. */ const DEFAULT_DICON_FILENAME = 's2dao.dicon'; /** * dicon namespace. */ const DEFAULT_DICON_NAMESPACE = 'pages.scheme'; /** * get Dicon file name from registry * @return string dicon filename */ protected function getDiconFileNameRegistry(){ return self::REGISTRY_DICON_FILENAME; } /** * get Dicon namespace from registry * @return string dicon namespace */ protected function getDiconNameSpaceRegistry(){ return self::REGISTRY_DICON_NAMESPACE; } /** * get dicon file name * @return string dicon file name */ protected function getDefaultDiconFileName(){ return Ficus_File::currentDir() ->resolve(self::DEFAULT_DICON_FILENAME)->getPath(); } /** * get defoult dicon namespace * @return string dicon namespace */ protected function getDefaultDiconNameSpace(){ return self::DEFAULT_DICON_NAMESPACE; } /** * get component * @param $name string name of component * @param $class string class name * @return Ficus_S2DaoComponentFactory */ public static function getComponent($name, $class = __CLASS__){ return parent::getComponent($name, $class); } /** * Get model factory * * @param $name string component name. * @return mixed component. */ public static function getModelFactory() { return self::getComponent(self::KEY_FACTORY); } /** * Get model factory * * @param $name string component name. * @return mixed component. */ public static function getS2DaoManager() { return self::getComponent(self::KEY_MANAGER); } } ?> ficus/db/s2dao/S2DaoManager.php100644 1751 144 5301 10647425602 11704 ISHITOYA Kentaro * @version $Id: S2DaoManager.php 14 2007-07-18 14:55:12Z ishitoya $ */ require_once("ficus/config/Registry.php"); /** * @class S2DaoManager */ class Ficus_S2DaoManager{ /** * dao object */ protected $dao = null; /** * set dao * @param $target string target entity name */ public function setTarget($target){ $this->dao = Ficus_S2DaoComponentFactory::getModelFactory()->getDao($target); } /** * get Entity * @param $id id */ public function getSingleEntity($id){ $entity = $this->dao->getById($id); if($entity->isEmpty()){ return null; } return $entity->get(0); } /** * get Entities * @param $ids array id list * @return S2Dao_ArrayList */ public function getEntities($ids){ $entities = new S2Dao_ArrayList(); foreach($ids as $id){ if(is_int($id)){ $entities->append($this->getSingleEntity($id)); } } if($entities->isEmpty()){ throw new Ficus_IllegalArgumentException("no entities related with ids"); } return $entities; } /** * get Pager entities */ public function getPagerDto($offset = 0, $limit = 10){ $dto = $this->dao->dto(); $dto->setOffset($offset); $dto->setLimit($limit); return $dto; } /** * deserializeEntity */ public function deserializeEntity($data){ $entity = $this->dao->entity(); $deserializer = new Ficus_S2DaoArrayEntityDeserializer(); $entity->deserialize($data, $deserializer); return $entity; } /** * get dao */ public function dao(){ return $this->dao; } /** * entity */ public function entity(){ return $this->dao->entity(); } } ?> ficus/db/s2dao/s2dao.dicon100644 1751 144 466 10645120255 10777 ficus/db/s2dao/models/S2DaoDataAccessObject.php100644 1751 144 15056 10645132217 14762 ISHITOYA Kentaro * @version $Id: S2DaoDataAccessObject.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_S2DaoDataAccessObject */ class Ficus_S2DaoDataAccessObject implements Ficus_S2DaoModelConstants{ /** * dao object */ protected $dao = null; /** * subject */ protected $subject = ""; /** * constructor */ public function __construct($target){ if(is_string($target)){ $this->dao = Ficus_S2DaoComponentFactory::getComponent($target); $classname = get_class($this); }else{ $this->dao = $target; $classname = get_class($this->dao); } if(preg_match("/.*?_(Auto)?([^_]+)Dao/", $classname, $regs)){ $this->subject = $regs[2]; }else{ $this->subject = $classname; } } /** * get dao instance from argument * @param $subject string subject name * @param $auto boolean true if auto dto * @return DAO class */ protected function getDataAccessObject($subject = null){ if(is_null($subject)){ $subject = $this->subject; } return Ficus_S2DaoComponentFactory::getModelFactory()->getDataAccessObject($subject); } /** * get dto instance from argument * @param $subject string subject name * @param $auto boolean true if auto dto * @return DTO class */ protected function getDto($subject = null){ if(is_null($subject)){ $subject = $this->subject; } return Ficus_S2DaoComponentFactory::getModelFactory()->getDto($subject); } /** * get entity instance from argument * @param $subject string subject name * @param $auto boolean true if auto dto * @return Entity class */ protected function getEntity($subject = null, $auto = false){ if(is_null($subject)){ $subject = $this->subject; } return Ficus_S2DaoComponentFactory::getModelFactory()->getEntity($subject); } /** * get entity class name */ public static function getEntityWithSubject($subject, $auto = false){ $entity = self::getClassName($subject, $auto, self::ENTITY_PACKAGE, self::ENTITY_SUFFIX); return Ficus_ClassLoader::load($entity); } /** * access dao with dto * @param $dto DTO class of condition * @return S2Dao_ArrayList result */ public function getWithCondition($dto){ $entities = $this->dao->getWithConditionList($dto); if($entities instanceof S2Dao_ArrayList && $entities->isEmpty() == false){ foreach($entities as $key => $entity){ $entities[$key] = $this->castEntity($entity, $this->getEntity()); } return $this->processResult($entities); } if($entities === 0){ return new S2Dao_ArrayList(); } return $entities; } /** * cast entity * @param $entity Ficus_S2DaoEntity entity * @param $class string class * @return Ficus_S2DaoEntity casted entity */ protected function castEntity($entity, $class){ return Ficus_Class::cast($entity, $class); } /** * process result * @param $results S2Dao_ArrayList * @return S2Dao_ArrayList result */ protected function processResult($results){ foreach($results as $entity){ $reader = new Ficus_S2DaoEntityAnnotationReader($entity); $properties = $reader->properties(); foreach($properties as $property){ if($reader->hasExpand($property)){ $expand = $reader->expand($property); $expand = explode(self::EXPAND_SEPARATOR, $expand); foreach($expand as $target){ $this->getExpandedEntity($entity, $property, $target); } } } } return $results; } /** * get expanded entity * @param $entity Ficus_S2DaoEntity TargetEntity * @param $property string property * @param $target string target */ protected function getExpandedEntity($entity, $property, $target){ $dao = $this->getDataAccessObject($target); $dto = $this->getDto($target); $target = $entity->get($property); if(($target instanceof Ficus_S2DaoEntity) == false || $target->hasId() == false){ return; } $dto->set($property, $target->id()); $entities = $dao->getWithCondition($dto); if($entities->size() == 0){ return; } $entity->set($property, $entities); } /** * get new Entity */ public function entity(){ return $this->getEntity(); } /** * get new Dto */ public function dto(){ return $this->getDto(); } /** * call interface function */ public function __call($name, $args){ $entities = $this->dao->{$name}($args[0]); if($entities instanceof S2Dao_ArrayList){ foreach($entities as $key => $entity){ $entities[$key] = $this->castEntity($entity, $this->getEntity()); } return $this->processResult($entities); }else if($entities instanceof Ficus_S2DaoEntity){ $list = new S2Dao_ArrayList(); $list->append($entities); return $this->processResult($list); }else{ return new S2Dao_ArrayList(); } throw new Ficus_MethodNotFoundException($e->getMessage()); } } ?> ficus/db/s2dao/models/S2DaoDataTransferObject.php100644 1751 144 4265 10645132217 15325 ISHITOYA Kentaro * @version $Id: S2DaoDataTransferObject.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/db/s2dao/models/S2DaoEntity.php"); /** * @class Ficus_S2DaoDataTransferObject */ class Ficus_S2DaoDataTransferObject extends Ficus_S2DaoEntity implements S2Dao_PagerCondition{ private $offset = 0; private $limit = null; private $count = 0; /** * @return Returns the total. */ public function getCount() { return $this->count; } /** * @param total The total to set. */ public function setCount($total) { $this->count = $total; } /** * @return Returns the limit. */ public function getLimit() { return $this->limit; } /** * @param limit The limit to set. */ public function setLimit($limit) { $this->limit = $limit; } /** * @return Returns the offset. */ public function getOffset() { return $this->offset; } /** * @param offset The offset to set. */ public function setOffset($offset) { $this->offset = $offset; } /** * get related DAO object * @return Ficus_Auto<{$classname}>Dao dao object */ public function dao(){ return Ficus_ComponentFactory::getComponent("Auto<{$classname}>Dao"); } } ?> ficus/db/s2dao/models/S2DaoEntity.php100644 1751 144 6526 10645132217 13076 ISHITOYA Kentaro * @version $Id: S2DaoEntity.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/lang/Class.php"); require_once("ficus/beans/Bean.php"); require_once("ficus/db/s2dao/models/S2DaoEntity.php"); require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_S2DaoEntity */ abstract class Ficus_S2DaoEntity extends Ficus_Bean implements Ficus_S2DaoModelConstants{ /** * get entity name */ public function getEntityName(){ $class = get_class($this); if(preg_match('/_(Auto)?(.*)Entity$/', $class, $regs)){ return $regs[2]; } return $class; } /** * cast class * @param $from Ficus_S2DaoEntity entity * @to $to string subject name */ protected function convert($from, $to, $auto = false){ if(is_null($from)){ return null; } if(is_object($to)){ $to = get_class($to); } $temp = Ficus_Dao::getEntityWithSubject($to, $auto); return Ficus_Class::cast($from, $temp); } /** * recursive update method */ public function update(){ $reader = new Ficus_S2DaoEntityAnnotationReader($this); $properties = $reader->properties(); if(count($properties) == 1){ return 0; } $dao = $this->dao(); $dao->update($this); foreach($properties as $property){ if($reader->type($property) == self::TYPE_FOREIGN){ $getter = "get" . ucfirst($property); $value = $this->{$getter}(); $id = $value->id(); if(is_null($id)){ continue; } $value->update(); } } } /** * recursive update method */ public function insert(){ $reader = new Ficus_S2DaoEntityAnnotationReader($this); $properties = $reader->properties(); foreach($properties as $property){ if($reader->type($property) != self::TYPE_FOREIGN){ continue; } $getter = "get" . ucfirst($property); $setter = "set" . ucfirst($property) . "Direct"; $value = $this->{$getter}(); if($value->isBlank() == false){ $value->insert(); $this->{$setter}($value->id()); } } $dao = $this->dao(); $dao->insert($this); } /** * get dao * @return Dao */ abstract public function dao(); } ?> ficus/db/s2dao/models/S2DaoModelConstants.php100644 1751 144 3746 10645132217 14560 ISHITOYA Kentaro * @version $Id: S2DaoModelConstants.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_S2DaoModelConstants */ interface Ficus_S2DaoModelConstants{ const REGISTRY_PREFIX = "s2dao.prefix"; const REGISTRY_PACKAGE_MODEL = "s2dao.package.model"; const REGISTRY_PACKAGE_AUTO = "s2dao.package.auto"; const AUTO_PREFIX = "Auto"; const DAO_PACKAGE = "dao"; const DTO_PACKAGE = "dto"; const ENTITY_PACKAGE = "entity"; const DAO_SUFFIX = "Dao"; const DTO_SUFFIX = "Dto"; const ENTITY_SUFFIX = "Entity"; const ANNOTATION_FORM = "FORM"; const ANNOTATION_VIEW = "VIEW"; const ANNOTATION_EXPAND = "EXPAND"; const ANNOTATION_TYPE = "TYPE"; const ANNOTATION_DATATYPE = "DATATYPE"; const ANNOTATION_LABEL = "LABEL"; const ANNOTATION_REMARK = "REMARK"; const ANNOTATION_VALIDATOR = "VALIDATOR"; const ANNOTATION_COLUMN = "COLUMN"; const VIEW_IGNORE = "ignore"; const EXPAND_SEPARATOR = ","; const CONTEXT_VIEW = "VIEW"; const CONTEXT_FORM = "FORM"; const TYPE_LIST = "list"; const TYPE_FOREIGN = "foreign"; const TYPE_DIRECT = "direct"; } ?> ficus/db/s2dao/models/S2DaoModelFactory.php100644 1751 144 11261 10645132217 14222 ISHITOYA Kentaro * @version $Id: S2DaoModelFactory.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); require_once("ficus/db/s2dao/models/S2DaoDataAccessObject.php"); /** * @class Ficus_S2DaoModelFactory */ class Ficus_S2DaoModelFactory implements Ficus_S2DaoModelConstants{ /** * string prefix */ protected static $prefix = ""; /** * string modelPackage */ protected static $modelPackage = ""; /** * string autoPackage */ protected static $autoPackage = ""; /** * constructor */ public function __construct(){ self::$prefix = Ficus_Registry::search(self::REGISTRY_PREFIX); self::$modelPackage = Ficus_Registry::search(self::REGISTRY_PACKAGE_MODEL); self::$autoPackage = Ficus_Registry::search(self::REGISTRY_PACKAGE_AUTO); if(is_null(self::$prefix) || is_null(self::$modelPackage) || is_null(self::$autoPackage)){ throw new Ficus_NotReadyException("s2dao.prefix, s2dao.package.model, s2dao.package.auto must be registered before runch"); } } /** * get dao instance from argument * @param $subject string subject name * @param $auto boolean true if auto dto * @return DAO class */ public function getDao($subject, $auto = false){ $dao = $this->getClassName($subject, $auto, self::DAO_PACKAGE, self::DAO_SUFFIX); $dao = preg_replace("/.*?" . self::$prefix . "/", "", $dao); try{ $dao = Ficus_S2DaoComponentFactory::getComponent($dao); }catch(S2Container_ComponentNotFoundRuntimeException $e){ $dao = self::AUTO_PREFIX . $dao; $dao = Ficus_S2DaoComponentFactory::getComponent($dao); } return new Ficus_S2DaoDataAccessObject($dao); } /** * get dto instance from argument * @param $subject string subject name * @param $auto boolean true if auto dto * @return DTO class */ public function getDto($subject, $auto = null){ if(is_null($auto)){ try{ return $this->getDto($subject, false); }catch(Ficus_ClassNotFoundException $e){ return $this->getDto($subject, true); } } $dto = $this->getClassName($subject, $auto, self::DTO_PACKAGE, self::DTO_SUFFIX); return Ficus_ClassLoader::load($dto); } /** * get entity instance from argument * @param $subject string subject name * @param $auto boolean true if auto dto * @return Entity class */ public function getEntity($subject, $auto = null){ if(is_null($auto)){ try{ return $this->getEntity($subject, false); }catch(Ficus_ClassNotFoundException $e){ return $this->getEntity($subject, true); } } $entity = $this->getClassName($subject, $auto, self::ENTITY_PACKAGE, self::ENTITY_SUFFIX); return Ficus_ClassLoader::load($entity); } /** * get class name from argument * @param $subject string subject name * @param $auto boolean true if auto dto * @param $suffix string suffix of class * @return string classname */ public static function getClassName($subject, $auto, $package, $suffix){ $subject = ucfirst($subject); if($auto){ $subject = self::AUTO_PREFIX . $subject; $pkg = self::$autoPackage . "."; }else{ $pkg = self::$modelPackage . "."; } $package = $pkg . $package . "."; return $package . self::$prefix . $subject . $suffix; } } ?> ficus/db/s2dao/models/serializer/S2DaoArrayEntityDeserializer.php100644 1751 144 7620 10645132217 20605 ISHITOYA Kentaro * @version $Id: S2DaoArrayEntityDeserializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/db/s2dao/models/S2DaoEntity.php"; require_once "ficus/beans/serializer/BeanDeserializer.php"; require_once "ficus/lang/Assert.php"; require_once "ficus/lang/reflect/ReflectionClass.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationProperty.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationClass.php"; /** * @class Ficus_S2DaoArrayEntityDeserializer */ class Ficus_S2DaoArrayEntityDeserializer implements Ficus_BeanDeserializer, Ficus_S2DaoModelConstants{ /** * deserialize entity from array * @param $data array array to deserialize * @param $entity Ficus_S2DaoEntity target entity * @return Ficus_S2DaoEntity entity */ public function deserialize($entity, $data){ $entity = $this->parseArray($entity, $data); return $entity; } /** * Deserialize Array to Entity * @param $entity Ficus_S2DaoEntity entity to parse * @param $data Array array to parse * @return Ficus_S2DaoEntity result entity * @throw Ficus_IllegalBeanException illegal entity. */ private function parseArray($entity, $data, $parent = null){ $reader = new Ficus_S2DaoEntityAnnotationReader($entity); if($data instanceof stdClass){ $data = (array)$data; } $properties = $reader->properties(); $class = get_class($entity); foreach($properties as $property){ $key = $class . "_" . $property; if(is_null($parent) == false){ $key = $parent . "__" . $key; } $getter = "get" . ucfirst($property); $setter = "set" . ucfirst($property); if($reader->type($property) == self::TYPE_DIRECT){ if($this->isEmpty($data, $key) == false){ $entity->{$setter}((integer)$data[$key]); }else{ continue; } }else if($reader->type($property) == self::TYPE_FOREIGN){ $prop = $entity->{$getter}(); $value = $this->parseArray($prop, $data, $key); $entity->{$setter}($value); }else if($reader->type($property) == self::TYPE_LIST){ $direct = $key . "Direct"; if($this->isEmpty($data, $direct) == false){ continue; } if($this->isEmpty($data, $key) == false){ $entity->{$setter . "Direct"}((integer)$data[$key]); } }else if($this->isEmpty($data, $key) == false){ $value = $data[$key]; $entity->{$setter}($value); } } return $entity; } private function isEmpty($data, $key){ if(isset($data[$key]) == false){ return true; }else if($data[$key] === null || $data[$key] === ""){ return true; } return false; } } ?> ficus/db/s2dao/models/annotation/S2DaoEntityAnnotationReader.php100644 1751 144 13127 10645132217 20441 ISHITOYA Kentaro * @version $Id: S2DaoEntityAnnotationReader.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/beans/Bean.php"); require_once("ficus/exception/PropertyNotFoundException.php"); require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_S2DaoEntityAnnotationReader */ class Ficus_S2DaoEntityAnnotationReader implements Ficus_S2DaoModelConstants{ /** * target annotations */ protected static $targets = array(self::ANNOTATION_FORM, self::ANNOTATION_VIEW, self::ANNOTATION_EXPAND, self::ANNOTATION_TYPE, self::ANNOTATION_DATATYPE, self::ANNOTATION_LABEL, self::ANNOTATION_REMARK, self::ANNOTATION_VALIDATOR, self::ANNOTATION_COLUMN); /** * @var $annotations array of annotations */ protected $annotations = array(); /** * @var $target ReflectionClass target entity */ protected $target = null; /** * gettarget * @return ReflectionClass */ public function getTarget(){ return $this->target; } /** * constructor * @param $entity Ficus_S2DaoEntity target entity */ public function __construct($entity){ $this->target = $entity; $class = new ReflectionClass($entity); $annotation = Ficus_BeanConstantAnnotationAccessor::getAccessor($entity); $properties = $class->getDefaultProperties(); $properties = array_keys($properties); foreach($properties as $property){ foreach(self::$targets as $target){ $this->setAnnotation($annotation, $property, $target); } } } /** * search annotation on property * @param $annotation Ficus_BeanConstantAnnotationAccessor accessor * @param $property string property name * @param $type string type of annotation */ protected function setAnnotation($annotation, $property, $type){ $name = "{$property}_$type"; if($annotation->has($name)){ $this->annotations[$property][$type] = $annotation->get($name); } } /** * get array of properties * @return array of property */ public function properties(){ return array_keys($this->annotations); } /** * check has anotation on property * @param $property string property name * @param $annotation string annotation name * @return boolean true if exists */ public function has($property, $annotation){ if(isset($this->annotations[$property][$annotation])){ return true; } return false; } /** * get annotation on property * @param $property string property name * @param $annotation string annotation name * @return mixed annotation */ public function get($property, $annotation){ if(isset($this->annotations[$property][$annotation]) == false){ throw new Ficus_ConstantNotFoundException("annotation $annotation is not defined on $property"); } return $this->annotations[$property][$annotation]; } /** * sort properties * @param $order array of property order */ public function sort($order){ $order = array_keys($order); $temp = array(); foreach($order as $key => $property){ if(isset($this->annotations[$property])){ $temp[$property] = $this->annotations[$property]; } } foreach($this->annotations as $key => $property){ if(isset($temp[$key])){ continue; } $temp[$key] = $property; } $this->annotations = $temp; } const METHOD_SIGNATURE = '/^(has)?(.*?)?(view|form|expand|type|datatype|label|remark|validator|column)?$/i'; /** * call method * @param $name string name of method * @param $arguments array of argument */ public function __call($name, $arguments){ if(preg_match(self::METHOD_SIGNATURE, $name, $regs)){ if(empty($regs[2])){ $property = $arguments[0]; }else{ $property = strtolower($regs[2][0]) . substr($regs[2], 1); } $type = strtoupper($regs[3]); if($regs[1] == "has"){ return $this->has($property, $type); } return $this->get($property, $type); }else{ throw new Ficus_MethodNotFoundException("method $name is not found"); } } } ?> ficus/db/s2dao/components21.dtd100644 1751 144 2773 10645120160 12014 ficus/db/Database.php100644 1751 144 4720 10646431661 10202 ISHITOYA Kentaro * @version $Id: Database.php 12 2007-07-15 14:41:51Z ishitoya $ * * database abstract layer */ require_once "ficus/db/DatabaseConstants.php"; /** * @class Ficus_Database */ abstract class Ficus_Database implements Ficus_DatabaseConstants { /** * connect to server * @param $dns String data source * @param $user String user name * @param $pass String password * @throw Soya_SQLException database error. */ public abstract function connect($dsn, $user = null, $pass = null); /** * execute query * @param $query String query * @param $parameters array paramters * @return query result * @throw Soya_SQLException database error. */ public abstract function query($query, $parameters = array()); /** * disconnect */ public abstract function disconnect(); /** * create dsn from parameter * @param $type String type of database * @param $host String host name * @param $dbname String database name * @return String dsn */ public function createDSN($type, $host, $dbname){ return "$type:dbname=$dbname host=$host"; } /** * begin transaction */ public abstract function begin(); /** * end transaction */ public abstract function commit(); /** * rollBack transaction */ public abstract function rollBack(); /** * is connected * @throw Ficus_NotReadyException not connected */ public abstract function isConnected(); /** * has error * @return boolean there are some error, return true */ public abstract function hasError(); } ?> ficus/db/PDODatabase.php100644 1751 144 13205 10646431661 10563 ISHITOYA Kentaro * @version $Id: PDODatabase.php 12 2007-07-15 14:41:51Z ishitoya $ * * */ require_once("ficus/db/Database.php"); require_once("ficus/exception/SQLException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_PDODatabase */ class Ficus_PDODatabase extends Ficus_Database { /** * @var $database pdo object */ protected $database = null; /** * @var $errorInfo string errorcode */ protected $errorInfo = null; /** * connect to server * @param $dns String data source * @param $user String user name * @param $pass String password * @throw Ficus_SQLException database error. */ public function connect($dsn, $user = null, $pass = null){ if(empty($user) && empty($pass)){ $this->database = new PDO($dsn); }else{ $this->database = new PDO($dsn, $user, $pass); } } /** * execute query * @param $query String query * @param $parameters array paramters * @return query result * @throw Ficus_SQLException database error. */ public function query($query, $parameters = array()){ $this->isConnected(); $result = null; if(preg_match("/^SELECT/", $query)){ $result = $this->executeQuery($query, $parameters); }else{ try{ $this->begin(); $result = $this->executeQuery($query, $parameters); $this->commit(); }catch(Ficus_SQLException $e){ $this->rollBack(); throw $e; } } return $result; } /** * check for multipul command */ protected function isMultipleCommand($query){ if(preg_match_all('/(?!--)(DELETE|INSERT|SELECT|UPDATE)(.+?);/ms', $query, $regs)){ if(count($regs[0]) > 1){ return true; } } return false; } /** * create statement and execute * @param $query String query * @param $parameters array paramters * @return query result * @throw Ficus_SQLException database error. */ protected function executeQuery($query, $parameters){ if($this->isMultipleCommand($query)){ $result = $this->database->exec($query); $this->errorInfo = $this->database->errorInfo(); if($result === false){ throw new Ficus_SQLException($this->errorInfo[2]); } return $result; } $statement = $this->database->prepare($query); foreach($parameters as $index => $param){ $index += 1; if(is_array($param) == false){ $statement->bindParam($index, $param); }else if($param[self::TYPE_INDEX] == self::PARAM_TEXT){ $statement->bindParam($index, $param[self::VALUE_INDEX]); }else if($param[self::TYPE_INDEX] == self::PARAM_LOB){ $statement->bindParam($index, $param[self::VALUE_INDEX], PDO::PARAM_LOB); }else{ throw new Ficus_IllegalArgumentException("type index of parameter is not text nor lob"); } } $result = $statement->execute(); $this->errorInfo = $statement->errorInfo(); if($result === false){ throw new Ficus_SQLException($this->errorInfo[2]); } return $statement; } /** * disconnect * pdo has no functionality to close connection. */ public function disconnect(){ $this->database = null; } /** * begin transaction */ public function begin(){ $this->isConnected(); $this->database->beginTransaction(); } /** * end transaction */ public function commit(){ $this->isConnected(); $this->database->commit(); } /** * rollBack transaction */ public function rollBack(){ $this->isConnected(); $this->database->rollBack(); } /** * is connected * @throw Ficus_NotReadyException not connected */ public function isConnected(){ if(is_null($this->database)){ throw new Ficus_NotReadyException("connection is not established"); } } /** * has error * @return boolean there are some error, return true */ public function hasError(){ if(is_null($this->errorCode)){ return false; } $class = substr($this->errorInfo[0], 0, 2); if($class === self::SQLSTATE_OK || $class === self::SQLSTATE_WARN){ return false; } return true; } /** * get error info * @return array error info */ public function errorInfo(){ return $this->errorInfo; } } ?> ficus/db/DatabaseConstants.php100644 1751 144 2522 10645132217 12067 ISHITOYA Kentaro * @version $Id: DatabaseConstants.php 2 2007-07-11 10:37:48Z ishitoya $ * * database constants */ /** * @interface Ficus_DatabaseConstants */ interface Ficus_DatabaseConstants { const PARAM_LOB = "lob"; const PARAM_TEXT = "text"; const TYPE_INDEX = 1; const VALUE_INDEX = 0; const SQLSTATE_OK = "00"; const SQLSTATE_WARN = "01"; const SQLSTATE_E_NODATA = "02"; const SQLSTATE_E_DYNAMIC = "07"; const SQLSTATE_E_CONNECTION = "08"; //@todo write down SQLSTATEs } ?> ficus/di/S2ContainerComponentFactory.php100644 1751 144 11260 10647426442 14066 ISHITOYA Kentaro * @version $Id: S2ContainerComponentFactory.php 15 2007-07-18 15:02:48Z ishitoya $ * * S2Container component factory */ require_once("ficus/io/File.php"); require_once("ficus/config/Registry.php"); /** * @class Ficus_S2ContainerComponentFactory */ abstract class Ficus_S2ContainerComponentFactory implements Ficus_ComponentFactory{ const DICON_PATH = "s2container.dicon_path"; /** * @var S2Container S2Container. */ private static $containers = array(); /** * @var Ficus_S2ContainerComponentFactory */ protected static $factory = null; /** * @var string dicon path */ protected $diconPath = null; /** * get Dicon file name from registry * @return string dicon filename */ protected abstract function getDiconFileNameRegistry(); /** * get Dicon namespace from registry * @return string dicon namespace */ protected abstract function getDiconNameSpaceRegistry(); /** * get dicon file name * @return string dicon file name */ protected abstract function getDefaultDiconFileName(); /** * get defoult dicon namespace * @return string dicon namespace */ protected abstract function getDefaultDiconNameSpace(); /** * instanciate factory */ protected static function getInstance($class){ return new $class; } /** * check for registry */ protected function checkForRegistry(){ if(Ficus_Registry::search(self::DICON_PATH) == false){ throw new Ficus_NotReadyException("s2container.dicon_path must be declared in Ficus_Registry before runch any function"); } return; } /** * Get dicon path. * * return string dicon path.. */ protected function getDiconPath() { $diconPath = Ficus_Registry::search($this->getDiconFileNameRegistry()); if($diconPath == false){ $diconPath = $this->getDefaultDiconFileName(); }else{ $candidates = Ficus_ClassPath::search($diconPath); if(empty($candidates)){ throw new Ficus_IllegalArgumentException("$diconPath is not resonable file name, check out class path"); } $diconPath = $candidates[0]; } return $diconPath; } /** * Get S2Container. * * return S2Container S2Container. */ protected function getS2Container() { if (empty(self::$containers)){ Ficus_AutoLoad::add(new Ficus_S2ContainerAutoLoad()); } if (is_null($this->diconPath) || isset(self::$containers[$this->diconPath]) == false) { $this->checkForRegistry(); $root = Ficus_Registry::search(self::DICON_PATH); if(defined("DICON_PATH") == false){ $candidates = Ficus_ClassPath::search($root); if(empty($candidates)){ throw new Ficus_IllegalArgumentException("$root is not resonable dicon path, check out class path"); } define("DICON_PATH", $candidates[0]); } $this->diconPath = $this->getDiconPath(); self::$containers[$this->diconPath] = S2ContainerFactory::create($this->diconPath); } return self::$containers[$this->diconPath]; } /** * get component * * @return component */ public static function getComponent($name, $class = __CLASS__){ if(is_null(self::$factory)){ self::$factory = self::getInstance($class); if(is_null(self::$factory)){ throw new Ficus_NotImplementedException("extended class must implement getInstance method"); } } return self::$factory->getS2Container()->getComponent($name); } } ?> ficus/di/ComponentFactory.php100644 1751 144 2264 10647426442 12002 ISHITOYA Kentaro * @version $Id: ComponentFactory.php 15 2007-07-18 15:02:48Z ishitoya $ * * S2Dao component factory */ /** * @class Ficus_ComponentFactory */ interface Ficus_ComponentFactory{ /** * get component * * @param $name string name of component * @return component */ public static function getComponent($name); } ?> ficus/io/YAMLFileReader.php100644 1751 144 4003 10645132217 11171 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: YAMLFileReader.php 2 2007-07-11 10:37:48Z ishitoya $ * * YAML File Reader for php */ require_once("ficus/io/AbstractFileReader.php"); require_once("spyc/spyc.php"); /** * @class Ficus_YAMLFileReader */ class Ficus_YAMLFileReader extends Ficus_AbstractFileReader{ /** extension of property file */ const PROPERTY_SUFFIX = "yml"; /** * read property file. * @param $package string property file name. * @param $suffix string suffix of property file name * @param $class string caller class * @throw Ficus_NotReadyException no initialized. * @throw Ficus_MultipleFileFoundException multiple file found. * @throw Ficus_FileNotFoundException file not found. */ public static function read($package, $suffix = "", $class = __CLASS__){ if(empty($suffix)){ $suffix = self::PROPERTY_SUFFIX; } return parent::read($package, $suffix, $class); } /** * on read * @param $filename string file name * @return array of result */ public function onRead($filename){ return Spyc::YAMLLoad($filename); } } ?> ficus/io/File.php100644 1751 144 22372 10645132217 7414 SUMI Masafumi * @version $Id: File.php 2 2007-07-11 10:37:48Z ishitoya $ * * File utility. */ require_once('ficus/io/Dir.php'); require_once('ficus/exception/MethodNotFoundException.php'); require_once('ficus/lang/ClassPath.php'); require_once('mime_magic/class.mime_magic.inc.php'); /** * @class Ficus_File */ class Ficus_File { /** * @var string path. */ private $path; /** * Constructor. * * @param $path string path. */ public function __construct($path = '') { $this->path = $path; } /** * Get path. * * @return string path. */ public function getPath() { return $this->path; } /** * Get file name * * @return string file name */ public function getFilename(){ return basename($this->path); } /** * Get extension */ public function getExtension(){ if(preg_match('/\.([^\.]+)$/', $this->path, $regs)){ return $regs[1]; } return null; } /** * Get Dir * * @return string dir name */ public function getDirname(){ return dirname($this->path); } /** * is Dir contains * * @param $pattern string pattern * @return boolean dir name contains patten */ public function dirnameContains($pattern){ $result = strstr($this->getDirname(), $pattern); if($result != false){ return true; } return false; } /** * To string. * * @return string path. */ public function toString() { return $this->getPath(); } /** * To string. * * @return string path. */ public function __toString() { return $this->getPath(); } /** * Call PHP filesystem function. * * @param $name string function name. * @param $arguments function arguments. * @return mixed function return value. * @throw Ficus_MethodNotFoundException method not found. */ public function __call($name, $arguments) { switch ($name) { case 'basename': case 'chgrp': case 'chmod': case 'chown': case 'copy': //case 'delete': case 'dirname': case 'file_exists': case 'file_get_contents': case 'file_put_contents': case 'file': case 'fileatime': case 'filectime': case 'filegroup': case 'fileinode': case 'filemtime': case 'fileperms': case 'filesize': case 'filetype': case 'is_dir': case 'is_executable': case 'is_file': case 'is_link': case 'is_readable': case 'is_uploaded_file': case 'is_writable': case 'is_writeable': case 'link': case 'linkinfo': case 'lstat': case 'mkdir': case 'move_uploaded_file': case 'parse_ini_file': case 'pathinfo': case 'readfile': case 'readlink': case 'realpath': case 'rename': case 'rmdir': case 'stat': case 'symlink': case 'tempnam': case 'touch': case 'unlink': if (is_array($arguments)) { $argumentsWithPath = array_merge(array($this->path), $arguments); } else { $argumentsWithPath = array($this->path); } return call_user_func_array($name, $argumentsWithPath); break; // path is not first argument. case 'fnmatch': $argumentsWithPath = array_merge(array($arguments[0], $this->path), array_slice($arguments, 1)); return call_user_func_array($name, $argumentsWithPath); break; // don't use path. case 'glob': case 'tempfile': return call_user_func_array($name, $arguments); break; } throw new Ficus_MethodNotFoundException($name); } /** * Normailze path separator. * * @param $separator string directory separator. * @return Ficus_File this. */ public function normalizePathSeparator($separator = null) { return new Ficus_File(Ficus_Dir::normalizePathSeparator($this->path, $separator)); } /** * Normailze path. * * @param $separator string directory separator. * @return Ficus_File this. */ public function normalize($separator = null) { return new Ficus_File(Ficus_Dir::normalize($this->path, $separator)); } /** * Resolve path. * * @param $relative string relative path. * @param $separator string directory separator. * @return Ficus_File this. */ public function resolve($relative, $separator = null) { return new Ficus_File(Ficus_Dir::resolve($this->path, $relative, $separator)); } /** * Current dir. * * @return Ficus_File current dir. */ public static function currentDir() { $trace = debug_backtrace(); $class = new ReflectionClass($trace[1]["class"]); return new Ficus_File(dirname($class->getFileName())); } /** * Current dir. * * @return string current dir. */ public static function currentDirStr() { $trace = debug_backtrace(); $class = new ReflectionClass($trace[1]["class"]); return dirname($class->getFileName()); } /** * Current dir. * * alias currentDir(). * * @return Ficus_File current dir. */ public static function pwd() { $trace = debug_backtrace(); $class = new ReflectionClass($trace[1]["class"]); return new Ficus_File(dirname($class->getFileName())); } /** * Current dir. * * alias currentDir(). * * @return string current dir. */ public static function pwdStr() { $trace = debug_backtrace(); $class = new ReflectionClass($trace[1]["class"]); return dirname($class->getFileName()); } /** * Current PHP file. * * @return Ficus_File current PHP file. */ public static function currentFile() { $trace = debug_backtrace(); $class = new ReflectionClass($trace[1]["class"]); return new Ficus_File($class->getFileName()); } /** * Current PHP file. * * @return string current PHP file. */ public static function currentFileStr() { $trace = debug_backtrace(); $class = new ReflectionClass($trace[1]["class"]); return $class->getFileName(); } /** * Create File. * * @param $path string path. * @return Ficus_File file. */ public static function create($path) { return new Ficus_File($path); } /** * Check if a file exists in the include path * * @version 1.2.1 * @author Aidan Lister * @link http://aidanlister.com/repos/v/function.file_exists_incpath.php * @param string $file Name of the file to look for * @return mixed The full path if file exists, FALSE if it does not */ public static function fileExistsInIncludePath ($file) { $paths = explode(PATH_SEPARATOR, get_include_path()); foreach ($paths as $path) { // Formulate the absolute path $fullpath = $path . DIRECTORY_SEPARATOR . $file; // Check it if (file_exists($fullpath)) { return $fullpath; } } return false; } /** * Check if a file exists in the classpath * * @param string $file Name of the file to look for * @return mixed The full path if file exists, FALSE if it does not */ public static function fileExistsInClassPath ($file) { $paths = Ficus_ClassPath::search($file); if(empty($paths)){ return false; } return $paths[0]; } /** * get mime type from filename */ public function mimetype(){ $mime = new mime_magic(); return $mime->filename2mime($this->path); } /** * add */ public function add($path){ $this->path .= $path; } } ?> ficus/io/AbstractFileReader.php100644 1751 144 6427 10645132217 12206 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: AbstractFileReader.php 2 2007-07-11 10:37:48Z ishitoya $ * * Abstract File Reader for php */ require_once("ficus/exception/FileNotFoundException.php"); require_once("ficus/exception/MultipleFileFoundException.php"); require_once("ficus/exception/NotReadyException.php"); require_once("ficus/lang/ClassPath.php"); require_once("ficus/lang/ClassPathElement.php"); require_once("ficus/io/Dir.php"); require_once("ficus/io/File.php"); require_once("ficus/io/FileReader.php"); /** * @class Ficus_AbstractFileReader */ abstract class Ficus_AbstractFileReader implements Ficus_FileReader { /** name of config dir*/ protected static $configDir = null; /** name of file to read*/ protected $filename = null; /** * set config path * @param $name string config dir name */ public static function setConfigDir($name){ self::$configDir = $name; } /** * read property file. * @param $package string property file name. * @param $suffix string suffix of property file name * @param $class string caller class * @throw Ficus_NotReadyException no initialized. * @throw Ficus_MultipleFileFoundException multiple file found. * @throw Ficus_FileNotFoundException file not found. */ public static function read($package, $suffix = "", $class = __CLASS__){ $filePath = Ficus_ClassPath::packageToDirectory($package); $packageDir = dirname($filePath); $filename = basename($filePath) . ".$suffix"; $found = array(); if(empty(self::$configDir)){ $filePath = $packageDir . "/" . $filename; }else{ $filePath = self::$configDir . "/" . $packageDir . "/" . $filename; } $files = Ficus_ClassPath::search($filePath); if(count($files) >= 2){ $files = implode(",", $files); throw new Ficus_MultipleFileFoundException("Multiple files are found. please check your settings. $files are found."); }else if(empty($files)){ $paths = Ficus_ClassPath::__toString(); throw new Ficus_FileNotFoundException(self::$configDir . "/$filename is not found in " . $paths . "."); } $reader = new $class(); return $reader->onRead($files[0]); } /** * on read * @param $filename string file name * @return array of result */ abstract public function onRead($filename); } ?> ficus/io/PropertyFileReader.php100644 1751 144 3774 10645132217 12271 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: PropertyFileReader.php 2 2007-07-11 10:37:48Z ishitoya $ * * Property File Reader for php */ require_once("ficus/io/AbstractFileReader.php"); /** * @class Ficus_PropertyFileReader */ class Ficus_PropertyFileReader extends Ficus_AbstractFileReader{ /** extension of property file */ const PROPERTY_SUFFIX = "ini"; /** * read property file. * @param $package string property file name. * @param $suffix string suffix of property file name * @param $class string caller class * @throw Ficus_NotReadyException no initialized. * @throw Ficus_MultipleFileFoundException multiple file found. * @throw Ficus_FileNotFoundException file not found. */ public static function read($package, $suffix = "", $class = __CLASS__){ if(empty($suffix)){ $suffix = self::PROPERTY_SUFFIX; } return parent::read($package, $suffix, $class); } /** * on read * @param $filename string file name * @return array of result */ public function onRead($filename){ return parse_ini_file($filename); } } ?> ficus/io/Dir.php100644 1751 144 24641 10645132217 7254 SUMI Masafumi * @version $Id: Dir.php 2 2007-07-11 10:37:48Z ishitoya $ * * Dir utility. */ require_once('ficus/lang/String.php'); require_once('ficus/lang/Assert.php'); require_once('ficus/io/PathPattern.php'); require_once('ficus/exception/DirException.php'); /** * @class Ficus_Dir */ class Ficus_Dir { /** * @var $pattern Ficus_PathPattern */ private $pattern; /** * @var $path Ficus_PathPattern */ private $path; /** * Constructor. * * @param $path string path * @param $pattern Ficus_PathPattern of search pattern. */ public function __construct($path, $pattern = null) { $this->setPath($path); $this->setPattern($pattern); } /** * Get pattern. * * @return Ficus_PathPattern of search pattern. */ public function getPattern() { return $this->pattern; } /** * Set pattern. * * @param $pattern Ficus_PathPattern of search pattern. */ public function setPattern($pattern) { Ficus_Assert::isTypeAllowNull($pattern, "Ficus_PathPattern"); if(is_null($pattern)){ $pattern = new Ficus_PathPattern(); } $this->pattern = $pattern; } /** * Get path. * * @return string of search pattern. */ public function getPath() { return $this->path; } /** * Set path. * * @param $path string path */ public function setPath($path) { if(is_dir($path)){ $path = $path . "/"; }else if(is_file($path)){ $path = dirname($path) . "/" . basename($path); }else{ throw new Ficus_IllegalArgumentException("$path is not dir nor file. check is readable"); } $this->path = self::normalize($path); } /** * add Path * @param $right String path * @param $check boolean check is dir exists. * @return Ficus_Dir this object */ public function add($right){ Ficus_Assert::isPrimitiveType($right, "string"); $path = $this->path . "/$right"; if(is_dir($path)){ $path .= "/"; } $path = Ficus_Dir::normalize($path); $dir = new Ficus_Dir($path, $this->pattern); return $dir; } /** * Each files. * * @param $callback callback of each files. * @param $path string start path. */ public function each($callback, $path = null) { if(is_null($path)){ $path = $this->path; } foreach (scandir($path, 1) as $entry) { $fullpath = $path . '/' . $entry; if (is_dir($fullpath) && $entry{0} != '.') { $this->each($callback, $fullpath); } else if (is_null($this->pattern) == false || $this->pattern->match($fullpath)) { call_user_func($callback, $fullpath); } } } /** * extract dir from passed dir * @param $path string path * @param $mark string mark * @param $additional string additional path * @param String */ public static function createInstance($path, $mark = null, $additional = null){ if(is_null($mark) == false){ $index = strrpos($path, $mark); if($index === false){ throw new Ficus_IllegalArgumentException("$mark is not found in $path"); } $path = substr($path, 0, $index); } if(is_dir($path)){ $dir = $path; }else if(is_file($path)){ $dir = dirname($path); }else{ throw new Ficus_IllegalArgumentException("$path is not exist"); } if(is_null($additional) == false){ $dir = $dir . "/" . $additional; } $dir .= "/"; return new Ficus_Dir($dir); } /** * equals * @param $right Ficus_Dir dir * @return boolean true if same */ public function equals($right){ if($right instanceof Ficus_Dir){ return ($right->path === $this->path); }else if(is_string($right)){ $dir = new Ficus_Dir($right); return $this->equals($dir); }else{ throw new Ficus_IllegalArgumentException("{$this->path} is not equals with {$right}"); } } /** * list files * @param $path String base dir * @return Array of found file and dirs. */ public function getList($path = null){ if(is_null($path)){ $path = $this->path; } $result = array(); foreach(scandir($path, 1) as $entry){ if($entry == "." || $entry == ".."){ continue; } $fullpath = $path . '/' . $entry; if(is_dir($fullpath) && $this->pattern->match($fullpath)){ $array = $this->getList($fullpath); $result = array_merge($result, $array); }else if($this->pattern->match($fullpath)){ $result[$entry] = $fullpath; } } return $result; } /** * Normailze path separator. * * @param $path string path. * @param $separator string directory separator. * @return string normalized path. */ public static function normalizePathSeparator($path, $separator = null) { if ($separator === null) { $separator = DIRECTORY_SEPARATOR; } else { assert($separator != '/' || $separator != '\\'); } $separatorPattern = array('\\' => '/\//', '/' => '/\\\/'); return preg_replace($separatorPattern[$separator], $separator, $path); } /** * Normalize path. * * @param $path string path. * @param $separator string directory separator. * @return string resolved path. */ public static function normalize($path, $separator = null) { Ficus_Assert::isPrimitiveType($path, "string"); $separator = ($separator === null) ? DIRECTORY_SEPARATOR : $separator; assert($separator != '/' || $separator != '\\'); $path = self::normalizePathSeparator($path, $separator); // // $schemePattern = array('/' => '/^[^:]+:\/\//', '\\' => '/^[^:]+:\\\\/'); if (preg_match($schemePattern[$separator], $path) > 0) { $str = new Ficus_String($path); $currentPattern = array('/' => '/\/\//', '\\' => '/\\\\/'); $ary = preg_split($currentPattern[$separator], $path, -1, PREG_SPLIT_NO_EMPTY); $path = $ary[0] . $separator . $separator . join($separator, array_slice($ary, 1)); if($str->endsWith("\\") || $str->endsWith("/")){ $path .= $separator; } } else { $currentPattern = array('/' => '/\/(?=\/)/', '\\' => '/\\\\(?=\\\\)/'); while (preg_match($currentPattern[$separator], $path) >= 1) { $path = preg_replace($currentPattern[$separator], '', $path); } } // ./ $currentPattern = array('/' => '/(?:\/\.\/|\/\.$)/', '\\' => '/(?:\\\\.\\\|\\\\.$)/'); while (preg_match($currentPattern[$separator], $path) >= 1) { $path = preg_replace($currentPattern[$separator], $separator, $path); } // ../ $parentPattern = array('/' => '/\/[^\.\/]+(?:\/\.\.\/|\/\.\.$)/', '\\' => '/\\\[^\.\\\]+(?:\\\\.\.\\\|\\\\.\.$)/'); while (preg_match($parentPattern[$separator], $path) >= 1) { $path = preg_replace($parentPattern[$separator], $separator, $path); } return $path; } /** * Is base dir. * * @param $path string path. * @return boolean true if $path is base dir. */ public static function isBaseDir($path) { if (strlen($path) === 0) { return false; } return ($path{0} == '/' || strpos($path, ':') !== false); } /** * Resolve path. * * @param $base string base path. * @param $relative string relative path. * @param $separator string directory separator. * @return string resolved path. * @throw Ficus_DirException no base dir or no relative dir. */ public static function resolve($base, $relative, $separator = null) { $separator = ($separator === null) ? DIRECTORY_SEPARATOR : $separator; if (!self::isBaseDir($base)) { throw new Ficus_DirException("No base dir: '$base'"); } if (self::isBaseDir($relative)) { throw new Ficus_DirException("No relative dir: '$relative'"); } $base = self::normalizePathSeparator($base, $separator); $relative = self::normalizePathSeparator($relative, $separator); return self::normalize($base . $separator . $relative, $separator); } /** * create dir * * @param $dir * @throw Ficus_DirException cannot create dir */ public static function mkdir($dir, $mode=0755){ $dir = self::normalize($dir); if(is_readable($dir)){ return true; } if(mkdir($dir, $mode, true) === false){ throw new Ficus_DirException("cannot create $dir"); } if(is_dir($dir) === false){ throw new Ficus_DirException("dir created, but $dir is not valid"); } return true; } /** * get string form * * @return string string */ public function __toString(){ return $this->getPath(); } } ?> ficus/io/FileReader.php100644 1751 144 2445 10645132217 10516 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: FileReader.php 2 2007-07-11 10:37:48Z ishitoya $ * * File Reader for php */ /** * @class Ficus_FileReader */ interface Ficus_FileReader { /** * read file. * @param $package string property file name. * @param $suffix string suffix of property file name * @param $class string caller class */ public static function read($package, $suffix="", $class=__CLASS__); } ?> ficus/io/PathPattern.php100644 1751 144 7741 10645132217 10752 ISHTIOYA Kentaro * @version $Id: PathPattern.php 2 2007-07-11 10:37:48Z ishitoya $ * * path pattern to describe pattern */ /** * @class Ficus_PathPattern */ class Ficus_PathPattern { /** * @var $includes array include patterns */ protected $includes = array(); /** * @var $excludes array exclude patterns */ protected $excludes = array(); /** * constructor * @pattern $defaultExclude boolean true to enable default Exclude pattern */ public function __construct($defaultExclude=true){ if($defaultExclude){ $this->addExclude("**/*~"); $this->addExclude("**/#*#"); $this->addExclude("**/.#*"); $this->addExclude("**/%*%"); $this->addExclude("**/._*"); $this->addExclude("**/CVS"); $this->addExclude("**/CVS/**"); $this->addExclude("**/.cvsignore"); $this->addExclude("**/SCCS"); $this->addExclude("**/SCCS/**"); $this->addExclude("**/vssver.scc"); $this->addExclude("**/.svn"); $this->addExclude("**/.svn/**"); } } /** * add include * @param $include string include pattern * @return Ficus_PathPattern fluent this object */ public function addInclude($include){ $this->includes[] = $this->convertPatternToRE($include); return $this; } /** * add exclude * @param $exclude string exclude pattern * @return Ficus_PathPattern fluent this object */ public function addExclude($exclude){ $this->excludes[] = $this->convertPatternToRE($exclude); return $this; } /** * match * @param $entry string subject * @return boolean true if match */ public function match($entry){ if(empty($this->includes) && empty($this->excludes)){ return true; } $matched = false; foreach($this->includes as $include){ if(preg_match($include, $entry)){ $matched = true; break; } } if($matched === false && empty($this->includes) == false){ return false; } foreach($this->excludes as $exclude){ if(preg_match($exclude, $entry)){ return false; } } return true; } /** * pattern to Reguler expression * @param $patten string pattern * @return reguler expression */ protected function convertPatternToRE($pattern){ $pattern = preg_replace('/^\/\*\*/', '**', $pattern); $pattern = preg_replace('/^\*\*\//', '**', $pattern); $pattern = str_replace(array('.', '/', '~', '^', '$', '(', ')', '{', '}', '|'), array('\.','\/', '\~', '\^', '\$', '\(', '\)', '\{', '\}', '\|'), $pattern); $pattern = str_replace('**', ".*?", $pattern); $pattern = preg_replace('/(? ficus/RDF/RDFQName.php100644 1751 144 6014 10645132217 10051 SUMI Masafumi * @version $Id: RDFQName.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/XML/QName.php"); require_once("ficus/collection/UnicodeIterator.php"); /** * @class Soya_RDFQName */ class Ficus_RDFQName extends Ficus_QName { /** * IS NCStartName? * * @param $unicode string unicode. * @return boolean is NCStartName? */ private static function isNCStartName($unicode) { $ncNameChars = Ficus_XMLUtils::getNCNameStartChar(); foreach ($ncNameChars as $charRange) { if ($charRange[0] <= $unicode && $unicode <= $charRange[1]) { return true; } } return false; } /** * IS NCName? * * @param $unicode string unicode. * @return boolean is NCName? */ private static function isNCName($unicode) { $ncNameChars = Ficus_XMLUtils::getNCNameChar(); foreach ($ncNameChars as $charRange) { if ($charRange[0] <= $unicode && $unicode <= $charRange[1]) { return true; } } return false; } /** * Split resource uri to namespace and local part. * * @param $nodeString string node string. * @return Ficus_QName resource qname. */ public static function createByString($nodeString) { // Why does not reverse iterator exist in SPL? $rev = array(); foreach (new Ficus_UnicodeIterator($nodeString) as $unicode) { $rev []= $unicode; } $rev = array_reverse($rev); // search NCStartName char and invalid char. foreach ($rev as $index => $unicode) { if (self::isNCStartName($unicode)) { $startCharPos = $index + 1; } else if (self::isNCName($unicode)) { } else { // invalid char before NCStartNameChar. break; } } if (isset($startCharPos)) { $pos = sizeof($rev) - $startCharPos; $ns = mb_substr($nodeString, 0, $pos); $local = mb_substr($nodeString, $pos); } else { $ns = $nodeString; $local = ''; } return new Ficus_RDFQName($ns, $local); } } ?> ficus/RDF/AnyNode.php100644 1751 144 2253 10645132217 10052 SUMI Masafumi * @version $Id: AnyNode.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/RDF/Node.php"); /** * @class Ficus_AnyNode */ interface Ficus_AnyNode extends Ficus_Node { /** * wild card node value. */ const WILD_CARD = "*"; /** * node value. * * @return mixed node value. */ public function value(); } ?> ficus/RDF/GraphFactory.php100644 1751 144 11154 10645132217 11126 SUMI Masafumi * @version $Id: GraphFactory.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/RDF/Graph.php"); /** * @class Ficus_GraphFactory */ interface Ficus_GraphFactory { /** * Create graph. * * @return Ficus_Graph */ public static function createGraph(); /** * Create any node. * * @return Ficus_AnyNode any node. */ public static function createAnyNode(); /** * Create blank node. * * @param $name Ficus_QName qname. * @return Ficus_BlankNode blank node. */ public static function createBlankNode($name); /** * Create literal node. * * @param mixed literal. * @return Ficus_LiteralNode literal node. */ public static function createLiteralNode(); /** * Create literal node. * * @param $literal string literal. * @param $type Ficus_LiteralType literal type. * @return Ficus_LiteralNode literal node. */ public static function createLiteralNodeByType($literal, $type); /** * Create string literal node. * * @param $literal string literal. * @return Ficus_LiteralNode string literal node. */ public static function createStringLiteral($literal); /** * Create typed literal node. * * @param $literal string literal. * @param $typeQName Ficus_QName type qname. * @return Ficus_LiteralNode typed literal node. */ public static function createTypedLiteral($literal, $typeQName); /** * Create plain literal node. * * @param $literal string literal. * @param $lang string lang name. * @return Ficus_LiteralNode plain literal node. */ public static function createPlainLiteral($literal, $lang); /** * Create resource node. * * @param mixed resource. * @return Ficus_ResourceNode resource node. */ public static function createResourceNode(); /** * Create resource node. * * @param $uri string uri. * @param $localPart string local part. * @return Ficus_ResourceNode resource node. */ public static function createResourceNodeByUri($uri, $localPart); /** * Create resource node. * * @param $qname Ficus_QName * @return Ficus_ResourceNode resource node. */ public static function createResourceNodeByQName($qname); /** * Create literal type. * * @param $type Ficus_QName type qname. * @return Ficus_LiteralType literal type. */ public static function createTyped($type); /** * Create literal type. * * @param $type Ficus_QName type qname. * @param $isPlain boolean is plain? * @return Ficus_LiteralType literal type. */ public static function createLiteralType($type, $isPlain); /** * Create literal lang. * * @param $lang string lang. * @return Ficus_LiteralType literal lang. */ public static function createLiteralLang($lang); /** * Create triple. * * @param $subject Ficus_ResourceNode subject node. * @param $predicate Ficus_ResourceNode predicate node. * @param $object Ficus_Node object node. */ public static function createTriple($subject, $predicate, $object); /** * Create quad. * * @param $name Ficus_ResourceNode name node. * @param $subject Ficus_ResourceNode subject node. * @param $predicate Ficus_ResourceNode predicate node. * @param $object Ficus_Node object node. */ public static function createQuad($name, $subject, $predicate, $object); /** * Create quad by triple. * * @param $name string name of triple. * @param $triple Ficus_Triple triple. * @return Ficus_Quad of quad. */ public static function createQuadByTriple($name, $triple); } ?> ficus/RDF/Graph.php100644 1751 144 5532 10645132217 7561 SUMI Masafumi * @version $Id: Graph.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/RDF/AnyNode.php"); require_once("ficus/RDF/Node.php"); require_once("ficus/RDF/BlankNode.php"); require_once("ficus/RDF/Quad.php"); require_once("ficus/lang/Arrays.php"); require_once("ficus/lang/Assert.php"); /** * @class Ficus_Graph */ interface Ficus_Graph extends IteratorAggregate { /** * add. * * @param $name Ficus_Node name. * @param $subject Ficus_Node subject. * @param $predicate Ficus_Node predicate. * @param $object Ficus_Node object. */ public function add($name, $subject, $predicate, $object); /** * add quad. * * @param $quad Ficus_Quad of quad. * @return boolean true if added; false if quad already exist. */ public function addQuad($quad); /** * add graph. * * @param $graph Ficus_Graph of graph. */ public function addGraph($graph); /** * remove quad. * * @param $quad Ficus_Quad Ficus_Quad of quad. */ public function removeQuad($quad); /** * contains quads. * * @param $quad Ficus_Quad * @return boolean true if contains quad. */ public function contains($quad); /** * find triple in this graph. * * @param $name Ficus_Node name. * @param $subject Ficus_Node subject. * @param $predicate Ficus_Node predicate. * @param $object Ficus_Node object. * @return Ficus_Graph found graph. */ public function find($name, $subject, $predicate, $object); /** * set namespaces. * * @param $namespaces array array of namespace */ public function setNamespaces($namespaces); /** * namespaces. * * @return array of $namespace. */ public function namespaces(); /** * count graph. * * @return int count of graph. */ public function count(); /** * Equals to another graph. * * @param $graph Ficus_Graph graph. */ public function equals($graph); } ?> ficus/RDF/Quad.php100644 1751 144 2311 10645132217 7402 SUMI Masafumi * @version $Id: Quad.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/RDF/Triple.php"); /** * @class Ficus_Quad */ interface Ficus_Quad extends Ficus_Triple { /** * set graph name. * * @param $name string name. */ public function setName($name); /** * get graph name. * * @return string name. */ public function name(); } ?> ficus/RDF/LiteralNode.php100644 1751 144 2720 10645132217 10716 SUMI Masafumi * @version $Id: LiteralNode.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/RDF/Node.php"); /** * @class Ficus_LiteralNode */ interface Ficus_LiteralNode // extends Ficus_Node { /** * literal. * * @return string of literal. */ public function literal(); /** * type. * * @return string of literal type. */ public function type(); /** * node value. * * @return mixed node value. */ public function value(); /** * toString. * * @return string literal with prefixed data type qname. */ public function toPrefixedString(); } ?> ficus/RDF/BlankNode.php100644 1751 144 2071 10645132217 10350 SUMI Masafumi * @version $Id: BlankNode.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_BlankNode */ interface Ficus_BlankNode //extends Ficus_ResourceNode { /** * Blank node namespace. */ const BLANK_NAMESPACE = "_:"; } ?> ficus/RDF/ResourceNode.php100644 1751 144 3675 10645132217 11123 SUMI Masafumi * @version $Id: ResourceNode.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/RDF/Node.php"); /** * @class Ficus_ResourceNode */ interface Ficus_ResourceNode extends Ficus_Node { const RESOURCE_NAMESPACE_SEPARATOR1 = '#'; const RESOURCE_NAMESPACE_SEPARATOR2 = '/'; const RESOURCE_NAMESPACE_SEPARATOR3 = ':'; /** * qname. * * @return Ficus_QName qname. */ public function qname(); /** * resource uri namespace. * * @return string uri. */ public function uri(); /** * resource uri namespace. * * @return string uri. */ public function namespace(); /** * resource local part. * * @return string local part. */ public function localPart(); /** * resource local part. * * @return string local part. */ public function localName(); /** * Split resource uri to namespace and local part. * * @param $nodeString string node string. * @return Ficus_QName resource qname. */ public static function toQNameByResourceString($nodeString); } ?> ficus/RDF/Node.php100644 1751 144 3313 10645132217 7400 SUMI Masafumi * @version $Id: Node.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_Node */ interface Ficus_Node { /** * compare node. * * @param $node Ficus_Node or string another node. * @return int */ public function compare($node); /** * equals node. * * @param $node Ficus_Node or string another node. * @return boolean return true if equals else return false. */ public function equals($node); /** * equals by node value. * * @param $node Ficus_Node or string another node. * @return boolean return true if equals else return false. */ public function equalsByValue($node); /** * toString. * * @return string Node to string. */ public function toString(); /** * toString. * * @return string Node to string. */ public function __toString(); } ?> ficus/RDF/LiteralType.php100644 1751 144 4537 10645132217 10762 SUMI Masafumi * @version $Id: LiteralType.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_LiteralType */ interface Ficus_LiteralType { /** * XML schema namespace. */ const NS_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema#"; /** * RDF schema namespace. */ const NS_RDF_SCHEMA = "http://www.w3.org/2000/01/rdf-schema#"; /** * Plain literal. */ const PLAIN_LITERAL = true; /** * Typed literal. */ const TYPED_LITERAL = false; /** * Type. * * @return string of literal type. */ public function type(); /** * Lang. * * @return string of literal lang. */ public function lang(); /** * Is plain literal. * * @return boolean true if plain literal. */ public function is_plain(); /** * Is typed literal. * * @return boolean true if typed literal. */ public function is_typed(); /** * Literal and literal type separator. */ public function separator(); /** * To string. * * @return string of literal. */ public function toString(); /** * To string. * * @return string of literal. */ public function __toString(); /** * To string of prefixed QName. * * @param $xsd string XML schema namespace prefix. * @param $rdfs string RDF schema namespace prefix. * @return string string of literal. */ public function toPrefixedQName($xsd = "xsd", $rdfs = "rdfs"); } ?> ficus/RDF/RDFTypes.php100644 1751 144 15204 10645132217 10175 SUMI Masafumi * @version $Id: RDFTypes.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_RDFTypes */ class Ficus_RDFTypes { /** * XML schema namespace. */ const NS_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema#"; /** * RDF namespace. */ const NS_RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; const XSD_STRING = 'string'; const XSD_BOOLEAN = 'boolean'; const XSD_DECIMAL = 'decimal'; const XSD_FLOAT = 'float'; const XSD_DOUBLE = 'double'; const XSD_DATE_TIME = 'dateTime'; const XSD_DATETIME = 'dateTime'; const XSD_TIME = 'time'; const XSD_DATE = 'date'; const XSD_G_YEAR_MONTH = 'gYearMonth'; const XSD_G_YEAR = 'gYear'; const XSD_G_MONTH_DAY = 'gMonthDay'; const XSD_G_DAY = 'gDay'; const XSD_G_MONTH = 'gMonth'; const XSD_HEX_BINARY = 'hexBinary'; const XSD_BASE64_BINARY = 'base64Binary'; const XSD_ANY_URI = 'anyURI'; const XSD_NORMALIZED_STRING = 'normalizedString'; const XSD_TOKEN = 'token'; const XSD_LANGUAGE = 'language'; const XSD_NMTOKEN = 'NMTOKEN'; const XSD_NAME = 'name'; const XSD_NC_NAME = 'NCName'; const XSD_NCNAME = 'NCName'; const XSD_INTEGER = 'integer'; const XSD_NON_POSITIVE_INTEGER = 'nonPositiveInteger'; const XSD_NEGATIVE_INTEGER = 'negativeInteger'; const XSD_LONG = 'long'; const XSD_INT = 'int'; const XSD_SHORT = 'short'; const XSD_BYTE = 'byte'; const XSD_NON_NEGATIVE_INTEGER = 'nonNegativeInteger'; const XSD_UNSIGNED_LONG = 'unsignedLong'; const XSD_UNSIGNED_INT = 'unsignedInt'; const XSD_UNSIGNED_SHORT = 'unsignedShort'; const XSD_UNSIGNED_BYTE = 'unsignedByte'; const XSD_POSITIVE_INTEGER = 'positiveInteger'; const RDF_XML_LITERAL = 'XMLLiteral'; /** * Get RDF Type. * * @return string RDF type QName. */ public function string() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_STRING); } public function boolean() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_BOOLEAN); } public function decimal() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_DECIMAL); } public function float() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_FLOAT); } public function double() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_DOUBLE); } public function dateTime() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_DATE_TIME); } public function time() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_TIME); } public function date() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_DATE); } public function gYearMonth() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_G_YEAR_MONTH); } public function gYear() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_G_YEAR); } public function gMonthDay() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_G_MONTH_DAY); } public function gDay() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_G_DAY); } public function gMonth() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_G_MONTH); } public function hexBinary() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_HEX_BINARY); } public function base64Binary() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_BASE64_BINARY); } public function anyURI() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_ANY_URI); } public function normalizedString() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_NORMALIZED_STRING); } public function token() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_TOKEN); } public function language() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_LANGUAGE); } public function NMTOKEN() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_NMTOKEN); } public function name() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_NAME); } public function NCName() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_NC_NAME); } public function integer() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_INTEGER); } public function nonPositiveInteger() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_NON_POSITIVE_INTEGER); } public function negativeInteger() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_NEGATIVE_INTEGER); } public function long() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_LONG); } public function int() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_INT); } public function short() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_SHORT); } public function byte() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_BYTE); } public function nonNegativeInteger() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_NON_NEGATIVE_INTEGER); } public function unsignedLong() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_UNSIGNED_LONG); } public function unsignedInt() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_UNSIGNED_INT); } public function unsignedShort() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_UNSIGNED_SHORT); } public function unsignedByte() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_UNSIGNED_BYTE); } public function positiveInteger() { return new Ficus_QName(self::NS_XML_SCHEMA, self::XSD_POSITIVE_INTEGER); } public function XMLLiteral() { return new Ficus_QName(self::NS_RDF, self::RDF_XML_LITERAL); } } ?> ficus/RDF/Triple.php100644 1751 144 4300 10645132217 7747 SUMI Masafumi * @version $Id: Triple.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_Triple */ interface Ficus_Triple { /** * set subject node. * * @param $subject string subject. */ public function setSubject($subject); /** * get subject node. * * @return string subject. */ public function subject(); /** * set predicate node. * * @param $predicate string predicate. */ public function setPredicate($predicate); /** * get predicate node. * * @return string predicate. */ public function predicate(); /** * set object node. * * @param $object string object. */ public function setObject($object); /** * get object node. * * @return string object. */ public function object(); /** * compare. * * @param $triple Triple another triple. */ public function compare($triple); /** * equals. * * @param $triple Triple another triple. * @see Ficus_Node */ public function equals($triple); /** * match nodes. * * @param $subject Ficus_Node subject node * @param $predicate Ficus_Node predicate node * @param $object Ficus_Node object node * @return boolean true if match. */ //public function match($subject, $predicate, $object); } ?> ficus/XML/QName.php100644 1751 144 6715 10645132217 7552 SUMI Masafumi * @version $Id: QName.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); require_once("ficus/lang/Types.php"); /** * @class Ficus_QName */ class Ficus_QName { /** * namespace uri. */ protected $uri = null; /** * localPart. */ protected $localPart = null; /** * constructor. * * @param $uri string string of uri. * @param $localPart string string of localPart. */ public function __construct($uri, $localPart) { Ficus_Assert::isPrimitiveType($uri, "string"); Ficus_Assert::isPrimitiveType($localPart, "string"); $this->uri = $uri; $this->localPart = $localPart; } /** * get uri namespace. * * @return String of uri. */ public function uri() { return $this->uri; } /** * get uri namespace. * * @return String of namespace uri. */ public function namespace() { return $this->uri; } /** * get localPart. * * @return String of localPart. */ public function localPart() { return $this->localPart; } /** * get localName. * * @return String of localName. * @see Ficus_QName::localPart */ public function localName() { return $this->localPart; } /** * get expanded name. * * @return String of qname. */ public function expandedName() { return $this->uri . $this->localPart; } /** * compare qname. * * @param $qname Ficus_QName or string another qname. * @return int */ public function compare($qname) { if (($cmp = strcmp($this->uri, $qname->uri)) == 0) { return strcmp($this->localPart, $qname->localPart); } return $cmp; } /** * equals qname. * * @param $qname Ficus_QName or string another qname. * @return boolean return true if equals else return false. */ public function equals($qname) { return ($this->uri == $qname->uri) && ($this->localPart == $qname->localPart); } /** * QName toString. * * @return string of QName. */ public function toString() { return $this->expandedName(); } /** * QName toString. * * @return string of QName. */ public function __toString() { return $this->expandedName(); } /** * is Empty * * @return boolean return true if empty */ public function isEmpty(){ if(empty($this->uri) && empty($this->localPart)){ return true; } return false; } } ?> ficus/XML/NamespacePrefixAlreadyExistException.php100644 1751 144 2275 10645132217 16016 SUMI Masafumi * @version $Id: NamespacePrefixAlreadyExistException.php 2 2007-07-11 10:37:48Z ishitoya $ * Namespace prefix already exist. */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_NamespacePrefixAlreadyExistException */ class Ficus_NamespacePrefixAlreadyExistException extends Ficus_Exception { } ?> ficus/XML/XMLUtils.php100644 1751 144 15434 10645132217 10250 SUMI Masafumi * @version $Id: XMLUtils.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once('ficus/lang/Unicode.php'); /** * @class Ficus_XMLUtils */ class Ficus_XMLUtils { /** * @var $nameStartChars array. */ static $nameStartChars; /** * @var $nameChars array. */ static $nameChars; /** * @var $nCNameStartChars array. */ static $nCNameStartChars; /** * @var $nCNameChars array. */ static $nCNameChars; /** * Char range compare. * * @param $a array of char range. * @param $b array of char range. * @return int see strcmp. */ static function rangeComp($a, $b) { if ($a[0] == $b[0]) { return 0; } return ($a[0] < $b[0]) ? -1 : 1; } /** * Get name start char. * * @return array of name start char ranges. */ static function getNameStartChar() { if (!isset(self::$nameStartChars)) { self::$nameStartChars = array_merge(self::getNCNameStartChar(), array(array(0x3A, 0x3A))); // : usort(self::$nameStartChars, array('Ficus_XMLUtils', 'rangeComp')); } return self::$nameStartChars; } /** * Get no colon name start char. * * @return array of no colon name start char ranges. */ static function getNCNameStartChar() { if (!isset(self::$nCNameStartChars)) { self::$nCNameStartChars = array( array(0x41, 0x5A), // A-Z array(0x5F, 0x5F), // _ array(0x61, 0x7A), // a-z array(0xC0, 0xD6), array(0xD8, 0xF6), array(0xF8, 0x2FF), array(0x370, 0x37D), array(0x37F, 0x1FFF), array(0x200C, 0x200D), array(0x2070, 0x218F), array(0x2C00, 0x2FEF), array(0x3001, 0xD7FF), array(0xF900, 0xFDCF), array(0xFDF0, 0xFFFD), array(0x10000, 0xEFFFF)); } return self::$nCNameStartChars; } /** * Get name char. * * @return array of name char ranges. */ static function getNameChar() { if (!isset(self::$nameChars)) { self::$nameChars = array_merge(self::getNCNameChar(), array(array(0x3A, 0x3A))); // : usort(self::$nameChars, array('Ficus_XMLUtils', 'rangeComp')); } return self::$nameChars; } /** * Get no colon name char. * * @return array of no colon name char ranges. */ static function getNCNameChar() { if (!isset(self::$nameStartChars)) { $nameStartChar = array ( array(0x2D, 0x2D), // - array(0x2E, 0x2E), // . array(0x30, 0x39), // 0-9 array(0xB7, 0xB7), array(0x0300, 0x036F), array(0x203F, 0x2040) ); self::$nCNameChars = array_merge(self::getNCNameStartChar(), $nameStartChar); usort(self::$nCNameChars, array('Ficus_XMLUtils', 'rangeComp')); } return self::$nCNameChars; } /** * Validate NCName. * * @param $utf string of utf. * @param $encoding string of unicode encoding name. * @return boolean true if validate. */ static public function validateNCName($utf, $encoding = Ficus_Unicode::UTF8) { $nCNameCharRanges = self::getNCNameStartChar(); $ret = ''; for ($i = 0; $i < mb_strlen($utf, $encoding); $i++) { $c = mb_substr($utf, $i, 1, $encoding); // Check NCName char ranges. $unicode = Ficus_Unicode::getUnicode($c, $encoding); $outOfRange = true; foreach ($nCNameCharRanges as $crange) { if ($crange[0] <= $unicode && $unicode <= $crange[1]) { $outOfRange = false; break; } else if ($unicode < $crange[0]) { break; } } if ($outOfRange) { return false; } $nCNameCharRanges = self::getNCNameChar(); } return true; } /** * Encode URI. * * not implemented. * * @param $utf string of utf. * @param $encoding string of unicode encoding name. * @return string of encoded NCName. */ static public function encodeURI($utf, $encoding = Ficus_Unicode::UTF8) { //$URICharRanges = self::getURIChar(); $nCNameCharRanges = self::getNCNameStartChar(); $ret = ''; for ($i = 0; $i < mb_strlen($utf, $encoding); $i++) { $c = mb_substr($utf, $i, 1, $encoding); // Check NCName char ranges. $unicode = Ficus_Unicode::getUnicode($c, $encoding); $outOfRange = true; foreach ($nCNameCharRanges as $crange) { if ($crange[0] <= $unicode && $unicode <= $crange[1]) { $outOfRange = false; break; } else if ($unicode < $crange[0]) { break; } } if ($outOfRange) { // encode. $hex = strtoupper(bin2hex($c)); $hex = (strlen($hex) % 2 == 0) ? $hex : '0' . $hex; $c = '%' . join('%', str_split($hex, 2)); } $ret .= $c; //$URICharRanges = self::getURIChar(); $nCNameCharRanges = self::getNCNameChar(); } return $ret; } /** * Decode NCName. * * Decoding indiscriminately. * * @param $nCName string of NCName. * @param $encoding string of unicode encoding name. * @return string of decoded NCName. */ static public function decodeURI($nCName) { return rawurldecode($nCName); } } ?> ficus/XML/NamespacePrefixes.php100644 1751 144 16007 10645132217 12166 SUMI Masafumi * @version $Id: NamespacePrefixes.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/XML/NamespacePrefixAlreadyExistException.php"); require_once("ficus/lang/Types.php"); /** * @class Ficus_NamespacePrefixes */ final class Ficus_NamespacePrefixes implements IteratorAggregate { /** * namespaces. */ private $namespaces; /** * auto prefix number. */ private $prefixNumber; /** * constructor. */ public function __construct() { $this->namespaces = array(); $this->prefixNumber = 1; } /** * add namespace. * * You can not set a prefix that already exist on a namespace. * But you can set different prefix on same namespace. * * @param $qName string namespace uri. * @param $prefix string namespace prefix. */ public function addNamespaceOf($qName, $prefix = null) { Ficus_Assert::typeHinting("Ficus_QName", $qName); $this->addNamespace($qName->uri(), $prefix); } /** * add namespace. * * You can not set a prefix that already exist on a namespace. * But you can set different prefix on same namespace. * When a prefix is not specified, It will automaticaly search same * namespace prefix. And if it is a new namespace, sets new prefix. * * @param $namespace string namespace uri. * @param $prefix string namespace prefix. * @throw Ficus_NamespacePrefixAlreadyExistException namespace prefix already exist. */ public function addNamespace($namespace, $prefix = null) { if ($prefix == null) { $alreadyPrefix = array_search($namespace, $this->namespaces); if ($alreadyPrefix !== FALSE) { $prefix = $alreadyPrefix; } else { $prefix = $this->newPrefix(); } } $already = $this->getNamespace($prefix); if ($already == $namespace) { return; } if ($already !== NULL) { throw new Ficus_NamespacePrefixAlreadyExistException( "already prefix: " + $prefix + ", existing namespace: " + $this->namespaces[$prefix] + ", tried to add namespace : " + $namespaces ); } $this->namespaces[$prefix] = $namespace; } /** * get namespace. * * @param $prefix string namespace prefix. * @return namespace or NULL if not found. */ public function getNamespace($prefix) { if(isset($this->namespaces[$prefix])){ return $this->namespaces[$prefix]; } return null; } /** * get prefix. * * @param $namespace string namespace uri. * @return array of namespace prefix or FALSE if not found. */ public function getPrefix($namespace) { $prefix = array_search($namespace, $this->namespaces); return $prefix !== FALSE ? $prefix : NULL; } /** * get prefixed qname. * * @param $qname string namespace uri. * @return array of namespace prefix or FALSE if not found. */ public function getPrefixedQName($qname) { return $this->getPrefix($qname->uri()) . ":" . $qname->localPart(); } /** * get prefix. * * @param $namespace string namespace uri. * @return array of namespace prefix or FALSE if not found. */ public function getPrefixes($namespace) { return array_keys($this->namespaces, $namespace); } /** * contains namespace. * * @param $namespace string namespace uri. */ public function contains($namespace) { return array_search($namespace, $this->namespaces) !== FALSE; } /** * contains namespace prefix. * * @param $prefix string namespace prefix. */ public function containsPrefix($prefix) { return array_key_exists($prefix, $this->namespaces); } /** * create new prefix. * * @return prefix string. */ private function newPrefix() { do { $newPrefix = sprintf("ns%d", $this->prefixNumber++); } while (array_key_exists($newPrefix, $this->namespaces)); return $newPrefix; } /** * extract namespaces in qnames. * * @param $qnames array array of Ficus_PrefixedQName. */ public function extractNamespaces($qnames) { foreach ($qnames as $qname) { if ($qname instanceof Ficus_PrefixedQName) { $this->addNamespace($qname->uri(), $qname->prefix()); } else { $this->addNamespace($qname->uri(), $this->newPrefix()); } } } /** * add prefix to array of QName. * * @param $qnames array qnames. * @return array prefixed qnames. */ public function addPrefixToQNames($qnames) { $prefixedQNames = array(); foreach ($qnames as $qname) { array_push($prefixedQNames, $this->addPrefixToQName($qname)); } return $prefixedQNames; } /** * add prefix to QName. * * @param $qname string qname. */ public function addPrefixToQName($qname) { if (($prefix = $this->getPrefix($qname->uri())) == NULL) { $prefix = $this->newPrefix(); } return new Ficus_PrefixedQName($qname->uri(), $qname->localPart(), $prefix); } /** * get iterator. * * return ArrayIterator of namespaces iterator. */ public function getIterator() { $ao = new ArrayObject($this->namespaces); return $ao->getIterator(); } /** * remove namespace repetition. * * return Ficus_NamespacePrefixes namespace repetition was removed. */ public function pack() { $packedNamespaces = new Ficus_NamespacePrefixes(); foreach ($this as $prefix => $uri) { if (!$packedNamespaces->contains($uri)) { $newPrefix = $prefix; while ($packedNamespaces->containsPrefix($newPrefix)) { $newPrefix = sprintf("ns%d", $packedNamespaces->prefixNumber++); } $packedNamespaces->addNamespace($uri, $newPrefix); } } return $packedNamespaces; } } ?> ficus/XML/PrefixedQName.php100644 1751 144 4651 10645132217 11236 SUMI Masafumi * @version $Id: PrefixedQName.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/lang/Types.php"); require_once("ficus/XML/QName.php"); /** * @class Ficus_PrefixedQName */ class Ficus_PrefixedQName extends Ficus_QName { /** * prefix. */ protected $prefix = NULL; /** * constructor. * * @param $uri string String of uri. * @param $localPart string String of localPart. * @param $prefix string String of prefix. */ public function __construct($uri, $localPart, $prefix) { parent::__construct($uri, $localPart); Ficus_Assert::isPrimitiveType($prefix, "string"); $this->prefix = $prefix; } /** * add prefix to qname. * * @param $qname Ficus_QName. * @param $prefix string prefix. * @return Ficus_PrefixedQName */ public static function addPrefix($qname, $prefix) { return new Ficus_PrefixedQName($qname->uri, $qname->localPart, $prefix); } /** * get prefix. * * @return String of prefix. */ public function prefix() { return $this->prefix; } /** * get prefixed name. * * @return String of qname. */ public function prefixedName() { return $this->prefix . ":" . $this->localPart; } /** * QName toString. * * @return string of QName. */ public function toString() { return $this->prefixedName(); } /** * QName toString. * * @return string of QName. */ public function __toString() { return $this->prefixedName(); } } ?> ficus/cli/CommandLineApplication.php100644 1751 144 4630 10647426442 13234 ISHITOYA Kentaro * @version $Id: CommandLineApplication.php 15 2007-07-18 15:02:48Z ishitoya $ * * Command line application */ require_once("ficus/cli/CommandLineArgument.php"); require_once("ficus/cli/CommandLineCommand.php"); require_once("ficus/cli/CommandLineManager.php"); require_once("ficus/cli/CommandLineCommandAnnotation.php"); /** * @class Soya_CommandLineApplication */ abstract class Soya_CommandLineApplication{ protected $commandManager = null; protected function __construct(){ $this->commandManager = new Soya_CommandLineManager($this); } public function execute($arguments){ if(count($arguments) == 0){ $arguments = array(); } $this->commandManager->execute($arguments); } public function __call($name, $params){ if(preg_match('/set(.+)/', $name, $regs)){ $name = $regs[1]; $name = strtolower($name[0]) . substr($name, 1); if(property_exists($this, $name)){ $this->{$name} = $params[0]; }else{ throw new Ficus_PropertyNotFoundException("property $name is not found in " . get_class($this) . "."); } } } /** * show help * @CommandLineCommand( * type = "Executable", * short = {?, h}, * long = {help}) */ public abstract function help(); /** * show version * @CommandLineCommand( * type = "Executable", * short = {V}, * long = {version}) */ public abstract function version(); } ?> ficus/cli/subversion/SVNStatusLine.php100644 1751 144 13251 10645132217 13552 ISHITOYA Kentaro * @version $Id: SVNStatusLine.php 2 2007-07-11 10:37:48Z ishitoya $ * * svn stasus line like * U hogehoge.php * @see http://subversion.bluegate.org/doc/re30.html */ require_once("ficus/io/File.php"); /** * @class Ficus_SVNStatusLine */ class Ficus_SVNStatusLine { const STATUS_ADDED = "A"; const STATUS_DELETED = "D"; const STATUS_UPDATED = "U"; const STATUS_MERGE = "G"; const STATUS_CONFLICT = "C"; const STATUS_NONE = "_"; const PATTERN = "/(A|D|U|G|C|_)(A|D|U|G|C| )\s+(.*)/"; /** * @var $fileStatus string status of file */ private $fileStatus; /** * @var $propertyStatus string status of property */ private $propertyStatus; /** * @var $file Ficus_File file */ private $file; /** * constructor * @param $line string status line */ public function __construct($line){ $this->parseLine($line); } /** * parse one line * @param $line string status line */ protected function parseLine($line){ if(preg_match(self::PATTERN, $line, $regs)){ $this->fileStatus = $regs[1]; $this->propertyStatus = $regs[2]; $this->file = new Ficus_File($regs[3]); }else{ throw new Ficus_IllegalArgumentException("this is not a subversion status line. $line"); } } /** * get status * @return string status part eg:UU _U CM etc */ public function getStatus(){ return $this->fileStatus . $this->propertyStatus; } /** * get file status * @return string status of file */ public function getFileStatus(){ return $this->fileStatus(); } /** * get property status * @param string status of property */ public function getPropertyStatus(){ return $this->propertyStatus; } /** * get file object * @return Ficus_File file */ public function getFile(){ return $this->file; } /** * is either file of property Added * @return boolean true if either file or property added */ public function isAdded(){ return $this->isFileAdded() || $this->isPropertyAdded(); } /** * is file Added * @return boolean true if file added */ public function isFileAdded(){ return $this->fileStatus == self::STATUS_ADDED; } /** * is property Added * @return boolean true if property added */ public function isPropertyAdded(){ return $this->propertyStatus == self::STATUS_ADDED; } /** * is deleted either file or property * @return boolean true if file or property deleted */ public function isDeleted (){ return $this->isFileDeleted() || $this->propertyDeleted(); } /** * is file deleted * @return boolean true if file deleted */ public function isFileDeleted (){ return $this->fileStatus == self::STATUS_DELETED; } /** * is property deleted * @return boolean true if property deleted */ public function isPropertyDeleted (){ return $this->propertyStatus == self::STATUS_DELETED; } /** * is updated * @return boolean true if anything updated */ public function isUpdated(){ return $this->isFileUpdated() || $this->isPropertyUpdated(); } /** * is file updated * @return boolean true when file updated */ public function isFileUpdated(){ return $this->fileStatus == self::STATUS_UPDATED; } /** * is property updated * @return boolean true when property updated */ public function isPropertyUpdated(){ return $this->propertyStatus == self::STATUS_UPDATED; } /** * is property or file merged * @return boolean true if property or file merged */ public function isMerged(){ return $this->isFileMerged() || $this->isPropertyMerged(); } /** * is file merged * @return boolean */ public function isFileMerged(){ return $this->fileStatus == self::STATUS_MERGE; } /** * is property merged * @return boolean true if property merged */ public function isPropertyMerged(){ return $this->propertyStatus == self::STATUS_MERGE; } /** * is something conflicted * @return boolean */ public function isConflicted(){ return $this->isFileConflicted() || $this->isPropertyConflicted(); } /** * is file conflicted * @return boolean */ public function isFileConflicted(){ return $this->fileStatus == self::STATUS_CONFLICT; } /** * is property conflicted * @return boolean true if property conflicted */ public function isPropertyConflicted(){ return $this->propertyStatus == self::STATUS_CONFLICT; } } ?> ficus/cli/subversion/SVNUpdate.php100644 1751 144 6401 10645132217 12660 ISHITOYA Kentaro * @version $Id: SVNUpdate.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes svn updat */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/subversion/SVNConstants.php"); require_once("ficus/lang/Runtime.php"); /** * @class Ficus_SVNUpdate */ class Ficus_SVNUpdate implements Ficus_SVNConstants { const COMMAND = "update"; /** * @var $repository string where to update */ private $repository = ""; /** * @var $ignoreExternals boolean wether to use --ignore-externals */ private $ignoreExternals = false; /** * constructor * @param $repository string where to update * @param $ignoreExternals boolean use option */ public function __construct($repository, $ignoreExternals = false){ $this->repository = $repository; $this->ignoreExternals = $ignoreExternals; } /** * execute command * @return array of Ficus_SVNConstants */ public function execute(){ if(empty($this->repository)){ throw new Ficus_IllegalArgumentException("repository is empty"); } $command = $this->createCommand(); $output = Ficus_Runtime::exec($command); $error = $output[Ficus_Runtime::ERROR]; unset($output[Ficus_Runtime::ERROR]); if(empty($error) == false){ throw new Ficus_IllegalArgumentException("some error occured. message:" . $error); } return $this->parseResult($output); } /** * parse result to status line object array * @param $output string result * @return array of Ficus_SVNStatusLine */ private function parseResult($output){ $result = array(); foreach($output as $line){ try{ $result[] = new Ficus_SVNStatusLine($line); }catch(Ficus_IllegalArgumentException $e){ continue; } } $last = $output[count($output) - 1]; if(preg_match("/[0-9]+/", $last, $regs)){ $result[self::REVISON] = $regs[0]; } return $output; } /** * create command * @return string command */ private function createCommand(){ $command = self::SVN . " "; $command .= self::COMMAND . " "; $command .= $this->repository . " "; if($this->ignoreExternals){ $command .= self::IGNORE_EXTERNALS; } return $command; } } ?> ficus/cli/subversion/SVNAdd.php100644 1751 144 4742 10645132217 12134 ISHITOYA Kentaro * @version $Id: SVNAdd.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes svn add */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/subversion/SVNConstants.php"); require_once("ficus/lang/Runtime.php"); /** * @class Ficus_SVNAdd */ class Ficus_SVNAdd implements Ficus_SVNConstants { const COMMAND = "add"; /** * @var $fileset array of file to add */ private $fileset = array(); /** * execute svn add * @return string output of svn add */ public function execute(){ if(empty($this->fileset)){ throw new Ficus_IllegalArgumentException("repository is empty"); } $command = $this->createCommand(); $output = Ficus_Runtime::exec($command); $error = $output[Ficus_Runtime::ERROR]; unset($output[Ficus_Runtime::ERROR]); if(empty($error) == false){ throw new Ficus_IllegalArgumentException("some error occured. message:" . $error); } return $this->parseResult($output); } /** * add file * @param $file string file name */ public function addFile($file){ $this->fileset[] = $file; } /** * parse result do nothing. * @param $output string * @return string result. */ private function parseResult($output){ return $output; } /** * create command * @return string command */ private function createCommand(){ $command = self::SVN . " "; $command .= self::COMMAND . " "; foreach($this->fileset as $file){ $command .= $file . " "; } return $command; } } ?> ficus/cli/subversion/SVNCommit.php100644 1751 144 5733 10645132217 12675 ISHITOYA Kentaro * @version $Id: SVNCommit.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes svn commit */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/subversion/SVNConstants.php"); require_once("ficus/lang/Runtime.php"); /** * @class Ficus_SVNCommit */ class Ficus_SVNCommit implements Ficus_SVNConstants { const COMMAND = "commit"; const MESSAGE = "-m"; /** * @var $message string commit message */ private $message = ""; /** * @var $fileset array of files to commit */ private $fileset = array(); /** * constructor * @param $message string commit message */ public function __construct($message){ $this->message = $message; } /** * execute command * @return array of output */ public function execute(){ if(empty($this->fileset)){ throw new Ficus_IllegalArgumentException("repository is empty"); } if(empty($this->message)){ throw new Ficus_IllegalArgumentException("message is empty"); } $command = $this->createCommand(); $output = Ficus_Runtime::exec($command); $error = $output[Ficus_Runtime::ERROR]; unset($output[Ficus_Runtime::ERROR]); if(empty($error) == false){ throw new Ficus_IllegalArgumentException("some error occured. message:" . $error); } return $this->parseResult($output); } /** * add file to commit * @param $file string path to file */ public function addFile($file){ $this->fileset[] = $file; } /** * parse result do nothing * @param $output array of result * @return array of result */ private function parseResult($output){ return $output; } /** * create command line * @return string command */ private function createCommand(){ $command = self::SVN . " "; $command .= self::COMMAND . " "; foreach($this->fileset as $file){ $command .= $file . " "; } $command .= self::MESSAGE . " \"" . $this->message . "\""; return $command; } } ?> ficus/cli/subversion/SVNConstants.php100644 1751 144 2257 10645132217 13417 ISITOYA Kentaro * @version $Id: SVNConstants.php 2 2007-07-11 10:37:48Z ishitoya $ * * subversion constants */ /** * @interface Ficus_SVNConstants */ interface Ficus_SVNConstants { const SVN = "svn"; const SVNLOOK = "svnlook"; const SVNADMIN = "svnadmin"; const IGNORE_EXTERNALS = "--ignore-externals"; const REVISION = "revision"; } ?> ficus/cli/subversion/SVNLookChanged.php100644 1751 144 6144 10645132217 13620 ISITOYA Kentaro * @version $Id: SVNLookChanged.php 2 2007-07-11 10:37:48Z ishitoya $ * * wrapper class for executing svnlook changed command */ require_once("ficus/cli/subversion/SVNConstants.php"); require_once("ficus/cli/subversion/SVNStatusLine.php"); require_once("ficus/lang/Runtime.php"); require_once("ficus/exception/CommandNotFoundException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_SVNLookChanged */ class Ficus_SVNLookChanged implements Ficus_SVNConstants { const COMMAND = "changed"; /** * @var $repository string repository to look up. */ private $repository = null; /** * @var $revision string revision number */ private $revision = null; /** * constructor * @param $repository string repository to look in * @param $revision string revision numver */ public function __construct($repository, $revision = null){ $this->repository = $repository; $this->revision = $revision; } /** * execute * @return array of Ficus_StatusLine */ public function execute(){ if(Ficus_Runtime::isCommandExists(self::SVNLOOK) == false){ throw new Ficus_CommandNotFoundException("command svnlook is not found in path"); } $command = $this->createCommand(); $output = Ficus_Runtime::exec($command); $error = $output[Ficus_Runtime::ERROR]; unset($output[Ficus_Runtime::ERROR]); if(empty($error) == false){ throw new Ficus_IllegalArgumentException($this->repository . " or " . $this->revision . " is illegal. cause of error :$error"); } $result = array(); foreach($output as $line){ try{ $result[] = new Ficus_SVNStatusLine($line); }catch(Ficus_IllegalArgumentException $e){ continue; } } return $result; } /** * create command * @return string created command */ private function createCommand(){ $command = self::SVNLOOK . " " . self::COMMAND; $command .= " " . $this->repository; if(is_null($this->revision) == false){ $command .= " -r " . $this->revision; } return $command; } } ?> ficus/cli/phing/PhingTestResult.php100644 1751 144 7061 10645132217 13064 ISHITOYA Kentaro * @version $Id: PhingTestResult.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes phing test result (depends on PHPUnit result formatting) */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/phing/Phing.php"); require_once("ficus/lang/Runtime.php"); /** * @class Ficus_PhingTestResult */ class Ficus_PhingTestResult { protected $fatalError = ""; protected $warnings = array(); protected $notices = array(); protected $failureCount = 0; protected $testCount = 0; protected $errorCount = 0; public function __construct($output){ $error = $output[Ficus_Runtime::ERROR]; unset($output[Ficus_Runtime::ERROR]); $this->parseError($error); $this->parseOutput($output); } protected function parseError($output){ $error = explode("\n", $output); foreach($error as $line){ if(preg_match('/fatal error/i', $line)){ $this->fatalError = $line; }else if(preg_match('/warning/i', $line)){ $this->warnings[]= $line; }else if(preg_match('/notice/i', $line)){ $this->notices[] = $line; } } } protected function parseOutput($output){ foreach($output as $line){ if(preg_match('/Tests Run: ([0-9]+)[^0-9]+([0-9]+)[^0-9]+([0-9]+)/i', $line, $regs)){ $this->testCount = $regs[1]; $this->failureCount = $regs[2]; $this->errorCount = $regs[3]; } } } public function getFatalError(){ return $this->fatalError; } public function getWarnings(){ return $this->warnings; } public function getNotices(){ return $this->notices; } public function getWarningCount(){ return count($this->warnings); } public function getNoticeCount(){ return count($this->notices); } public function getFailureCount(){ return $this->failureCount; } public function getTestCount(){ return $this->testCount; } public function getErrorCount(){ return $this->errorCount; } public function isSucceeded(){ return empty($this->fatalError); } public function __toString(){ $str = $this->getTestCount() . " tests executed.\n"; $str .= " " . $this->getFailureCount() . " Failures.\n"; $str .= " " . $this->getErrorCount() . " Errors.\n"; $str .= "Additionaly, while executing test task,\n"; $str .= " " . $this->getWarningCount() . " of Warnings reported.\n"; $str .= " " . $this->getNoticeCount() . " of Notices reported.\n"; $str .= "\n"; return $str; } } ?> ficus/cli/phing/PhingTest.php100644 1751 144 4560 10645132217 11666 ISHITOYA Kentaro * @version $Id: PhingTest.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes phing test (depends on PHPUnit result formatting) */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/phing/Phing.php"); require_once("ficus/cli/phing/PhingTestResult.php"); require_once("ficus/lang/Runtime.php"); /** * @class Ficus_PhingTest */ class Ficus_PhingTest extends Ficus_Phing { const COMMAND = "test"; const PACKAGE = "-Dpackage="; /** * @var $package string package name */ private $package; /** * constructor * @param $root string root dir * @param $package string package name */ public function __construct($root, $package = null){ parent::__construct($root); $this->package = $package; } /** * execute. this is depends on phpunit2 result format. * @return Ficus_PhingTestResult result of phing test. */ public function onExecute(){ $command = $this->createCommand(); $output = Ficus_Runtime::exec($command); $error = $output[Ficus_Runtime::ERROR]; unset($output[Ficus_Runtime::ERROR]); $result = new Ficus_PhingTestResult($output); return $result; } /** * create command * @return string command */ protected function createCommand(){ $command = parent::createCommand(); $command .= self::COMMAND . " "; if(empty($this->package) == false){ $command .= self::PACKAGE . $this->package; } return $command; } } ?> ficus/cli/phing/Phing.php100644 1751 144 4527 10645132217 11031 ISHITOYA Kentaro * @version $Id: Phing.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes phing abstract class */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/phing/PhingConstants.php"); require_once("ficus/lang/Runtime.php"); /** * @class Ficus_Phing */ abstract class Ficus_Phing implements Ficus_PhingConstants { const FILE = "-f"; /** * @var $root string root dir */ protected $root; /** * @var $buildxml string build file */ protected $buildxml = null; /** * constructor * @param $root string root directory to execute phing */ protected function __construct($root){ $this->root = $root; } /** * set buildxml * @param $buildxml string buildxml name */ public function setBuildXML($buildxml){ $this->buildxml = $buildxml; } /** * execute * @return misc subclass's return value */ public function execute(){ $preserv = getcwd(); chdir($this->root); $result = $this->onExecute(); chdir($preserv); return $result; } /** * create command * @return string ./phing -f build.xml */ protected function createCommand(){ $command = self::PHING . " "; if(empty($this->buildxml) == false){ $command .= self::FILE . " " . $this->buildxml . " "; } return $command; } /** * execute method * @return misc misc */ protected abstract function onExecute(); } ?> ficus/cli/phing/PhingConstants.php100644 1751 144 2050 10645132217 12713 ISITOYA Kentaro * @version $Id: PhingConstants.php 2 2007-07-11 10:37:48Z ishitoya $ * * subversion constants */ /** * @interface Ficus_PhingConstants */ interface Ficus_PhingConstants { const PHING = "./phing"; } ?> ficus/cli/CommandLineArgument.php100644 1751 144 5243 10647426442 12554 ISHITOYA Kentaro * @version $Id: CommandLineArgument.php 15 2007-07-18 15:02:48Z ishitoya $ * * Command line argument class */ /** * @class Soya_CommandLineArgument */ class Soya_CommandLineArgument{ const PREFIX = "-"; const PREFIX_LONG = "--"; const ARGUMENT_PATTERN = '/(-|--)([^ ]+)/'; private $names = array(); private $value = null; public function __construct($shortNames = array(), $longNames = array()){ $this->names[self::PREFIX] = $shortNames; $this->names[self::PREFIX_LONG] = $longNames; } public function addShortName($name){ $this->names[self::PREFIX] = $name; } public function addLongName($name){ $this->names[self::PREFIX_LONG] = $name; } public function addShortNames($names){ $this->names[self::PREFIX] = array_merge($this->names[self::PREFIX], $names); } public function addLongNames($names){ $this->names[self::PREFIX_LONG] = array_merge($this->name[self::PREFIX_LONG], $names); } public function value(){ return $this->value; } public function check($arguments, $type){ if(empty($this->names[self::PREFIX]) && empty($this->names[self::PREFIX_LONG])){ return false; } reset($arguments); while($argument = next($arguments)){ if(preg_match(self::ARGUMENT_PATTERN, $argument, $regs) == false){ continue; } foreach($this->names[$regs[1]] as $name){ if($regs[2] == $name){ if($type == Soya_CommandLineCommand::PARAMETER){ $this->value = next($arguments); } return true; } } } return false; } } ?>ficus/cli/AbstractCommandExecutor.php100644 1751 144 5651 10647426442 13447 ISHITOYA Kentaro * @version $Id: AbstractCommandExecutor.php 15 2007-07-18 15:02:48Z ishitoya $ * * executes phing abstract class */ require_once("ficus/beans/Bean.php"); require_once("ficus/cli/CommandExecutor.php"); /** * @class Ficus_AbstractCommandExecutor */ abstract class Ficus_AbstractCommandExecutor extends Ficus_Bean implements Ficus_CommandExecutor { /** * @var $root string root dir */ protected $root; /** * @var $root string command */ protected $command; /** * @var $result array of result */ protected $result = array(); /** * @var $error */ protected $error = false; /** * execute * @return misc subclass's return value */ public function execute(){ if($this->isEmptyCommand()){ throw new Ficus_NotReadyException("command is not ready for runch"); } if($this->isEmptyRoot() == false){ $preserv = getcwd(); chdir($this->root); } $this->result = $this->onExecute(); if($this->isEmptyRoot() == false){ chdir($preserv); } $result = $this->processResult(); if($result === false){ $this->error = true; } return $result; } /** * execute method * @return array of result */ protected function onExecute(){ return Ficus_Runtime::exec($this->createCommand()); } /** * process result * @param $result array of result */ protected abstract function processResult(); /** * add option to command string */ protected function addOption($command, $option, $value = null){ if(is_null($value)){ $command .= " $option"; }else{ $command .= " $option $value"; } return $command; } /** * get error stream from current result * @return string error stream */ public function getErrorStream(){ if(isset($this->result[self::RESULT_ERROR])){ return $this->result[self::RESULT_ERROR]; } return ""; } } ?> ficus/cli/CommandLineCommand.php100644 1751 144 3540 10647426442 12346 ISHITOYA Kentaro * @version $Id: CommandLineCommand.php 15 2007-07-18 15:02:48Z ishitoya $ * * Command line command */ /** * @class Soya_CommandLineCommand */ class Soya_CommandLineCommand{ const SIMPLE = "simple"; const PARAMETER = "parameter"; const EXECUTABLE = "executable"; private $argument; private $function; private $name = ""; private $type; public function __construct($name, $type, $function, $argument){ $this->name = $name; $this->type = $type; $this->argument = $argument; $this->function = $function; } public function name(){ return $this->name; } public function argument(){ return $this->argument; } public function type(){ return $this->type; } public function check($args){ return $this->argument->check($args, $this->type); } public function execute(){ if($this->type == self::EXECUTABLE){ call_user_func($this->function, null); } } } ?>ficus/cli/ffmpeg/FFMpeg.php100644 1751 144 7202 10645132217 11220 ISHITOYA Kentaro * @version $Id: FFMpeg.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes ffmpeg abstract class */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/AbstractCommandExecutor.php"); require_once("ficus/cli/ffmpeg/FFMpegConstants.php"); /** * @class Ficus_FFMpeg */ abstract class Ficus_FFMpeg extends Ficus_AbstractCommandExecutor implements Ficus_FFMpegConstants { /** * @var filename target filename */ protected $filename = null; /** * constructor */ public function __construct(){ $this->setCommand(self::FFMPEG); } /** * create command * @return string ./ffmpeg -f build.xml */ protected function createCommand(){ if($this->isEmptyFilename()){ throw new Ficus_NotReadyException("filename is not specified"); } $command = $this->command(); $command = $this->addOption($command, self::INPUT, $this->filename()); return $command; } /** * get trimmed * @param $regs array input * @param $key string key * @return string trimmed string */ protected final function getTrimmed($regs, $key){ return trim($regs[$key]); } /** * calcurate length from string representation time * @param $length string like 00:00:01:0 * @return integer calcurated length in integer */ protected final function calcLength($length){ if(preg_match('/([0-9]+):([0-9]+):([0-9]+)\.([0-9]+)/', $length, $regs)){ $hour = (integer)$this->getTrimmed($regs, 1); $minuite = (integer)$this->getTrimmed($regs, 2); $second = (integer)$this->getTrimmed($regs, 3); $mili = (integer)$this->getTrimmed($regs, 4); $time = 0; $time += $hour * 3600 * 1000; $time += $minuite * 60 * 1000; $time += $second * 1000; $time += $mili; return $time; } return 0; } /** * get size * @param $width integer width * @param $height integer height * @return string size string representation */ protected final function getSizeString($width, $height){ return $width . "x" . $height; } /** * get time string * @param $time integer milisecond * @return string 00:00:00.50 */ protected final function getTimeString($time){ if($time < 0){ return "00:00:00.0"; } $hour = (integer)($time / 1000 / 3600); $time -= $hour * 1000 * 3600; $minuite = (integer)($time / 1000 / 60); $time -= $minuite * 1000 * 60; $second = (integer)($time / 1000); $time -= $second * 1000; $mili = $time; return sprintf("%02d:%02d:%02d.%d", $hour, $minuite, $second, $mili); } } ?> ficus/cli/ffmpeg/FFMpegVideoInfo.php100644 1751 144 5524 10645132217 13030 ISHITOYA Kentaro * @version $Id: FFMpegVideoInfo.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes ffmpeg abstract class */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/ffmpeg/FFMpeg.php"); require_once("ficus/media/video/VideoBean.php"); require_once("ficus/media/audio/AudioBean.php"); /** * @class Ficus_FFMpegVideoInfo */ class Ficus_FFMpegVideoInfo extends Ficus_FFMpeg { /** * video bean */ protected $video = null; /** * audio bean */ protected $audio = null; /** * process result * @return boolean true if no error */ protected function processResult(){ $result = $this->getErrorStream(); if(preg_match('/Duration: (.*?), start: (.*?), bitrate: (.*?) .*?Video: (.*?), (.*?), (.*?)x(.*?), (.*?) /ms', $result, $regs)){ $video = new Ficus_VideoBean(); $audio = new Ficus_AudioBean(); $video->setFilename($this->filename); $audio->setFilename($this->filename); $length = $this->calcLength($this->getTrimmed($regs, 1)); $video->setLength($length); $video->setBitrate($this->getTrimmed($regs, 2)); $video->setCodec($this->getTrimmed($regs, 4)); $video->setColor($this->getTrimmed($regs, 5)); $video->setWidth($this->getTrimmed($regs, 6)); $video->setHeight($this->getTrimmed($regs, 7)); $video->setFps($this->getTrimmed($regs, 8)); $this->video = $video; if(preg_match('/Audio: (.*?), (.*?), (.*?), (.*?) /ms', $result, $regs)){ $audio->setLength($length); $audio->setCodec($this->getTrimmed($regs, 1)); $audio->setFrequency($this->getTrimmed($regs, 2)); $audio->setMethod($this->getTrimmed($regs, 3)); $audio->setBitrate($this->getTrimmed($regs, 4)); $this->audio = $audio; } return true; }else{ return false; } } } ?> ficus/cli/ffmpeg/FFMpegConvertCodec.php100644 1751 144 6661 10645132217 13527 ISHITOYA Kentaro * @version $Id: FFMpegConvertCodec.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes ffmpeg abstract class */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/ffmpeg/FFMpeg.php"); require_once("ficus/media/video/VideoBean.php"); require_once("ficus/media/audio/AudioBean.php"); /** * @class Ficus_FFMpegConvertCodec */ class Ficus_FFMpegConvertCodec extends Ficus_FFMpeg { const DEFAULT_HEIGHT = 240; const DEFAULT_WIDTH = 320; const DEFAULT_AUDIO_FREQUENCY = 44100; const DEFAULT_AUDIO_CHANNELS = 2; const DEFAULT_CODEC = Ficus_VideoConstants::CODEC_FLASH; /** * @var $overwrite boolean */ protected $overwrite = false; /** * @var $output string output filename */ protected $output = null; /** * @var $width integer width */ protected $width = self::DEFAULT_WIDTH; /** * @var $height integer height */ protected $height = self::DEFAULT_HEIGHT; /** * @var $audioFrequency */ protected $audioFrequency = self::DEFAULT_AUDIO_FREQUENCY; /** * @var $audioChannels */ protected $audioChannels = self::DEFAULT_AUDIO_CHANNELS; /** * @var $codec */ protected $codec = self::DEFAULT_CODEC; /** * create command * @return string ./ffmpeg -f build.xml */ protected function createCommand(){ $command = parent::createCommand(); if($this->isEmptyOutput()){ throw new Ficus_NotReadyException("output file name is not specified"); } if($this->overwrite){ $command = $this->addOption($command, self::OVERWRITE); } $size = $this->getSizeString($this->width, $this->height); $command = $this->addOption($command, self::VIDEO_SIZE, $size); $command = $this->addOption($command, self::AUDIO_FREQUENCY, $this->audioFrequency); $command = $this->addOption($command, self::AUDIO_CHANNELS, $this->audioChannels); $filename = basename($this->output); $filename = dirname($this->output) . "\\" . substr($filename, 0, strpos($filename, ".") + 1) . $this->codec; $command = $this->addOption($command, $filename); return $command; } /** * process result * @return boolean true if no error */ protected function processResult(){ $result = $this->getErrorStream(); if(preg_match('/muxing overhead/', $result)){ return true; }else{ return false; } } } ?> ficus/cli/ffmpeg/FFMpegCreateThumbnail.php100644 1751 144 11135 10645132217 14230 ISHITOYA Kentaro * @version $Id: FFMpegCreateThumbnail.php 2 2007-07-11 10:37:48Z ishitoya $ * * executes ffmpeg abstract class */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/cli/ffmpeg/FFMpeg.php"); require_once("ficus/media/video/VideoBean.php"); require_once("ficus/media/audio/AudioBean.php"); /** * @class Ficus_FFMpegCreateThumbnail */ class Ficus_FFMpegCreateThumbnail extends Ficus_FFMpeg { const DEFAULT_HEIGHT = 160; const DEFAULT_WIDTH = 120; const DEFAULT_START = 0; const DEFAULT_DURATION = 1; const DEFAULT_FORMAT = Ficus_ImageConstants::FORMAT_JPEG; const DEFAULT_FILENAME_FORMAT = "{\$num}"; /** * @var $overwrite boolean */ protected $overwrite = false; /** * @var $width integer width */ protected $width = self::DEFAULT_WIDTH; /** * @var $height integer height */ protected $height = self::DEFAULT_HEIGHT; /** * @var $start */ protected $start = self::DEFAULT_START; /** * @var $end */ protected $end = null; /** * @var $offset */ protected $offset = self::DEFAULT_START; /** * @var $num */ protected $num = 0; /** * @var $duration */ protected $duration = self::DEFAULT_DURATION; /** * @var $format */ protected $format = self::DEFAULT_FORMAT; /** * @var $outputDirectory */ protected $outputDirectory = null; /** * @var $outputFilenameFormat */ protected $filenameFormat = self::DEFAULT_FILENAME_FORMAT; /** * execute method * @return array of result */ protected function onExecute(){ if($this->isEmptyEnd()){ $command = new Ficus_FFMpegVideoInfo(); $command->setFilename($this->filename()); $command->execute(); $this->setEnd($command->video()->length()); } $offset = $this->start; $this->num = 0; while($offset < $this->end){ $this->offset = $this->getTimeString($offset); $this->result = Ficus_Runtime::exec($this->createCommand()); if($this->processResult() == false){ return false; } $this->num++; $offset += $this->duration * 1000; } return true; } /** * create command * @return string ./ffmpeg -f build.xml */ protected function createCommand(){ $command = parent::createCommand(); if($this->overwrite){ $command = $this->addOption($command, self::OVERWRITE); } $size = $this->getSizeString($this->width, $this->height); $command = $this->addOption($command, self::FORMAT, self::FORMAT_IMAGE); $command = $this->addOption($command, self::OFFSET, $this->offset); $command = $this->addOption($command, self::VIDEO_FRAMES, 1); $command = $this->addOption($command, self::VIDEO_SIZE, $size); if(is_dir($this->outputDirectory) == false){ mkdir($this->outputDirectory, 0755, true); } $filename = str_replace('{$num}', $this->num, $this->filenameFormat); $filename .= "." . $this->format; $filename = $this->outputDirectory . "\\$filename"; $command = $this->addOption($command, $filename); return $command; } /** * process result * @return boolean true if no error */ protected function processResult(){ if($this->result === true){ return true; }else if($this->result === false){ return false; } $result = $this->getErrorStream(); if(preg_match('/muxing overhead/', $result)){ return true; } return false; } } ?> ficus/cli/ffmpeg/FFMpegConstants.php100644 1751 144 2541 10645132217 13116 ISITOYA Kentaro * @version $Id: FFMpegConstants.php 2 2007-07-11 10:37:48Z ishitoya $ * * subversion constants */ /** * @interface Ficus_FFMpegConstants */ interface Ficus_FFMpegConstants { const FFMPEG = "ffmpeg.exe"; const INPUT = "-i"; const FORMAT = "-f"; const FORMAT_IMAGE = "image2"; const OVERWRITE = "-y"; const OFFSET = "-ss"; const AUDIO_FREQUENCY = "-ar"; const AUDIO_CHANNELS = "-ac"; const VIDEO_BITRATE = "-b"; const VIDEO_SIZE = "-s"; const VIDEO_FRAMES = "-vframes"; } ?> ficus/cli/CommandLineManager.php100644 1751 144 11443 10647426442 12363 ISHITOYA Kentaro * @version $Id: CommandLineManager.php 15 2007-07-18 15:02:48Z ishitoya $ * * Command line command manager */ require_once("ficus/lang/reflect/ReflectionClass.php"); require_once("ficus/lang/reflect/annotation/ReflectionAnnotationProperty.php"); require_once("ficus/lang/reflect/annotation/ReflectionAnnotationClass.php"); /** * @class Soya_CommandLineManager */ class Soya_CommandLineManager{ private $application = null; private $commands = array(); private $defaultCommand = ""; public function __construct($application){ $this->application = $application; Ficus_ReflectionAnnotation::setPrefixes(array('Soya_', 'Ficus_')); $refClass = new Ficus_ReflectionClass($application); $class = new Ficus_ReflectionAnnotationClass($refClass); $methods = $class->getMethods(); foreach($methods as $method){ if($method->hasAnnotation("CommandLineCommand")){ $annotation = $method->getAnnotation("CommandLineCommand"); $command = $this->createExecutableCommand($annotation, $application, $method->getName()); $this->add($command); } } $properties = $class->getProperties(); foreach($properties as $property){ if($property->hasAnnotation("CommandLineCommand")){ $annotation = $property->getAnnotation("CommandLineCommand"); $command = $this->createParameterCommand($annotation, $property->getName()); $this->add($command); } } } public function add($command){ $this->commands[$command->name()] = $command; } private function createParameterCommand($annotation, $name){ $argument = new Soya_CommandLineArgument($annotation->getShort(), $annotation->getLong()); $command = new Soya_CommandLineCommand($name, Soya_CommandLineCommand::PARAMETER, null, $argument); return $command; } private function createExecutableCommand($annotation, $object, $name){ $argument = new Soya_CommandLineArgument($annotation->getShort(), $annotation->getLong()); $command = new Soya_CommandLineCommand($name, Soya_CommandLineCommand::EXECUTABLE, array($object, $name), $argument); if($annotation->isDefault()){ $this->defaultCommand = $name; } return $command; } public function setDefaultCommand($command){ $this->defaultCommand = $command; } public function execute($args){ $prepare = array(); foreach($this->commands as $command){ if($command->check($args)){ $prepare[$command->name()] = $command; if($command->type() == Soya_CommandLineCommand::PARAMETER){ $setter = "set" . $command->name(); $this->application->{$setter}($command->argument()); }else if($command->type() == Soya_CommandLineCommand::SIMPLE){ $setter = "set" . $command->name(); $this->application->{$setter}(true); } } } $executed = false; foreach($prepare as $command){ if($command->type() == Soya_CommandLineCommand::EXECUTABLE){ $command->execute(); $executed = true; } } if($executed == false){ $this->commands[$this->defaultCommand]->execute(); } } } ?> ficus/cli/CommandExecutorConstants.php100644 1751 144 2126 10647426442 13652 ISITOYA Kentaro * @version $Id: CommandExecutorConstants.php 15 2007-07-18 15:02:48Z ishitoya $ * * subversion constants */ /** * @interface Ficus_CommandExecutorConstants */ interface Ficus_CommandExecutorConstants { const RESULT_ERROR = "error"; } ?> ficus/cli/CommandLineCommandAnnotation.php100644 1751 144 4247 10647426442 14406 ISHITOYA Kentaro * @version $Id: CommandLineCommandAnnotation.php 15 2007-07-18 15:02:48Z ishitoya $ * * Command line application */ /** * @class Soya_CommandLineCommandAnnotation */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; require_once "ficus/exception/IllegalAnnotationException.php"; class Soya_CommandLineCommandAnnotation extends Ficus_ReflectionAnnotation{ private $short; private $long; private $isDefault; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); $this->short = $arguments["short"]; $this->long = $arguments["long"]; if(array_key_exists("default", $arguments)){ $this->isDefault = $arguments["default"]; }else{ $this->idDefault = false; } } /** * get short name */ public function getShort(){ return $this->short; } /** * get long name */ public function getLong(){ return $this->long; } /** * isDefault */ public function isDefault(){ return $this->isDefault; } } ?> ficus/cli/CommandExecutor.php100644 1751 144 2366 10647426442 11763 ISHITOYA Kentaro * @version $Id: CommandExecutor.php 15 2007-07-18 15:02:48Z ishitoya $ * * executes phing abstract class */ require_once("ficus/lang/Runtime.php"); require_once("ficus/cli/CommandExecutorConstants.php"); /** * @class Ficus_CommandExecutor */ interface Ficus_CommandExecutor extends Ficus_CommandExecutorConstants { /** * execute * @return misc subclass's return value */ public function execute(); } ?> ficus/ext/date/AstorogyDate.php100644 1751 144 11703 10645132217 12244 ISHITOYA Kentaro * @version $Id: AstorogyDate.php 2 2007-07-11 10:37:48Z ishitoya $ */ /** * @class Ficus_AstorogyDate */ class Ficus_AstorogyDate{ const MODE_TWELFTH = "12"; const MODE_THIRTEENTH = "13"; const ARIES = 0; const TAURUS = 1; const GEMINI = 2; const CANCER = 3; const LEO = 4; const VIRGO = 5; const LIBRA = 6; const SCROPIO = 7; const SAGITTARIUS = 8; const CAPRICORN = 9; const AQUERIUS = 10; const PISCES = 11; const OPHIUCHUS = 12; public static function examin($month, $day, $mode = self::MODE_TWELFTH){ if($mode == self::MODE_TWELFTH){ if(($month == 3 && $day >= 21) || ($month == 4 && $day <= 19)){ return self::ARIES; }else if(($month == 4 && $day >= 20) || ($month == 5 && $day <= 20)){ return self::TAURUS; }else if(($month == 5 && $day >= 21) || ($month == 6 && $day <= 21)){ return self::GEMINI; }else if(($month == 6 && $day >= 22) || ($month == 7 && $day <= 22)){ return self::CANCER; }else if(($month == 7 && $day >= 23) || ($month == 8 && $day <= 22)){ return self::LEO; }else if(($month == 8 && $day >= 23) || ($month == 9 && $day <= 22)){ return self::VIRGO; }else if(($month == 9 && $day >= 23) || ($month == 10 && $day <= 23)){ return self::LIBRA; }else if(($month == 10 && $day >= 24) || ($month == 11 && $day <= 22)){ return self::SCROPIO; }else if(($month == 11 && $day >= 23) || ($month == 12 && $day <= 22)){ return self::SAGITTARIUS; }else if(($month == 12 && $day >= 23) || ($month == 1 && $day <= 19)){ return self::CAPRICORN; }else if(($month == 1 && $day >= 20) || ($month == 2 && $day <= 18)){ return self::AQUERIUS; }else if(($month == 2 && $day >= 19) || ($month == 3 && $day <= 20)){ return self::PISCES; } }else{ if(($month == 3 && $day >= 19) || ($month == 4 && $day <= 13)){ return self::ARIES; }else if(($month == 4 && $day >= 14) || ($month == 5 && $day <= 20)){ return self::TAURUS; }else if(($month == 5 && $day >= 21) || ($month == 6 && $day <= 19)){ return self::GEMINI; }else if(($month == 6 && $day >= 22) || ($month == 7 && $day <= 10)){ return self::CANCER; }else if(($month == 7 && $day >= 11) || ($month == 8 && $day <= 15)){ return self::LEO; }else if(($month == 8 && $day >= 16) || ($month == 9 && $day <= 29)){ return self::VIRGO; }else if(($month == 9 && $day >= 30) || ($month == 10 && $day <= 22)){ return self::LIBRA; }else if(($month == 10 && $day >= 23) || ($month == 11 && $day <= 29)){ return self::SCROPIO; }else if(($month == 11 && $day >= 30) || ($month == 12 && $day <= 17)){ return self::OPHIUCHUS - 5; }else if(($month == 12 && $day >= 18) || ($month == 1 && $day <= 18)){ return self::SAGITTARIUS + 1; }else if(($month == 1 && $day >= 19) || ($month == 2 && $day <= 15)){ return self::CAPRICORN + 1; }else if(($month == 2 && $day >= 16) || ($month == 3 && $day <= 10)){ return self::AQUERIUS + 1; }else if(($month == 3 && $day >= 11) || ($month == 4 && $day <= 18)){ return self::PISCES + 1; } } } } ?> ficus/ext/pukiwiki/PukiWikiConstants.php100644 1751 144 2204 10645132217 14163 ISHITOYA Kentaro * @version $Id: PukiWikiConstants.php 2 2007-07-11 10:37:48Z ishitoya $ * * Page component factory */ /** * @interface Ficus_PukiWikiConstants */ interface Ficus_PukiWikiConstants { const ENCODING_EUC = "EUC-JP"; const ENCODING_UTF8 = "UTF8"; const WIKI_EXT = ".txt"; } ?> ficus/ext/pukiwiki/PukiWiki.php100644 1751 144 4174 10645132217 12276 ISHITOYA Kentaro * @version $Id: PukiWiki.php 2 2007-07-11 10:37:48Z ishitoya $ * * access to pukiwiki */ require_once("ficus/ext/pukiwiki/PukiWikiConstants.php"); /** * @class Ficus_PukiWiki */ class Ficus_PukiWiki implements Ficus_PukiWikiConstants { /** * wiki encoding */ private static $encoding = self::ENCODING_EUC; /** * get file name from page name * @param $pagename string name of the page * @return string page name */ public static function getFileName($pagename){ $pagename = mb_convert_encoding($pagename, self::$encoding, mb_detect_encoding($pagename)); $pagename = strtoupper(bin2hex($pagename)); return $pagename . self::WIKI_EXT; } /** * get page name from name * @param $name string name of the page * @return string page name */ public static function getPageName($pagename){ $pagename = mb_convert_encoding($pagename, self::$encoding, mb_detect_encoding($pagename)); $pagename = rawurlencode($pagename); return $pagename; } /** * set encoding * @param $encoding string encoding */ public static function setEncoding($encoding){ self::$encoding = $encoding; } } ?> ficus/ext/pukiwiki/format/PukiWikiFormat.php100644 1751 144 2465 10645132217 14740 ISHITOYA Kentaro * @version $Id: PukiWikiFormat.php 2 2007-07-11 10:37:48Z ishitoya $ * * pukiwiki definition list converter */ require_once("ficus/ext/pukiwiki/PukiWikiConstants.php"); /** * @class Ficus_PukiWikiFormat */ abstract class Ficus_PukiWikiFormat implements Ficus_PukiWikiConstants { /** * convert string * @param $str string target string * @return string converted string */ abstract public function convert($str); } ?> ficus/ext/pukiwiki/format/PukiWikiUnorderedList.php100644 1751 144 3171 10645132217 16266 ISHITOYA Kentaro * @version $Id: PukiWikiUnorderedList.php 2 2007-07-11 10:37:48Z ishitoya $ * * pukiwiki unordered list converter */ require_once("ficus/ext/pukiwiki/format/PukiWikiFormat.php"); /** * @class Ficus_PukiWikiUnorderedList */ class Ficus_PukiWikiUnorderedList extends Ficus_PukiWikiFormat { /** * convert string * @param $str string target string * @return string converted string */ public function convert($str){ $lines = explode("\n", $str); $count = count($lines); $datas = array(); for($i = 0; $i < $count; $i++){ $line = $lines[$i]; if(preg_match("/^-([^\|]+?)$/", $line, $regs)){ $datas[] = $regs[1]; } } return $datas; } } ?> ficus/ext/pukiwiki/format/PukiWikiParagraph.php100644 1751 144 3650 10645132217 15412 ISHITOYA Kentaro * @version $Id: PukiWikiParagraph.php 2 2007-07-11 10:37:48Z ishitoya $ * * pukiwiki paragraph converter(extracts between * and *) */ require_once("ficus/ext/pukiwiki/format/PukiWikiFormat.php"); /** * @class Ficus_PukiWikiParagraph */ class Ficus_PukiWikiParagraph extends Ficus_PukiWikiFormat { /** * convert string * @param $str string target string * @return string converted string */ public function convert($str){ $lines = explode("\n", $str); $count = count($lines); $datas = array(); for($i = 0; $i < $count; $i++){ $line = $lines[$i]; if(preg_match("/^\*+\s?(.*?)\s?(\[#.*?\])?$/", $line, $regs)){ $i++; for(; $i < $count && preg_match("/^\*+\s?(.*)$/", $lines[$i]) == false; $i++){ $datas[$regs[1]][] = $lines[$i]; } $i--; $datas[$regs[1]] = implode("\n", $datas[$regs[1]]); } } return $datas; } } ?> ficus/ext/pukiwiki/format/PukiWikiDefinitionList.php100644 1751 144 3221 10645132217 16423 ISHITOYA Kentaro * @version $Id: PukiWikiDefinitionList.php 2 2007-07-11 10:37:48Z ishitoya $ * * pukiwiki definition list converter */ require_once("ficus/ext/pukiwiki/format/PukiWikiFormat.php"); /** * @class Ficus_PukiWikiDefinitionList */ class Ficus_PukiWikiDefinitionList extends Ficus_PukiWikiFormat { /** * convert string * @param $str string target string * @return string converted string */ public function convert($str){ $lines = explode("\n", $str); $count = count($lines); $datas = array(); for($i = 0; $i < $count; $i++){ $line = $lines[$i]; if(preg_match("/^:([^\|]+?)\|(.*)(~$)?/", $line, $regs)){ $datas[$regs[1]] = $regs[2]; } } return $datas; } } ?> ficus/net/rmi/fml/FMLRMI.php100644 1751 144 6112 10645132217 11221 ISHITOYA Kentaro * @version $Id: FMLRMI.php 2 2007-07-11 10:37:48Z ishitoya $ * * access to pukiwiki */ require_once("ficus/net/mail/Mail.php"); require_once("ficus/net/rmi/AbstractRemoteMethodInvocation.php"); /** * @class Ficus_FMLRMI */ class Ficus_FMLRMI extends Ficus_AbstractRemoteMethodInvocation { const FML_LANGUAGE = "LANGUAGE"; const FML_PROC = "PROC"; const FML_MLNAME = "ML"; const ARCHIVE_MLNAME = "ml_name"; const ARCHIVE_NUMBER = "ml_no"; const CMD_NEWML = "newml"; const LANG_JP = "Japanese"; /** * create mailing list * @param $name string name of mailing list * @param $encoding string encoding if setted, convert response */ public function newML($name, $encoding = null){ if(empty($name)){ throw new Ficus_IllegalArgumentException("name must not be empty"); }else if(preg_match('/^[a-z0-9_]+$/', $_REQUEST["ml_name"]) == false){ throw new Ficus_IllegalArgumentException("name must be a-z0-9_"); } $request = array(self::FML_LANGUAGE => self::LANG_JP, self::FML_PROC => self::CMD_NEWML, self::FML_MLNAME => $name); $response = $this->invoke($request); if(is_null($encoding)){ return $response; }else{ return mb_convert_encoding($response, $encoding, $this->encoding); } } /** * get archive * @param $name string name of the mailing list * @param $no integer number of the archive * @return Ficus_Mail mail object */ public function getArchive($name, $no){ if(empty($name)){ throw new Ficus_IllegalArgumentException("ml name must not be empty"); }else if(empty($no)){ throw new Ficus_IllegalArgumentException("ml number must not be empty"); }else if(preg_match('/^[0-9]+$/', $no) == false){ throw new Ficus_IllegalArgumentException("ml number must specified in numbers."); } $request = array(self::ARCHIVE_MLNAME => $name, self::ARCHIVE_NUMBER => $no); $response = $this->invoke($request); $mail = new Ficus_Mail(); $mail->decode($response); return $mail; } } ?> ficus/net/rmi/RMIComponentFactory.php100644 1751 144 5315 10645132217 13323 SUMI Masafumi * @version $Id: RMIComponentFactory.php 2 2007-07-11 10:37:48Z ishitoya $ * * RMI component factory */ require_once("ficus/io/File.php"); require_once("ficus/config/Registry.php"); require_once("ficus/lang/AutoLoad.php"); require_once("ficus/lang/S2ContainerAutoLoad.php"); require_once("ficus/lang/ClassLoaderAutoLoad.php"); require_once("ficus/net/rmi/RemoteMethodInvocation.php"); require_once("ficus/net/rmi/fml/FMLRMI.php"); require_once("ficus/net/rmi/pukiwiki/PukiWikiRMI.php"); /** * @class Ficus_RMIComponentFactory */ class Ficus_RMIComponentFactory { /** * Default dicon file name. */ const DEFAULT_DICON_FILE = 'rmi.dicon'; /** * dicon namespace. */ const DICON_NAMESPACE = 'rmi'; /** * @var S2Container S2Container. */ private static $container = null; /** * Get dicon path. * * return string dicon path.. */ private static function getDiconPath() { $diconPath = Ficus_File::currentDir() ->resolve(self::DEFAULT_DICON_FILE)->getPath(); return $diconPath; } /** * Get S2Container. * * return S2Container S2Container. */ private static function getS2Container() { if (self::$container == null) { $diconPath = self::getDiconPath(); self::$container = S2ContainerFactory::create($diconPath); Ficus_AutoLoad::add(new Ficus_S2ContainerAutoLoad()); } return self::$container; } /** * Get RMI component * * @param $name string name of RemoteMethodInvocation * @return Ficus_RemoteMethodInvocation RMI component. */ public static function getRMIComponent($name) { $container = self::getS2Container(); $componentName = self::DICON_NAMESPACE . '.' . strtolower($name); return $container->getComponent($componentName); } } ?> ficus/net/rmi/AbstractRemoteMethodInvocation.php100644 1751 144 14075 10645132217 15616 ISHITOYA Kentaro * @version $Id: AbstractRemoteMethodInvocation.php 2 2007-07-11 10:37:48Z ishitoya $ * * remote method invocation abstract class. implements some http methods. */ require_once("HTTP/Request.php"); require_once("ficus/net/rmi/RemoteMethodInvocation.php"); /** * @class Ficus_AbstractRemoteMethodInvocation */ abstract class Ficus_AbstractRemoteMethodInvocation implements Ficus_RemoteMethodInvocation { const HTTP_VERSION_11 = "1.1"; const USER_AGENT = "Infocrew Accessor"; const ENCODING_EUC = "EUC-JP"; const ENCODING_UTF8 = "UTF-8"; const ENCODING_ISOJP = "ISO-2022-JP"; /** * @var $endpoint string endpoint */ protected $endpoint = ""; /** * @var $response string response */ protected $response = ""; /** * HTTP_Request object */ protected $http = null; /** * user */ protected $user = ""; /** * password */ protected $password = ""; /** * agent */ protected $agent = self::USER_AGENT; /** * method */ protected $method = HTTP_REQUEST_METHOD_POST; /** * headers */ protected $headers = array(); /** * httpver */ protected $httpVersion = self::HTTP_VERSION_11; /** * @var $encoding string pukiwiki encoding */ protected $encoding = self::ENCODING_EUC; /** * invoke remote method * @param $request array of request * @return string result */ public final function invoke($request){ if(empty($this->endpoint)){ throw new Ficus_IllegalArgumentException("endpoint must not be empty"); } $this->http = new HTTP_Request($this->endpoint); $this->http->setHttpVer($this->httpVersion); $this->http->setMethod($this->method); $this->http->addHeader('User-Agent', $this->agent); if(empty($this->user) == false){ $this->http->setBasicAuth($this->user, $this->password); } $this->onInvocation($request); $response = $this->http->sendRequest(); if(PEAR::isError($response)){ return $this->processError($response); }else{ return $this->processResponse($this->http->getResponseBody()); } } /** * invoke remote method * @param $request array of request */ public function onInvocation($request){ if(is_array($request)){ foreach($request as $name => $value){ $this->addPostData($name, $value); } } } /** * add post data * @param $name string name of data * @param $value string value of data */ protected function addPostData($name, $value){ $this->http->addPostData($name, $value); } /** * process Response * @param $response string response of remote method * @return string result */ protected final function processResponse($response){ return $this->onProcessResponse($response); } /** * process Response * @param $response Object response of remote method * @return string result */ protected function onProcessResponse($response){ return $response; } /** * process Response * @param $response string response of remote method * @return string result */ protected final function processError($response){ return $this->onProcessError($response); } /** * process Error * @param $response Object response of remote method * @return string result */ protected function onProcessError($response){ return $response->getMessage(); } /** * get response * @return string response of last invocation */ public function getResponse(){ return $this->response; } /** * set endpoint * @param $endpoint endpoint of method */ public function setEndpoint($endpoint){ $this->endpoint = $endpoint; } /** * set user * @param $user string user name */ public function setUser($user){ $this->user = $user; } /** * set password * @param $password string password */ public function setPassword($password){ $this->password = $password; } /** * set User agent * @param $agent string agent */ public function setAgent($agent){ $this->agent = $agent; } /** * set Http version * @param $version string version of http */ public function setHTTPVersion($version){ $this->httpVersion = $version; } /** * set Method * @param $method string method of http */ public function setMethod($method){ $this->method = $method; } /** * set encoding * @param $encoding string encoding */ public function setEncoding($encoding){ $this->encoding = $encoding; } /** * encode * @param $data string to encode * @return string encoded data */ protected function getEncoded($data){ $src = mb_detect_encoding($data); return mb_convert_encoding($data, $this->encoding, $src); } } ?> ficus/net/rmi/rmi.dicon100644 1751 144 433 10645120256 10531 ficus/net/rmi/pukiwiki/PukiWikiRMI.php100644 1751 144 5002 10645132217 13412 ISHITOYA Kentaro * @version $Id: PukiWikiRMI.php 2 2007-07-11 10:37:48Z ishitoya $ * * access to pukiwiki */ require_once("ficus/net/rmi/AbstractRemoteMethodInvocation.php"); /** * @class Ficus_PukiWikiRMI */ class Ficus_PukiWikiRMI extends Ficus_AbstractRemoteMethodInvocation { const PUKIWIKI_PAGENAME = "page"; const PUKIWIKI_WRITE = "write"; const PUKIWIKI_CMD = "cmd"; const PUKIWIKI_CONTENTS = "msg"; const PUKIWIKI_DIGEST = "digest"; const CMD_EDIT = "edit"; /** * create page * @param $name string name of page * @param $contents string contents of page * @param $encoding string encoding if setted, convert response */ public function createPage($name, $contents, $encoding = null){ if(empty($name)){ throw new Ficus_IllegalArgumentException("name must not be empty"); }else if(empty($contents)){ throw new Ficus_IllegalArgumentException("contents mut not be empty"); } $request = array(self::PUKIWIKI_PAGENAME => $this->getEncoded($name), self::PUKIWIKI_CMD => self::CMD_EDIT, self::PUKIWIKI_WRITE => true, self::PUKIWIKI_CONTENTS => $this->getEncoded($contents), self::PUKIWIKI_DIGEST => md5("")); $response = $this->invoke($request); if(is_null($encoding)){ return $response; }else{ return mb_convert_encoding($response, $encoding, $this->encoding); } } /** * get file name from page name * @param $name string name of page name * @return string page name */ public function getFileName($pagename){ } } ?> ficus/net/rmi/pukiwiki/PukiWikiUtility.php100644 1751 144 4202 10645132217 14427 ISHITOYA Kentaro * @version $Id: PukiWikiUtility.php 2 2007-07-11 10:37:48Z ishitoya $ * * access to pukiwiki */ /** * @class Ficus_PukiWikiUtility */ class Ficus_PukiWikiUtility { const ENCODING_EUC = "EUC-JP"; const WIKI_EXT = ".txt"; /** * wiki encoding */ private static $encoding = self::ENCODING_EUC; /** * get file name from page name * @param $pagename string name of the page * @return string page name */ public static function getFileName($pagename){ $pagename = mb_convert_encoding($pagename, self::$encoding, mb_detect_encoding($pagename)); $pagename = strtoupper(bin2hex($pagename)); return $pagename . self::WIKI_EXT; } /** * get page name from name * @param $name string name of the page * @return string page name */ public static function getPageName($pagename){ $pagename = mb_convert_encoding($pagename, self::$encoding, mb_detect_encoding($pagename)); $pagename = rawurlencode($pagename); return $pagename; } /** * set encoding * @param $encoding string encoding */ public static function setEncoding($encoding){ self::$encoding = $encoding; } } ?> ficus/net/rmi/RemoteMethodInvocation.php100644 1751 144 2636 10645132217 14112 ISHITOYA Kentaro * @version $Id: RemoteMethodInvocation.php 2 2007-07-11 10:37:48Z ishitoya $ * * */ /** * @class Ficus_RemoteMethodInvocation */ interface Ficus_RemoteMethodInvocation { /** * invoke remote method * @param $request array of request */ public function onInvocation($request); /** * get response * @return string response of last invocation */ public function getResponse(); /** * set endpoint * @param $endpoint endpoint of method */ public function setEndpoint($endpoint); } ?> ficus/net/rmi/ConcreteRemoteMethodInvocation.php100644 1751 144 2270 10645132217 15567 ISHITOYA Kentaro * @version $Id: ConcreteRemoteMethodInvocation.php 2 2007-07-11 10:37:48Z ishitoya $ * * access to pukiwiki */ require_once("ficus/net/rmi/AbstractRemoteMethodInvocation.php"); /** * @class Ficus_ConcreateRemoteMethodInvocation */ class Ficus_ConcreateRemoteMethodInvocation extends Ficus_AbstractRemoteMethodInvocation { } ?> ficus/net/rmi/components21.dtd100644 1751 144 2773 10645120160 11774 ficus/net/URIFactoryImpl.php100644 1751 144 3770 10645132217 11506 SUMI Masafumi * @version $Id: URIFactoryImpl.php 2 2007-07-11 10:37:48Z ishitoya $ * * URIFactoryImpl for php */ require_once('ficus/net/URIFactory.php'); require_once("ficus/net/URI.php"); require_once("ficus/net/OpaqueURI.php"); require_once("ficus/net/MailtoURI.php"); require_once("ficus/exception/ClassNotFoundException.php"); /** * @class Ficus_URIFactoryImpl */ class Ficus_URIFactoryImpl implements Ficus_URIFactory { /** * Get suffix of class name. * * @return string suffix. */ public function getSuffix() { return 'URI'; } /** * Default URI . * * @param $uri string URI. * @return Ficus_URI URI. */ public function defaultInstance($uri) { throw new Ficus_ClassNotFoundException($uri); } /** * Factory method. * * @param $uri string URI. * @return Ficus_URI URI. */ public function createInstance($scheme, $uri) { $className = 'Ficus_' . ucwords(strtolower($scheme)) . $this->getSuffix(); if (class_exists($className)) { return new $className($uri); } else { return $this->defaultInstance($uri); } } } ?> ficus/net/mail/Mail.php100644 1751 144 13172 10645132217 10516 ISHITOYA Kentaro * @version $Id: Mail.php 2 2007-07-11 10:37:48Z ishitoya $ * * Mail for php */ require_once("ficus/beans/Bean.php"); require_once("ficus/net/mail/MailAttachment.php"); require_once("Mail/Mail.php"); require_once("Mail/mimeDecode.php"); /** * @class Ficus_Mail */ class Ficus_Mail extends Ficus_Bean{ const ENCODING_ISO_2022_JP = "iso-2022-jp"; const ENCODING_UTF8 = "utf-8"; /** * title */ protected $subject = ""; /** * to */ protected $to = ""; /** * from */ protected $from = ""; /** * date */ protected $date = ""; /** * charset */ protected $charset = self::ENCODING_ISO_2022_JP; /** * attachments */ protected $attachments = array(); /** * body */ protected $body = ""; /** * encoding */ protected $encoding = self::ENCODING_UTF8; /** * smtp host */ protected $host = "localhost"; /** * smtp port */ protected $port = 25; /** * smtp auth */ protected $auth = false; /** * smtp username */ protected $username = ""; /** * smtp password */ protected $password = ""; /** * send mail */ public function send(){ if($this->isEmptySubject()){ throw new Ficus_NotReadyException("subject is not setted"); } if($this->isEmptyBody()){ throw new Ficus_NotReadyException("body is empty"); } if($this->isEmptyTo()){ throw new Ficus_NotReadyException("to address is empty"); } if($this->isEmptyFrom()){ throw new Ficus_NotReadyException("from address is empty"); } $options = array("host" => $this->host, "port" => $this->port, "auth" => $this->auth, "username" => $this->username, "password" => $this->password, "localhost" => "localhost"); $headers = array("From" => $this->from, "To" => $this->to, "Subject" => $this->getEncoded($this->subject)); $mail = Mail::factory("SMTP", $options); $mail->send($this->to, $headers, $this->getEncoded($this->body)); } /** * decode mail archive * @param $archive string mail archive */ public function decode($archive){ $params['include_bodies'] = true; $params['decode_bodies'] = true; $params['decode_headers'] = true; $decoder = new Mail_mimeDecode($archive); $mail = $decoder->decode($params); if(PEAR::isError($mail)){ throw new Ficus_IllegalArgumentException($mail->getMessage()); } if(isset($mail->ctype_parameters["boundary"])){ $primary = $mail->parts[0]; $charset = $primary->ctype_parameters["charset"]; $this->body = $this->getDecoded($mail->parts[0]->body); for($i = 1; $i < count($mail->parts); $i++){ $attachment = new Ficus_MailAttachment(); $attachment->setCharset($charset); $attachment->decode($mail->parts[$i]); $attachment->setFilename($this->getDecoded($attachment->filename())); $this->attachments[] = $attachment; } }else{ $this->charset = $mail->ctype_parameters["charset"]; $this->body = $this->getDecoded($mail->body); } $this->subject = $this->getDecoded($mail->headers["subject"]); $this->to = $this->getDecoded($mail->headers["to"]); $this->from = $this->getDecoded($mail->headers["from"]); $this->date = $this->getDecoded($mail->headers["date"]); } /** * get decoded string * @param $target string target string to decode * @return string decoded string */ protected function getDecoded($target){ return mb_convert_encoding(trim($target), $this->encoding, $this->charset); } /** * get encoded string * @param $target string target string to encode * @return string encoded string */ protected function getEncoded($target){ return mb_convert_encoding(trim($target), $this->charset, $this->encoding); } /** * get attachment * @param $filename string filename * @return Ficus_MailAttachment attachment */ public function getAttachment($filename){ foreach($this->attachments as $attachment){ if($attachment->filename() == $filename){ return $attachment; } } throw new Ficus_IllegalArgumentException("$filename is not found"); } } ?> ficus/net/mail/MailAttachment.php100644 1751 144 3344 10645132217 12507 ISHITOYA Kentaro * @version $Id: MailAttachment.php 2 2007-07-11 10:37:48Z ishitoya $ * * MailAttachment for php */ require_once("ficus/beans/Bean.php"); /** * @class Ficus_MailAttachment */ class Ficus_MailAttachment extends Ficus_Bean{ const ENCODING_ISO_2022_JP = "iso-2022-jp"; const ENCODING_UTF8 = "utf-8"; /** * filename */ protected $filename = ""; /** * body */ protected $body = ""; /** * charset */ protected $charset = self::ENCODING_ISO_2022_JP; /** * mime */ protected $mime = ""; /** * part */ protected $part = array(); /** * set part */ public function decode($part){ $this->part = $part; $this->filename = $part->d_parameters["filename"]; $this->body = $part->body; $this->mime = $part->ctype_primary . "/" . $part->ctype_secondary; } } ?> ficus/net/OpaqueURI.php100644 1751 144 4664 10645132217 10512 SUMI Masafumi * @version $Id: OpaqueURI.php 2 2007-07-11 10:37:48Z ishitoya $ * * Opaque URI. */ require_once("ficus/net/URI.php"); require_once("ficus/net/AbsoluteURI.php"); require_once("ficus/net/URIBuilder.php"); require_once("ficus/exception/URISyntaxException.php"); /** * @class Ficus_OpaqueURI */ class Ficus_OpaqueURI extends Ficus_URI implements Ficus_AbsoluteURI { /** * Constructor. * * @param $uri string URI. * @throw Ficus_URISyntaxException invalid opaque URI. */ public function __construct($uri) { parent::__construct($uri); } /** * Parse opaque URI. */ protected function parse() { parent::parse(); $specific = $this->getSpecific(); if ($specific{0} == '/') { throw new Ficus_URISyntaxException("No opaque URI. " . $this->uri); } } /** * Resovle relative URI. * * @param $uri mixed string or Ficus_URI relative URI. */ final public function resolve($uri) { if ($uri->isAbsolute()) { return $uri; } if (!is_null($uri->getRawFragment())) { $fragment = $uri->getRawFragment(); } else { $fragment = $this->getRawFragment(); } return Ficus_URIBuilder::createByParts($this->getRawScheme(), null, $this->getRawSpecific(), null, $fragment); } /** * Normalize URI. * * @return Ficus_OpaqueURI URI. */ final public function normalize() { return $this; } } ?> ficus/net/FileURL.php100644 1751 144 2251 10645132217 10130 SUMI Masafumi * @version $Id: FileURL.php 2 2007-07-11 10:37:48Z ishitoya $ * * FileURL */ require_once("ficus/net/URL.php"); /** * @class Ficus_FileURL */ class Ficus_FileURL extends Ficus_URL { /** * Get default scheme. * * @return string scheme name. */ final public function getDefaultScheme() { return 'file'; } } ?> ficus/net/URIBuilder.php100644 1751 144 11421 10645132217 10653 SUMI Masafumi * @version $Id: URIBuilder.php 2 2007-07-11 10:37:48Z ishitoya $ * * URIBuilder */ require_once("ficus/net/URIFactoryComponentFactory.php"); require_once("ficus/lang/Types.php"); require_once("ficus/exception/URISyntaxException.php"); /** * @class Ficus_URIBuilder */ class Ficus_URIBuilder { /** * uri patten */ const URI_PATTERN = '/^(?:([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\+\\-\\.]*):)?([^#]*)(#(?:[;\\/\\?:@&=\\+\\$,]|[a-zA-Z0-9]|[\\-_\\.!~\\*\'\\(\\)])*)?/'; /** * uri pattern that extractable to local part and namespace */ const EXTRACTABLE_URI_PATTERN = '/[a-zA-Z][a-zA-Z0-9\+\-\.]*:.*[#\/:].*$/'; /** * Build URI factory method. * * @param $uri string URI string. * @return mixed Ficus_URI or Ficus_URL or Ficus_URN. * @throw Ficus_URISyntaxException invalid URI. */ public static function create($uri) { return self::build($uri); } /** * Create URI factory method. * * @param $uri string URI string. * @return mixed Ficus_URI or Ficus_URL or Ficus_URN. * @throw Ficus_URISyntaxException invalid URI. */ public static function build($uri) { $uri = Ficus_Types::toStringOf($uri); if (preg_match(self::URI_PATTERN, $uri, $matches) === 0) { throw new Ficus_URISyntaxException("Syntax error: '$uri'"); } $scheme = $matches[1]; $specific = $matches[2]; $fragment = isset($matches[3]) ? $matches[3] : null; if ($scheme == '') { // relative URI. return new Ficus_HierarchicalURI($uri); } try { $builder = Ficus_URIFactoryComponentFactory::getBuilderComponent($scheme); return $builder->createInstance($scheme, $uri); } catch (S2Container_ComponentNotFoundRuntimeException $e) { if ($specific{0} == '/' && $specific{1} == '/') { // unknown URL return new Ficus_URL($uri); } else if ($specific{0} == '/') { // unknown hierarchical URI return new Ficus_HierarchicalURI($uri); } else { // unknown URI return new Ficus_OpaqueURI($uri); } } catch (Ficus_ClassNotFoundException $e) { return null; } catch (Exception $e) { // TODO check out that S2Container's exception throw $e; } } /** * Create by parts. * * @param $scheme string scheme. * @param $authority string authority. * @param $path string path. * @param $query string query. * @param $fragment string fragment. * @return Ficus_URI URI. */ public static function createByParts($scheme, $authority, $path, $query, $fragment) { $uri = self::createURIStringByParts($scheme, $authority, $path, $query, $fragment); return self::create($uri); } /** * Create URI string by parts. * * @param $scheme string scheme. * @param $authority string authority. * @param $path string path. * @param $query string query. * @param $fragment string fragment. * @return string URI. */ public static function createURIStringByParts($scheme, $authority, $path, $query, $fragment) { $uri = ''; $uri .= ($scheme) ? $scheme . ':' : ''; $uri .= ($authority) ? '//' . $authority : ''; $uri .= ($path) ? $path : ''; $uri .= ($query) ? '?' . $query : ''; $uri .= ($fragment) ? '#' . $fragment : ''; return $uri; } /** * Check passed string is URI or URN and it is extractable. * @param $string string actual string * @return boolean true if is URI or URN */ public static function isExtractableURI($string){ return (preg_match(self::EXTRACTABLE_URI_PATTERN, $string) != false); } } ?> ficus/net/HttpsURL.php100644 1751 144 2260 10645132217 10353 SUMI Masafumi * @version $Id: HttpsURL.php 2 2007-07-11 10:37:48Z ishitoya $ * * HttpsURL */ require_once("ficus/net/URL.php"); /** * @class Ficus_HttpsURL */ class Ficus_HttpsURL extends Ficus_URL { /** * Get default scheme. * * @return string scheme name. */ final public function getDefaultScheme() { return 'https'; } } ?> ficus/net/URICharacters.php100644 1751 144 4633 10645132217 11333 SUMI Masafumi * @version $Id: URICharacters.php 2 2007-07-11 10:37:48Z ishitoya $ * * URICharacters for php */ /** * @class Ficus_URICharacters */ interface Ficus_URICharacters { /** * Gen delimiter charactor. */ const C_COLON = 0x3A; // : const C_SLASH = 0x2F; // / const C_QUESTION = 0x3F; // ? const C_SHARP = 0x23; // # const C_LEFT_SQUARE_BRACKET = 0x5B; // [ const C_RIGHT_SQUARE_BRACKET= 0x5D; // ] const C_ATMARK = 0x40; // @ /** * Sub delimiter charactor. */ const C_EXCLAMATION = 0x21; // ! const C_DOLLAR = 0x24; // $ const C_AMPERSAND = 0x26; // & const C_APOSTROPHE = 0x27; // ' const C_LEFT_CURLY_BRACKET = 0x7B; // { const C_RIGHT_CURLY_BRACKET = 0x7D; // } const C_ASTERISK = 0x2A; // * const C_PLUS = 0x2B; // + const C_COMMA = 0x2C; // , const C_SEMICOLON = 0x3B; // ; const C_EQUALS = 0x3D; // = /** * etc. */ const C_HYPHEN = 0x2D; // - const C_DOT = 0x2E; // . const C_UNDERBAR = 0x5F; // _ const C_TILDE = 0x7E; // ~ /** * Alphabet. */ const C_CAPITAL_A = 0x41; const C_CAPITAL_Z = 0x5A; const C_SMALL_A = 0x61; const C_SMALL_Z = 0x7A; /** * Digit. */ const C_ZERO = 0x30; const C_NINE = 0x39; } ?> ficus/net/URLFactoryImpl.php100644 1751 144 3143 10645132217 11503 SUMI Masafumi * @version $Id: URLFactoryImpl.php 2 2007-07-11 10:37:48Z ishitoya $ * * URLFactoryImpl for php */ require_once("ficus/net/URIFactoryImpl.php"); require_once("ficus/net/URL.php"); require_once("ficus/net/HttpURL.php"); require_once("ficus/net/HttpsURL.php"); require_once("ficus/net/FtpURL.php"); require_once("ficus/net/FileURL.php"); /** * @class Ficus_URLFactoryImpl */ class Ficus_URLFactoryImpl extends Ficus_URIFactoryImpl { /** * Get suffix of class name. * * @return string suffix. */ public function getSuffix() { return 'URL'; } /** * Default URI . * * @param $uri string URI. * @return Ficus_URI URI. */ public function defaultInstance($uri) { return new Ficus_URL($uri); } } ?> ficus/net/URIFactory.php100644 1751 144 2270 10645132217 10656 SUMI Masafumi * @version $Id: URIFactory.php 2 2007-07-11 10:37:48Z ishitoya $ * * URIFactory for php */ /** * @class Ficus_URIFactory */ interface Ficus_URIFactory { /** * Factory method. * * @param $scheme string URI scheme. * @param $uri string URI. * @return Ficus_URI URI. */ public function createInstance($scheme, $uri); } ?> ficus/net/MailtoURI.php100644 1751 144 3527 10645132217 10502 SUMI Masafumi * @version $Id: MailtoURI.php 2 2007-07-11 10:37:48Z ishitoya $ * * MailtoURI */ require_once("ficus/net/OpaqueURI.php"); /** * @class Ficus_MailtoURI */ class Ficus_MailtoURI extends Ficus_OpaqueURI { /** * Get default scheme. * * @return string scheme name. */ final public function getDefaultScheme() { return 'mailto'; } /** * Get mail address. * * @return string mail address. */ public function getMail() { return $this->getPath(); } /** * Get raw mail address. * * @return string raw mail address. */ public function getRawMail() { return $this->getRawPath(); } /** * Get mail address. * * @return string mail address. */ public function getMailAddress() { return $this->getMail(); } /** * Get raw mail address. * * @return string raw mail address. */ public function getRawMailAddress() { return $this->getRawMail(); } } ?> ficus/net/FtpURL.php100644 1751 144 2242 10645132217 10002 SUMI Masafumi * @version $Id: FtpURL.php 2 2007-07-11 10:37:48Z ishitoya $ * * FtpURL */ require_once("ficus/net/URL.php"); /** * @class Ficus_FtpURL */ class Ficus_FtpURL extends Ficus_URL { /** * Get default scheme. * * @return string scheme name. */ final public function getDefaultScheme() { return 'ftp'; } } ?> ficus/net/WSDL.php100644 1751 144 26441 10645132217 7466 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: WSDL.php 2 2007-07-11 10:37:48Z ishitoya $ * * WSDL for php */ require_once("ficus/lang/Assert.php"); require_once("ficus/net/URI.php"); require_once("ficus/parameters/ValidatableComplexParameter.php"); require_once("ficus/parameters/visitors/ParameterToWSDLConverter.php"); require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/exception/URISyntaxException.php"); /** * @class Ficus_WSDL */ class Ficus_WSDL{ //namespaces const XMLNS_WSDL = "http://schemas.xmlsoap.org/wsdl/"; const XMLNS_XSD = "http://www.w3.org/2001/XMLSchema"; const XMLNS_SOAP = "http://schemas.xmlsoap.org/wsdl/soap/"; const XMLNS_SOAPENC = "http://schemas.xmlsoap.org/wsdl/soap/encoding/"; //prefixes //tns for PEAR::SOAP const P_TYPENS = "tns:"; const P_XSD = "xsd:"; const P_SOAPENC = "SOAP-ENC:"; //soap const SOAP_TRANSPORT = "http://schemas.xmlsoap.org/soap/http"; const SOAP_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"; const SOAP_ENCODED = "encoded"; const SOAP_LITERAL = "literal"; const SOAP_RPC = "rpc"; const SOAP_DOCUMENT = "document"; /** * @var $dom DomDocument */ private $dom = null; /** * @var $wsdl string WSDL string style */ private $wsdl = null; /** * @var $endPoint string */ private $endPoint = null; /** * @var $targetNS string target Namespace. In Soya usualy "urn:soya:module:..." */ private $targetNS = null; /** * @var $portName string */ private $portName = null; /** * @var $serviceName string "Service" */ private $serviceName = null; /** * @var $bindingName string "Binding" */ private $bindingName = null; /** * @var $operationName string */ private $operationName = null; /** * @var $bindingStyle string style rpc/document default is rpc */ private $bindingStyle = null; /** * @var $bindingUse string body encoded/literal default is encoded */ private $bindingUse = null; /** * @var outputParameter Ficus_ValidatableComplexParameter output parameter */ private $outputParameter = null; /** * $inputParameter Ficus_ValidatableComplexParameter input parameter */ private $inputParameter = null; /** * Constructor * * In and out array format is like this * array("HogeRequest" => array("HP" => "xsd:int", "MP" => "typens:MP")) * array key will treat as name and array value will be type. * * @param $endPoint string endpoint of this service * @param $targetNS string targetNameSpace * @param $operationName string operationName * @param $portName string portName will be prefix of binding and so on. * @param $in Ficus_ValidatableComplexParameter input param * @param $out Ficus_ValidatableComplexParameter output param */ function __construct($endPoint, $targetNS, $operationName, $portName, $in, $out = null){ $this->setEndPoint($endPoint); $this->setTargetNameSpace($targetNS); $this->setPortName($portName); $this->setOperationName($operationName); $this->setInput($in); $this->setOutput($out); $this->dom = new DOMDocument("1.0", "utf-8"); $this->bindingStyle = self::SOAP_RPC; $this->bindingUse = self::SOAP_ENCODED; } /** * set binding-style * @param $style String bindingStyle * @throw Ficus_IllegalArgumentException no rpc or no document. */ public function setBindingStyle($style){ $style = trim($style); if($style !== self::SOAP_RPC || $style !== self::SOAP_DOCUMENT){ throw new Ficus_IllegalArgumentException( "Style must be rpc or document : param = $style"); } $this->bindingStyle = $style; } /** * set binding-use * @param $use String bindingUse * @throw Ficus_IllegalArgumentException no encoded or no literal. */ public function setBindingUse($use){ $use = trim($use); if($use !== self::SOAP_ENCODED || $use !== self::SOAP_LITERAL){ throw new Ficus_IllegalArgumentException( "Use must be encoded or literal : param = $use"); } $this->bindingUse = $use; } /** * serialize WSDL * @return string WSDL */ public function serialize(){ if(empty($this->wsdl)){ $this->createDefinitionElement(); } return $this->wsdl; } /** * create Definition Element */ private function createDefinitionElement(){ //create definition element $root = $this->dom->createElementNS(self::XMLNS_WSDL, "definitions"); $this->dom->appendChild($root); $root->setAttribute("name", $this->serviceName); $root->setAttribute("targetNamespace", $this->targetNS); //for fucking php DOM functions. $root->setAttribute("xmlns:xsd" , self::XMLNS_XSD); $root->setAttribute("xmlns:soap", self::XMLNS_SOAP); $root->setAttribute("xmlns:SOAP-ENC", self::XMLNS_SOAPENC); $root->setAttribute("xmlns:tns" , $this->targetNS); $converter = new Ficus_ParameterToWSDLConverter($this, $this->dom); $this->input->accept($converter); $this->output->accept($converter); $root->appendChild($converter->getConvertedTypes()); foreach($converter->getConvertedMessages() as $message){ $root->appendChild($message); } $root->appendChild($this->createPortTypeElement()); $root->appendChild($this->createBindingElement()); $root->appendChild($this->createServiceElement()); $this->wsdl = $this->dom->saveXML(); } /** * create portType Element * @return DomElemet */ private function createPortTypeElement(){ $portType = $this->dom->createElement("portType"); $portType->setAttribute("name", $this->portName); $operation = $this->dom->createElement("operation"); $operation->setAttribute("name", $this->operationName); $input = $this->dom->createElement("input"); $input->setAttribute( "message", self::P_TYPENS . $this->input->name()); $output = $this->dom->createElement("output"); $output->setAttribute( "message", self::P_TYPENS . $this->output->name()); $operation->appendChild($input); $operation->appendChild($output); $portType->appendChild($operation); return $portType; } /** * create Binding Element * @return DomElements */ private function createBindingElement(){ $binding = $this->dom->createElement("binding"); $binding->setAttribute("name", $this->bindingName); $binding->setAttribute("type", self::P_TYPENS . $this->portName); $soap_binding = $this->dom->createElementNS( self::XMLNS_SOAP, "soap:binding"); $soap_binding->setAttribute("style", $this->bindingStyle); $soap_binding->setAttribute("transport", self::SOAP_TRANSPORT); $operation = $this->dom->createElement("operation"); $operation->setAttribute("name", $this->operationName); $operation->setAttribute("soapAction", $this->operationName); $soap_operation = $this->dom->createElementNS( self::XMLNS_SOAP, "soap:operation"); $soap_operation->setAttribute("soapAction", $this->operationName); $input = $this->dom->createElement("input"); $input_soap_body = $this->dom->createElementNS( self::XMLNS_SOAP, "soap:body"); $input_soap_body->setAttribute("use", self::SOAP_ENCODED); $input_soap_body->setAttribute("namespace", $this->targetNS); $input_soap_body->setAttribute("encodingStyle", self::SOAP_ENCODING); $output = $this->dom->createElement("output"); $output_soap_body = $this->dom->createElementNS( self::XMLNS_SOAP, "soap:body"); $output_soap_body->setAttribute("use", self::SOAP_ENCODED); $output_soap_body->setAttribute("namespace", $this->targetNS); $output_soap_body->setAttribute("encodingStyle", self::SOAP_ENCODING); $binding->appendChild($soap_binding); $input->appendChild($input_soap_body); $output->appendChild($output_soap_body); $operation->appendChild($soap_operation); $operation->appendChild($input); $operation->appendChild($output); $binding->appendChild($operation); return $binding; } /** * create Service Element * @return DomElements */ private function createServiceElement(){ $service = $this->dom->createElement("service"); $service->setAttribute("name", $this->serviceName); $port = $this->dom->createElement("port"); $port->setAttribute("name", $this->portName); $port->setAttribute("binding", self::P_TYPENS . $this->bindingName); $address = $this->dom->createElementNS( self::XMLNS_SOAP, "soap:address"); $address->setAttribute("location", $this->endPoint); $port->appendChild($address); $service->appendChild($port); return $service; } /** * validate() and set endPoint * @param $endPoint string endPoint URI * @throw Ficus_URISyntaxException invalid. */ private function setEndPoint($endPoint){ try { Ficus_URIBuilder::create($endPoint); } catch (Ficus_URISyntaxException $e) { throw new Ficus_URISyntaxException( "End point URI must be valid! : $endPoint"); } $this->endPoint = $endPoint; } /** * validate() and set targetNS * @param $targetNS string targetNS URI * @throw Ficus_URISyntaxException invalid. */ private function setTargetNameSpace($targetNS){ try { Ficus_URIBuilder::create($targetNS); } catch (Ficus_URISyntaxException $e) { throw new Ficus_URISyntaxException( "Target Namespace URI is invalid : $targetNS"); } $this->targetNS = $targetNS; } /** * get TargetNS * @return string targetNS */ public function targetNameSpace(){ return $this->targetNS; } /** * validate() and set portName * @param $portName string set port name * @throw Ficus_IllegalArgumentException invalid port name. */ private function setPortName($portName){ if(empty($portName)){ throw new Ficus_IllegalArgumentException( "Port Name is Invalid : $portName"); } $this->portName = $portName . "PortType"; $this->serviceName = $portName . "Service"; $this->bindingName = $portName . "Binding"; } /** * validate() and set operationName * @param $operationName string set operation name * @throw Ficus_IllegalArgumentException invalid operation name. */ private function setOperationName($operationName){ if(empty($operationName)){ throw new Ficus_IllegalArgumentException( "Operation Name is Invalid : $operationName"); } $this->operationName = $operationName; } /** * validate() and set Input parameter * @param $input Ficus_ValidatableComplexParameter input array */ private function setInput($input){ Ficus_Assert::typeHinting('Ficus_ValidatableComplexParameter', $input); $this->input = $input; } /** * validate() and set Output parameter * @param $output Ficus_ValidatableComplexParameter output array */ private function setOutput($output){ Ficus_Assert::typeHinting('Ficus_ValidatableComplexParameter', $output); $this->output = $output; } } ?> ficus/net/URISyntax.php100644 1751 144 44417 10645132217 10566 SUMI Masafumi * @version $Id: URISyntax.php 2 2007-07-11 10:37:48Z ishitoya $ * * URISyntax for php */ require_once("ficus/collection/UnicodeIterator.php"); require_once("ficus/exception/URISyntaxException.php"); require_once("ficus/lang/Object.php"); require_once("ficus/lang/Unicode.php"); require_once("ficus/net/URICharacters.php"); require_once("ficus/XML/XMLUtils.php"); /** * @class Ficus_URISyntax */ class Ficus_URISyntax extends Ficus_Object implements Ficus_URICharacters { /** * URI pattern. */ const URI_PATTERN = '/^(?:([^:\/\?#]+)(:))?(?:(\/\/)([^\/\?#]*))?([^\?#]*)(?:(\?)([^#]*))?(?:(#)(.*))?/'; /** * Index of matches URI pattern. */ const MATCH_SCHEME = 1; const MATCH_AUTHORITY = 4; const MATCH_PATH = 5; const MATCH_QUERY = 7; const MATCH_FRAGMENT = 9; /** * URI scheme pattern. */ const SCHEME_PATTERN = '/^(?:[a-zA-Z][a-zA-Z0-9\+\-\.]*)$|^$/'; /** * URI port pattern. */ const PORT_PATTERN = '/^[0-9]*/'; /** * IPv4 dec_octet pattern. */ const DEC_OCTET_PATTERN = '/([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/'; /** * Alphabet char ranges. */ protected static $alpha = array( array(self::C_CAPITAL_A, self::C_CAPITAL_Z), array(self::C_SMALL_A, self::C_SMALL_Z) ); /** * Digit char ranges. */ protected static $digit = array( array(self::C_ZERO, self::C_NINE) ); /** * Gen delimiters char ranges. */ protected static $gen_delims = array( self::C_COLON, self::C_SLASH, self::C_QUESTION, self::C_SHARP, self::C_LEFT_SQUARE_BRACKET, self::C_RIGHT_SQUARE_BRACKET, self::C_ATMARK, ); /** * Sub delimiters char ranges. */ protected static $sub_delims = array( self::C_EXCLAMATION, self::C_DOLLAR, self::C_AMPERSAND, self::C_APOSTROPHE, self::C_LEFT_CURLY_BRACKET, self::C_RIGHT_CURLY_BRACKET, self::C_ASTERISK, self::C_PLUS, self::C_COMMA, self::C_SEMICOLON, self::C_EQUALS ); /** * Instance it self. */ protected static $self; /** * Constructor. */ protected function __construct() { } /** * static constructor. */ public static function createInstance() { if (!isset(self::$self)) { self::$self = new Ficus_URISyntax(); } return self::$self; } /** * Get syntax type. */ public function getSyntaxType() { return 'URI'; } /** * Get unreserved chars. * * IRI can use UCS charactor in some component. * * @return array of unreserved chars. */ public function getUnreservedChars() { return array_merge(self::$alpha, self::$digit, array(self::C_HYPHEN), array(self::C_DOT), array(self::C_UNDERBAR), array(self::C_TILDE)); } /** * Get pchars. * * @return array of pchars. */ public function getPChars() { return array_merge(self::getUnreservedChars(), self::$sub_delims, array(self::C_ATMARK), array(self::C_COLON)); } /** * Get segment chars. * * @return array of segment chars. */ public function getSegmentChars() { return array_merge(self::getUnreservedChars(), self::$sub_delims, array(self::C_ATMARK), array(self::C_COLON), array(self::C_SLASH)); } /** * Get segment no colon chars. * * @return array of segment no colon chars. */ public function getSegmentNCChars() { return array_merge(self::getUnreservedChars(), self::$sub_delims, array(self::C_ATMARK), array(self::C_SLASH)); } /** * Get fragment chars. * * @return array of fragment chars. */ public function getFragmentChars() { return array_merge(self::getPChars(), array(self::C_SLASH), array(self::C_QUESTION)); } /** * Get query chars. * * IRI can use private charactor in query. * * @return array of query chars. */ public function getQueryChars() { return self::getFragmentChars(); } /** * Get userInfo chars. * * @return array of userInfo chars. */ public function getUserInfoChars() { return array_merge(self::getUnreservedChars(), self::$sub_delims, array(self::C_COLON)); } /** * Get IPvFuture chars. * * @return array of IPvFuture chars. */ public function getIpvfutureChars() { return array_merge(self::getUnreservedChars(), self::$sub_delims, array(self::C_COLON)); } /** * Get reg-name chars. * * @return array of reg-name chars. */ public function getRegNameChars() { return array_merge(self::getUnreservedChars(), self::$sub_delims); } /** * Validate char in ranges. * * @param $code string unicode character code. * @param $validChars array of array of unicode pairs valid char ranges. * @return boolean true if valid. */ protected function validateChar($code, array $validChars = null) { foreach ($validChars as $charRange) { if (is_array($charRange)) { if ($charRange[0] <= $code && $code <= $charRange[1]) { return true; } } else { if ($charRange == $code) { return true; } } } return false; } /** * Validate string in char ranges. * * @param $str string string. * @param $validChars array of array of unicode pairs valid char ranges. * @return boolean true if valid. */ public function validateString($str, array $validChars = null) { foreach (new Ficus_UnicodeIterator($str) as $code) { if (!self::validateChar($code, $validChars)) { return false; } } return true; } /** * encode invalid string. * * @param $str string string. * @param $validChars array of array of unicode pairs valid char ranges. * @return boolean true if valid. */ public function encodeString($str, array $validChars = null) { if (is_null($str)) { return null; } $ret = ''; foreach (new Ficus_MBStringIterator($str) as $char) { $code = Ficus_Unicode::getUnicode($char); if (self::validateChar($code, $validChars)) { $ret .= $char; } else { $ret .= $this->encodeChar($char); } } return $ret; } /** * Encode char. * * @param $char string UTF-8 character. * @return string encoded string. */ protected function encodeChar($char) { $hex = strtoupper(bin2hex($char)); // need 2 or 4 character. $hex = (strlen($hex) % 2 == 0) ? $hex : '0' . $hex; return '%' . join('%', str_split($hex, 2)); } /** * Validate scheme. * * @param $host string scheme. * @return void. */ public function validateScheme($scheme) { if (preg_match(self::SCHEME_PATTERN, $scheme) == 0) { throw new Ficus_URISyntaxException("Illegal charcter in {$this->getSyntaxType()} scheme : '{$scheme}'."); } } /** * Validate authority. * * @param $host string authority. * @return void. */ public function validateAuthority($authority) { list($userInfo, $host) = preg_split('/@/', $authority, 2); list($host, $port) = preg_split('/:/', $host, 2); self::validateUserInfo($userInfo); self::validateHost($host); self::validatePort($port); } /** * Validate userInfo. * * @param $host string userInfo. * @return void. */ public function validateUserInfo($userInfo) { // pre-replace pct-encoded $decoded = Ficus_XMLUtils::decodeURI($userInfo); if (!self::validateString($decoded, self::getUserInfoChars())) { throw new Ficus_URISyntaxException("Illegal charcter in {$this->getSyntaxType()} userInfo : {$userInfo}."); } } /** * Encode userInfo. * * @param $host string userInfo. * @return string encoded userInfo. */ public function encodeUserInfo($userInfo) { return $this->encodeString($userInfo, self::getUserInfoChars()); } /** * Validate host. * * @param $host string host. * @return void. */ public function validateHost($host) { if (self::validateIPLiteral($host)) { return; } if (self::validateIPV4Address($host)) { return; } if (!self::validateRegName($host)) { throw new Ficus_URISyntaxException("Illegal charcter in {$this->getSyntaxType()} host : {$host}."); } } /** * Encode host. * * @param $host string host. * @return string encoded host. */ public function encodeHost($host) { if (self::validateIPLiteral($host)) { return $host; } if (self::validateIPV4Address($host)) { return $host; } return $this->encodeString($host, self::getRegNameChars()); } /** * Validate port. * * @param $host string port. * @return void. */ public function validatePort($port) { if (preg_match(self::PORT_PATTERN, $port) == 0) { throw new Ficus_URISyntaxException("Illegal charcter in {$this->getSyntaxType()} port : {$port}."); } } /** * Validate path. * * @param $path string path. * @return void. */ public function validatePath($path) { if (strlen($path) == 0) { return true; } else if ($path{0} == '/') { // path-abempty = *( "/" segment ) // path-absolute = "/" [ segment-nz *( "/" sgement ) ] return $this->validateString($path, self::getSegmentChars()); } else if ($noscheme) { // path-noscheme = segment-nz-nc *( "/" segment ) $charset = self::getSegmentNCChars(); foreach (preg_split('/\//', $path, 2) as $segment) { if (!$this->validateString($segment, $charset)) { return false; } $charset = self::getSegmentChars(); } return true; } else { // path-rootless = segment-nz *( "/" segment ) return $this->validateString($path, self::getSegmentChars()); } } /** * Encode path. * * @param $path string path. * @param $noscheme boolean true if no scheme. * @return string encoded path. */ public function encodePath($path, $noscheme = false) { if (strlen($path) == 0) { // path-abempty = *( "/" segment ) // path-empty = 0 return $path; } else if ($path{0} == '/') { // path-abempty = *( "/" segment ) // path-absolute = "/" [ segment-nz *( "/" sgement ) ] return $this->encodeString($path, self::getSegmentChars()); } else if ($noscheme) { // path-noscheme = segment-nz-nc *( "/" segment ) $segments = array(); $charset = self::getSegmentNCChars(); foreach (preg_split('/\//', $path, 2) as $segment) { $segments []= $this->encodeString($segment, $charset); $charset = self::getSegmentChars(); } return join('/', $segments); } else { // path-rootless = segment-nz *( "/" segment ) return $this->encodeString($path, self::getSegmentChars()); } return $path; } /** * Validate query. * * @param $host string query. * @return void. */ public function validateQuery($query) { if (!self::validateString($query, self::getQueryChars())) { throw new Ficus_URISyntaxException("Illegal charcter in {$this->getSyntaxType()} query : {$query}."); } } /** * Encode query. * * @param $host string query. * @return string encoded query. */ public function encodeQuery($query) { return $this->encodeString($query, self::getQueryChars()); } /** * Validate fragment. * * @param $host string fragment. * @return void. */ public function validateFragment($fragment) { if (!self::validateString($fragment, self::getFragmentChars())) { throw new Ficus_URISyntaxException("Illegal charcter in {$this->getSyntaxType()} fragment : {$fragment}."); } } /** * Encode fragment. * * @param $host string fragment. * @return string encoded fragment. */ public function encodeFragment($fragment) { return $this->encodeString($fragment, self::getFragmentChars()); } /** * Validate IP-literal. * * @param $host string hostname. * @return boolean true if valid. */ public function validateIPLiteral($host) { if (preg_match('/^\[(.*)\]$/', $host, $matches) == 0) { return false; } if (Ficus_Unicode::at($matches[1], 0) == "v") { return self::validateIPvfuture($matches[1]); } else { return self::validateIPv6address($matches[1]); } } /** * Validate IPv6 address. * * @param $host string hostname. * @return boolean true if valid. */ public function validateIPv6Address($host) { $groups = preg_split('/::/', $host); $left = preg_split('/:/', $groups[0]); if (sizeof($groups) > 1) { $v6 = array_merge($left, preg_split('/:/', $group[1])); } else { $v6 = $left; } $last = array_slice($v6, -1); if (preg_match('/\./', $last[0])) { $v4 = array_pop($v6); if (!self::validateIPV4address($v4)) { return false; } if (sizeof($v6) > 6) { return false; } } else if (sizeof($v6) > 8) { return false; } foreach ($v6 as $hex) { if (preg_match('/^[0-9a-fA-F]{1,4}$/', $hex) == 0) { return false; } } return true; } /** * Validate IPvfuture address. * * @param $host string hostname. * @return boolean true if valid. */ public function validateIPvfuture($host) { if (preg_match('/^v[0-9A-Fa-f]\./', $host) == 0) { return false; } $last = mb_substr($host, 3, -1, Ficus_Unicode::UTF8); return self::validateString($last, self::getIpvfutureChars()); } /** * Validate IPv4 address. * * @param $host string hostname. * @return boolean true if valid. */ public function validateIPV4Address($host) { $ip = array_fill(0, 4, substr(self::DEC_OCTET_PATTERN, 1, -1)); $IPV4Pattern = '/' . join('\\.', $ip) . '/'; return preg_match($IPV4Pattern, $host) > 0; } /** * Validate reg-name. * * @param $host string reg-name. * @return bolean if valid. */ public function validateRegName($host) { // pre-replace pct-encoded $decoded = Ficus_XMLUtils::decodeURI($host); return self::validateString($decoded, self::getRegNameChars()); } /** * Split URI component. * * @param $uri IRI or URI. * @reutrn array of components. */ public function splitComponent($uri) { if (preg_match(self::URI_PATTERN, $uri, $matches) == 0) { throw new Ficus_URISyntaxException("Syntax error: {$this->uri}"); } $components = array(); $components []= $this->matchURIComponent($matches, self::MATCH_SCHEME); $components []= $this->matchURIComponent($matches, self::MATCH_AUTHORITY); $components []= $matches[self::MATCH_PATH]; $components []= $this->matchURIComponent($matches, self::MATCH_QUERY); $components []= $this->matchURIComponent($matches, self::MATCH_FRAGMENT); return $components; } /** * Get match URI component. * * @param $matches array matches of URI pattern. * @param $componentType int Index of matches URI pattern. * @return string matches component. */ private function matchURIComponent($matches, $componentType) { static $delimiters = array(self::MATCH_SCHEME => array(2, ':'), self::MATCH_AUTHORITY => array(3, '//'), self::MATCH_QUERY => array(6, '?'), self::MATCH_FRAGMENT => array(8, '#')); $delim = $delimiters[$componentType]; if (isset($matches[$delim[0]]) && $matches[$delim[0]] == $delim[1]) { return $matches[$componentType]; } else { return null; } } } ?> ficus/net/IsbnURN.php100644 1751 144 2223 10645132217 10145 SUMI Masafumi * @version $Id: IsbnURN.php 2 2007-07-11 10:37:48Z ishitoya $ * * IsbnURN */ require_once("ficus/net/URN.php"); /** * @class Ficus_IsbnURN */ class Ficus_IsbnURN extends Ficus_URN { /** * Get default NID. * * @return string NID. */ final public function getDefaultNID(){ return 'isbn'; } } ?> ficus/net/URI.php100644 1751 144 31622 10645132217 7351 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: URI.php 2 2007-07-11 10:37:48Z ishitoya $ * * URI for php */ require_once("ficus/lang/Object.php"); require_once("ficus/lang/Types.php"); require_once("ficus/net/IRISyntax.php"); require_once("ficus/net/URISyntax.php"); require_once("ficus/lang/Unicode.php"); require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/exception/URISyntaxException.php"); /** * @class Ficus_URI */ class Ficus_URI extends Ficus_Object { /** * @var $uri string Passed plain string. */ protected $uri; /** * @var $scheme string scheme. */ protected $scheme; /** * @var $specific string authority. */ protected $authority; /** * @var string userInfo. */ protected $userInfo; /** * @var string host. */ protected $host; /** * @var string port. */ protected $port; /** * @var $specific string path. */ protected $path; /** * @var $fragment string query. */ protected $query; /** * @var $fragment string fragment. */ protected $fragment; /** * @var $syntax URI syntax. */ protected $syntax; const IRI = 'IRI'; const URI = 'URI'; /** * Constructor. * * @param $uri mixed URI to be parsed. */ public function __construct($uri, Ficus_URISyntax $syntax = null, $encoding = Ficus_Unicode::UTF8) { $this->uri = rawurldecode($uri); if (is_null($syntax)) { $this->syntax = Ficus_URISyntax::createInstance(); } else { $this->syntax = $syntax; } $this->parse(); } /** * Validate scheme. */ public function validateScheme() { if (!is_null($this->scheme)) { $this->syntax->validateScheme($this->scheme); } if (strcasecmp($this->getDefaultScheme(), $this->getScheme()) !== 0) { throw new Ficus_URISyntaxException("Illegal URI scheme : '{$this->getScheme()}' is not '{$this->getDefaultScheme()}'."); } } /** * Split specific. * * @throw Ficus_URISyntaxException invalid URI. */ final protected function splitComponent() { list($this->scheme, $this->authority, $this->path, $this->query, $this->fragment) = $this->syntax->splitComponent($this->uri); } /** * Constructor. * * @param $uri mixed URI to be parsed. */ static public function createIRI($uri) { return new Ficus_URI($uri, Ficus_IRISyntax::createInstance()); } /** * Constructor. * * @param $uri mixed URI to be parsed. */ static public function createURI($uri) { return new Ficus_URI($uri, Ficus_URISyntax::createInstance()); } /** * Parse URL. */ protected function parse() { $this->splitComponent(); $this->parseAuthority(); $this->validateScheme(); } /** * Parse authority. */ protected function parseAuthority() { if (is_null($this->authority) || strlen($this->authority) == 0) { return; } if (preg_match('/^(?:([^@]*)(@))?(.*)(?:(:)([0-9]*))?$/', $this->authority, $matches) == 0) { throw new Ficus_URISyntaxException('Bad authority'); } $this->userInfo = isset($matches[2]) && $matches[2] == '@' ? $matches[1] : null; $this->host = isset($matches[3]) ? $matches[3] : null; $this->port = isset($matches[4]) && $matches[4] == ':' ? $matches[5] : null; } /** * Get default scheme. * * @return string scheme name. */ public function getDefaultScheme() { return strtolower($this->getScheme()); } /** * Get scheme. * * @return string scheme. */ public function getScheme() { return $this->scheme; } /** * Get raw scheme. * * @return string raw scheme. */ public function getRawScheme() { return $this->getScheme(); } /** * Get scheme specific part. * * @return string scheme specific part. */ public function getSpecific() { $specific = ''; $specific .= is_null($this->authority) ? '' : '//' . $this->getAuthority(); $specific .= is_null($this->path) ? '' : $this->getPath(); $specific .= is_null($this->query) ? '' : '?' . $this->getQuery(); return $specific; } /** * Get raw scheme specific part. * * @return string raw scheme specific part. */ public function getRawSpecific() { $specific = ''; $specific .= is_null($this->authority) ? '' : '//' . $this->authority; $specific .= is_null($this->path) ? '' : $this->path; $specific .= is_null($this->query) ? '' : '?' . $this->query; return $specific; } /** * Get scheme authority part. * * @return string scheme authority part. */ public function getAuthority() { if (is_null($this->authority)) { return null; } $ret = ''; $ret .= is_null($this->userInfo) ? '' : $this->getUserInfo() . '@'; $ret .= $this->getHost(); $ret .= is_null($this->port) ? '' : $this->port; return $ret; } /** * Get raw authority. * * @return string raw authority. */ public function getRawAuthority() { return $this->authority; } /** * Get user. * * @return string user. */ final public function getUserInfo() { return $this->syntax->encodeUserInfo($this->userInfo); } /** * Get raw user. * * @return string raw user. */ final public function getRawUserInfo() { return $this->userInfo; } /** * Get host. * * @return string host. */ final public function getHost() { return $this->syntax->encodeHost($this->host); } /** * Get host. * * @return string host. */ final public function getRawHost() { return $this->host; } /** * Get port. * * @return string port. */ final public function getPort() { return $this->port; } /** * Get scheme path part. * * @return string scheme path part. */ public function getPath() { return $this->syntax->encodePath($this->path, is_null($this->scheme)); } /** * Get raw path. * * @return string raw path. */ public function getRawPath() { return $this->path; } /** * Get query. * * @return string query. */ public function getQuery() { return $this->syntax->encodeQuery($this->query); } /** * Get raw query. * * @return string raw query. */ public function getRawQuery() { return $this->query; } /** * Get fragment. * * @return string fragment. */ public function getFragment() { return $this->syntax->encodeFragment($this->fragment); } /** * Get raw fragment. * * @return string raw fragment. */ public function getRawFragment() { return $this->fragment; } /** * Get raw URI. * * @return string raw URI. */ public function getRawURI() { return $this->uri; } /** * To string. * * @return String URI. */ public function toString() { return $this->uri; } /** * To string. * * @return String URI. */ public function __toString() { return $this->uri; } /** * Get URI. * * @return string URI. */ public function getURI() { return $this->uri; } /** * */ public function toAsciiString() { $uri = ''; $uri .= is_null($this->getScheme()) ? '' : $this->getScheme() . ":"; $uri .= is_null($this->getAuthority()) ? '' : '//' . $this->getAuthority(); $uri .= is_null($this->getPath()) ? '' : $this->getPath(); $uri .= is_null($this->getQuery()) ? '' : '?' . $this->getQuery(); $uri .= is_null($this->getFragment()) ? '' : '#' . $this->getFragment(); return new Ficus_URI($uri); } /** * Get URI. * * @return string URI. */ public function toURI() { if ($this->syntax instanceof Ficus_URISyntax) { return $this; } return new Ficus_URI($this->uri); } /** * Convert to IRI. * * @return Ficus_URI IRI. */ public function toIRI() { if ($this->syntax instanceof Ficus_IRISyntax) { return $this; } return new Ficus_URI(rawurldecode($this->uri), Ficus_IRISyntax::createInstance()); } /** * Resovle relative URI. * * @param $relative mixed string or Ficus_URI relative URI. */ public function resolve($uri) { Ficus_Assert::typeHinting('Ficus_URI', $uri); if ($uri->isAbsolute()) { if ($uri instanceof Ficus_HierarchicalURI && $this->getScheme() == $uri->getScheme()) { // 3) $uriScheme = null; } else { return $uri; } } else { $uriScheme = $uri->getRawScheme(); } // add query and fragment. if (strlen($uriScheme) == 0 && is_null($uri->getAuthority()) && strlen($uri->getPath()) == 0 && strlen($uri->getQuery()) == 0 && !is_null($uri->getFragment())) { if ($this->getFragment() === $uri->getFragment()) { return $this; } $uri = Ficus_URIBuilder::createURIStringByParts($this->getRawScheme(), $this->getRawAuthority(), $this->getRawPath(), $this->getRawQuery(), $uri->getRawFragment()); return new self($uri, $this->syntax); } // 4), 5) if ($uri->getAuthority()) { // 7) $uri = Ficus_URIBuilder::createURIStringByParts($this->getRawScheme(), $uri->getRawAuthority(), $uri->getRawPath(), $uri->getRawQuery(), $uri->getRawFragment()); return new self($uri, $this->syntax); } else { if (substr($uri->getRawPath(), 0, 1) == '/') { $path = $uri->getRawPath(); } else { // 4), 6) $path = substr($this->getRawPath(), 0, strlen($this->getRawPath()) - strlen(strrchr($this->getRawPath(), '/'))); if ($path) { $path = Ficus_Dir::resolve($path, $uri->getRawPath(), '/'); } else { $path = $uri->getRawPath(); } if ($path{0} != '/') { $path = '/' . $path; } } $uri = Ficus_URIBuilder::createURIStringByParts($this->getRawScheme(), $this->getRawAuthority(), $path, $uri->getRawQuery(), $uri->getRawFragment()); return new self($uri, $this->syntax); } } /** * Is absolute URI. * * @return boolean true if absolute URL. */ public function isAbsolute() { return !is_null($this->getScheme()); } /** * Normalize URI. * * @return Ficus_URI URI. */ public function normalize() { } } ?> ficus/net/URL.php100644 1751 144 3417 10645132217 7335 SUMI Masafumi * @version $Id: URL.php 2 2007-07-11 10:37:48Z ishitoya $ * * URL */ require_once("ficus/net/HierarchicalURI.php"); require_once("ficus/exception/URISyntaxException.php"); /** * @class Ficus_URL */ class Ficus_URL extends Ficus_HierarchicalURI { /** * Authority pattern. */ const AUTHORITY_PATTERN = '/(?:([^@]+)(@))?([^:]+)(?:(:)(.*))?/'; /** * Parse URL. * * @throw Ficus_URISyntaxException invalid URL. */ protected function parse() { parent::parse(); // URL is absolute URI if (preg_match(self::AUTHORITY_PATTERN, $this->authority, $matches)) { if (isset($mathces[2]) && $mathces[2] == '@') { $this->user = $matches[1]; } $this->host = is_null($matches[3]) ? '' : $matches[3]; if (isset($matches[4]) && $matches[4] == ':') { $this->port = isset($matches[5]) ? $matches[5] : null; } } } } ?> ficus/net/URN.php100644 1751 144 5322 10645132217 7334 SUMI Masafumi * @version $Id: URN.php 2 2007-07-11 10:37:48Z ishitoya $ * * URN */ require_once("ficus/net/OpaqueURI.php"); require_once("ficus/exception/URISyntaxException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_URN */ class Ficus_URN extends Ficus_OpaqueURI { /** * Get default scheme. * * @return string scheme name. */ final public function getDefaultScheme() { return 'urn'; } /** * Parse URN. * * @throw Ficus_URISyntaxException invalid NID in URN. */ protected function parse(){ parent::parse(); $pathes = preg_split('/:/', $this->getPath()); $this->nid = $pathes[0]; if (preg_match('/[a-zA-Z0-9][a-zA-Z0-9\\-]{1,31}/', $this->nid) === 0) { throw new Ficus_URISyntaxException("Illegal URN NID: {$this->nid}"); } if (strcasecmp($this->getDefaultNID(), $this->nid) !== 0) { throw new Ficus_URISyntaxException("Illegal URN NID: {$this->nid} is not {$this->getDefaultNID()}."); } $this->nss = array_slice($pathes, 1); } /** * Get default NID. * * @return string NID. */ public function getDefaultNID() { return strtolower($this->nid); } /** * Get NID. * * @return string NID. */ final public function getNID() { return $this->nid; } /** * Get NSS. * * @param $num int number of NSS. * @return mixed NSS array or NSS[$num]. * @throw Ficus_IllegalArgumentException illegal number. */ final public function getNSS($num = null){ if ($num === null) { return $this->nss; } else if (is_numeric($num)) { return isset($this->nss[$num]) ? $this->nss[$num] : null; } else { throw new Ficus_IllegalArgumentException("getNSS() need numeric argument."); } } } ?> ficus/net/AbsoluteURI.php100644 1751 144 1773 10645132217 11034 SUMI Masafumi * @version $Id: AbsoluteURI.php 2 2007-07-11 10:37:48Z ishitoya $ * * Absolute URI for php */ /** * @interface Ficus_AbsoluteURI */ interface Ficus_AbsoluteURI { } ?> ficus/net/Cookie.php100644 1751 144 12105 10645132217 10116 ISHITOYA Kentaro * @version $Id: Cookie.php 2 2007-07-11 10:37:48Z ishitoya $ * * cookie object for page */ /** * @class Ficus_Cookie */ class Ficus_Cookie { const VALUE = "value"; const EXPIRE = "expire"; const SECURE = "secure"; const PATH = "path"; const DOMAIN = "domain"; const HTTPONLY = "httponly"; /** * @var $name string name of cookie */ protected $name = null; /** * @var $data string data sended */ protected $values = array(); /** * construct */ public function __construct(){ } /** * setcookie * @param $name string name of cookie * @param $value string value of cookie * @param $path string path * @param $domain string domain * @param $expire integer expire time, minuites * @param $secure boolean secure * @param $httponly boolean httponly */ public function set($name, $value, $path = null, $domain = null, $expire = 0, $secure = false, $httponly = false){ $expire = ($expire === 0) ? 0 : time() - $expire * 60; if(is_null($path)){ $path = new Ficus_String($_SERVER["REQUEST_URI"]); $path = ($path->endsWith("/")) ? $path : dirname($path) . "/"; } $domain = (is_null($domain)) ? $_SERVER["SERVER_HOST"] : $domain; $secure = ($secure) ? 1 : 0; $httponly = ($httponly) ? 1 : 0; $this->data[$name] = array(self::VALUE => $value, self::EXPIRE => $expire, self::PATH => $path, self::DOMAIN => $domain, self::SECURE => $secure, self::HTTPONLY => $httponly); setcookie($name, $value, $expire, $path, $domain, $secure, $httponly); } /** * update cookie value * @param $name string name of cookie * @param $value string value of cookie * @param $expire integer expire time, minuites * @param $secure boolean secure * @param $httponly boolean httponly */ public function update($name, $value, $path = null, $domain = null, $expire = 0, $secure = false, $httponly = false){ $this->remove($name); $this->set($name, $value, $path, $domain, $expire, $secure, $httponly); } /** * change cookie expires * @param $name string name of cookie to delete * @param $expire integer expire time, minuites */ public function touch($name, $expire = null){ $value = $this->data[$name][self::VALUE]; $path = $this->data[$name][self::PATH]; $domain = $this->data[$name][self::DOMAIN]; $secure = $this->data[$name][self::SECURE]; $httponly = $this->data[$name][self::HTTPONLY]; if(is_null($expire)){ $expire = $this->data[$name][self::EXPIRE]; } $this->remove($name); $this->set($name, $value, $path, $domain, $expire, $secure, $httponly); } /** * change cookie expires * @param $expire integer expire time, minuites */ public function touchAll($expire = null){ foreach($this->data as $key => $data){ $this->touch($key, $expire); } } /** * get cookie value * @param $name string name of cookie * @return string value of cookie */ public function get($name){ if($this->isExists($name) == false){ throw new Ficus_IllegalArgumentException("cookie $name is not found."); } $value = $_COOKIE[$name]; $this->data[$name] = array(self::VALUE => $value); return $value; } /** * remove cookie * @param $name string name of cookie to delete */ public function remove($name){ setcookie($name, 0, time() - 3000); unset($this->data[$name]); } /** * remove all */ public function removeAll(){ foreach($this->data as $key => $data){ $this->remove($key); } } /** * check is exists * @param $name string name of cookie to check */ public function isExists($name){ if(isset($_COOKIE[$name]) == false){ return false; } return true; } } ?> ficus/net/IRISyntax.php100644 1751 144 5466 10645132217 10533 SUMI Masafumi * @version $Id: IRISyntax.php 2 2007-07-11 10:37:48Z ishitoya $ * * IRISyntax for php */ require_once("ficus/net/URISyntax.php"); /** * @class Ficus_IRISyntax */ class Ficus_IRISyntax extends Ficus_URISyntax { /** * Get syntax type. */ public function getSyntaxType() { return 'IRI'; } /** * static constructor. */ public static function createInstance() { if (!isset(self::$self)) { self::$self = new Ficus_IRISyntax(); } return self::$self; } /** * UCS char ranges. */ protected static $ucschar = array( array( 0xA0, 0xD7FF), array( 0xF900, 0xFDCF), array( 0xFDF0, 0xFFEF), array(0x10000, 0x1FFFD), array(0x20000, 0x2FFFD), array(0x30000, 0x3FFFD), array(0x40000, 0x4FFFD), array(0x50000, 0x5FFFD), array(0x60000, 0x6FFFD), array(0x70000, 0x7FFFD), array(0x80000, 0x8FFFD), array(0x90000, 0x9FFFD), array(0xA0000, 0xAFFFD), array(0xB0000, 0xBFFFD), array(0xC0000, 0xCFFFD), array(0xD0000, 0xDFFFD), array(0xE1000, 0xEFFFD) ); /** * Private use area char ranges. */ protected static $iprivate = array( array( 0xE000, 0xF8FF), array( 0xF0000, 0xFFFFD), array(0x100000, 0x10FFFD) ); /** * Constructor. */ protected function __construct() { } /** * Get unreserved chars. * * IRI can use UCS charactor in some component. * * @return array of unreserved char ranges. */ public function getUnreservedChars() { return array_merge(parent::getUnreservedChars(), self::$ucschar); } /** * Get query chars. * * IRI can use private charactor in query. * * @return array of unreserved char ranges. */ public function getQueryChars() { return array_merge(self::getFragmentChars(), self::$iprivate); } } ?> ficus/net/Mailer.php100644 1751 144 3616 10645132217 10105 ISHITOYA Kentaro * @version $Id: Mailer.php 2 2007-07-11 10:37:48Z ishitoya $ * * simple mailer */ /** * @class Ficus_Mailer */ class Ficus_Mailer { /** * @var $from string from */ private $from; /** * @var $to string to */ private $to; /** * constructor * @param $from string from * @param $to string to */ public function __construct($from, $to){ $this->from = $from; $this->to = $to; } /** * send a mail to address. * @param $subject String subject * @param $message String message */ public function send($subject, $message){ if(empty($this->to) || empty($this->from)){ throw new Ficus_IllegalArgumentException("to or from is not setted"); } $headers = $this->createHeaders(); mail($this->to, $subject, $message, $headers); } /** * create headers. */ private function createHeaders(){ $headers = array(); $headers[] = "From : " . $this->from; return implode('\r\n', $headers); } } ?> ficus/net/HttpURL.php100644 1751 144 2251 10645132217 10170 SUMI Masafumi * @version $Id: HttpURL.php 2 2007-07-11 10:37:48Z ishitoya $ * * HttpURL */ require_once("ficus/net/URL.php"); /** * @class Ficus_HttpURL */ class Ficus_HttpURL extends Ficus_URL { /** * Get default scheme. * * @return string scheme name. */ final public function getDefaultScheme() { return 'http'; } } ?> ficus/net/urn.dicon100644 1751 144 403 10645120256 7754 ficus/net/components21.dtd100644 1751 144 2773 10645120160 11205 ficus/net/URIFactoryComponentFactory.php100644 1751 144 6151 10646431661 14101 SUMI Masafumi * @version $Id: URIFactoryComponentFactory.php 12 2007-07-15 14:41:51Z ishitoya $ * * URI component factory */ require_once("ficus/io/File.php"); require_once("ficus/config/Registry.php"); require_once("ficus/lang/AutoLoad.php"); require_once("ficus/lang/S2ContainerAutoLoad.php"); require_once("ficus/lang/ClassLoaderAutoLoad.php"); require_once("ficus/net/URLFactoryImpl.php"); /** * @class Ficus_URIComponentFactory */ class Ficus_URIFactoryComponentFactory { /** * Default dicon file name. */ const DEFAULT_DICON_FILE = 'uri.dicon'; /** * URI dicon path. */ const DICON_PATH = 'FICUS_URI_DICON_PATH'; /** * URI extend dicon path. */ const EXTEND_DICON_PATH = 'FICUS_URI_EXTEND_DICON_PATH'; /** * dicon namespace. */ const DICON_NAMESPACE = 'uri.scheme'; /** * @var S2Container S2Container. */ private static $container = null; /** * Get dicon path. * * return string dicon path.. */ private static function getDiconPath() { if (!defined(self::DICON_PATH)) { define(self::DICON_PATH, preg_replace('/\\\/', '/', dirname(__FILE__))); } $diconPath = Ficus_Registry::search(self::EXTEND_DICON_PATH); if ($diconPath === false || !is_readable($diconPath)) { $diconPath = Ficus_File::currentDir() ->resolve(self::DEFAULT_DICON_FILE)->getPath(); } return $diconPath; } /** * Get S2Container. * * return S2Container S2Container. */ private static function getS2Container() { if (self::$container == null) { $diconPath = self::getDiconPath(); self::$container = S2ContainerFactory::create($diconPath); Ficus_AutoLoad::add(new Ficus_S2ContainerAutoLoad()); } return self::$container; } /** * Get URI builder component. * * @param $scheme string scheme. * @return Ficus_URIBuilder URI component. */ public static function getBuilderComponent($scheme) { $container = self::getS2Container(); $componentName = self::DICON_NAMESPACE . '.' . strtolower($scheme); return $container->getComponent($componentName); } } ?> ficus/net/URNFactoryImpl.php100644 1751 144 5132 10645132217 11505 SUMI Masafumi * @version $Id: URNFactoryImpl.php 2 2007-07-11 10:37:48Z ishitoya $ * * URNFactoryImpl */ require_once("ficus/net/URIFactoryImpl.php"); require_once("ficus/net/URN.php"); require_once("ficus/net/IsbnURN.php"); require_once("ficus/exception/URISyntaxException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_URNFactoryImpl */ class Ficus_URNFactoryImpl extends Ficus_URIFactoryImpl { /** * Get suffix of class name. * * @return string suffix. */ public function getSuffix() { return 'URN'; } /** * Default URI . * * @param $uri string URI. * @return Ficus_URI URI. */ public function defaultInstance($uri) { return new Ficus_URN($uri); } /** * Factory method. * * @param $uri string URI. * @return Ficus_URI URI. */ public function createInstance($scheme, $uri) { try { $split = preg_split('/:/', $uri); $componentKey = 'urn.nid.' . strtolower($split[1]); $component = Ficus_URIFactoryComponentFactory::getBuilderComponent($scheme, $componentKey); if (!($component instanceof Ficus_URNFactoryImpl)) { return $component->createInstance($scheme, $uri); } } catch (S2Container_ComponentNotFoundRuntimeException $e) { // do nothing. //var_dump($e->getMessage()); } catch (Ficus_MethodNotFoundException $e) { var_dump($e->getTraceAsString()); } catch (Exception $e) { var_dump(get_class($e)); var_dump($e->getMessage()); } $split = preg_split('/:/', $uri); $nid = $split[1]; return Ficus_URIFactoryImpl::createInstance($nid, $uri); } } ?> ficus/net/HierarchicalURI.php100644 1751 144 4270 10645132217 11627 SUMI Masafumi * @version $Id: HierarchicalURI.php 2 2007-07-11 10:37:48Z ishitoya $ * * URI for php */ require_once("ficus/net/URI.php"); require_once("ficus/net/URIBuilder.php"); require_once("ficus/lang/Assert.php"); /** * @class Ficus_HierarchicalURI */ class Ficus_HierarchicalURI extends Ficus_URI { /** * Constructor. * * @param $uri mixed URI to be parsed. */ public function __construct($uri) { parent::__construct($uri); } /** * Parse URL. */ protected function parse() { parent::parse(); if (is_null($this->authority)) { if ($this->isAbsolute() && $this->path{0} != '/') { throw new Ficus_URISyntaxException('No Hierarchical URI. ' . $this->uri); } } } /** * Is absolute URI. * * Relative URI has not scheme. * * @return boolean true if absolute URL. */ public function isAbsolute() { return !is_null($this->getScheme()); } /** * Normalize URI. * * @return Ficus_URI URI. */ public function normalize() { $normalizedPath = Ficus_Dir::normalizePath($this->getPath()); $uri = $this->getScheme() . $this->getAuthority() . $normalizedPath; $uri .= '?' . $this->getQuery() . '#' . $this->getFragment(); return self::create($uri); } } ?> ficus/net/uri.dicon100644 1751 144 2021 10646431550 7770 ficus/FicusPathInitializer.php100644 1751 144 13046 10645132217 12216 ISHITOYA Kentaro * @version $Id: FicusPathInitializer.php 2 2007-07-11 10:37:48Z ishitoya $ * * ficus path initilaizer for ficus * use this class to use ficus package. * usage example : * require_once("path/to/FicusPathInitialize.php"); * Ficus_FicusPathInitializer::setUp(); * * if you want to use logger or config or depended library class, use set* * function before use them. */ /** * @class Ficus_FicusPathInitializer */ class Ficus_FicusPathInitializer { /** * @var $configDir string config dir for PropertyFileReader. */ private static $configDir = ""; /** * @var $loggerDir string logger dir for Logger */ private static $loggerDir = ""; /** * @var $libDir string library dir */ private static $libDir = ""; /** * @var $paths array path */ private static $paths = array(); /** * @var $initialized boolean true if initialized */ private static $initialized = false; /** * set config dir * @param $configDir string config dir */ public static function setConfigDirectory($configDir){ self::$configDir = $configDir; } /** * set logger dir * @param $loggerDir string logger dir */ public static function setLoggerDirectory($loggerDir){ self::$loggerDir = $loggerDir; } /** * set library dir * @param $libDir string library dir */ public static function setLibraryDirectory($libDir){ self::$libDir = $libDir; } /** * add paths */ public static function addPath($path, $name = null){ if(self::$initialized){ require_once("ficus/lang/Assert.php"); Ficus_Assert::isType($path, "Ficus_ClassPathElement"); Ficus_ClassPath::add($path, $name); }else{ self::$paths[] = $path; } } /** * add autoload paths */ public static function addAutoLoadPath($path, $prefix = ""){ if(self::$initialized){ require_once("ficus/lang/Assert.php"); Ficus_Assert::isType($path, "Ficus_ClassPathElement"); Ficus_AutoClassLoader::add($path, $prefix); }else{ throw new Exception("before call add Auto load class, must call setup method."); } } public static function addIncludePath($paths){ if(is_string($paths)){ $paths = array($paths); } $systemIncludePaths = explode(PATH_SEPARATOR, get_include_path()); $includePaths = array_merge($paths, $systemIncludePaths); set_include_path(implode(PATH_SEPARATOR, $includePaths)); } /** * initialize. set include path */ private static function initialize(){ $includePaths = array(); $includePaths[] = self::convertDirectorySeparator(self::$libDir); $includePaths = array_merge($includePaths, self::$paths); self::addIncludePath($includePaths); self::$initialized = true; } /** * set up ficus. */ public static function setUp() { self::initialize(); require_once("ficus/lang/ClassPath.php"); require_once("ficus/lang/ClassPathElement.php"); require_once("ficus/io/Dir.php"); if(empty(self::$loggerDir) == false || empty(self::$configDir) == false){ require_once("ficus/io/PropertyFileReader.php"); Ficus_ClassPath::add( new Ficus_ClassPathElement( new Ficus_Dir(self::$configDir)), "conf"); } if(empty(self::$loggerDir) == false){ require_once("ficus/logging/Logger.php"); Ficus_Logger::initialize(self::$loggerDir); } require_once("ficus/lang/AutoLoad.php"); require_once("ficus/lang/S2ContainerAutoLoad.php"); require_once("ficus/lang/ClassLoaderAutoLoad.php"); Ficus_AutoLoad::add(new Ficus_S2ContainerAutoLoad()); Ficus_AutoLoad::add(new Ficus_ClassLoaderAutoLoad()); $pattern = new Ficus_PathPattern(); $pattern->addInclude("**ficus"); $dir = Ficus_Dir::createInstance(__FILE__, "ficus"); $dir->setPattern($pattern); $src = new Ficus_ClassPathElement($dir); Ficus_ClassPath::add($src, "ficus"); require_once("ficus/lang/AutoClassLoader.php"); } /** * teardown */ public static function tearDown(){ Ficus_ClassPath::clear(); } /** * convert DIRECTORY_SEPARATOR * * @param $path string path. */ private static function convertDirectorySeparator($path){ $needle = (DIRECTORY_SEPARATOR == '/') ? '\\' : '\?'; return str_replace($needle, DIRECTORY_SEPARATOR, $path); } } ?> ficus/lang/ClassLoaderAutoLoad.php100644 1751 144 2556 10645132217 12656 ISHITOYA Kentaro * @version $Id: ClassLoaderAutoLoad.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/lang/AutoLoad.php"); require_once("ficus/lang/AutoClassLoader.php"); /** * @class Ficus_ClassLoaderAutoLoad */ class Ficus_ClassLoaderAutoLoad extends Ficus_AutoLoad{ /** * abstract autoload * @param $classname string class name to load * @return boolean true if load succeeded */ protected function load($classname){ return Ficus_AutoClassLoader::import($classname); } } ?> ficus/lang/reflect/ReflectionProperty.php100644 1751 144 3462 10645132217 14311 ISHITOYA Kentaro * @version $Id: ReflectionProperty.php 2 2007-07-11 10:37:48Z ishitoya $ * * Implement getDocComment */ require_once "ficus/lang/PHPVersion.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_ReflectionProperty */ class Ficus_ReflectionProperty extends ReflectionProperty { /** * implementation of getDocComment available from php5.1.0 * @return string document comment */ public function getDocComment(){ if(Ficus_PHPVersion::isOlderThan("5.1.0")){ $class = $this->getDeclaringClass(); $filename = $class->getFileName(); $file = file_get_contents($filename); $pattern = '/(\/\*\*(?:(?!\/\*\*).)*?\*\/)(?:(?!\/\*\*)[^\$])*?\$%s/ms'; $pattern = sprintf($pattern, $this->getName()); preg_match($pattern, $file, $matches); return $matches[1]; }else{ return parent::getDocComment(); } } } ?> ficus/lang/reflect/ReflectionClass.php100644 1751 144 6067 10645132217 13536 ISHITOYA Kentaro * @version $Id: ReflectionClass.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/PHPVersion.php"; require_once "ficus/lang/reflect/ReflectionProperty.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_ReflectionClass */ class Ficus_ReflectionClass extends ReflectionClass { /** * return *all* properties. * all means that parent class's property is included. */ public function getAllProperties(){ $properties = $this->getProperties(); $parent = $this->getParentClass(); if($parent){ $parentClass = new Ficus_ReflectionClass($parent->getName()); $parentProperties = $parentClass->getAllProperties(); $properties = array_merge($properties, $parentProperties); } return $properties; } /** * return Ficus_ReflectionProperty when php version < 5.1.0 * @return array array of Ficus_ReflectionProperty */ public function getProperties(){ $properties = parent::getProperties(); if(Ficus_PHPVersion::isOlderThan("5.1.0")){ $ret = array(); foreach($properties as $property){ $ret[] = new Ficus_ReflectionProperty($this->getName(), $property->getName()); } return $ret; } return $properties; } /** * return Ficus_ReflectionProperty when php version < 5.1.0 * @param $name string target Parameter name * @return Ficus_ReflectionProperty */ public function getProperty($name){ $property = parent::getProperty($name); if(Ficus_PHPVersion::isOlderThan("5.1.0")){ return new Ficus_ReflectionProperty($this->getName(), $property->getName()); } return $property; } /** * implements hasMethod * @param $name string * @return boolean return true, when method $name is exists */ public function hasMethod($name){ if(Ficus_PHPVersion::isOlderThan("5.1.0")){ return is_callable($this->getName(), $name); } return parent::hasMethod($name); } } ?> ficus/lang/reflect/ReflectionAnnotation.php100644 1751 144 7324 10645132217 14600 * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: ReflectionAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since File available since Release 1.0.0 */ /** * Abstract base class for Annotations. * * @category PHP * @package Ficus_ReflectionAnnotation * @author Sebastian Bergmann * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since Class available since Release 1.0.0 */ abstract class Ficus_ReflectionAnnotation { private $reflector; private $arguments; private static $prefixes; /** * Constructor. * * @param Reflector $reflector * @param Array $arguments * @param Array $prefixes * @throws InvalidArgumentException * @access protected */ protected function __construct($reflector, $arguments) { if (!($reflector instanceof ReflectionClass || $reflector instanceof ReflectionFunction || $reflector instanceof ReflectionMethod || $reflector instanceof ReflectionProperty)) { throw new InvalidArgumentException; } $this->reflector = $reflector; $this->arguments = $arguments; // XXX: TODO: Implement parameter mapping. } /** * set class name prefix * * @param array $prefixes */ public static final function setPrefixes($prefixes){ self::$prefixes = $prefixes; } /** * Factory for concrete implementations of Ficus_ReflectionAnnotation. * * @param Object $reflector * @param String $name * @param Array $arguments * @return Ficus_ReflectionAnnotation * @throws ReflectionException * @access public * @static * @final */ public static final function factory($reflector, $name, $arguments) { $className = $name . 'Annotation'; if(class_exists($className) == false){ $className = ucfirst($name) . 'Annotation'; foreach(self::$prefixes as $prefix){ if(class_exists($prefix . $className)){ $className = $prefix . $className; break; } } } $class = new ReflectionClass($className); if ($class->isSubclassOf('Ficus_ReflectionAnnotation') && $class->isInstantiable()) { return $class->newInstance( $reflector, $arguments ); } } /** * Returns the reflector this annotation is associated with. * * @return Reflector * @access public */ public final function getReflector() { return $this->reflector; } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?> ficus/lang/reflect/annotation/ReflectionAnnotationFunction.php100644 1751 144 7532 10645132217 20461 * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: ReflectionAnnotationFunction.php 2 2007-07-11 10:37:48Z ishitoya $ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since File available since Release 1.0.0 */ require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationAnnotatedElement.php'; require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationParser.php'; require_once 'ficus/lang/reflect/ReflectionAnnotation.php'; /** * Extension to ReflectionFunction that is aware of Annotations. * * @category PHP * @package Ficus_ReflectionAnnotation * @author Sebastian Bergmann * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since Class available since Release 1.0.0 */ class Ficus_ReflectionAnnotationFunction extends ReflectionFunction implements Ficus_ReflectionAnnotationAnnotatedElement { private $annotations; /** * Constructor. * * @param mixed $class * @throws InvalidArgumentException * @access public */ public function __construct($function) { if (is_string($function)) { parent::__construct($function); } else if ($function instanceof ReflectionFunction) { parent::__construct($function->getName()); } else { throw new InvalidArgumentException; } $this->annotations = Ficus_ReflectionAnnotationParser::parseAnnotations($this->getDocComment()); } /** * Returns the function's annotations. * * @return Ficus_ReflectionAnnotation[] * @access public */ public function getAnnotations() { $annotations = array(); foreach ($this->annotations as $name => $arguments) { $annotations[] = Ficus_ReflectionAnnotation::factory( $this, $name, $arguments ); } return $annotations; } /** * Returns the function's annotation specified by its name. * * @param String $name * @return Ficus_ReflectionAnnotation * @throws ReflectionException * @access public */ public function getAnnotation($name) { if (isset($this->annotations[$name])) { return Ficus_ReflectionAnnotation::factory( $this, $name, $this->annotations[$name] ); } else { throw new ReflectionException( sprintf( 'Function "%s" does not have annotation "%s"', $this->getName(), $name ) ); } } /** * Returns wether an annotation exists or not. * * @param String $name * @return boolean * @access public */ public function hasAnnotation($name) { return isset($this->annotations[$name]); } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?> ficus/lang/reflect/annotation/ReflectionAnnotationAnnotatedElement.php100644 1751 144 4163 10645132217 22120 * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: ReflectionAnnotationAnnotatedElement.php 2 2007-07-11 10:37:48Z ishitoya $ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since File available since Release 1.0.0 */ /** * Represents an annotated element of the program currently running. * * @category PHP * @package Ficus_ReflectionAnnotation * @author Sebastian Bergmann * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since Interface available since Release 1.0.0 */ interface Ficus_ReflectionAnnotationAnnotatedElement { /** * Returns the annotations. * * @return Ficus_ReflectionAnnotation[] * @access public */ public function getAnnotations(); /** * Returns annotation by name. * * @param String $name * @return Ficus_ReflectionAnnotation * @access public */ public function getAnnotation($name); /** * Returns wether an annotation exists or not. * * @param String $name * @return boolean * @access public */ public function hasAnnotation($name); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?> ficus/lang/reflect/annotation/ReflectionAnnotationClass.php100644 1751 144 12577 10645132217 17766 * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: ReflectionAnnotationClass.php 2 2007-07-11 10:37:48Z ishitoya $ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since File available since Release 1.0.0 */ require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationAnnotatedElement.php'; require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationMethod.php'; require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationParser.php'; require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationProperty.php'; require_once 'ficus/lang/reflect/ReflectionAnnotation.php'; /** * Extension to ReflectionClass that is aware of Annotations. * * @category PHP * @package Ficus_ReflectionAnnotation * @author Sebastian Bergmann * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since Class available since Release 1.0.0 */ class Ficus_ReflectionAnnotationClass extends ReflectionClass implements Ficus_ReflectionAnnotationAnnotatedElement { private $annotations; /** * Constructor. * * @param mixed $class * @throws InvalidArgumentException * @access public */ public function __construct($class) { if (is_string($class)) { parent::__construct($class); } else if ($class instanceof ReflectionClass) { parent::__construct($class->getName()); } else { throw new InvalidArgumentException; } $this->annotations = Ficus_ReflectionAnnotationParser::parseAnnotations($this->getDocComment()); } /** * Returns the class' annotations. * * @return Ficus_ReflectionAnnotation[] * @access public */ public function getAnnotations() { $annotations = array(); foreach ($this->annotations as $name => $arguments) { $annotations[] = Ficus_ReflectionAnnotation::factory( $this, $name, $arguments ); } return $annotations; } /** * Returns the class' annotation specified by its name. * * @param String $name * @return Ficus_ReflectionAnnotation * @throws ReflectionException * @access public */ public function getAnnotation($name) { if (isset($this->annotations[$name])) { return Ficus_ReflectionAnnotation::factory( $this, $name, $this->annotations[$name] ); } else { throw new ReflectionException( sprintf( 'Class "%s" does not have annotation "%s"', $this->getName(), $name ) ); } } /** * Returns wether an annotation exists or not. * * @param String $name * @return boolean * @access public */ public function hasAnnotation($name) { return isset($this->annotations[$name]); } /** * Returns an array of this class' methods. * * @return Ficus_ReflectionAnnotationMethod[] * @access public */ public function getMethods() { $methods = array(); foreach (parent::getMethods() as $method) { $methods[] = new Ficus_ReflectionAnnotationMethod($this->getName(), $method->getName()); } return $methods; } /** * Returns the class' method specified by its name. * * @param string $name * @return Ficus_ReflectionAnnotationMethod * @access public */ public function getMethod($name) { return new Ficus_ReflectionAnnotationMethod($this->getName(), $name); } /** * Returns an array of this class' properties. * * @return Ficus_ReflectionAnnotationProperty[] * @access public */ public function getProperties() { $properties = array(); foreach (parent::getProperties() as $property) { $properties[] = new Ficus_ReflectionAnnotationProperty($this->getName(), $property->getName()); } return $properties; } /** * Returns the class' property specified by its name. * * @param string $name * @return Ficus_ReflectionAnnotationProperty * @access public */ public function getProperty($name) { return new Ficus_ReflectionAnnotationProperty($this->getName(), $name); } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?> ficus/lang/reflect/annotation/ReflectionAnnotationParser.php100644 1751 144 14777 10645132217 20161 * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: ReflectionAnnotationParser.php 2 2007-07-11 10:37:48Z ishitoya $ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since File available since Release 1.0.0 */ /** * Parser for Annotations. * * @category PHP * @package Ficus_ReflectionAnnotation * @author Sebastian Bergmann * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since Class available since Release 1.0.0 */ class Ficus_ReflectionAnnotationParser { const ANNOTATION_PATTERN = '/@([^\s]+?(?=[\s\(]))\s*(\(\s*((?:(?!^@).)*)\s*\)|([^\n]+))/ms'; // '/@([^\s]+?(?=[\s\(]))\s*\(\s*((?:(?!^@).)*)\s*\)/ms'; const ARRAY_PATTERN = '/([^\s]*?)\s*=\s*\{(.*?)\}(?=\s*,\s*[^{]+?=\s*\{|$)/ms'; const QUOTED_PATTERN = '/([^\s]*?)\s*=\s*"(.*?)((? $match){ if(empty($match) == false){ $matches[2][$key] = $match; } } $annotations = array_combine($matches[1], $matches[2]); foreach($annotations as $name => $annotation){ $annotations[$name] = self::parseAnnotationContents($name, $annotation); } $comments = preg_split('/\n/', $docComment); if(array_key_exists(self::T_BRIEF, $annotations) == false && empty($comments[1]) == false){ $annotations[self::T_BRIEF] = $comments[1]; } if(array_key_exists(self::T_COMMENT, $annotations) == false){ $comment = ""; for($i = 2; $i < count($comments); $i++){ if(empty($comments[$i]) == false){ $comment .= $comments[$i]; }else{ $annotations[self::T_COMMENT] = $comment; break; } } } return $annotations; } /** * Parser for Annotation Contents * * @param string $name name of annotation * @param string $annotations contents of annotation * @return array array of parsed contents * @access public */ public static function parseAnnotationContents($name, $annotation){ if(preg_match(self::JAVA_STYLE_PATTERN, $annotation)){ preg_match_all(self::ARRAY_PATTERN, $annotation, $arrayMatches); $annotation = preg_replace(self::ARRAY_PATTERN, "", $annotation); $arrayContents = array(); while(($name = each($arrayMatches[1])) !== false && ($value = each($arrayMatches[2])) !== false){ $arrayContents[$name["value"]] = self::parseArrayAnnotationContents($value["value"]); } preg_match_all(self::QUOTED_PATTERN, $annotation, $quotedMatches); $annotation = preg_replace(self::QUOTED_PATTERN, "", $annotation); preg_match_all(self::VALUE_PATTERN, $annotation, $valueMatches); $keys = array_merge($quotedMatches[1], $valueMatches[1]); $values = array_merge($quotedMatches[2], $valueMatches[2]); $contents = array_combine($keys, $values); $contents = array_merge($contents, $arrayContents); return $contents; }else{ return $annotation; } } /** * Parse Array Annotation Contents * * @param string $contents contents of annotation * @return array array of parsed contents * @access public */ public static function parseArrayAnnotationContents($annotation){ $contents = array(); $arrayPattern = '/(([^\s]*?)\s*=\s*)?\{(.*?)\}(?=\s*,\s*{|$)/ms'; $valuePattern = '/(([^\s]*?)\s*=\s*)?(\"(.*?)(? ficus/lang/reflect/annotation/ReflectionAnnotationProperty.php100644 1751 144 7710 10645132217 20516 * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: ReflectionAnnotationProperty.php 2 2007-07-11 10:37:48Z ishitoya $ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since File available since Release 1.0.0 */ require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationAnnotatedElement.php'; require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationParser.php'; require_once 'ficus/lang/reflect/ReflectionAnnotation.php'; require_once 'ficus/lang/reflect/ReflectionProperty.php'; /** * Extension to ReflectionProperty that is aware of Annotations. * * @category PHP * @package Ficus_ReflectionAnnotation * @author Sebastian Bergmann * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since Class available since Release 1.0.0 */ class Ficus_ReflectionAnnotationProperty extends Ficus_ReflectionProperty implements Ficus_ReflectionAnnotationAnnotatedElement { private $annotations; /** * Constructor. * * @param * @param * @throws InvalidArgumentException * @access public */ public function __construct($class, $name = '') { if (is_string($class)) { parent::__construct($class, $name); } else if ($class instanceof ReflectionProperty) { parent::__construct($class->getDeclaringClass()->getName(), $class->getName()); } else { throw new InvalidArgumentException; } $this->annotations = Ficus_ReflectionAnnotationParser::parseAnnotations($this->getDocComment()); } /** * Returns the property's annotations. * * @return Ficus_ReflectionAnnotation[] * @access public */ public function getAnnotations() { $annotations = array(); foreach ($this->annotations as $name => $arguments) { $annotations[] = Ficus_ReflectionAnnotation::factory( $this, $name, $arguments ); } return $annotations; } /** * Returns the property's annotation specified by its name. * * @param String $name * @return Ficus_ReflectionAnnotation * @throws ReflectionException * @access public */ public function getAnnotation($name) { if (isset($this->annotations[$name])) { return Ficus_ReflectionAnnotation::factory( $this, $name, $this->annotations[$name] ); } else { throw new ReflectionException( sprintf( 'Property "%s" does not have annotation "%s"', $this->getName(), $name ) ); } } /** * Returns wether an annotation exists or not. * * @param String $name * @return boolean * @access public */ public function hasAnnotation($name) { return isset($this->annotations[$name]); } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?> ficus/lang/reflect/annotation/ReflectionAnnotationMethod.php100644 1751 144 7570 10645132217 20116 * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: ReflectionAnnotationMethod.php 2 2007-07-11 10:37:48Z ishitoya $ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since File available since Release 1.0.0 */ require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationAnnotatedElement.php'; require_once 'ficus/lang/reflect/annotation/ReflectionAnnotationParser.php'; require_once 'ficus/lang/reflect/ReflectionAnnotation.php'; /** * Extension to ReflectionMethod that is aware of Annotations. * * @category PHP * @package Ficus_ReflectionAnnotation * @author Sebastian Bergmann * @copyright 2005 Sebastian Bergmann * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/ Ficus_ReflectionAnnotation * @since Class available since Release 1.0.0 */ class Ficus_ReflectionAnnotationMethod extends ReflectionMethod implements Ficus_ReflectionAnnotationAnnotatedElement { private $annotations; /** * Constructor. * * @param * @param * @throws InvalidArgumentException * @access public */ public function __construct($class, $name = '') { if (is_string($class)) { parent::__construct($class, $name); } else if ($class instanceof ReflectionMethod) { parent::__construct($class->getDeclaringClass()->getName(), $class->getName()); } else { throw new InvalidArgumentException; } $this->annotations = Ficus_ReflectionAnnotationParser::parseAnnotations($this->getDocComment()); } /** * Returns the method's annotations. * * @return Ficus_ReflectionAnnotation[] * @access public */ public function getAnnotations() { $annotations = array(); foreach ($this->annotations as $name => $arguments) { $annotations[] = Ficus_ReflectionAnnotation::factory( $this, $name, $arguments ); } return $annotations; } /** * Returns the method's annotation specified by its name. * * @param String $name * @return Ficus_ReflectionAnnotation * @throws ReflectionException * @access public */ public function getAnnotation($name) { if (isset($this->annotations[$name])) { return Ficus_ReflectionAnnotation::factory( $this, $name, $this->annotations[$name] ); } else { throw new ReflectionException( sprintf( 'Method "%s" does not have annotation "%s"', $this->getName(), $name ) ); } } /** * Returns wether an annotation exists or not. * * @param String $name * @return boolean * @access public */ public function hasAnnotation($name) { return isset($this->annotations[$name]); } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?> ficus/lang/Range.php100644 1751 144 4055 10645132217 10061 SUMI Masafumi * @version $Id: Range.php 2 2007-07-11 10:37:48Z ishitoya $ * * Util Range. */ require_once('ficus/lang/Assert.php'); require_once('ficus/lang/RangeIterator.php'); /** * @class Ficus_Range */ class Ficus_Range implements IteratorAggregate { /** * Constructor. * * @param $first int first value. * @param $last int last value. */ public function __construct($first, $last = null) { Ficus_Assert::isPrimitiveType($first, 'int'); Ficus_Assert::isPrimitiveTypeAllowNull($last, 'int'); if ($first > $last) { throw new Ficus_IllegalArgumentException("first value larger than last. {$first, $last}"); } $this->first = $first; $this->last = isset($last) ? $last : $first; } /** * Contains. * * @param $value int value. * @return boolean if contains between first and last. */ public function contains($value) { Ficus_Assert::isPrimitiveType($value, 'int'); return ($this->first <= $value && $value <= $this->last); } /** * Get iterator. * * @return Iterator iterator. */ public function getIterator() { return new Ficus_RangeIterator($this->first, $this->last); } } ?> ficus/lang/PlatformInformation.php100644 1751 144 2762 10645132217 13022 ISHITOYA Kentaro * @version $Id: PlatformInformation.php 2 2007-07-11 10:37:48Z ishitoya $ * * fetch platform information that this script runs on. */ /** * @class Ficus_PlatformInformation */ class Ficus_PlatformInformation { const WINDOWS = "Windows"; const LINUX = "linux"; const UNIX = "unix"; public static function isWindows(){ return (self::getOSInformation() == self::WINDOWS); } private function getOSInformation(){ if(isset($_ENV["OS"])){ $os = self::WINDOWS; }else if(isset($_ENV["OSTYPE"])){ $os = self::LINUX; }else{ $os = self::UNIX; } return $os; } } ?> ficus/lang/Array.php100644 1751 144 22712 10647426442 10133 SUMI Masafumi * @version $Id: Array.php 15 2007-07-18 15:02:48Z ishitoya $ * * Array wrapper class. */ require_once('ficus/exception/NotSupportedException.php'); require_once('ficus/exception/MethodNotFoundException.php'); /** * @class Ficus_Array */ class Ficus_Array implements IteratorAggregate { /** * @var $array array. */ private $array; /** * Constructor. * * @param $array array. */ public function __construct() { if (func_num_args() == 1 && is_array(func_get_arg(0))) { $this->array = func_get_arg(0); } else { $this->array = func_get_args(); } } /** * Copy. * * @return Ficus_Array clone myself. */ public function copy() { return new Ficus_Array($this->array); } /** * At element. * * @return mixed element of array. */ public function at($index) { return $this->array[$index]; } /** * As array. * * @return array this array. */ public function asArray() { return $this->array; } /** * Get iterator. * * @return ArrayObject iterator. */ public function getIterator() { return new ArrayObject($this->array); } /** * Equals. * * @param $array mixed array or Ficus_Array. * @return boolean true if equals. */ public function equals($array) { if ($array instanceof Ficus_Array) { return ($this->array == $array->asArray()); } else { return ($this->array == $array); } } /** * Call PHP arrays function. * * @param $name array function name. * @param $arguments function arguments. * @return mixed function return value. * @throw Ficus_MethodNotFoundException method not found. */ public function __call($name, $arguments) { $arguments = array_map(array($this, 'asArrayFilter'), $arguments); if (substr($name, -1) == '_') { $strip = true; $name = substr($name, 0, -1); } else { $strip = false; } $ret = $this->call($name, $arguments); if (!$strip && is_array($ret)) { return new Ficus_Array($ret); } else { return $ret; } } /** * Call PHP arrays function. * * @param $name array function name. * @param $arguments function arguments. * @return mixed function return value. * @throw Ficus_MethodNotFoundException method not found. */ protected function call($name, $arguments) { switch ($name) { case 'change_key_case': case 'chunk': case 'combine': //(array keys, array values) case 'count_values': case 'diff_assoc': case 'diff_key': case 'diff_uassoc': case 'diff_ukey': case 'diff': case 'filter': case 'flip': case 'intersect_assoc': case 'intersect_key': case 'intersect_uassoc': case 'intersect_ukey': case 'intersect': case 'keys': case 'merge_recursive': case 'merge': case 'multisort': case 'pad': case 'pop': case 'product': case 'push': case 'rand': case 'reduce': case 'reverse': case 'shift': case 'slice': case 'splice': case 'sum': case 'udiff_assoc': case 'udiff_uassoc': case 'udiff': case 'uintersect_assoc': case 'uintersect_uassoc': case 'uintersect': case 'unique': case 'unshift': case 'values': case 'walk_recursive': case 'walk': $name = 'array_' . $name; case 'array_change_key_case': case 'array_chunk': case 'array_combine': //(array keys, array values) case 'array_count_values': case 'array_diff_assoc': case 'array_diff_key': case 'array_diff_uassoc': case 'array_diff_ukey': case 'array_diff': case 'array_filter': case 'array_flip': case 'array_intersect_assoc': case 'array_intersect_key': case 'array_intersect_uassoc': case 'array_intersect_ukey': case 'array_intersect': case 'array_keys': case 'array_merge_recursive': case 'array_merge': case 'array_multisort': case 'array_pad': case 'array_pop': case 'array_product': case 'array_push': case 'array_rand': case 'array_reduce': case 'array_reverse': case 'array_shift': case 'array_slice': case 'array_splice': case 'array_sum': case 'array_udiff_assoc': case 'array_udiff_uassoc': case 'array_udiff': case 'array_uintersect_assoc': case 'array_uintersect_uassoc': case 'array_uintersect': case 'array_unique': case 'array_unshift': case 'array_values': case 'array_walk_recursive': case 'array_walk': case 'arsort': case 'asort': case 'count': case 'current': case 'each': case 'end': case 'extract': case 'key': case 'krsort': case 'ksort': case 'natcasesort': case 'natsort': case 'next': case 'pos': case 'prev': case 'reset': case 'rsort': case 'shuffle': case 'sizeof': case 'sort': case 'uasort': case 'uksort': case 'usort': if (is_array($arguments)) { $argumentsWithArray = array_merge(array($this->array), $arguments); } else { $argumentsWithArray = array($this->array); } return call_user_func_array($name, $argumentsWithArray); break; // this array is second argument. case 'key_exists': case 'map': case 'search': $name = 'array_' . $name; case 'array_key_exists': case 'array_map': case 'array_search': case 'in_array': $arrangedArguments = array(); $arrangedArguments []= $arguments[0]; $arrangedArguments []= $this->array; $arrangedArguments += array_slice($arguments, 1); return call_user_func_array($name, $arrangedArguments); break; //case 'array_fill': //case 'compact': //case 'list': //case 'range': default: break; } throw new Ficus_MethodNotFoundException($name); } /** * As array filter. * * @param $array Ficus_array array. * @return array primitive array. */ public function asArrayFilter($arg) { return ($arg instanceof Ficus_Array) ? $arg->asArray() : $arg; } /** * string to array. fazy. * * @param $string string * @return array of value */ public static function stringToArray($string){ $values = explode(",", $string); foreach($values as $key => $value){ $values[$key] = trim($value); } return $values; } /** * convert encoding * * @param $target array values to convert * @param $dest string dest encoding * @param $src string source encoding */ public static function convertEncoding($target, $dest = null, $src = null){ if(!extension_loaded("mbstring")){ throw new Ficus_NotSupportedException("mbstring is not supported on this computer"); } if(is_null($dest)){ $dest = mb_detect_encoding("åá¤å¡äåá¬å¡èåá´å¡ëåáºå¡ïåáÂå¡óåᎷ"); } if(is_null($src)){ $hint = ""; foreach($target as $key => $value){ $hint .= $key . $value; } $src = mb_detect_encoding($hint, "EUC-JP,SJIS,UTF-8,JIS,ASCII"); } $converted = array(); foreach($target as $key => $value){ $key = mb_convert_encoding($key, $dest, $src); $value = mb_convert_encoding($value, $dest, $src); $converted[$key] = $value; } return $converted; } } ?> ficus/lang/ClassPath.php100644 1751 144 11540 10645132217 10724 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ClassPath.php 2 2007-07-11 10:37:48Z ishitoya $ * * class path for php */ require_once("ficus/lang/Assert.php"); require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/lang/ClassPathElement.php"); /** * @class Ficus_ClassPath */ class Ficus_ClassPath { /** Package separator charactor */ const PACKAGE_SEPARATOR = "."; const ESCAPED_DOT = "#####"; /** * @var $classPaths array of Ficus_ClassPathElement class paths */ private static $paths = array(); /** * @var $defaultDir Ficus_Dir default directory **/ private static $defaultDir = ""; /** * @var $cache array of cache */ private static $cache = array(); /** * @var $expandedPaths array of cache */ private static $expandedPaths = array(); /** * get class Paths. * @return array array of class path */ public static function paths(){ return self::$paths; } /** * clear class Path * @return void */ public static function clear(){ self::$paths = array(); self::$cache = array(); self::$expandedPaths = array(); } /** * add base directory * @param $path Ficus_ClassPathElement base directory * @return void * @throw Ficus_IllegalArgumentException no directory. */ public static function add($path, $name = null){ Ficus_Assert::isTypeAllowNull($path, "Ficus_ClassPathElement"); if(is_null($name)){ self::$paths[] = $path; }else{ self::$paths[$name] = $path; } self::$cache = array(); self::$expandedPaths = array(); } /** * get named classpath * @param $name string path name * @return string class path * @throw Ficus_IllegalArgumentException directory not found. */ public static function get($name){ if(isset(self::$paths[$name])){ return self::$paths[$name]; }else{ throw new Ficus_IllegalArgumentException("class path named $name is not found"); } } /** * Package to directory. * * @param $package string package. * @return string directory. */ public static function packageToDirectory($package) { return str_replace(self::PACKAGE_SEPARATOR, '/', $package); } /** * Directory to package. * * @param $directory string directory. * @return string package. */ public static function directoryToPackage($directory) { return str_replace('/', self::PACKAGE_SEPARATOR, $directory); } /** * to String * @return string string */ public static function __toString(){ if(empty(self::$paths)){ return "class paths is empty"; }else{ $expanded = self::getExpandedClassPaths(); $string = implode(" ", $expanded); return $string; } } /** * search paths for file * @param $path string search path * @return Array of found path */ public static function search($file){ if(isset(self::$cache[$file])){ return self::$cache[$file]; } if(empty(self::$paths)){ throw new Ficus_NotReadyException("Class Path is not initialized. please check ficus/Ficus_ClassPath.php"); } $result = array(); foreach(self::$paths as $path){ $ret = $path->search($file); $result = array_merge($ret, $result); } $result = array_unique($result); self::$cache[$file] = $result; return $result; } /** * get expanded class path * @return array of Ficus_Dir */ public static function getExpandedClassPaths(){ $classPaths = array(); foreach(self::$paths as $element){ $paths = $element->paths(); $classPaths = array_merge($classPaths, $paths); } return $classPaths; } } ?> ficus/lang/RangeIterator.php100644 1751 144 4350 10645132217 11571 SUMI Masafumi * @version $Id: RangeIterator.php 2 2007-07-11 10:37:48Z ishitoya $ * * Util RangeIterator. */ /** * @class Ficus_RangeIterator */ class Ficus_RangeIterator implements Iterator { /** * Current value. */ private $current; /** * First value. */ private $first; /** * Last value. */ private $last; /** * Constructor. */ public function __construct($first, $last = null) { $this->first = $first; if (isset($last)) { $this->last = $last; } else { $this->last = $first; } $this->current = $first; } /** * Return the current number. * * @return int current number. */ public function current() { return $this->current; } /** * Return the key of the current number. * * @return int current char position. */ public function key() { return $this->current - $this->first; } /** * Move forward to next number. */ public function next() { $this->current++; } /** * Rewind the Iterator to the first number. */ public function rewind() { $this->current = $this->first; } /** * Check if there is a current char after calls to rewind() or next(). */ public function valid() { return $this->current <= $this->last; } } ?> ficus/lang/S2ContainerAutoLoad.php100644 1751 144 2764 10645132217 12612 ISHITOYA Kentaro * @version $Id: S2ContainerAutoLoad.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/lang/AutoLoad.php"); require_once("s2container.php5/S2Container.php"); /** * @class Ficus_S2ContainerAutoLoad */ class Ficus_S2ContainerAutoLoad extends Ficus_AutoLoad{ /** * constructor */ public function __construct(){ S2ContainerClassLoader::import(S2CONTAINER_PHP5); } /** * abstract autoload * @param $classname string class name to load * @return boolean true if load succeeded */ protected function load($classname){ return S2ContainerClassLoader::load($classname); } } ?> ficus/lang/PHPVersion.php100644 1751 144 14120 10645132217 11034 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: PHPVersion.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/Assert.php"; require_once "ficus/exception/IllegalArgumentException.php"; /** * @class Ficus_PHPVersion */ class Ficus_PHPVersion { const VERSION_PATTERN = '/(([0-9]+)\.([0-9]+)\.([0-9]+))-?(.*)/'; const WHOLE = "whole"; const MAJOR = "major"; const MINOR = "minor"; const RELEASE = "release"; const INFO = "info"; /** @var string phpversion information*/ private static $version = null; /** @var array version array*/ private static $versionArray = null; /** * constructor */ public function __construct(){ $this->initialize(); } /** * is newer than param * @param $version string * @return boolean if current version newer than the version, return true */ public function isNewerThan($version){ self::initialize(); return version_compare(self::$version, $version, ">"); } /** * is older than param version * @param $version string * @return boolean if current version older than the version, return true */ public function isOlderThan($version){ self::initialize(); return version_compare(self::$version, $version, "<"); } /** * is same version of * @param $version string * @return boolean if current version same version, return true */ public function isSame($version){ self::initialize(); return version_compare(self::$version, $version, "eq"); } /** * is the version between $version1 and $version2 * @param $version1 string * @param $version2 string * @return boolean return true if current version between 1 and 2. */ public function isBetween($version1, $version2){ self::initialize(); $version1 = self::createVersionArray($version1); $version2 = self::createVersionArray($version2); $result1 = version_compare(self::$versionArray[self::WHOLE], $version1[self::WHOLE], ">="); $result2 = version_compare(self::$versionArray[self::WHOLE], $version2[self::WHOLE], "<="); return ($result1 && $result2); } /** * getMajorVersion * @param $version string version string * @return string major version */ public function getMajor($version = null){ self::initialize(); if(is_null($version)){ return self::$versionArray[self::MAJOR]; }else{ $versionArray = self::createVersionArray($version); return $versionArray[self::MAJOR]; } } /** * getMinorVersion * @param $version string version string * @return string minor version */ public function getMinor($version = null){ self::initialize(); if(is_null($version)){ return self::$versionArray[self::MINOR]; }else{ $versionArray = self::createVersionArray($version); return $versionArray[self::MINOR]; } } /** * getReleaseVersion * @param $version string version string * @return string major version */ public function getRelease($version = null){ self::initialize(); if(is_null($version)){ return self::$versionArray[self::RELEASE]; }else{ $versionArray = self::createVersionArray($version); return $versionArray[self::RELEASE]; } } /** * get Info * @param $version string version string * @return string major version */ public function getInfo($version = null){ self::initialize(); if(is_null($version)){ return self::$versionArray[self::INFO]; }else{ $versionArray = self::createVersionArray($version); return $versionArray[self::INFO]; } } /** * getMajorVersion * @return string current version */ public function getCurrentVersion(){ self::initialize(); return self::$version; } /** * initialize */ private static function initialize(){ if(is_null(self::$version)){ self::$version = phpversion(); self::$versionArray = self::createVersionArray(self::$version); } } /** * create Array * @param $version string version string * @return array array of version * @throw Ficus_IllegalArgumentException invalid version. */ private function createVersionArray($version){ $array = array(); if(preg_match(self::VERSION_PATTERN, $version, $matches)){ $array[self::WHOLE] = $matches[1]; $array[self::MAJOR] = $matches[2]; $array[self::MINOR] = $matches[3]; $array[self::RELEASE] = $matches[4]; if(isset($matches[5])){ $array[self::INFO] = $matches[5]; }else{ $array[self::INFO] = null; } }else{ throw new Ficus_IllegalArgumentException("specified version number is not a PHP standardized version number. : $version"); } return $array; } } ?> ficus/lang/LibraryErrorTrapper.php100644 1751 144 3154 10645132217 13000 SUMI Masafumi * @version $Id: LibraryErrorTrapper.php 2 2007-07-11 10:37:48Z ishitoya $ * * Traps Library Error(E_STRICT) */ /** * Traps Library Error(E_STRICT) * * @param $errno Error number(excepting only E_STRICT) * @param $errstr Error Description * @param $errfile File path to error occured * @param $errline Line number where error occured * @see set_error_handler */ function LibraryErrorTrapper ($errno, $errstr, $errfile, $errline) { if (eregi("build[\\\\/]lib[\\\\/]", $errfile) || eregi("[\\\\/]PEAR[\\\\/]", $errfile)) { // do nothing. } else { echo "Strict Standards: " . $errstr . " in " . $errfile . " on line " . $errline . "\n"; } } /** * Set Error handler */ //set_error_handler("LibraryErrorTrapper", E_STRICT); ?> ficus/lang/FatalErrorHandler.php100644 1751 144 13206 10645132217 12402 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: FatalErrorHandler.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/logging/Logger.php"); require_once("ficus/io/PropertyFileReader.php"); require_once("ficus/exception/NotReadyException.php"); /** * @class Ficus_FatalErrorHandler */ class Ficus_FatalErrorHandler { const CONFIG_FILE = "logger"; const LOGGING_STARTED = 0; const LOGGING_NOTSTARTED = 1; const INI_DISPLAY_ERRORS = "display_errors"; const INI_OUTPUT_BUFFERING = "output_buffering"; const INI_ERROR_LOG = "error_log"; const ERROR_FILE = "error_file"; const ERROR_BACKTRACE = "error_backtrace"; /** * @var $status integer status */ private static $status = null; /** * @var $filename string logfile */ private static $filename = null; /** * @var $backtrace boolean backtrace */ private static $backtrace = false; /** * @var $isInitialized boolean isInitialized */ private static $isInitialized = false; /** * @var $isAvailable boolean isAvailable */ private static $isAvailable = false; /** * @var $oldValues array oldValues */ private static $oldValues = array(); /** * initialize parameters */ private static function initialize(){ $ini = Ficus_PropertyFileReader::read(self::CONFIG_FILE); self::$filename = dirname(__FILE__) . "/../" . $ini[self::ERROR_FILE]; self::$backtrace = (bool)$ini[self::ERROR_BACKTRACE]; if((self::isOptionAvailable(self::INI_DISPLAY_ERRORS) == false && self::$oldValues[self::INI_DISPLAY_ERRORS] == false) || self::isOptionAvailable(self::INI_ERROR_LOG) == false){ self::$isAvailable = false; }else{ self::$isAvailable = true; } self::$status = self::LOGGING_NOTSTARTED; self::$isInitialized = true; } /** * checkINIOption is available * @param $option string ini option * @return boolean true if available */ private static function isOptionAvailable($option){ if(is_string($option) == false || empty($option)){ return false; } self::$oldValues[$option] = ini_get($option); $result = ini_set($option, "true"); $result2 = ini_set($option, self::$oldValues[$option]); if((self::$oldValues[$option] !== false && $result === false) || (self::$oldValues[$option] === false && $result === false && $result2 === false)){ return false; } return true; } /** * check ini_set is available * @return boolean true if avaliable */ public static function isAvailable(){ if(self::$isInitialized == false){ self::initialize(); } return self::$isAvailable; } /** * start logging * * @throw Ficus_NotReadyException error handler is not ready. */ public static function startLogging(){ if(self::isAvailable() == false){ throw new Ficus_NotReadyException("Fatal Error Handler is not Ready."); }else if(self::$status == self::LOGGING_NOTSTARTED){ ini_set(self::INI_DISPLAY_ERRORS, true); ini_set(self::INI_ERROR_LOG, self::$filename); ob_start(array("Ficus_FatalErrorHandler", "fatal_error_handler")); self::$status = self::LOGGING_STARTED; } } /** * end logging * * @throw Ficus_NotReadyException error handler is not ready. */ public static function endLogging(){ if(self::isAvailable() == false){ throw new Ficus_NotReadyException("Fatal Error Handler is not Ready."); }else if(self::$status == self::LOGGING_STARTED){ ob_end_flush(); ini_set(self::INI_DISPLAY_ERRORS, self::$oldValues[self::INI_DISPLAY_ERRORS]); ini_set(self::INI_ERROR_LOG, self::$oldValues[self::INI_ERROR_LOG]); self::$status = self::LOGGING_NOTSTARTED; } } /** * fatal error handler checks buffer all the time * @param $buffer string output buffer */ public static function fatal_error_handler($buffer) { if(preg_match("/Fatal error<\/b>.*/", $buffer, $match)){ $log = "\n" . trim($match[0]); if(self::$backtrace){ $buf = explode("\n", $buffer); foreach($buf as $backtrace){ if(preg_match("/^#/", $backtrace)){ $log .= "\n" . $backtrace; } } } $log .= "\n"; error_log($log); } return $buffer; } } ?> ficus/lang/Bytes.php100644 1751 144 6513 10645132217 10114 ISHITOYA Kentaro * @version $Id: Bytes.php 2 2007-07-11 10:37:48Z ishitoya $ * * Byte util */ require_once("ficus/lang/Types.php"); /** * @class Ficus_Bytes */ class Ficus_Bytes { /** * @var Array of bytes */ protected $bytes = array(); /** * constructor * @param $string data to format bytes */ public function __construct($string = null){ if(is_null($string)){ return; } $data = Ficus_Types::toStringOf($string); $bytes = array(); for($i = 0; $i < strlen($data); $i++){ $bytes[] = ord($data[$i]); } $this->bytes = $bytes; } /** * length * @return integer length of bytes */ public function length(){ return count($this->bytes); } /** * fill bytes with $pad * @param $length integer length of fill * @param $byte integer to fill * @param Ficus_Bytes filled Byte */ public function fill($length, $byte){ $bytes = array(); for($i = 0; $i < $length; $i++){ $bytes[] = $byte; } $byte = new Ficus_Bytes(); $byte->bytes = $bytes; return $byte; } /** * xor * @param $right Ficus_Bytes to xor * @return Ficus_Bytes byte */ public function xorWith($right){ if(count($right->bytes) != count($this->bytes)){ throw new Ficus_IllegalArgumentException("count of bytes is mismatch"); } $bytes = array(); foreach($this->bytes as $index => $byte){ $bytes[] = $byte ^ $right->bytes[$index]; } $byte = new Ficus_Bytes(); $byte->bytes = $bytes; return $byte; } /** * padding * @param $length integer padding length with this length * @param $pad integer padding integer * @return Ficus_Bytes byte object */ public function padding($length, $pad){ $count = count($this->bytes); $bytes = $this->bytes; for($i = $count; $i < $length; $i++){ $bytes[] = $pad; } $byte = new Ficus_Bytes(); $byte->bytes = $bytes; return $byte; } /** * get bytes * @return array of bytes */ public function getBytes(){ return $this->bytes; } /** * toString * @return string bytes */ public function __toString(){ $string = ""; foreach($this->bytes as $byte){ $string .= chr($byte); } return $string; } } ?> ficus/lang/Assert.php100644 1751 144 17442 10645132217 10312 SUMI Masafumi * @author ISHITOYA Kentaro * @version $Id: Assert.php 2 2007-07-11 10:37:48Z ishitoya $ * * Util Assert */ require_once("ficus/exception/AssertException.php"); require_once("ficus/exception/TypeMismatchException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_Assert */ class Ficus_Assert { /** * type check. * * throw TypeMismatchException if $var not instance of type. * subclass instance not equal superclass. * * @param $type of class * @param $var of var * @throw Ficus_TypeMismatchException type mismatch. */ public static function isType($var, $type) { if (get_class($var) != $type) { throw new Ficus_TypeMismatchException("$type: " . get_class($var)); } return true; } /** * type check. * * throw TypeMismatchException if $var not a specified primitive type. * * @param $type of primitive * @param $var of var * @throw Ficus_TypeMismatchException type mismatch. */ public static function isPrimitiveType($var, $type) { $assertFunction = "is_$type"; if (function_exists($assertFunction) === false){ throw new Ficus_TypeMismatchException("php type $type was not found"); } else if ($assertFunction($var) === false){ throw new Ficus_TypeMismatchException("$type: " . gettype($var)); } return true; } /** * type check. * * throw TypeMismatchException if $var not instance of type. * * @param $type of class * @param $var of var * @throw Ficus_TypeMismatchException type mismatch. */ public static function isInstanceOf($var, $type) { if (!($var instanceof $type)) { throw new Ficus_TypeMismatchException("$type: " . get_class($var)); } return true; } /** * type hinting check. * * throw TypeMismatchException if $var not instance of type. * * @param $type of class * @param $var of var * @throw Ficus_TypeMismatchException type mismatch. */ public static function typeHinting($type, $var) { if (!($var instanceof $type)) { self::throwTypeMismatch($type, $var); } return true; } /** * type check. * * throw TypeMismatchException if $var not a specified primitive type. * But allow null. * * @param $type of primitive * @param $var of var * @throw Ficus_TypeMismatchException type mismatch. */ public static function isPrimitiveTypeAllowNull($var, $type) { if(is_null($var)){ return true; } $assertFunction = "is_$type"; if (function_exists($assertFunction) === false){ throw new Ficus_TypeMismatchException("php type $type was not found"); } else if ($assertFunction($var) === false){ throw new Ficus_TypeMismatchException("$type: " . gettype($var)); } return true; } /** * type check allow null value. * * throw TypeMismatchException if $var not instance of type. * subclass instance not equal superclass. * * @param $type of class * @param $var of var * @throw Ficus_TypeMismatchException type mismatch. */ public static function isTypeAllowNull($var, $type) { if(is_null($var)){ return true; } if (get_class($var) != $type) { throw new Ficus_TypeMismatchException("$type: " . get_class($var)); } return true; } /** * array key exists * * throws TypeMismatchException when $array is not Array, and * throws IllegalArgumentException when $array key $key is not exists. * * @param $array Array of array * @param $key String key * @throw Ficus_TypeMismatchException * @throw Ficus_IllegalArgumentException */ public static function isKeyExists($array, $key){ Ficus_Assert::isPrimitiveType($array, "array"); if(array_key_exists($key, $array) == false){ throw new Ficus_IllegalArgumentException("$key is not exists in array"); } if(is_null($array[$key])){ throw new Ficus_IllegalArgumentException("$key exists in array, but is null"); } return true; } /** * array key exists allow null * * throws TypeMismatchException when $array is not Array, and * throws IllegalArgumentException when $array key $key is not exists. * * @param $array Array of array * @param $key String key * @throw Ficus_TypeMismatchException * @throw Ficus_IllegalArgumentException */ public static function isKeyExistsAllowNull($array, $key){ Ficus_Assert::isPrimitiveType($array, "array"); if(array_key_exists($key, $array) == false){ throw new Ficus_IllegalArgumentException("$key is not exists in array"); } return true; } /** * type hinting check allow null. * * throw TypeMismatchException if $var not instance of type. * * @param $type of class * @param $var of var * @throw Ficus_TypeMismatchException type mismatch. */ public static function typeHintingAllowNull($type, $var) { if ($var != null && !($var instanceof $type)) { self::throwTypeMismatch($type, $var); } return true; } /** * throw TypeMismatchException * * @param $type of class * @param $var of var * @throw Ficus_TypeMismatchException type mismatch. */ protected static function throwTypeMismatch($type, $var) { $backtrace = debug_backtrace(); throw new Ficus_TypeMismatchException("Argument " . self::getType($var) . " mismatch $type " . " called by " . "{$backtrace[1]['file']}" . "({$backtrace[1]['line']})"); } /** * get type or object type. * * @param $type mixed * @return string of type name or class name. */ public static function getType($type) { if (gettype($type) == "object") { return get_class($type); } else { return gettype($type); } } /** * get backtrace. * * @param $level int backtrace level. * @return array of backtrace. */ protected static function getBacktrace($level) { $backtrace = debug_backtrace(); return $backtrace[$level+1]; } /** * assert callback. * * @param $file string file name * @param $line int line number * @param $code string source code * @exception Ficus_AssertException assert. */ public static function callback($file, $line, $code) { throw new Ficus_AssertException("$code in $file($line)"); } } assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_CALLBACK, array("Ficus_Assert", "callback")); ?> ficus/lang/ClassPathElement.php100644 1751 144 7500 10645132217 12217 ISHITOYA Kentaro * @version $Id: ClassPathElement.php 2 2007-07-11 10:37:48Z ishitoya $ * * class path element */ /** * @class Ficus_ClassPathElement */ class Ficus_ClassPathElement { const CACHE_RECURSIVE = "recursive"; const CACHE_NORMAL = "normal"; /** * @var $pattern Ficus_PathPattern pattern */ private $pattern; /** * @var $dir string target dir */ private $dir; /** * @var $paths array of path */ private $paths = array(); /** * @var $cache array of cache */ private $cache = array(); /** * construct class path element * @param $dir string root dir * @param $pattern Ficus_PathPattern pattern to apply */ public function __construct($dir, $pattern = null){ if(empty($dir)){ throw new Ficus_IllegalArgumentException("dir is empty"); } if(is_string($dir)){ $dir = new Ficus_Dir($dir); } Ficus_Assert::isType($dir, "Ficus_Dir"); Ficus_Assert::isTypeAllowNull($pattern, "Ficus_PathPattern"); if(is_null($pattern)){ $this->paths[] = $dir; }else{ $dir->setPattern($pattern); $this->paths[] = $dir; } $this->pattern = $pattern; } /** * get paths * @return array of path */ public function paths(){ return $this->paths; } /** * search * @param $needle string path * @param $recursive boolean true to search recursive * @return array found paths */ public function search($needle, $recursive = false){ if($recursive){ return $this->recursiveSearch($needle); } if(isset($this->cache[self::CACHE_NORMAL][$needle])){ return $this->cache[self::CACHE_NORMAL][$needle]; } $result = array(); foreach($this->paths as $path){ $path = $path . "/" . $needle; $path = Ficus_Dir::normalize($path); if(is_readable($path)){ $result[] = $path; } } $this->cache[self::CACHE_NORMAL][$needle] = $result; return $result; } /** * recursive search * @param $needle string path * @return array found paths */ public function recursiveSearch($needle){ if(isset($this->cache[self::CACHE_RECURSIVE]) == false){ $this->cache[self::CACHE_RECURSIVE] = array(); foreach($this->paths as $path){ $paths = $path->getList(); $this->cache[self::CACHE_RECURSIVE] = array_merge($this->cache[self::CACHE_RECURSIVE], $paths); } } if(isset($this->cache[self::CACHE_RECURSIVE][$needle])){ return array($this->cache[self::CACHE_RECURSIVE][$needle]); } return array(); } /** * to string * @return string */ public function __toString(){ return implode(",", $this->paths); } } ?> ficus/lang/Serializable.php100644 1751 144 2027 10645132217 11430 ISHITOYA Kentaro * @version $Id: Serializable.php 2 2007-07-11 10:37:48Z ishitoya $ * * serializable interface */ /** * @class Ficus_Serializable */ interface Ficus_Serializable extends Serializable { } ?> ficus/lang/String.php100644 1751 144 22121 10645132217 10305 SUMI Masafumi * @version $Id: String.php 2 2007-07-11 10:37:48Z ishitoya $ * * String wrapper class. */ require_once('ficus/exception/MethodNotFoundException.php'); /** * @class Ficus_String */ class Ficus_String { /** * @var $string string. */ private $string; /** * Constructor. * * @param $string string. */ public function __construct($string) { $this->string = $string; } /** * Contains str. * * @param $str string needle. * @return boolean if $str contains this string. */ public function contains($str) { return $this->strstr($str) != FALSE; } /** * To string. * * @return string this string. */ public function toString() { return $this->string; } /** * To string. * * @return string this string. */ public function __toString() { return $this->string; } /** * equals * @param $string Ficus_String right * @return boolean true if equals */ public function equals($right){ if(is_object($right) == false){ $string = (string)$right; }else if($right instanceof Ficus_String){ $string = $right->string; }else if(is_object($right) && method_exists($right, "__toString")){ $string = $right->__toString(); }else{ throw new Ficus_IllegalArgumentException("right object is not able to convert to string."); } return ($this->string == $string); } /** * starts with * @param $pattern string */ public function startsWith($pattern){ return (strpos($this->string, $pattern) === 0); } /** * ends with * @param $pattern string */ public function endsWith($pattern){ $plength = strlen($pattern); $index = strrpos($this->string, $pattern); if($index === false){ return false; } if(strlen($this->string) - $plength == $index){ return true; } return false; } /** * make lowercase first caractor * @return String processed string */ public function lowerCaseFirst(){ $first = substr($this->string, 0, 1); return new Ficus_String(strtolower($first) . substr($this->string, 1)); } /** * Copy. * * @return Ficus_String clone myself. */ public function copy() { return new Ficus_String($this->string); } /** * Call PHP strings function. * * @param $name string function name. * @param $arguments function arguments. * @return mixed function return value. * @throw Ficus_MethodNotFoundException method not found. */ public function __call($name, $arguments) { if (substr($name, -1) == '_') { $strip = true; $name = substr($name, 0, -1); } else { $strip = false; } $ret = $this->call($name, $arguments); if (!$strip && is_string($ret)) { return new Ficus_String($ret); } else { return $ret; } } /** * Call PHP strings function. * * @param $name string function name. * @param $arguments function arguments. * @return mixed function return value. * @throw Ficus_MethodNotFoundException method not found. */ protected function call($name, $arguments) { switch ($name) { case 'addcslashes': case 'addslashes': case 'bin2hex': case 'chop': case 'chunk_split': case 'convert_cyr_string': case 'convert_uudecode': case 'convert_uuencode': case 'count_chars': case 'crc32': case 'crypt': case 'hebrev': case 'hebrevc': case 'html_entity_decode': case 'htmlentities': case 'htmlspecialchars_decode': case 'htmlspecialchars': case 'levenshtein': case 'ltrim': case 'md5_file': case 'md5': case 'metaphone': case 'money_format': case 'nl2br': case 'number_format': case 'ord': case 'parse_str': case 'quoted_printable_decode': case 'QuoteMeta': case 'rtrim': case 'sha1': case 'similar_text': case 'soundex': case 'sscanf': case 'str_pad': case 'str_repeat': case 'str_rot13': case 'str_shuffle': case 'str_split': case 'str_word_count': case 'strcasecmp': case 'strchr': case 'strcmp': case 'strcoll': case 'strcspn': case 'strip_tags': case 'stripcslashes': case 'stripos': case 'stripslashes': case 'stristr': case 'strlen': case 'strnatcasecmp': case 'strnatcmp': case 'strncasecmp': case 'strncmp': case 'strpbrk': case 'strpos': case 'strrchr': case 'strrev': case 'strripos': case 'strrpos': case 'strspn': case 'strstr': case 'strtok': case 'strtolower': case 'strtoupper': case 'strtr': case 'substr_compare': case 'substr_count': case 'substr_replace': case 'substr': case 'trim': case 'ucfirst': case 'ucwords': case 'wordwrap': if (is_array($arguments)) { $argumentsWithString = array_merge(array($this->string), $arguments); } else { $argumentsWithString = array($this->string); } return call_user_func_array($name, $argumentsWithString); break; // this string is second argument. case 'explode': $arrangedArguments = array(); $arrangedArguments []= $arguments[0]; $arrangedArguments []= $this->string; $arrangedArguments += array_slice($arguments, 1); return call_user_func_array($name, $arrangedArguments); break; // this string is third argument. case 'str_ireplace': case 'str_replace': $arrangedArguments = array(); $arrangedArguments += array_slice($arguments, 0, 2); $arrangedArguments []= $this->string; $arrangedArguments += array_slice($arguments, 2); return call_user_func_array($name, $arrangedArguments); break; //case 'chr': // string chr(int ascii) //case 'fprintf': //case 'get_html_translation_table': //case 'implode': //case 'join': //case 'localeconv': //case 'nl_langinfo': //case 'printf': //case 'setlocale': //case 'sha1_file': //case 'sprintf': //case 'vfprintf': //case 'vprintf': //case 'vsprintf': //case 'echo': //case 'print': default: break; } throw new Ficus_MethodNotFoundException($name); } /** * convert uri to html link * @param $string string to convert * @return string converted string */ public static function convertLink($string){ return ereg_replace( "(https?|ftp|file)(://[[:alnum:]\+\$\;\?\.%,!#~*/:@&=_-]+)", "\\1\\2", $string); } /** * convert mail address to mailto link * @param $string string address * @return string converted string */ public static function convertMailAddress($string){ if(preg_match('/(.+) <(.*@.*)>/', $string, $regs)){ return '' . $regs[1] . " " . '<' . $regs[2] . ">";; }else if(preg_match('/<(.*@.*)>/', $string, $regs)){ return '<' . $regs[1] . ">"; } } } ?> ficus/lang/Object.php100644 1751 144 4460 10645132217 10233 SUMI Masafumi * @version $Id: Object.php 2 2007-07-11 10:37:48Z ishitoya $ * * Object */ require_once('ficus/exception/MethodNotFoundException.php'); require_once('ficus/exception/PropertyNotFoundException.php'); /** * @class Ficus_Object */ class Ficus_Object { /** * Get property by name. * * @param $name string property name. * @return mixed property value. * @throw Ficus_PropertyNotFoundException property not found. */ public function __get($name) { if ($name == 'scalar') { return $this->toString(); } throw new Ficus_PropertyNotFoundException('Call to undefined method ' . get_class($this) . "::$name"); } /** * Call method by name. * * @param $name string method name. * @param $arguments array arguments of method. * @return mixed return value of method. * @throw Ficus_MethodNotFoundException method not found. */ public function __call($name, $arguments) { if (method_exists($this, $name)) { call_user_func_array(array($this, $name), $arguments); } else { throw new Ficus_MethodNotFoundException('Call to undefined method ' . get_class($this) . "::$name()"); } } /** * To string. * * @return string to string of this object. */ public function __toString() { if (method_exists($this, 'toString')) { return $this->toString(); } else { return ''; } } } ?> ficus/lang/Class.php100644 1751 144 12001 10645132217 10100 ISHTIOYA Kentaro * @version $Id: Class.php 2 2007-07-11 10:37:48Z ishitoya $ * * class utility class */ /** * @class Ficus_Class */ class Ficus_Class { const PREFIX_SEPARATOR = "_"; const PACKAGE_SEPARATOR = "."; /** * @var $target object target object */ private $target = null; /** * @var $classname string target object class name cache purpose */ private $classname = null; /** * constructor * @param $target object target object */ public function __construct($target){ $this->setTarget($target); } /** * set target object * @param $target object target object */ public function setTarget($target){ if(is_object($target)){ $this->target = $target; $this->classname = get_class($target); }else if(is_string($target)){ $this->classname = $target; }else{ throw new Ficus_IllegalArgumentException("target must be an object"); } } /** * get prefix from object class name * @return string prefix */ public function prefix(){ $classname = $this->classname(); $index = strpos($classname, self::PREFIX_SEPARATOR); return substr($classname, 0, $index + 1); } /** * get package name * @return string package name */ public function package(){ $index = strrpos($this->classname, self::PACKAGE_SEPARATOR); if($index !== false){ return substr($this->classname, 0, $index); }else{ return ""; } } /** * get class name * @return string class name */ public function shortname(){ $classname = $this->classname(); $index = strpos($classname, self::PREFIX_SEPARATOR); if($index !== false){ return substr($classname, $index + 1); }else{ return $classname; } } /** * get Target * @return object target object */ public function target(){ return $this->target; } /** * get class name * @return string class name */ public function classname(){ $index = strrpos($this->classname, self::PACKAGE_SEPARATOR); if($index !== false){ return substr($this->classname, $index + 1); }else{ return $this->classname; } } /** * class qname * @return string class qname */ public function qname($prefix = null){ if(is_null($prefix)){ return $this->classname; }else{ $classname = $this->package(); if(empty($classname) == false){ $classname .= self::PACKAGE_SEPARATOR; } return $classname . $prefix . ucfirst($this->classname()); } } /** * file name * @param $ext string extension for file * @return string file name */ public function filename($ext = ""){ $classname = $this->package(); if(empty($classname) == false){ $classname .= self::PACKAGE_SEPARATOR; } $classname .= $this->shortname(); return str_replace(self::PACKAGE_SEPARATOR, "/", $classname) . $ext; } /** * cast class * @param $src Object target object * @param $dest mixed string of classname or object * @return casted class */ public function cast($src, $dest){ if(($src instanceof Ficus_Serializable) && is_object($dest) && ($dest instanceof Ficus_Serializable)){ $serialized = $src->serialize(); $dest->unserialize($serialized); return $dest; }else if(is_string($dest) && class_exists($dest)){ $serialized = serialize($src); $object = str_replace(get_class($src), $dest, $serialized); $retval = unserialize($object); if($retval == false){ throw new Ficus_ClassCastException("Can not cast class " . get_class($src) . " to $dest."); } return $retval; }else{ throw new Ficus_ClassCastException("Can not cast class. illegal argument."); } } } ?> ficus/lang/Runtime.php100644 1751 144 12312 10645132217 10463 ISHITOYA Kentaro * @version $Id: Runtime.php 2 2007-07-11 10:37:48Z ishitoya $ * * utility to execute command line command */ require_once("ficus/lang/Assert.php"); require_once("ficus/exception/NotReadyException.php"); require_once("ficus/exception/NotSupportedException.php"); require_once("ficus/lang/PlatformInformation.php"); /** * @class Ficus_Runtime */ class Ficus_Runtime { const ERROR = "error"; /** * command search path */ protected static $paths = array(); /** * add path * @param $path string path */ public static function addPath($path){ self::$paths[] = $path; } /** * create env * @return array of env */ private static function createEnv(){ if(empty(self::$paths) == false){ $path = implode(PATH_SEPARATOR, self::$paths); return array('PATH' => $path); } return null; } /** * execute command. * @param $command string command line command * @param $parameters array array of parameters * @return array of command output. * @throw Ficus_TypeMismatchException */ public static function exec($command, $parameters = null){ Ficus_Assert::isPrimitiveTypeAllowNull($parameters, "array"); if(is_null($parameters) == false){ $param = implode(' ', $parameters); $command .= ' ' . $param; } $specs = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')); $env = self::createEnv(); $command = str_replace("\\", "/", $command); $command = escapeshellcmd($command); $process = proc_open($command, $specs, $pipes, null, $env); if(is_resource($process) == false){ throw new Ficus_NotReadyException("Process is not started. command is $command."); } $output = stream_get_contents($pipes[1]); fclose($pipes[1]); $error = stream_get_contents($pipes[2]); fclose($pipes[2]); $output = explode("\n", $output); $output[self::ERROR] = $error; proc_close($process); return $output; } /** * execute command with input. * @param $command string command line command * @param $inputs array array of command line input * @param $parameters array array of parameters * @return array of command output. * @throw Ficus_TypeMismatchException * @throw Ficus_NotReadyException */ public static function execWithInput($command, $inputs, $parameter = null){ Ficus_Assert::isPrimitiveTypeAllowNull($inputs, "array"); Ficus_Assert::isPrimitiveTypeAllowNull($command, "array"); if(is_null($parameters) == false){ $param = implode(' ', $parameters); $command .= ' ' . $param; } $specs = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')); $env = self::createEnv(); $process = proc_open($command, $specs, $pipes, null, $env); if(is_resource($process) == false){ throw new Ficus_NotReadyException("Process is not started. command is $command."); } if(is_null($inputs) == false){ foreach($inputs as $input){ fwrite($pipes[0], $input); sleep(1); } fclose($pipes[0]); } $output = stream_get_contents($pipes[1]); $error = stream_get_contents($pipes[2]); $output = explode("\n", $output); $output[self::ERROR] = $error; fclose($pipes[1]); fclose($pipes[2]); proc_close($process); return $output; } /** * is command exists * @param $command string target command * @return boolean return true if command exists */ public static function isCommandExists($command){ if(Ficus_PlatformInformation::isWindows()){ throw new Ficus_NotSupportedException("windows platform is not supported for this function."); } $output = self::exec("which " . $command); $output = implode(' ', $output); if(count($output) == 0 || preg_match('/command not found/', $output) || preg_match("/no $command/", $output)){ return false; }else{ return true; } } } ?> ficus/lang/Unicode.php100644 1751 144 3731 10645132217 10413 SUMI Masafumi * @version $Id: Unicode.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_Unicode */ class Ficus_Unicode { /** * UTF-8 */ const UTF8 = 'UTF-8'; /** * UTF-16 */ const UTF16 = 'UTF-16'; /** * UCS-4 */ const UCS4 = 'UCS-4'; /** * Get Unicode number from unicode encoding. * * @param $utf string unicode encoding string. * @param $enc string unicode encoding name. * @return int unicode number. */ public static function getUnicode($utf, $encoding = self::UTF8) { // UCS-4 is the same as Unicode number. $ucs = mb_convert_encoding($utf, self::UCS4, $encoding); $hex = bin2hex(mb_substr($ucs, 0, 1, self::UCS4)); return hexdec($hex); } public static function at($str, $pos, $encoding = self::UTF8) { return mb_substr($str, $pos, 1, $encoding); } public static function first($str, $encoding = self::UTF8) { return mb_substr($str, 0, 1, $encoding); } public static function last($str, $encoding = self::UTF8) { return mb_substr($str, mb_strlen($str, $encoding) - 1, 1, $encoding); } } ?> ficus/lang/Arrays.php100644 1751 144 5051 10645132217 10263 SUMI Masafumi * @version $Id: Arrays.php 2 2007-07-11 10:37:48Z ishitoya $ * * Util Type utility. */ require_once("ficus/exception/TypeMismatchException.php"); /** * @class Ficus_Arrays */ class Ficus_Arrays { /** * collect equals key. * * example: * $ary = Ficus_Arrays::delete($ary, $target, * create_function('$obj1, $obj2', 'return $obj1->equals($obj2);')); * * @param $ary array target * @param $obj mixed object defined equals(). * @param $callback callback predicate function * @return array of equals $obj */ public static function delete($ary, $obj, $callback) { $survivor = array(); foreach ($ary as $element) { if (!call_user_func($callback, $element, $obj)) { array_push($survivor, $element); } } return $survivor; } /** * collect equals key. * * example: * $ary = Ficus_Arrays::deleteBy($ary, $target, "equals"); * * @param $ary array target * @param $obj mixed object defined equals(). * @param $function string predicate method name * @return array of equals $obj */ public static function deleteBy($ary, $obj, $function) { $survivor = array(); foreach ($ary as $element) { if (!$element->$function($obj)) { array_push($survivor, $element); } } return $survivor; } /** * Array to string. * * @param $array array. * @return string string. */ static public function arrayToString($array) { $buf = ''; foreach ($array as $element) { $buf .= $element->__toString(); } return $buf; } } ?> ficus/lang/ClassLoader.php100644 1751 144 25014 10645132217 11237 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ClassLoader.php 2 2007-07-11 10:37:48Z ishitoya $ * * Class Loader for php */ require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/exception/ClassNotFoundException.php"); require_once("ficus/exception/MultipleClassDefinitionFoundException.php"); require_once("ficus/exception/NotReadyException.php"); require_once("ficus/lang/ClassPath.php"); require_once("ficus/io/Dir.php"); require_once("ficus/test/PathInitializer.php"); /** * @class Ficus_ClassLoader */ class Ficus_ClassLoader { const CACHE_IMPORT = "import"; const CACHE_CONSTRUCT = "construct"; /** * @var $cache Array cache */ private static $cache = array(); /** * import class * @param $classPath string class name to import * @param $classname string class if classqname and classname are not same * @throw Ficus_NotReadyException no initialized. * @throw Ficus_ClassNotFoundException class not found. * @throw Ficus_MultipleClassDefinitionFoundException multiple definition. */ public static function import($classPath, $classname=""){ $index = $classPath; if(empty($classname)){ if(preg_match('/.*?\.?([^\.]+)$/', $classPath, $regs) == false){ throw new Ficus_IllegalArgumentException("class path $classPath is illegal"); } $classname = $regs[1]; } if(class_exists($classname)){ return; } $result = self::normalizeClassPath($classPath, $classname); $classPath = $result[0]; $classname = $result[1]; $classPath = self::searchForClass($classPath); self::$cache[self::CACHE_IMPORT][$index] = $classPath; require_once($classPath); if(!class_exists($classname)){ throw new Ficus_ClassNotFoundException(__FILE__ . ": " . "class " . $classname . " not found in " . $classPath . "."); } } /** * normalize Class path * @param $classPath string class name to import * @param $classname string class if classqname and classname are not same * @throw Ficus_ClassNotFoundException class not found. */ protected static function normalizeClassPath($classPath, $classname){ $classPath = Ficus_ClassPath::packageToDirectory($classPath); $classPath = ereg_replace(Ficus_ClassPath::ESCAPED_DOT, Ficus_ClassPath::PACKAGE_SEPARATOR, $classPath); $regs = array(); //case hogehoge/ugeuge/moge.php or the hogehoge/moge.php if(preg_match("/(.*)\/(([^\/]*_)?([^\/]*))$/", $classPath, $regs)){ $classname = empty($classname) ? $regs[2] : $classname; $shortname = $regs[4]; $rootpath = array(); //$classPath = self::$classPath . self::$defaultDir . "/"; $classPath = $regs[1] . "/" . $shortname . ".php"; //class is placed in root path then class path is class name. }else if(ereg("_([^\/_]*)", $classPath, $regs)){ $classname = empty($classname) ? $classPath : $classname; $shortname = $regs[1]; $classPath = $shortname . ".php"; }else{ throw new Ficus_ClassNotFoundException(__FILE__ . ": " . "class " . $classPath . " not found."); } return array($classPath, $classname); } /** * search for class * @param $classPath string class name to import * @throw Ficus_ClassNotFoundException class not found. * @throw Ficus_MultipleClassDefinitionFoundException multiple definition. */ protected static function searchForClass($classPath){ $foundClasses = Ficus_ClassPath::search($classPath); if(count($foundClasses) >= 2){ throw new Ficus_MultipleClassDefinitionFoundException("Multiple Class Definition Found. found classes are " . implode(",", $foundClasses) . "."); }else if(empty($foundClasses)){ throw new Ficus_ClassNotFoundException(__FILE__ . ": " . "class " . $classPath . " not found."); } return $foundClasses[0]; } /** * not only import but load class. * @param $classQName String qualified class name * @param $parameter array parameters for constructor * @return Mixed instance of class */ public static function load($classQName, $parameter = null){ if(isset(self::$cache[self::CACHE_IMPORT][$classQName]) == false){ self::import($classQName); } if(preg_match("/\.?([^.]*)$/", $classQName, $regs)){ return self::constructClass($regs[1], $parameter); } return null; } /** * load class with class name. * Use this method when class file name and class name is differ. * @param $classPath string class to import * @param $className string class name to load * @param $parameter array parameters for constructor * @return Mixed instance of class */ public static function loadWithClassName($classPath, $className, $parameter = null){ self::import($classPath, $className); return self::constructClass($className, $parameter); } /** * load class from file * Use this method when class is not saved yet. * @param $source string source code. * @param $className string class name to load * @param $alternate boolean when the class name is already exists. * @param $parameter array parameters for constructor * @return Mixed instance of class */ public static function loadFromFile($source, $classname, $alternate = false, $parameter = null){ $source = str_replace(array(""), "", $source); if($alternate){ $alt = self::getAlternateClassname($classname); $source = preg_replace("/^class $classname/m", "class $alt", $source); $classname = $alt; } eval($source); return self::constructClass($classname, $parameter); } /** * get Alternate classname * @param $classname string class name * @return string alternate classname */ private function getAlternateClassname($classname){ for($i = 1; class_exists($classname); $i++){ $classname = "{$classname}_1"; } return $classname; } /** * construct class with a constructor parameters. * please give me an idea to make better this code * @param $className string className * @param $param array constructor parameter * @throw Ficus_IllegalArgumentException not instantiable. */ private function constructClass($className, $param){ $start = microtime(true); if(isset(self::$cache[self::CACHE_CONSTRUCT][$className]) == false){ $class = new ReflectionClass($className); if($class->isAbstract() || $class->isInterface()){ throw new Ficus_IllegalArgumentException("this class $className can not instantiable"); } $requiredParamCount = 0; $paramCount = 0; $constructor = $class->getConstructor(); self::$cache[self::CACHE_CONSTRUCT][$className] = $constructor; }else{ $constructor = self::$cache[self::CACHE_CONSTRUCT][$className]; } if(is_null($constructor) == false){ $requiredParamCount =$constructor->getNumberOfRequiredParameters(); $paramCount = $constructor->getNumberOfParameters(); } if(is_null($param)){ if($requiredParamCount != 0){ throw new Ficus_IllegalArgumentException("this class's constructor have required parameters."); } return new $className(); } if(is_array($param) == false){ throw new Ficus_IllegalArgumentException("parameter must be array"); } $count = count($param); if($count < $requiredParamCount || $count > $paramCount){ throw new Ficus_IllegalArgumentException("wrong parameter count."); } switch($count){ case (0) : return new $className(); case (1) : return new $className($param[0]); case (2) : return new $className($param[0], $param[1]); case (3) : return new $className($param[0], $param[1], $param[2]); case (4) : return new $className( $param[0], $param[1], $param[2], $param[3]); case (5) : return new $className( $param[0], $param[1], $param[2], $param[3], $param[4]); case (6) : return new $className( $param[0], $param[1], $param[2], $param[3], $param[4], $param[5]); case (7) : return new $className( $param[0], $param[1], $param[2], $param[3], $param[4], $param[5], $param[6]); case (8) : return new $className( $param[0], $param[1], $param[2], $param[3], $param[4], $param[5], $param[6], $param[7]); case (9) : return new $className( $param[0], $param[1], $param[2], $param[3], $param[4], $param[5], $param[6], $param[7], $param[8]); case (10) : return new $className( $param[0], $param[1], $param[2], $param[3], $param[4], $param[5], $param[6], $param[7], $param[8], $param[9]); default : throw new Ficus_IllegalArgumentException("This method supports only max 10 parameter now."); } } } ?> ficus/lang/S2AnAAutoLoad.php100644 1751 144 3065 10645132217 11322 ISHITOYA Kentaro * @version $Id: S2AnAAutoLoad.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/lang/AutoLoad.php"); require_once("s2container.php5/S2Container.php"); require_once("s2ana.php5/S2AnA.php"); /** * @class Ficus_S2AnAAutoLoad */ class Ficus_S2AnAAutoLoad extends Ficus_AutoLoad{ /** * constructor */ public function __construct(){ S2ContainerClassLoader::import(S2CONTAINER_PHP5); S2ContainerClassLoader::import(S2ANA_PHP5); } /** * abstract autoload * @param $classname string class name to load * @return boolean true if load succeeded */ protected function load($classname){ return S2ContainerClassLoader::load($classname); } } ?> ficus/lang/annotation/TypeAnnotation.php100644 1751 144 3157 10645132217 14155 ISHITOYA Kentaro * @version $Id: TypeAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_TypeAnnotation */ class Ficus_TypeAnnotation extends Ficus_ReflectionAnnotation { /** * type */ private $type; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); $this->type = trim($arguments); } /** * get type * @return string type */ public function getType(){ return $this->type; } } ?> ficus/lang/annotation/PackageAnnotation.php100644 1751 144 3223 10645132217 14561 ISHITOYA Kentaro * @version $Id: PackageAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_PackageAnnotation */ class Ficus_PackageAnnotation extends Ficus_ReflectionAnnotation { /** * package */ private $package; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); $this->package = trim($arguments); } /** * get package * @return string package */ public function getPackage(){ return $this->package; } } ?> ficus/lang/annotation/ParamAnnotation.php100644 1751 144 4166 10645132217 14275 ISHITOYA Kentaro * @version $Id: ParamAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_ParamAnnotation */ class Ficus_ParamAnnotation extends Ficus_ReflectionAnnotation { /** * name */ private $name; /** * type */ private $type; /** * comment */ private $comment; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); preg_match('/\$([^ ]+) ([^ ]+)(.*)/', trim($arguments), $matches); $this->name = $matches[1]; $this->type = $matches[2]; $this->comment = $matches[3]; } /** * get type * @return string type */ public function getType(){ return $this->type; } /** * get name * @return string name */ public function getName(){ return $this->name; } /** * get comment * @return string comment */ public function getComment(){ return $this->comment; } } ?> ficus/lang/annotation/ReturnAnnotation.php100644 1751 144 3637 10645132217 14516 ISHITOYA Kentaro * @version $Id: ReturnAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_ReturnAnnotation */ class Ficus_ReturnAnnotation extends Ficus_ReflectionAnnotation { /** * type */ private $type; /** * comment */ private $comment; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); preg_match('/^([^ ]+)(.*)/', trim($arguments), $matches); $this->type = $matches[1]; $this->comment = $matches[2]; } /** * get type * @return string type */ public function getType(){ return $this->type; } /** * get comment * @return string comment */ public function getComment(){ return $this->comment; } } ?> ficus/lang/annotation/ClassAnnotation.php100644 1751 144 3175 10645132217 14301 ISHITOYA Kentaro * @version $Id: ClassAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_ClassAnnotation */ class Ficus_ClassAnnotation extends Ficus_ReflectionAnnotation { /** * class */ private $class; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); $this->class = trim($arguments); } /** * get class * @return string class */ public function getClass(){ return $this->class; } } ?> ficus/lang/annotation/DefinedbyAnnotation.php100644 1751 144 3233 10645132217 15120 ISHITOYA Kentaro * @version $Id: DefinedbyAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_DefinedByAnnotation */ class Ficus_DefinedbyAnnotation extends Ficus_ReflectionAnnotation { /** * defined by */ private $definedby; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); $this->definedby = trim($arguments); } /** * get Name * @return string name */ public function getDefinedBy(){ return $this->definedby; } } ?> ficus/lang/annotation/CommentAnnotation.php100644 1751 144 3224 10645132217 14631 ISHITOYA Kentaro * @version $Id: CommentAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_CommentAnnotation */ class Ficus_CommentAnnotation extends Ficus_ReflectionAnnotation { /** * comment */ private $comment; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); $this->comment = trim($arguments); } /** * get comment * @return string comment */ public function getComment(){ return $this->comment; } } ?> ficus/lang/annotation/VarAnnotation.php100644 1751 144 6137 10645132217 13765 ISHITOYA Kentaro * @version $Id: VarAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_VarAnnotation */ class Ficus_VarAnnotation extends Ficus_ReflectionAnnotation { const T_NAME = "name"; const T_TYPE = "type"; const T_COMMENT = "comment"; const T_ISARRAY = "isArray"; const T_VAR = "var"; /** * array of annotations */ private $annotations = array(); /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ preg_match('/\$([^\s]+)\s+(([a|A]rray)\s+of\s+(.*)|([^\s]+)\s+(.*))/', $arguments, $matches); $annotations = array(); if($matches[3] == "array"){ $this->annotations[self::T_NAME] = $matches[1]; $this->annotations[self::T_TYPE] = $matches[4]; $this->annotations[self::T_COMMENT] = $matches[2]; $this->annotations[self::T_ISARRAY] = true; }else{ $this->annotations[self::T_NAME] = $matches[1]; $this->annotations[self::T_TYPE] = $matches[5]; $this->annotations[self::T_COMMENT] = $matches[6]; $this->annotations[self::T_ISARRAY] = false; } parent::__construct($reflector, $arguments); } /** * get Name * @return string name */ public function getName(){ return $this->annotations[self::T_NAME]; } /** * get Type * @return string type */ public function getType(){ return $this->annotations[self::T_TYPE]; } /** * get COMMENT * @return string comment */ public function getComment(){ return $this->annotations[self::T_COMMENT]; } /** * is Array * @return boolean */ public function isArray(){ return $this->annotations[self::T_ISARRAY]; } /** * is Class * @return boolean */ public function isClass(){ if(strpos($this->getType(), "urn:") !== false){ return true; } return false; } } ?> ficus/lang/annotation/AuthorAnnotation.php100644 1751 144 3761 10645132217 14477 ISHITOYA Kentaro * @version $Id: AuthorAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_AuthorAnnotation */ class Ficus_AuthorAnnotation extends Ficus_ReflectionAnnotation { /** * author */ private $author; /** * email */ private $email; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); if(preg_match('/mailto:(.*?)">(.*?)email = $matches[1]; $this->author = $matches[2]; }else{ $this->author = trim($arguments); } } /** * get author * @return string author */ public function getAuthor(){ return $this->author; } /** * get email * @return string email */ public function getEmail(){ return $this->email; } } ?> ficus/lang/annotation/BriefAnnotation.php100644 1751 144 3176 10645132217 14264 ISHITOYA Kentaro * @version $Id: BriefAnnotation.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/reflect/ReflectionAnnotation.php"; require_once "ficus/lang/Assert.php"; /** * @class Ficus_BriefAnnotation */ class Ficus_BriefAnnotation extends Ficus_ReflectionAnnotation { /** * defined by */ private $brief; /** * constructor * @param $reflector object reflector object * @param $arguments string arguments written in annotation section */ public function __construct($reflector, $arguments){ parent::__construct($reflector, $arguments); $this->brief = trim($arguments); } /** * get Brief * @return string brief */ public function getBrief(){ return $this->brief; } } ?> ficus/lang/S2DaoAutoLoad.php100644 1751 144 3066 10645132217 11367 ISHITOYA Kentaro * @version $Id: S2DaoAutoLoad.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/lang/AutoLoad.php"); require_once("s2container.php5/S2Container.php"); require_once("s2dao.php5/S2Dao.php"); /** * @class Ficus_S2DaoAutoLoad */ class Ficus_S2DaoAutoLoad extends Ficus_AutoLoad{ /** * constructor */ public function __construct(){ S2ContainerClassLoader::import(S2CONTAINER_PHP5); S2ContainerClassLoader::import(S2DAO_PHP5); } /** * abstract autoload * @param $classname string class name to load * @return boolean true if load succeeded */ protected function load($classname){ return S2ContainerClassLoader::load($classname); } } ?> ficus/lang/AutoClassLoader.php100644 1751 144 7626 10645132217 12061 ISHITOYA Kentaro * @version $Id: AutoClassLoader.php 2 2007-07-11 10:37:48Z ishitoya $ * * load class from search path. */ require_once("ficus/lang/ClassLoader.php"); require_once("ficus/lang/ClassPathElement.php"); /** * @class Ficus_AutoClassLoader */ class Ficus_AutoClassLoader extends Ficus_ClassLoader { /** * @var $paths array search paths */ private static $paths = array(); /** * @return array paths */ public static function paths(){ return self::$paths; } /** * add search path * @param $path Ficus_ClassPathElement search path * @param $prefix String prefix of class */ public static function add($path, $prefix =""){ Ficus_Assert::isType($path, "Ficus_ClassPathElement"); self::$paths[$prefix][] = $path; } /** * import class * @param $classPath string class name to import * @param $classname string class if classqname and classname are not same * @throw Ficus_NotReadyException no initialized. * @throw Ficus_ClassNotFoundException class not found. * @throw Ficus_MultipleClassDefinitionFoundException multiple definition. */ public static function import($classPath, $classname=""){ try{ $result = self::normalizeClassPath($classPath, ""); $classPath = $result[0]; $classname = $result[1]; $prefix = self::getPrefix($classname); $index = strrpos($classPath, DIRECTORY_SEPARATOR); if($index !== false){ $filename = substr($classPath, $index + 1); }else{ $filename = $classPath; } $paths = array(); if(empty($prefix) || isset(self::$paths[$prefix]) == false){ foreach(self::$paths as $path){ $paths = array_merge($paths, $path); } }else{ $paths = self::$paths[$prefix]; } $classes = array(); foreach($paths as $path){ $found = $path->search($filename, true); $classes = array_merge($found, $classes); } if(empty($classes)){ throw new Ficus_ClassNotFoundException("class is not found"); } $class = $classes[0]; require_once($class); if(!class_exists($classname)){ return false; } }catch(Ficus_IllegalArgumentException $e){ return false; }catch(Ficus_ClassNotFoundException $e){ return false; } return true; } /** * clear */ public static function clear(){ self::$paths = array(); } /** * get prefix from classname * @param $classname string classname * @return string prefix */ protected static function getPrefix($classname){ $index = strpos($classname, "_"); if($index === false){ return ""; } $prefix = substr($classname, 0, $index); return $prefix; } } ?> ficus/lang/AutoLoad.php100644 1751 144 3721 10645132217 10534 ISHITOYA Kentaro * @version $Id: AutoLoad.php 2 2007-07-11 10:37:48Z ishitoya $ */ /** * @class Ficus_AutoLoad */ abstract class Ficus_AutoLoad { /** * autoloads function classes */ protected static $autoloads = array(); /** * abstract autoload * @param $classname string class name to load * @return boolean true if load succeeded */ protected abstract function load($classname); /** * add auto load instance */ public static function add(Ficus_AutoLoad $autoload){ self::$autoloads[get_class($autoload)] = $autoload; } /** * autoload function * @param $classname string class name toload * @return boolean true if load succeeded */ public static function autoload($classname){ if(empty($classname)){ return false; } foreach(self::$autoloads as $autoload){ if($autoload->load($classname)){ return true; } } return false; } } if (!function_exists('__autoload')) { function __autoload($class = null){ Ficus_AutoLoad::autoload($class); } } ?> ficus/lang/Random.php100644 1751 144 3737 10645132217 10253 ISHITOYA Kentaro * @version $Id: Random.php 2 2007-07-11 10:37:48Z ishitoya $ */ /** * @class Ficus_Random */ class Ficus_Random { /** * create rondomized integer, alias of nextInteger * @param $min int minimal number * @param $max int maximam number * @return int randomized integer */ public function next($min = 0, $max = 0){ return $this->nextInteger($min, $max); } /** * create randomized integer * @param $min int minimal number * @param $max int maximam number * @return int randomized integer */ public function nextInteger($min = 0, $max = 0){ if(($min == 0 && $max == 0) || ($min < $max) == false){ return mt_rand(); } return mt_rand($min, $max); } /** * create rondamized hash string * @param $length int length of hash * @return string hash string */ public function nextString($length = 0){ $random = $this->next(); $hash = sha1(uniqid(mt_rand(), true)); if($length == 0){ return $hash; }else{ return substr($hash, 0, $length); } } } ?> ficus/lang/Types.php100644 1751 144 13163 10645132217 10151 SUMI Masafumi * @version $Id: Types.php 2 2007-07-11 10:37:48Z ishitoya $ * * Util Type utility. */ require_once("ficus/lang/reflect/ReflectionClass.php"); require_once("ficus/exception/TypeMismatchException.php"); /** * @class Ficus_Types */ class Ficus_Types { /** * cast var to specified type * @param $value mixed target value * @param $type string type to cast * @param $type casted value */ public static function cast($var, $type){ switch($type){ case("int") : return (int)$var; case("string") : return (string) $var; case("array") : return (array) $var; case("double") : return (double) $var; case("float") : return (float) $var; case("boolean") : return (boolean) $var; } throw new Ficus_ClassCastException("not supported type :$type"); } /** * to string of object. * * @param $obj mixed scalar or object defined toString or String. * @return String of $obj. * @throw Ficus_TypeMismatchException $obj has no toString(). */ public static function toStringOf($obj) { if (is_string($obj)) { return $obj; } else if (is_scalar($obj)) { return strval($obj); } else if (method_exists($obj, "toString")) { return $obj->toString(); } else if (method_exists($obj, "__toString")) { return $obj->__toString(); } else if ($obj === NULL) { return ''; } else { throw new Ficus_TypeMismatchException("toString not defined in " . gettype($obj)); } } /** * compare same class of string. * * @param $left mixed left argument. * @param $right mixed right argument. * @return int compare left and right. */ public static function compareByToString($left, $right) { $left = self::toStringOf($left); $right = self::toStringOf($right); return strcmp($left, $right); /* this code cause of seg fault!*/ //return strcmp(self::toStringOf($left), self::toStringOf($right)); } /** * equals same class of string. * * @param $left mixed left argument. * @param $right mixed right argument. * @return int left equals right. */ public static function equalsByToString($left, $right) { return (self::toStringOf($left) == self::toStringOf($right)); } /** * to array form of object. * * @param $obj mixed object defined toArray * @return array form of $obj. * @throw Ficus_TypeMismatchException $obj has no toArray(). */ public static function toArrayOf($obj) { if (is_array($obj) || $obj instanceof stdClass) { $ret = array(); foreach($obj as $key => $element){ if($element instanceof stdClass){ $casted = (array)$element; foreach($casted as $castedKey => $castedElement){ if(is_object($castedElement) || is_array($castedElement)){ $casted[$castedKey] = self::toArrayOf($castedElement); } } $ret[$key] = $casted; }else if(is_object($element) || is_array($element)){ $ret[$key] = self::toArrayOf($element); }else{ $ret[$key] = $element; } } return $ret; } else if (method_exists($obj, "toArray")) { return $obj->toArray(); } else if (is_object($obj)) { return self::objectToArray($obj); } else { throw new Ficus_TypeMismatchException("toArray does not defined in " . gettype($obj) . ":" . $obj); } } /** * convert object to array * @param $object mixed object to convert * @return array array of object array form */ private function objectToArray($object){ $result = array(); $class = new Ficus_ReflectionClass($object); $props = $class->getAllProperties(); foreach($props as $prop){ $name = $prop->getName(); $value = null; if($prop->isPublic()){ $value = $prop->getValue($object); }else{ $getMethod = "get" . ucfirst($name); if(method_exists($object, $getMethod)){ $method = $class->getMethod($getMethod); }else if(method_exists($object, $name)){ $method = $class->getMethod($name); }else{ continue; } $value = $object->{$method->getName()}(); } if(is_object($value)){ $value = self::objectToArray($value); }else if(is_array($value)){ $value = self::toArrayOf($value); } $result[$name] = $value; } return $result; } } ?> ficus/test/DbUnitTestCase.php100644 1751 144 7043 10646431661 11712 SUMI Masafumi * @version $Id: DbUnitTestCase.php 12 2007-07-15 14:41:51Z ishitoya $ * * DbUnit Testcase. */ require_once "PHPUnit/Framework/TestCase.php"; /** * @class Ficus_DbUnitTestCase */ abstract class Ficus_DbUnitTestCase extends PHPUnit_Framework_TestCase { /** * PDO connector. */ private $connector; /** * Setup Testcase * * @throw Exception setup error. */ public function setUp() { $dbini = Ficus_PropertyFileReader::read($this->getDbPropertyName()); $this->connector = new Ficus_PDODatabase(); $dsn = $this->connector->createDSN($dbini['dbtype'], $dbini['host'], $dbini['dbname']); $this->connector->connect($dsn, $dbini['user'], $dbini['password']); if ($this->getDeleteSQL() != '') { $deleteSQL = file_get_contents($this->getDeleteSQL()); if ($deleteSQL === false) { throw new Exception("Delete SQL file not found." . $this->getDeleteSQL()); } if (($ret = $this->connector->query($deleteSQL)) === false) { throw new Exception("Database error!! " . $this->connector->ErrorMsg()); } } if ($this->getInitSQL() != '') { $initSQL = file_get_contents($this->getInitSQL()); if ($initSQL === false) { throw new Exception("Init SQL file not found." . $this->getInitSQL()); } if (($ret = $this->connector->query($initSQL)) === false) { throw new Exception("Database error!! " . $this->connector->ErrorMsg()); } } } /** * Clean up Testcase * * @throw Exception setup error. */ public function tearDown() { if (($ret = $this->connector->query(file_get_contents($this->getDeleteSQL()))) === false) { throw new Exception("Database error!! " . $this->connector->ErrorMsg()); } $this->connector->disconnect(); } /** * Get connector. */ public function getConnector() { return $this->connector; } /** * Execute SQL. * * @param $sql string SQL. * @throw Exception setup error. */ public function executeQuery($sql) { if (($ret = $this->connector->query($sql)) === false) { throw new Exception("database error!! " . $this->connector->ErrorMsg()); } if($ret instanceof PDOStatement){ return $ret->fetchAll(); } return $ret; } /** * */ abstract public function getDeleteSQL(); /** * */ abstract public function getInitSQL(); /** * */ abstract public function getDbPropertyName(); } ?> ficus/test/PathInitializer.php100644 1751 144 2601 10645132217 12156 ISHITOYA Kentaro * @version $Id: PathInitializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ /** * @class Ficus_PathInitializer */ interface Ficus_PathInitializer { // path names const SRC_PATH = "src"; const WEBAPPS_PATH = "webapps"; const LIB_PATH = "lib"; const BUILD_PATH = "build"; const CONF_PATH = "conf"; const TESTS_PATH = "conf"; const TESTDATA_PATH = "testdata"; /** * Initialize */ public static function setUp(); /** * teardown */ public static function tearDown(); } ?> ficus/collection/UnicodeIterator.php100644 1751 144 2572 10645132217 13341 SUMI Masafumi * @version $Id: UnicodeIterator.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once('ficus/collection/MBStringIterator.php'); require_once('ficus/lang/Unicode.php'); /** * @class Ficus_UnicodeIterator */ class Ficus_UnicodeIterator extends Ficus_MBStringIterator { /** * Return the current char unicode. * * @return int current char unicode. */ public function current() { $char = mb_substr($this->string, $this->position, 1, $this->encoding); return Ficus_Unicode::getUnicode($char); } } ?> ficus/collection/Stack.php100644 1751 144 4227 10645132217 11305 SUMI Masafumi * @version $Id: Stack.php 2 2007-07-11 10:37:48Z ishitoya $ * * Util Stack collection utility. */ /** * @class Ficus_Stack */ class Ficus_Stack implements IteratorAggregate { /** * @var array stack. */ private $stack; /** * Constructor. */ public function __construct() { $this->stack = array(); } /** * Push stack. * * @param $element mixed element. * @return Ficus_Stack return this. */ public function push($element) { $this->stack[] = $element; return $this; } /** * Top of stack. * * @return mixed top value of stack. */ public function top() { return end($this->stack); } /** * Pop stack. * * @return mixed top value of stack. */ public function pop() { return array_pop($this->stack); } /** * Count stack. * * @return int count stack. */ public function count() { return count($this->stack); } /** * Get iterator. * * @return ArrayIterator */ public function getIterator() { return new ArrayObject($this->stack); } /** * Stack to array. * * @return array array of stack values. */ public function toArray() { return clone($stack); } } ?> ficus/collection/SimpleMap.php100644 1751 144 12277 10645132217 12153 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: SimpleMap.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/collection/Map.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_SimpleMap * Simple implementation of Ficus_Map */ class Ficus_SimpleMap implements Ficus_Map{ /** * @var $elements array elements */ protected $elements = array(); /** * constructor * @param $keys Array key array of elements * @param $elements Array elements to add this map * @throw Ficus_IllegalArgumentException illegal argument. */ public function __construct($keys = array(), $elements = array()){ if(is_array($elements) == false || is_array($elements) == false){ throw new Ficus_IllegalArgumentException("passed parameter is not an array"); } if(count($elements) !== count($keys)){ throw new Ficus_IllegalArgumentException("passed keys and elements is not same size"); } while($key = current($keys)){ $this->put($key, current($elements)); next($keys); next($elements); } } /** * add element to Collection * @param $key key of element to add * @param $element Element to add the Map * @return value returns old value if the key found in Map * @throw Ficus_IllegalArgumentException illegal argument. */ public function put($key, $element){ if(is_null($key)){ throw new Ficus_IllegalArgumentException("passed key is null"); } $oldvalue = null; if(isset($this->elements[$key])){ $oldvalue = $this->elements[$key]; } $this->elements[$key] = $element; return $oldvalue; } /** * clear all elements in the Map. */ public function clear(){ $this->elements = array(); } /** * remove element from the Map * @param $key string element to remove * @return element returns old value if key exists */ public function remove($key){ $oldvalue = null; if(isset($this->elements[$key])){ $oldvalue = $this->elements[$key]; unset($this->elements[$key]); } return $oldvalue; } /** * get element from the Map * @param $key string element to get * @return element */ public function get($key){ if(isset($this->elements[$key])){ return $this->elements[$key]; } return null; } /** * get size of the Map * @return integer size of this Map */ public function size(){ return count($this->elements); } /** * to array * @return Array array presentation of Map */ public function toArray(){ return $this->elements; } /** * returns true if Map is empty * @return boolean true if the Map is empty */ public function isEmpty(){ return empty($this->elements); } /** * returns key array from the Map * @return Array array of the keys of Map */ public function keys(){ return array_keys($this->elements); } /** * return value array from the Map * @return Array array of the values of Map */ public function values(){ return array_values($this->elements); } /** * rewind elements */ public function rewind() { reset($this->elements); } /** * return value of current array pointer position * @return Object value of current array pointer position */ public function current() { return current($this->elements); } /** * return key of current array pointer position * @return string key of current position */ public function key() { return key($this->elements); } /** * move to next array pointer position and return next var * @return Object next pointer position value */ public function next() { return next($this->elements); } /** * check is current position is legal array pointer position * @return boolean returns true if its valid */ public function valid() { //current key is NOT null return !(is_null(key($this->elements))); } } ficus/collection/TypedMap.php100644 1751 144 6000 10645132217 11752 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: TypedMap.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/lang/ClassLoader.php"); require_once("ficus/lang/Assert.php"); require_once("ficus/collection/SimpleMap.php"); require_once("ficus/exception/ClassNotFoundException.php"); require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/exception/TypeMismatchException.php"); /** * @class Ficus_TypedMap */ class Ficus_TypedMap extends Ficus_SimpleMap{ /** * @var $elements array elements */ protected $elements = array(); /** * @var $type string Type */ protected $type = null; /** * constructor * @param $type String Type to check * @param $keys Array key array of elements * @param $elements Array elements to add this map * @throw Ficus_IllegalArgumentException illegal argument. */ public function __construct($type, $keys = array(), $elements = array()){ if(class_exists($type) == false && interface_exists($type) == false){ try{ Ficus_ClassLoader::import($type); }catch(Ficus_ClassNotFoundException $e){ throw new Ficus_IllegalArgumentException("passed type is not valid type $type"); } } $this->type = $type; parent::__construct($keys, $elements); } /** * add element to Collection * @param $key key of element to add * @param $element Element to add the Map * @return value returns old value if the key found in Map * @throw Ficus_IllegalArgumentException illegal argument. */ public function put($key, $element){ try{ Ficus_Assert::isInstanceOf($element, $this->type); }catch(Ficus_TypeMismatchException $e){ throw new Ficus_IllegalArgumentException("passed element is not instance of {$this->type}, it is" . get_class($element) . "."); } return parent::put($key, $element); } /** * return type of this Map * @return string type of this Map */ public function type(){ return $this->type; } } ficus/collection/Map.php100644 1751 144 4567 10645132217 10764 ISHITOYA Kentaro * @version $Id: Map.php 2 2007-07-11 10:37:48Z ishitoya $ * * This interface implementation is ported from Java Map interface * http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/java/ficus/Map.html */ /** * @interface Ficus_Map */ interface Ficus_Map extends Iterator{ /** * add element to Collection * @param $key string key of this element * @param $element Element to add the Map * @return element returns old value if the key had found in the Map */ public function put($key, $element); /** * clear all elements in the Map. */ public function clear(); /** * remove element from the Map * @param $key string element to remove * @return element returns old value if key exists */ public function remove($key); /** * get element from the Map * @param $key string element to get * @return element */ public function get($key); /** * get size of the Map * @return integer size of this Map */ public function size(); /** * to array * @return Array array presentation of Map */ public function toArray(); /** * returns true if Map is empty * @return boolean true if the Map is empty */ public function isEmpty(); /** * returns key array from the Map * @return Array array of the keys of Map */ public function keys(); /** * return value array from the Map * @return Array array of the values of Map */ public function values(); } ficus/collection/MBStringIterator.php100644 1751 144 4453 10645132217 13440 SUMI Masafumi * @version $Id: MBStringIterator.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once('ficus/lang/Unicode.php'); /** * @class Ficus_MBStringIterator */ class Ficus_MBStringIterator implements Iterator { /** * @var string. */ protected $string; /** * @var position. */ protected $position; /** * @var encoding. */ protected $encoding; /** * Constructor. * * @param $string string. * @param $encoding encoding. */ public function __construct($string, $encoding = Ficus_Unicode::UTF8) { $this->string = $string; $this->encoding = $encoding; } /** * Return the current char. * * @return string current char. */ public function current() { return mb_substr($this->string, $this->position, 1, $this->encoding); } /** * Return the key of the current char. * * @return int current char position. */ public function key() { return $this->position; } /** * Move forward to next char. */ public function next() { $this->position++; } /** * Rewind the Iterator to the first char. */ public function rewind() { $this->position = 0; } /** * Check if there is a current char after calls to rewind() or next(). */ public function valid() { return $this->position < mb_strlen($this->string, $this->encoding); } } ?> ficus/collection/Collection.php100644 1751 144 4724 10645132217 12335 ISHITOYA Kentaro * @version $Id: Collection.php 2 2007-07-11 10:37:48Z ishitoya $ * * This interface implementation is ported from Java Collection interface * http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/java/ficus/Collection.html */ /** * @interface Ficus_Collection */ interface Ficus_Collection { /** * add element to Collection * @param $element Element to add * @return boolean returns true if collection had modified by insertion */ public function add($element); /** * add All elements in parameter * @param $elements Array Array of elements to add collection * @return boolean returns true if collection had modified by insertion */ public function addAll($elements); /** * clear all elements in the collection. */ public function clear(); /** * remove element from the collection * @param $element element to remove * @return boolean returns true if collection had modified by operation */ public function remove($element); /** * remove element from the collection * @param $element element to remove * @return boolean returns true if collection had modified by operation */ public function removeAll($element); /** * get size of the collection * @return integer size of this collection */ public function size(); /** * to array * @return Array array presentation of collection */ public function toArray(); /** * returns true if collection is empty * @return boolean true if the collection is empty */ public function isEmpty(); } ficus/beans/BeanComponentFactory.php100644 1751 144 6562 10645132217 13261 SUMI Masafumi * @version $Id: BeanComponentFactory.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once "ficus/lang/AutoLoad.php"; require_once "ficus/lang/S2ContainerAutoLoad.php"; require_once "ficus/lang/ClassLoaderAutoLoad.php"; require_once "ficus/lang/ClassPath.php"; require_once "ficus/test/PathInitializer.php"; /** * @class Ficus_BeanComponentFactory */ class Ficus_BeanComponentFactory { const CONTEXT_BUILD = "mock"; const CONTEXT_DEPLOY = "deploy"; /** * @var $context string context */ private static $context = Ficus_BeanComponentFactory::CONTEXT_DEPLOY; /** * @var $cache array cache */ private static $cache = array(); /** * @var S2Container container. */ private $container = null; /** * @var Soya_ComponentFactory self. */ private static $factory = null; /** * Constructor. */ private function __construct() { $confDir = Ficus_ClassPath::get(Ficus_PathInitializer::CONF_PATH); $confDir = $confDir->paths(); $confDir = $confDir[0]; if(defined('SOYA_DICON_PATH') == false){ define(SOYA_DICON_PATH, $confDir); } if(self::$context === self::CONTEXT_DEPLOY){ $diconPath = $confDir . "soya.dicon"; }else if(self::$context === self::CONTEXT_BUILD){ $diconPath = $confDir . "mock.dicon"; } $this->container = S2ContainerFactory::create($diconPath); } /** * set context and reset factory * * @param $context string build or deploy */ public static function setContext($context){ if(self::$context !== $context){ self::$context = $context; self::$factory = null; } } /** * Get factory. * * @param $context string context * @return S2Container container. */ public static function getContainer($context = null) { if (self::$factory === null || ($context !== null) && self::$context !== $context) { Ficus_AutoLoad::add(new Ficus_S2ContainerAutoLoad()); Ficus_AutoLoad::add(new Ficus_ClassLoaderAutoLoad()); self::$factory = new Ficus_BeanComponentFactory(); } return self::$factory->container; } /** * Get component. * * @param $name string component name. * @return mixed component. */ public static function getComponent($name) { $container = self::getContainer(); return $container->getComponent($name); } } ?> ficus/beans/serializer/BeanDeserializer.php100644 1751 144 2317 10645132217 14554 ISHITOYA Kentaro * @version $Id: BeanDeserializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ /** * @interface Ficus_BeanDeserializer */ interface Ficus_BeanDeserializer{ /** * unserialize bean * @param $bean Ficus_Bean target bean * @param $data array array to deserialize * @return Ficus_Bean bean */ public function deserialize($bean, $data); } ?> ficus/beans/serializer/PHPBeanSerializer.php100644 1751 144 4271 10645132217 14614 ISHITOYA Kentaro * @version $Id: PHPBeanSerializer.php 2 2007-07-11 10:37:48Z ishitoya $ * * generates php bean source codes. * Templates and tokens are defined in abstract class. */ require_once "ficus/beans/serializer/BeanSerializer.php"; require_once "ficus/beans/BeanTemplate.php"; /** * @package ficus.beans.serializer * @class Ficus_PHPBeanTypeSerializer */ class Ficus_PHPBeanSerializer implements Ficus_BeanSerializer{ /** default source code template file name*/ const DEFAULT_TEMPLATE = "bean_php.tpl"; /** template name */ private $templateName = null; /** * set template name * @param $templateName string template name */ public function setTemplateName($templateName){ $this->templateName = $templateName; } /** * Generate Source Code From essences * @param $essence array essence of source code * @param $template_name string smarty template filename * @return string source code */ public function serialize($bean){ if(is_file($this->templateName) == false){ $this->templateName = self::DEFAULT_TEMPLATE; } $template = new Ficus_BeanTemplate(); $template->assign("bean", $bean); $source = $template->fetch($this->templateName); return $source; } } ?> ficus/beans/serializer/ArrayBeanDeserializer.php100644 1751 144 6311 10645132217 15551 ISHITOYA Kentaro * @version $Id: ArrayBeanDeserializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/beans/Bean.php"; require_once "ficus/beans/BeanManager.php"; require_once "ficus/beans/annotation/BeanAnnotationAccessor.php"; require_once "ficus/beans/serializer/BeanDeserializer.php"; require_once "ficus/exception/IllegalBeanException.php"; require_once "ficus/lang/Assert.php"; require_once "ficus/lang/reflect/ReflectionClass.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationProperty.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationClass.php"; /** * @class Ficus_ArrayBeanDeserializer */ class Ficus_ArrayBeanDeserializer implements Soya_BeanDeserializer{ /** * @var $manager Ficus_BeanManager manager */ private $manager = null; /** * serialize bean to RDF * @param $data array array to deserialize * @param $bean Ficus_Bean target bean * @return Ficus_Bean bean */ public function deserialize($bean, $data){ $this->manager = new Ficus_BeanManager(); $bean = $this->parseArray($bean, $data); return $bean; } /** * Deserialize Array to Bean * @param $bean Ficus_Bean bean to parse * @param $data Array array to parse * @return Ficus_Bean result bean * @throw Ficus_IllegalBeanException illegal bean. */ private function parseArray($bean, $data){ if($data instanceof stdClass){ $data = (array)$data; } $accessor = Ficus_BeanAnnotationAccessor::getAccessor($bean); $properties = $accessor->getPropertyAnnotations(); foreach($properties as $property){ $setter = "set" . ucfirst($property->getName()); if(array_key_exists($property->getName(), $data) == false){ continue; } $contents = $data[$property->getName()]; if($property->isArray()){ $bean->{$setter}($contents); }else if($property->isLiteral()){ $bean->{$setter}(trim($contents)); }else{ $type = $property->getType(); $propBean = $this->manager->search($type); $propBean = $this->parseArray($propBean, $contents); $bean->{$setter}($propBean); } } return $bean; } } ?> ficus/beans/serializer/BeanSerializer.php100644 1751 144 2222 10645132217 14236 ISHITOYA Kentaro * @version $Id: BeanSerializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ /** * @interface Ficus_BeanSerializer */ interface Ficus_BeanSerializer{ /** * serialize bean * @param $bean Ficus_Bean target bean * @return string serialized data */ public function serialize($bean); } ?> ficus/beans/serializer/ErrorBeanDeserializer.php100644 1751 144 5553 10645132217 15573 ISHITOYA Kentaro * @version $Id: ErrorBeanDeserializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/beans/Bean.php"; require_once "ficus/beans/BeanManager.php"; require_once "ficus/beans/annotation/BeanAnnotationAccessor.php"; require_once "ficus/beans/serializer/BeanDeserializer.php"; require_once "ficus/exception/IllegalBeanException.php"; require_once "ficus/lang/Assert.php"; require_once "ficus/lang/reflect/ReflectionClass.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationProperty.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationClass.php"; /** * @class Ficus_ErrorBeanDeserializer */ class Ficus_ErrorBeanDeserializer implements Soya_BeanDeserializer{ /** * @var $manager Ficus_BeanManager manager */ private $manager = null; /** * serialize bean to RDF * @param $data array array to deserialize * @param $bean Ficus_ErrorBean target bean * @return Ficus_Bean bean */ public function deserialize($bean, $data){ Ficus_Assert::isInstanceOf( $bean, "Ficus_Beans_cc_guarana_soya_system_ErrorBean"); Ficus_Assert::isInstanceOf($data, "Exception"); $this->manager = new Ficus_BeanManager(); $bean = $this->parseError($bean, $data); return $bean; } /** * Deserialize Exception * @param $bean Ficus_ErrorBean bean to parse * @param $data Exception to parse * @return Ficus_ErrorBean result bean * @throw Ficus_IllegalBeanException illegal bean. */ private function parseError($bean, $data){ $bean->setType(get_class($data)); $bean->setMessage($data->getMessage()); $bean->setTrace($data->getTraceAsString()); $bean->setFile($data->getFile()); $bean->setLine($data->getLine()); if($data->getCause() != null){ $cause = $bean->getCauseBean(); $bean->setCause($this->parseError($cause, $data->getCause())); } return $bean; } } ?> ficus/beans/serializer/JSONBeanSerializer.php100644 1751 144 3422 10645132217 14733 ISHITOYA Kentaro * @version $Id: JSONBeanSerializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/beans/serializer/BeanSerializer.php"; /** * @package core.beans.serializer * @class Soya_JSONBeanSerializer */ class Soya_JSONBeanSerializer implements Soya_BeanSerializer{ /** * encoding */ private $encoding = null; /** * constructor */ public function __construct($encoding = ""){ $this->setEncoding($encoding); } /** * serialize bean to RDFSchema * @param $bean Soya_Bean bean to serialize * @return string rdf string */ public function serialize($bean){ $array = $bean->serialize("Array"); $string = json_encode($array); return $string; } /** * set encoding * @param $encoding string encoding of encoded json */ public function setEncoding($encoding){ $this->encoding = $encoding; } } ?> ficus/beans/serializer/ArrayBeanSerializer.php100644 1751 144 5217 10645132217 15244 ISHITOYA Kentaro * @version $Id: ArrayBeanSerializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/beans/serializer/BeanSerializer.php"; /** * @package ficus.beans.serializer * @class Ficus_ArrayBeanSerializer */ class Ficus_ArrayBeanSerializer implements Soya_BeanSerializer{ /** * constructor */ public function __construct(){ } /** * serialize bean to RDFSchema * @param $bean Ficus_Bean bean to serialize * @return string rdf string */ public function serialize($bean){ return $this->parseBean($bean); } /** * serialize one bean to RDFSchema * and if property value is Bean instance, call back this method. * @param $bean Ficus_Bean bean to parse * @return array generated array * @throw Ficus_MethodNotFoundException getter method not found */ private function parseBean($bean){ $result = Array(); $class = new ReflectionClass($bean); $properties = $class->getProperties(); foreach($properties as $property){ $value = $bean->{$property->getName()}(); if(empty($value)){ continue; } if(is_array($value)){ $temp = array(); foreach($value as $v){ if(empty($v)){ continue; } if($v instanceof Ficus_Bean){ $temp[] = $this->parseBean($v); }else{ $temp[] = $v; } } $value = $temp; }else if($value instanceof Ficus_Bean){ $value = $this->parseBean($value); } $result[$property->getName()] = $value; } return $result; } } ?> ficus/beans/serializer/BeanSerializerFactory.php100644 1751 144 3421 10645132217 15570 ISHITOYA Kentaro * @version $Id: BeanSerializerFactory.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/ClassLoader.php"; /** * @package ficus.beans.serializer * @class Ficus_BeanSerializerFactory */ class Ficus_BeanSerializerFactory{ const SIGNATURE = "Ficus_%sBeanSerializer"; const PACKAGE = "beans.serializer."; /** * create serializer * @param $bean Ficus_Bean bean to serialize * @return string rdf string */ public function create($type){ try{ $serializer = self::PACKAGE . $type; $instance = Ficus_ClassLoader::load($serializer); if($instance instanceof Ficus_BeanSerializer){ return $instance; } }catch(Ficus_ClassNotFoundException $e){ } $serializer = self::PACKAGE . sprintf(self::SIGNATURE, $type); return Ficus_ClassLoader::load($serializer); } } ?> ficus/beans/serializer/StringBeanSerializer.php100644 1751 144 5035 10645132217 15432 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: StringBeanSerializer.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/Assert.php"; require_once "ficus/beans/Bean.php"; require_once "ficus/beans/serializer/BeanSerializer.php"; require_once "ficus/beans/annotation/BeanAnnotationAccessor.php"; require_once "ficus/beans/BeanComponentFactory.php"; require_once "kaibashira/RDF/RDFReader.php"; require_once "kaibashira/RDF/RDFWriter.php"; /** * @package ficus.beans.serializer * @class Ficus_StringBeanSerializer */ class Ficus_StringBeanSerializer implements Soya_BeanSerializer{ /** * serialize bean to String * @param $bean Ficus_Bean bean to serialize * @return string String string */ public function serialize($bean){ $string = self::parseBean($bean); return $string; } /** * serialize one bean to RDF * and if property value is Bean instance, call back this method. * @param $bean Ficus_Bean bean to parse * @param $graph Ficus_Graph graph to add triple * @return Ficus_Bean result node */ private function parseBean($bean){ Ficus_Assert::typeHinting("Ficus_Bean", $bean); $accessor = Ficus_BeanAnnotationAccessor::getAccessor($bean); $properties = $accessor->getPropertyAnnotations(); $return = ""; foreach($properties as $property){ $value = $bean->{$property->getName()}(); if($property->isClass() && is_null($value) == false){ $return .= $this->parseBean($value); }else{ $return .= $value; } } return $return; } } ?> ficus/beans/serializer/BeanDeserializerFactory.php100644 1751 144 3730 10645132217 16104 ISHITOYA Kentaro * @version $Id: BeanDeserializerFactory.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/lang/ClassLoader.php"; /** * @package ficus.beans.serializer * @class Ficus_BeanDeserializerFactory */ class Ficus_BeanDeserializerFactory{ const SIGNATURE = "beans.serializer.Ficus_%sBeanDeserializer"; /** * create deserializer * @param $bean Ficus_Bean bean to deserialize * @return string rdf string */ public function create($data){ $type = null; if(is_array($data)){ $type = "Array"; }else if(strpos($data, " ficus/beans/annotation/BeanConstantAnnotationAccessor.php100644 1751 144 10505 10645132217 17460 ISHITOYA Kentaro * @version $Id: BeanConstantAnnotationAccessor.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/beans/Bean.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationProperty.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationClass.php"; /** * @class Ficus_BeanConstantAnnotationAccessor */ class Ficus_BeanConstantAnnotationAccessor{ const METHOD_SIGNATURE = '/^(get|has)([a-zA-Z][a-zA-Z0-9_]*)/'; /** * @var $annotations */ protected $annotations = null; /* * construct with bean * @param $annotations Ficus_ReflectionAnnotation */ protected function __construct($annotations){ $this->annotations = $annotations; } /** * get accessor * @param $bean Ficus_Bean bean to parse * @throw Ficus_IllegalBeanException illegal bean. */ public static final function getAccessor($bean){ Ficus_Assert::isInstanceOf($bean, "Ficus_Bean"); $class = new Ficus_ReflectionClass($bean); $annotations = array_merge($class->getConstants(), $class->getStaticProperties()); return new Ficus_BeanConstantAnnotationAccessor($annotations); } /** * get constant * @param $name string of constant to get * @return mixed value of constant * @throw Ficus_ConstantNotFoundException when name was not exist */ public function get($name){ if($this->has($name)){ return $this->annotations[$name]; }else{ throw new Ficus_ConstantNotFoundException("$name constant is not found"); } } /** * check for constant existans * @param $name string name of constant * @return boolean true if exists */ public function has($name){ if(isset($this->annotations[$name])){ return true; } return false; } /** * get Property with name * @return Ficus_ReflectionAnnotationProperty annotations */ public function getAnnotations(){ return $this->annotations; } /** * syntax suger * @param $name string name of function * @param $argument array of argument */ public function __call($name, $argument){ if(preg_match(self::METHOD_SIGNATURE, $name, $matches)){ $operator = $matches[1]; $constant = $this->getProperName($matches[2]); switch($operator){ case "has" : return $this->has($constant); } if(is_null($constant)){ throw new Ficus_ConstantNotFoundException("$name constant is not found"); } switch($operator){ case "get" : return $this->get($constant); } } $constant = $this->getProperName($name); if(is_null($constant)){ throw new Ficus_ConstantNotFoundException("$name constant is not found"); } return $this->get($constant); } /** * get proper name from given string * @param $name string name of constant * @return string proper name */ protected function getProperName($name){ $constant = strtolower($name[0]) . substr($name, 1); if($this->has($constant)){ return $constant; } $constant = ucfirst($name); if($this->has($constant)){ return $constant; } return null; } } ?> ficus/beans/annotation/BeanAnnotationAccessor.php100644 1751 144 11236 10645132217 15750 ISHITOYA Kentaro * @version $Id: BeanAnnotationAccessor.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/beans/Bean.php"; require_once "ficus/lang/annotation/AuthorAnnotation.php"; require_once "ficus/lang/annotation/BriefAnnotation.php"; require_once "ficus/lang/annotation/ClassAnnotation.php"; require_once "ficus/lang/annotation/CommentAnnotation.php"; require_once "ficus/lang/annotation/ClassAnnotation.php"; require_once "ficus/lang/annotation/DefinedbyAnnotation.php"; require_once "ficus/lang/annotation/PackageAnnotation.php"; require_once "ficus/lang/annotation/VarAnnotation.php"; require_once "ficus/beans/annotation/BeanPropertyAnnotationAccessor.php"; require_once "ficus/beans/annotation/BeanClassAnnotationAccessor.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationProperty.php"; require_once "ficus/lang/reflect/annotation/ReflectionAnnotationClass.php"; /** * @class Ficus_BeanAnnotationAccessor */ abstract class Ficus_BeanAnnotationAccessor{ const T_VAR = "var"; const T_DEFINEDBY = "definedby"; const T_NAME = "name"; const T_TYPE = "type"; const T_COMMENT = "comment"; const T_QNAME = "qname"; const T_BRIEF = "brief"; const T_CLASS = "class"; const T_PACKAGE = "package"; const T_AUTHOR = "author"; /** * @var $annotations */ protected $annotations = null; /* * construct with bean * @param $annotations Ficus_ReflectionAnnotation */ public function __construct($annotations){ $this->annotations = $annotations; } /** * get accessor * @param $bean Ficus_Bean bean to parse * @throw Ficus_IllegalBeanException illegal bean. */ public static final function getAccessor($bean){ Ficus_ReflectionAnnotation::setPrefixes(array('Ficus_', 'Ficus_')); Ficus_Assert::isInstanceOf($bean, "Ficus_Bean"); $refClass = new Ficus_ReflectionClass($bean); $annotations = new Ficus_ReflectionAnnotationClass($refClass); $class = new Ficus_BeanClassAnnotationAccessor($annotations); $properties = $refClass->getProperties(); $propAnnotations = array(); foreach($properties as $property){ $property = new Ficus_BeanPropertyAnnotationAccessor( new Ficus_ReflectionAnnotationProperty($property)); $class->addProperty($property); } return $class; } /** * get Property with name * @return Ficus_ReflectionAnnotationProperty annotations */ public function getAnnotations(){ return $this->annotations; } /** * get property name * @return string name of property */ public function getName(){ return $this->getAnnotation(self::T_NAME); } /** * get property type * @return string type of property */ public function getType(){ return $this->getAnnotation(self::T_TYPE); } /** * get property comment * @return string comment of property */ public function getComment(){ return $this->getAnnotation(self::T_COMMENT); } /** * get property label * @return string label of property */ public function getLabel(){ return $this->getAnnotation(self::T_BRIEF); } /* * get property qname * @return string qname of property */ public function getQName(){ return $this->getAnnotation(self::T_QNAME); } /** * get property definedby * @return string definedby of property */ public function getDefinition(){ return $this->getAnnotation(self::T_DEFINEDBY); } /** * get Annotation from name * @param $name string annotation name * @return string annotation value */ abstract protected function getAnnotation($name); } ?> ficus/beans/annotation/BeanClassAnnotationAccessor.php100644 1751 144 10650 10645132217 16735 ISHITOYA Kentaro * @version $Id: BeanClassAnnotationAccessor.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/beans/annotation/BeanAnnotationAccessor.php"; /** * @class Ficus_BeanClassAnnotationAccessor */ class Ficus_BeanClassAnnotationAccessor extends Ficus_BeanAnnotationAccessor{ /** * @var $properties */ private $properties = null; /** * construct with bean * @param $bean Ficus_Bean target bean */ public function __construct($annotations){ parent::__construct($annotations); } /** * set properties annotations * @param $property Ficus_BeanPropertyAnnotationAccessor accessor */ public function addProperty($property){ $property->setDomain($this->getQName()); $this->properties[$property->getName()] = $property; } /** * get Annotation from name * @param $name string annotation name * @return string annotation value */ protected function getAnnotation($name){ if($name == self::T_BRIEF){ $annotation = $this->annotations->getAnnotation(self::T_BRIEF); return $annotation->getBrief(); }else if($name == self::T_COMMENT){ $annotation = $this->annotations->getAnnotation(self::T_COMMENT); return $annotation->getComment(); }else if($name == self::T_NAME){ $annotation = $this->annotations->getAnnotation(self::T_CLASS); $class = $annotation->getClass(); preg_match('/[^_]+_Beans.*_([^_]+)Bean/', $class, $matches); return $matches[1]; }else if($name == self::T_TYPE){ $annotation = $this->annotations->getAnnotation(self::T_CLASS); return $annotation->getClass(); }else if($name == self::T_COMMENT){ $annotation = $this->annotations->getAnnotation(self::T_COMMENT); return $annotation->getComment(); }else if($name == self::T_BRIEF){ $annotation = $this->annotations->getAnnotation(self::T_BRIEF); return $annotation->getBrief(); }else if($name == self::T_DEFINEDBY){ $annotation = $this->annotations->getAnnotation(self::T_DEFINEDBY); return $annotation->getDefinedBy(); } } /** * type name */ public function getTypename(){ $classname = str_replace(".", "_", strtolower($this->getPackageName())); $classname = "{$classname}_" . $this->getName(); return $classname; } /** * get ClassAnnotation * @return Ficus_ReflectionAnnotationClass */ public function getClassAnnotation(){ return $this->classAnnotation; } /** * get property author * @return string author of class */ public function getAuthor(){ $annotation = $this->annotations->getAnnotation(self::T_AUTHOR); return $annotation->getAuthor(); } /** * get property author * @return string author of class */ public function getPackageName(){ $annotation = $this->annotations->getAnnotation(self::T_PACKAGE); return $annotation->getPackage(); } /** * get PropertyAnnotations * @reuturn array array of Ficus_ReflectionAnnotationProperty */ public function getPropertyAnnotations(){ return $this->properties; } /** * get Property with name * @param $name string name of property * @return Ficus_ReflectionAnnotationProperty annotations */ public function getPropertyAnnotation($name){ return $this->properties[$name]; } } ?> ficus/beans/annotation/BeanPropertyAnnotationAccessor.php100644 1751 144 6716 10645132217 17504 ISHITOYA Kentaro * @version $Id: BeanPropertyAnnotationAccessor.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once "ficus/beans/annotation/BeanAnnotationAccessor.php"; /** * @class Ficus_BeanPropertyAnnotationAccessor */ class Ficus_BeanPropertyAnnotationAccessor extends Ficus_BeanAnnotationAccessor{ /** * domain */ private $domain = null; /** * construct with bean * @param $annotations annotations */ public function __construct($annotations){ parent::__construct($annotations); } /** * set Domain */ public function setDomain($domain){ $this->domain = $domain; } /** * get Annotation from name * @param $name string annotation name * @return string annotation value */ protected function getAnnotation($name){ if($name == self::T_BRIEF){ $annotation = $this->annotations->getAnnotation(self::T_BRIEF); return $annotation->getBrief(); }else if($name == self::T_COMMENT){ $annotation = $this->annotations->getAnnotation(self::T_COMMENT); return $annotation->getComment(); }else if($name == self::T_DEFINEDBY){ $annotation = $this->annotations->getAnnotation(self::T_DEFINEDBY); return $annotation->getDefinedBy(); }else if($name == self::T_QNAME){ $domain = $this->getDomain(); return "$domain." . $this->getName(); }else{ $annotation = $this->annotations->getAnnotation(self::T_VAR); $name = "get" . ucfirst($name); return $annotation->{$name}(); } } /** * get domain * @return string domain */ public function getDomain(){ return $this->domain; } /** * get range * @return string range */ public function getRange(){ $annotation = $this->annotations->getAnnotation(self::T_VAR); return $annotation->getType(); } /** * is property is array * @return boolean is property is array */ public function isArray(){ $annotation = $this->annotations->getAnnotation(self::T_VAR); return $annotation->isArray(); } /** * is property is class * @return boolean is property is class */ public function isClass(){ $annotation = $this->annotations->getAnnotation(self::T_VAR); return $annotation->isClass(); } /** * is property is literal * @return boolean is property is literal */ public function isLiteral(){ return (!$this->isClass()); } } ?> ficus/beans/Bean.php100644 1751 144 23003 10645132217 10053 ISHITOYA Kentaro * @version $Id: Bean.php 2 2007-07-11 10:37:48Z ishitoya $ * * Abstract Bean. * __set and __get mediates $bean->setData() of $bean->getData() * on Java or other languge, you must implement * $bean->set("Data", $object) or $bean->get("Data") to mediate beans method. */ require_once "ficus/lang/Serializable.php"; require_once "ficus/net/URI.php"; require_once "ficus/exception/MethodNotFoundException.php"; require_once "ficus/exception/IllegalArgumentException.php"; require_once "ficus/exception/PropertyNotFoundException.php"; require_once "ficus/exception/NotReadyException.php"; require_once "ficus/beans/BeanComponentFactory.php"; require_once "ficus/beans/annotation/BeanAnnotationAccessor.php"; /** * @class Ficus_Bean */ abstract class Ficus_Bean implements Ficus_Serializable{ const METHOD_SIGNATURE = '/^(set|get|add|delete|shift|push|pop|insert|numOf|count|clear|has|isEmpty|is|enable|disable)([a-zA-Z][a-zA-Z0-9_]*)/'; const METHOD_SIGNATURE_SUFFIX = '/^([a-zA-Z][a-zA-Z0-9_]*?)(EqualsTo)/'; const BEAN_METHOD_SIGNATURE = '/^get([a-zA-Z][a-zA-Z0-9_]*)Bean/'; /** * serialize bean * @param $type string type of serializer * @return string serialized string */ public function serialize($type = null){ if(is_null($type)){ $reflection = new ReflectionClass($this); $props = $reflection->getDefaultProperties(); foreach($props as $key => $value){ $props[$key] = $this->$key; } return serialize($props); } if($type instanceof Ficus_BeanSerializer){ $serializer = $type; }else{ $factory = Ficus_BeanComponentFactory::getComponent("BeanSerializerFactory"); $serializer = $factory->create($type); } if(func_num_args() > 1){ $arguments = func_get_args(); array_shift($arguments); return $serializer->serialize($this, $arguments); }else{ return $serializer->serialize($this); } } public function unserialize($serialized){ $unserialized = unserialize($serialized); foreach($unserialized as $key => $value){ $this->$key = $value; } } /** * deserialize bean * @param $type string type of deserializer */ public function deserialize($data, $deserializer=null){ if(($deserializer instanceof Ficus_BeanDeserializer) == false){ $factory = Ficus_BeanComponentFactory::getComponent( "BeanDeserializerFactory"); $deserializer = $factory->create($data); } return $deserializer->deserialize($this, $data); } /** * create clone * @return Ficus_Bean cloned object */ public function createClone(){ $clone = clone $this; return $clone; } /** * set value to specified property * @param $name string property name * @param $value mixed value to set */ public function set($name, $value){ if($this->has($name) == false){ throw new Ficus_PropertyNotFoundException("property $name is not found"); } $this->{$name} = $value; } /** * get value * @return mixed value */ public function get($name, $index = null){ if($this->has($name) == false){ throw new Ficus_PropertyNotFoundException("property $name is not found"); } $method = "get" . ucfirst($name); if(method_exists($this, $method)){ return $this->{$method}(); } if(is_null($index)){ return $this->{$name}; }else{ return $this->{$name}[$index]; } } /** * has property * @param $name string property name * @return boolean true if property exists */ public function has($name){ return property_exists($this, $name); } /** * other functions */ public function __call($name, $arguments){ return $this->__onCall($name, $arguments); } /** * handle call */ protected function __onCall($name, $arguments){ $class = new ReflectionClass($this); if($class->hasProperty($name)){ $property = $class->getProperty($name); if($property->isStatic()){ $values = $class->getStaticProperties(); $value = $values[$name]; }else{ $value = $this->{$name}; } if(isset($arguments[0])){ return $value[$arguments[0]]; }else{ return $value; } } if(preg_match(self::METHOD_SIGNATURE, $name, $matches)){ $operator = $matches[1]; $property = strtolower($matches[2][0]) . substr($matches[2], 1); switch($operator){ case "has" : return $this->has($property); } if($this->has($property)){ switch($operator){ case "set" : $this->{$property} = $arguments[0]; return; case "get" : if(isset($arguments[0])){ if(is_null($arguments[0])){ return null; } if(isset($this->{$property}[$arguments[0]])){ return $this->{$property}[$arguments[0]]; }else{ return null; } } return $this->{$property}; case "add" : case "push" : return array_push($this->{$property}, $arguments[0]); case "shift" : return array_shift($this->{$property}); case "pop" : return array_pop($this->{$property}); case "delete" : if(isset($arguments[0])){ if((is_numeric($arguments[0]) || is_string($arguments[0])) && isset($this->{$property}[$arguments[0]])){ $temp = $this->{$property}[$arguments[0]]; unset($this->{$property}[$arguments[0]]); return $temp; }else{ foreach($this->{$property} as $key => $item){ if($item == $arguments[0]){ unset($this->{$property}[$key]); return $item; } } return; } } break; case "insert" : if(isset($arguments[0])){ $this->{$property}[$arguments[0]] = $arguments[1]; return; } break; case "numOf" : case "count" : return count($this->{$property}); case "clear" : if(is_array($this->{$property})){ $this->{$property} = array(); }else{ $this->{$property} = null; } return; case "isEmpty" : return empty($this->{$property}); case "is" : return (boolean)$this->{$property}; case "enable" : $this->{$property} = true; return; case "disable" : $this->{$property} = false; return; } } } if(preg_match(self::METHOD_SIGNATURE_SUFFIX, $name, $matches)){ $operator = $matches[2]; $property = strtolower($matches[1][0]) . substr($matches[1], 1); if($this->has($property)){ switch($operator){ case "EqualsTo" : return Ficus_Types::equalsByToString($arguments[0], $this->{$property}); } } } if(method_exists($this, $name)){ call_user_func_array(array($this, $name), $arguments); }else if(isset($property) && $this->has($property) == false){ throw new Ficus_PropertyNotFoundException("property $property is not found."); }else{ throw new Ficus_MethodNotFoundException("method $name is not found."); } } } ficus/media/audio/AudioBean.php100644 1751 144 2726 10647426442 12126 ISHITOYA Kentaro * @version $Id: AudioBean.php 15 2007-07-18 15:02:48Z ishitoya $ * * Page component factory */ require_once("ficus/beans/Bean.php"); require_once("ficus/media/audio/AudioConstants.php"); /** * @class Ficus_AudioBean */ class Ficus_AudioBean extends Ficus_Bean implements Ficus_AudioConstants{ /** * length */ protected $length; /** * filename */ protected $filename; /** * bitrate */ protected $bitrate; /** * frequency */ protected $frequency; /** * codec */ protected $codec; /** * method */ protected $method; } ?> ficus/media/audio/AudioConstants.php100644 1751 144 2014 10647426442 13223 ISITOYA Kentaro * @version $Id: AudioConstants.php 15 2007-07-18 15:02:48Z ishitoya $ * * subversion constants */ /** * @interface Ficus_AudioConstants */ interface Ficus_AudioConstants { } ?> ficus/media/image/ImageConstants.php100644 1751 144 2053 10647426442 13170 ISITOYA Kentaro * @version $Id: ImageConstants.php 15 2007-07-18 15:02:48Z ishitoya $ * * subversion constants */ /** * @interface Ficus_AudioConstants */ interface Ficus_ImageConstants { const FORMAT_JPEG = "jpg"; } ?> ficus/media/video/VideoConstants.php100644 1751 144 2053 10647426442 13240 ISITOYA Kentaro * @version $Id: VideoConstants.php 15 2007-07-18 15:02:48Z ishitoya $ * * subversion constants */ /** * @interface Ficus_VideoConstants */ interface Ficus_VideoConstants { const CODEC_FLASH = "flv"; } ?> ficus/media/video/VideoBean.php100644 1751 144 3066 10647426442 12136 ISHITOYA Kentaro * @version $Id: VideoBean.php 15 2007-07-18 15:02:48Z ishitoya $ * * Page component factory */ require_once("ficus/beans/Bean.php"); require_once("ficus/media/video/VideoConstants.php"); /** * @class Ficus_VideoBean */ class Ficus_VideoBean extends Ficus_Bean implements Ficus_VideoConstants{ /** * length */ protected $length; /** * filename */ protected $filename; /** * bitrate */ protected $bitrate; /** * fps */ protected $fps; /** * height */ protected $height; /** * width */ protected $width; /** * codec */ protected $codec; /** * color */ protected $color; } ?> ficus/pages/PageController.php100644 1751 144 11111 10646126776 12150 ISHITOYA Kentaro * @version $Id: PageController.php 7 2007-07-14 10:55:18Z ishitoya $ */ require_once("smarty/Smarty.class.php"); require_once("ficus/pages/PageModeExtractor.php"); require_once("ficus/lang/ClassLoader.php"); require_once("ficus/exception/ClassNotFoundException.php"); require_once("ficus/exception/PageNotFoundException.php"); require_once("ficus/lang/Class.php"); require_once("ficus/lang/String.php"); require_once("ficus/pages/PageComponentFactory.php"); require_once("ficus/pages/PageConstants.php"); /** * @class Ficus_PageController */ class Ficus_PageController implements Ficus_PageConstants{ /** * cache dir */ protected $cacheDir = null; /** * base dir */ protected $baseDir = null; /** * pages */ protected $pages = array(); /** * mode extractor */ protected $extractor = null; /** * constructor */ public function __construct(){ $templates = Ficus_Dir::normalize(Ficus_File::currentDir() . "/templates"); Ficus_PageComponentFactory::getSmarty()->addPath(self::TEMPLATE_NAME, $templates); } /** * set base dir */ public function setBaseDir($base){ $this->baseDir = Ficus_Dir::normalize($base); $template = $this->baseDir . "/" . self::TEMPLATES_DIR; $smarty = Ficus_PageComponentFactory::getSmarty(); $smarty->addUserPath(self::TEMPLATE_NAME, $template); $smarty->setTemplateDir($template); } /** * call method * @param $name string name of page * @param $mode string name of mode * @param $buffering boolean buffering * @return mixed return value of method */ public function execute($name = null, $mode = null, $buffering = false){ $request = new Ficus_PageRequest(func_get_args()); if(is_null($name)){ $name = Ficus_PageComponentFactory::getPageLoader()->dispatch($request); } if($this->isPageExists($name) == false){ $this->addPage($name); } if(is_null($mode)){ $mode = $this->getMode($name); } $page = $this->pages[$name]["page"]; if($page->authorization() == self::FORWARDED){ return; } if($buffering == true){ try{ Ficus_Assert::isInstanceOf($page, "Ficus_BufferedPage"); }catch(Ficus_TypeMismatchException $e){ throw new Ficus_IllegalArgumentException("out buffering is on, but page has not ability to buffer."); } $page->enableOutputBuffering(); }else{ if($page instanceof Ficus_BufferedPage){ $page->disableOutputBuffering(); } } return call_user_func(array($page, $mode), $request); } /** * get mode from extractor * @param $name String name of page * @return String of mode name */ protected function getMode($name){ $mode = $this->pages[$name]["extractor"]->getMode(); return $mode; } /** * add a page to pages array * @param $name String name of page */ protected function addPage($name){ $page = Ficus_PageComponentFactory::getPageLoader()->load($name); $extractor = new Ficus_PageModeExtractor($page); $extractor->setDefaultMode($page->getDefaultMode()); $this->pages[$name]["page"] = $page; $this->pages[$name]["extractor"] = $extractor; } /** * checks page exist in pages array * @param $name String name of page * @return boolean return true if page exists */ protected function isPageExists($name){ return array_key_exists($name, $this->pages); } } ?>ficus/pages/AbstractInlinePage.php100644 1751 144 3656 10645132217 12710 ISHITOYA Kentaro * @version $Id: AbstractInlinePage.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/pages/InlinePage.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_AbstractInlinePage */ abstract class Ficus_AbstractInlinePage extends Ficus_InlinePage{ /** * constructor */ protected function onConstruct(){ } /** * on called * @param $mode string name of mode * @param $args array of args of do method */ protected function onDo($mode, $args){ } /** * on done * @param $mode string name of mode * @param $args array of args of do method */ protected function onDone($mode, $args){ $this->display(); } /** * on exception * @param $mode string name of mode * @param $args array of args of do method * @param $exception Exception exception */ protected function onException($mode, $args, $exception){ $this->display(self::PAGE_EXCEPTION_TEMPLATE); } /** * show default */ public function doDefault(){ } } ?>ficus/pages/AbstractPage.php100644 1751 144 4321 10645132217 11537 ISHITOYA Kentaro * @version $Id: AbstractPage.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/pages/Page.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_AbstractPage */ abstract class Ficus_AbstractPage extends Ficus_Page{ /** * constructor */ protected function onConstruct(){ } /** * get default mode * @return string default mode name */ public function getDefaultMode(){ return self::PAGE_DEFAULT_MODE; } /** * on called * @param $mode string name of mode * @param $args array of args of do method */ protected function onDo($mode, $args){ $this->setNextAction(self::PAGE_DEFAULT_MODE); } /** * on exception * @param $mode string name of mode * @param $args array of args of do method * @param $exception Exception exception */ protected function onException($mode, $args, $exception){ $template = Ficus_Registry::search(self::REGISTRY_EXCEPTION_TEMPLATE); if($template){ $this->display($template); }else{ $this->display(self::DEFAULT_EXCEPTION_TEMPLATE); } } /** * on authorization */ protected function onAuthorization(){ return self::AUTHORIZATION_NOT_REQUIRED; } /** * show default */ public function doDefault(){ } } ?>ficus/pages/beans/PageVisitBean.php100644 1751 144 4702 10645132217 12753 ISHITOYA Kentaro * @version $Id: PageVisitBean.php 2 2007-07-11 10:37:48Z ishitoya $ * * Page component factory */ require_once("ficus/beans/Bean.php"); /** * @class Ficus_PageVisitBean */ class Ficus_PageVisitBean extends Ficus_Bean implements S2AnA_AuthenticationContext, Ficus_PageConstants{ /** * environments */ protected $request; /** * user name */ protected $user; /** * password */ protected $password; /** * constructor */ public function __construct(){ $this->getUserPrincipal(); } /** * is guest * @return boolean true if guest */ public function isGuest(){ return ($this->user === self::USER_GUEST); } /** * is logined * @return boolean true if logined */ public function isLogined(){ return ($this->isGuest() === false); } /** * user authentication */ public function getUserPrincipal(){ $this->request = $_REQUEST; if(isset($_SERVER[self::KEY_USER])){ $this->user = $_SERVER[self::KEY_USER]; $this->password = $_SERVER[self::KEY_PASSWORD]; }else{ session_start(); if(isset($_SESSION[self::KEY_USER])){ $this->user = $_SESSION[self::KEY_USER]; }else{ $this->user = self::USER_GUEST; } } } /** * is authenticated */ public function isAuthenticated(){ return $this->isLogined(); } /** * is user in role */ public function isUserInRole($roleName){ return true; } } ?> ficus/pages/beans/PageEnvironmentsBean.php100644 1751 144 2471 10645132217 14345 ISHITOYA Kentaro * @version $Id: PageEnvironmentsBean.php 2 2007-07-11 10:37:48Z ishitoya $ * * Page component factory */ require_once("ficus/beans/Bean.php"); /** * @class Ficus_PageEnvironmentsBean */ class Ficus_PageEnvironmentsBean extends Ficus_Bean implements Ficus_PageConstants{ /** * environments */ protected $values; /** * constructor */ public function __construct(){ $this->values = array_merge($_SERVER, $_ENV); } } ?> ficus/pages/scaffold/util/ScaffoldTemplateParser.php100644 1751 144 7141 10645132217 16332 ISHITOYA Kentaro * @version $Id: ScaffoldTemplateParser.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_ScaffoldTemplateParser */ class Ficus_ScaffoldTemplateParser implements Ficus_S2DaoModelConstants{ public static function getTemplate($part){ Ficus_Assert::isInstanceOf($part, "Ficus_ScaffoldPart"); if($part->value() instanceof Ficus_S2DaoEntity){ $entityName = $part->value()->getEntityName(); $settings = Ficus_Registry::search("tableSettings"); if(isset($settings[$entityName]) && isset($settings[$entityName]["view"])){ return $settings[$entityName]["view"]; } } return false; } public static function parse($template, $part, $recursive = true){ Ficus_Assert::isInstanceOf($part, "Ficus_ScaffoldPart"); preg_match_all('/[{][$](.+?)[}]/', $template, $regs); $ret = $template; foreach($regs[1] as $property){ $name = explode(".", $property); $value = self::getValue($name, $part, $recursive); if(is_null($value) == false){ $ret = str_replace("{\$$property}", $value, $ret); } } if($ret == $template){ return ""; }else{ return $ret; } } protected static function getValue($name, $part, $recursive){ $prop = array_shift($name); if($part instanceof Ficus_ScaffoldPart){ $part = $part->getParts($prop); if($part instanceof Ficus_ScaffoldPart){ if($part->type() == self::TYPE_LIST){ $key = $part->value()->name(); if(is_null($key) == false){ return $part->value()->names($part->value()->name()); } $key = $part->value()->name(); $names = $part->value()->names(); $i = 0; foreach($names as $name){ if($i == $key){ return $name; } $i++; } return null; }else if(empty($name) == false){ return self::getValue($name, $part, $recursive); } } $value = $part->value(); if($recursive == true&& $value instanceof Ficus_S2DaoEntity){ $template = self::getTemplate($value); if(is_null($template) == false){ return self::parse($template, $value, $recursive); } } return $value; } return null; } } ?>ficus/pages/scaffold/util/ScaffoldMediator.php100644 1751 144 12077 10647425604 15201 ISHITOYA Kentaro * @version $Id: ScaffoldMediator.php 14 2007-07-18 14:55:12Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_ScaffoldMediator */ class Ficus_ScaffoldMediator implements Ficus_ScaffoldConstants{ /** * target entity */ protected $target = null; /** * configuration */ protected $configuration = null; /** * s2daoManager */ protected $daoManager = null; /** * entity */ protected $entity = null; /** * request */ protected $request = null; /** * organizer factory */ protected $organizerFactory = null; /** * smarty */ protected $smarty = null; /** * form bean */ protected $form = null; /** * construct * @param $target string target entity name */ public function __construct(){ $settings = Ficus_Registry::search(self::REGISTRY_SETTINGS); $this->configuration = new Ficus_ScaffoldConfiguration($settings); $this->daoManager = new Ficus_S2DaoManager(); $this->request = new Ficus_PageRequest(); $this->organizerFactory = new Ficus_ScaffoldOrganizerFactory($this); $this->smarty = Ficus_ScaffoldComponentFactory::getSmarty(); $templates = Ficus_Dir::normalize(Ficus_File::currentDir() . "/../templates"); $this->smarty->addPath(self::SCAFFOLD_TEMPLATES, $templates); if(Ficus_Registry::search(self::REGISTRY_SCAFFOLD_TEMPLATES)){ $dir = Ficus_Registry::search(self::REGISTRY_SCAFFOLD_TEMPLATES); $templates = Ficus_ClassPath::search($dir); if(empty($templates)){ throw new Ficus_IllegalArgumentException("directory $dir is not found in class path"); } $templates = $templates[0]; $this->smarty->addUserPath(self::SCAFFOLD_TEMPLATES, $templates); } } /** * set target * @param $target string target */ public function setTarget($target){ $this->target = $target; $this->daoManager->setTarget($target); } /** * set entity */ public function setEntity($entity){ $this->entity = $entity; } /** * set form bean */ public function setFormBean($bean){ $this->form = $bean; } /** * get form bean */ public function formBean(){ return $this->form; } /** * set request */ public function setRequest($request){ $this->request = $request; } /** * get request */ public function request(){ return $this->request; } /** * get entity */ public function entity(){ return $this->entity; } /** * get smarty */ public function smarty(){ return $this->smarty; } /** * configuration * @return Ficus_ScaffoldConfiguration */ public function configuration(){ $this->isInitialized(); return $this->configuration; } /** * organizer factory */ public function organizerFactory(){ return $this->organizerFactory; } /** * table */ public function table($name = null){ if(is_null($name)){ $name = $this->target; } return $this->configuration->table($name); } /** * dao managert * @return Ficus_S2DaoManager */ public function daoManager(){ $this->isInitialized(); return $this->daoManager; } /** * get Container */ public function getContainer($entity){ $builder = new Ficus_ConcreteScaffoldBuilder($this); return $builder->build($entity); } /** * deserializeEntity */ public function getEntityFromRequest(){ return $this->daoManager->deserializeEntity( $this->request->requests()); } /** * check is initialized */ protected final function isInitialized(){ if(is_null($this->target)){ throw new Ficus_NotReadyException("target must be initialized before runch any public functions"); } return; } } ?>ficus/pages/scaffold/util/TableManagerProxy.php100644 1751 144 4751 10645132217 15330 ISHITOYA Kentaro * @version $Id: TableManagerProxy.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/beans/Bean.php"); require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_TableManagerProxy */ class Ficus_TableManagerProxy extends Ficus_Bean{ /** * @var entity entity */ protected $entity; /** * get form. * @param $table string target table name * @return string form html */ public function getForm($table, $mode){ $controller = Ficus_PageComponentFactory::getPageController(); if($this->isEmptyEntity() == false){ $form = $controller->execute("common.TableManager", $mode, true, array("table" => $table), array("inline" => "inline"), array("entity" => $entity)); }else{ $form = $controller->execute("common.TableManager", $mode, true, array("table" => $table), array("inline" => "inline")); } return $form; } /** * change Action and Mode * @param $form string form * @param $nextAction string next action * @return string normalized form */ public function normalizeForm($form, $pagename, $nextAction){ $form = preg_replace('/action=".*?"/', "action=\"?$pagename\"", $form); $form = preg_replace('/type="submit" name=".*?"/', "type=\"submit\" name=\"$nextAction\"", $form); return $form; } } ?> ficus/pages/scaffold/ScaffoldManager.php100644 1751 144 17372 10647426442 14036 ISHITOYA Kentaro * @version $Id: ScaffoldManager.php 15 2007-07-18 15:02:48Z ishitoya $ */ require_once("ficus/config/Registry.php"); /** * @class Ficus_ScaffoldManager */ class Ficus_ScaffoldManager extends Ficus_Bean implements Ficus_ScaffoldConstants{ /** * foreperson */ protected $foreperson = null; /** * target */ protected $target = null; /** * page */ protected $page = null; /** * action */ protected $action = null; /** * mediator */ protected $mediator = null; /** * fuzzy */ protected $fuzzy = false; /** * construct */ public function __construct($page){ $this->mediator = new Ficus_ScaffoldMediator(); $this->guess($page); } /** * is guess able * @return boolean true if guessable */ public function isGuessable(){ if($this->page instanceof Ficus_ScaffoldPage && $this->page->isEmptyTarget() == false){ return true; } return $this->page->request()->has(self::KEY_TARGET); } /** * guess action * @param $args array of request */ public function guess($page){ $this->setPage($page); $request = $page->request(); $form = new Ficus_ScaffoldFormBean(); $form->setAction($page->nextAction()); $form->setPage($page->pagename()); $this->setFormFromRequest($form, "target", self::KEY_TARGET); $this->setFormFromRequest($form, "do", self::KEY_DO); $this->setFormFromRequest($form, "method", self::KEY_METHOD); $this->setFormFromRequest($form, "message", self::KEY_MESSAGE); $this->setFormFromRequest($form, "transition", self::KEY_TRANSITION); $this->setFormFromRequest($form, "submitTitle", self::KEY_SUBMIT_TITLE); $this->setFormBean($form); if($this->isGuessable()){ if($page instanceof Ficus_ScaffoldPage){ $target = $page->target(); $foreperson = $page->foreperson(); }else{ $target = $request->extractAsString(self::KEY_TARGET); $foreperson = $request->extractAsString(self::KEY_FOREPERSON); } $this->setTarget($target); $this->setAction($foreperson); } } /** * set bean data from request */ private function setFormFromRequest($form, $property, $key){ $value = $this->page->request()->extractAsString($key); if(is_null($value) == false){ $form->set($property, $value); } } /** * set request */ public function setPage($page){ $this->page = $page; } /** * set Target * @param $target string target */ public function setTarget($target){ $this->initialize($target); $this->formBean()->setTarget($target); } /** * set Action */ public function setAction($action){ $this->isInitialized(); $this->action = $action; $this->foreperson = $this->createForeperson($this->action); $this->formBean()->setForeperson($action); } /** * set form bean */ public function setFormBean($bean){ $this->mediator->setFormBean($bean); } /** * get form bean */ public function formBean(){ return $this->mediator->formBean(); } /** * mediator */ public function mediator(){ return $this->mediator; } /** * organize a scaffold */ public function organize(){ $this->isInitialized(); if(is_null($this->action)){ throw new Ficus_NotReadyException("action is empty, you must run guess or setAction before runch organize method"); } $scaffold = $this->foreperson->organize(); $smarty = Ficus_ScaffoldComponentFactory::getSmarty(); $form = $this->mediator->formBean(); if(is_null($form) == false){ $smarty->assign(self::KEY_PAGE, $form->page()); $smarty->assign(self::KEY_METHOD, $form->method()); $smarty->assign(self::KEY_ACTION, $form->action()); $smarty->assign(self::KEY_TARGET, $form->target()); $smarty->assign(self::KEY_DO, $form->do()); $smarty->assign(self::KEY_MESSAGE, $form->message()); $smarty->assign(self::KEY_TRANSITION, $form->transition()); $smarty->assign(self::KEY_FOREPERSON, $form->foreperson()); $smarty->assign(self::KEY_SUBMIT_TITLE, $form->submitTitle()); } $smarty->assign(self::KEY_SCAFFOLD, $scaffold); $scaffold = $smarty->fetch($this->template($this->action)); if($this->fuzzy){ $header = $smarty->fetch(self::TEMPLATE_HEADER); $footer = $smarty->fetch(self::TEMPLATE_FOOTER); $scaffold = $header . $scaffold . $footer; } return $scaffold; } /** * set entity */ public function setEntity($entity){ $this->mediator->setEntity($entity); } /** * get deserialized entity */ public function getEntityFromRequest(){ return $this->mediator->getEntityFromRequest(); } /** * fuzzy */ public function setFuzzy($fuzzy){ $this->fuzzy = $fuzzy; } /** * is initialized */ protected final function isInitialized(){ if(is_null($this->target)){ throw new Ficus_NotReadyException("target is empty, you must run setTarget or guess before runch any public functions"); } } /** * get template */ protected function template($action){ return "Scaffold" . ucfirst($action); } /** * initialize */ protected function initialize($target){ $this->target = $target; $this->mediator->setTarget($this->target); $this->mediator->setRequest($this->page->request()); } /** * create foreperson * @param $action string action * @param $mediator Ficus_ScaffoldMediator mediator * @return UTil_ScaffoldForeperson */ protected function createForeperson($action){ switch($action){ case(self::ACTION_VIEW): return new Ficus_ViewScaffoldForeperson($this->mediator); case(self::ACTION_LIST): return new Ficus_ListScaffoldForeperson($this->mediator); case(self::ACTION_EDIT): return new Ficus_EditScaffoldForeperson($this->mediator); case(self::ACTION_NEW): return new Ficus_NewScaffoldForeperson($this->mediator); case(self::ACTION_DELETE): return new Ficus_DeleteScaffoldForeperson($this->mediator); default: throw new Ficus_NotSupportedException("scaffold foreperson $action is not available"); } } } ?> ficus/pages/scaffold/ScaffoldConstants.php100644 1751 144 5544 10647426442 14416 ISHITOYA Kentaro * @version $Id: ScaffoldConstants.php 15 2007-07-18 15:02:48Z ishitoya $ */ require_once("ficus/config/Registry.php"); /** * @interface ScaffoldConstants */ interface Ficus_ScaffoldConstants{ const REGISTRY_SETTINGS = "scaffoldSettings"; const REGISTRY_TABLESETTINGS = "tableSettings"; const REGISTRY_SMARTYCACHE = "smarty.cache"; const REGISTRY_SCAFFOLD_TEMPLATES = "scaffold.templates"; const REGISTRY_NOLABELS = "nolabels"; const REGISTRY_EXCLUDES = "excludes"; const REGISTRY_NOCHILDREN = "nochildren"; const REGISTRY_DEFAULTS = "defaults"; const REGISTRY_TRANSITION = "transition"; const REGISTRY_PROPERTIES = "properties"; const REGISTRY_VALIDATORS = "validators"; const REGISTRY_CONSTRAINT = "constraint"; const REGISTRY_PARENT = "parent"; const METHOD_PREFIX = "do"; const ACTION_PREFIX = "scaffold"; const ACTION_NEW = "new"; const ACTION_LIST = "list"; const ACTION_VIEW = "view"; const ACTION_EDIT = "edit"; const ACTION_DELETE = "delete"; const DO_DEFAULT = "default"; const DO_CHILDREN = "children"; const DO_CONFIRM = "confirm"; const DO_SUBMIT = "submit"; const SCAFFOLD_TEMPLATES = "scaffold"; const TEMPLATE_HEADER = "scaffoldHeader"; const TEMPLATE_FOOTER = "scaffoldFooter"; const KEY_SCAFFOLD = "scaffold"; const KEY_PAGE = "scaffold_nextPage"; const KEY_METHOD = "scaffold_method"; const KEY_ACTION = "scaffold_nextAction"; const KEY_TARGET = "scaffold_target"; const KEY_DO = "scaffold_do"; const KEY_MESSAGE = "scaffold_message"; const KEY_TRANSITION = "scaffold_transition"; const KEY_SUBMIT_TITLE = "scaffold_submitTitle"; const KEY_FOREPERSON = "scaffold_foreperson"; const KEY_HELPER = "scaffold_helper"; const KEY_ID = "scaffold_id"; const KEY_IDS = "scaffold_ids"; const METHOD_POST = "post"; const METHOD_GET = "get"; const SMARTY_SCAFFOLD = "scaffold"; const DEFAULT_SCAFFOLD_TEMPLATE = "Scaffold.tpl"; } ?> ficus/pages/scaffold/ListScaffoldForeperson.php100644 1751 144 4063 10647425604 15412 ISHITOYA Kentaro * @version $Id: ListScaffoldForeperson.php 14 2007-07-18 14:55:12Z ishitoya $ */ require_once("ficus/pages/AbstractPage.php"); require_once("ficus/config/Registry.php"); require_once("ficus/db/s2dao/models/serializer/S2DaoArrayEntityDeserializer.php"); require_once("common/AbstractPage.php"); /** * @class Ficus_ListScaffoldForeperson */ class Ficus_ListScaffoldForeperson extends Ficus_AbstractScaffoldForeperson{ /** * do default */ public function doDefault(){ $dto = $this->mediator->daoManager()->getPagerDto($args); $helper = new S2Dao_PagerViewHelper($dto); $entities = $this->mediator->daoManager()->dao()->getWithCondition($dto); $container = $this->mediator->getContainer($entities); $organizer = $this->mediator->organizerFactory()->createListOrganizer(); $organizer->setItemTemplate("itemWithMenu"); $organizer->setRowTemplate("rowWithMenu"); $organizer->setHeaderTemplate("headerWithMenu"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); $this->mediator->smarty()->assign(self::KEY_HELPER, $helper); return $container->build(); } } ?> ficus/pages/scaffold/ScaffoldPage.php100644 1751 144 12737 10647426442 13340 ISHITOYA Kentaro * @version $Id: ScaffoldPage.php 15 2007-07-18 15:02:48Z ishitoya $ */ require_once("ficus/pages/BufferedPage.php"); /** * @class Ficus_Page */ abstract class Ficus_ScaffoldPage extends Ficus_BufferedPage implements Ficus_ScaffoldConstants{ protected $manager = null; protected $target = null; protected $foreperson = null; /** * on called * @param $mode string name of mode * @param $args array of args of do method */ protected function onDo($mode, $args){ if(($action = $this->isScaffoldAction($mode))){ Ficus_PageComponentFactory::getSmarty()->addPath(self::SMARTY_SCAFFOLD, Ficus_Dir::normalize(Ficus_File::currentDir() . "/templates")); if(empty($this->target)){ if($this->request->has(self::KEY_TARGET)){ $this->target = $this->request->extractAsString(self::KEY_TARGET); }else{ throw new Ficus_NotReadyException("scaffold action needs target table, set " . self::KEY_TARGET . "parameter or set target property."); } } $this->foreperson = strtolower($action); $action = $this->getScaffoldAction($action); $this->setNextAction($action); $this->manager = new Ficus_ScaffoldManager($this); } } /** * exec scaffold */ protected function buildScaffold(){ $scaffold = $this->manager->organize(); $this->assign(self::SMARTY_SCAFFOLD, $scaffold); } /** * on execute finished * @param $mode string name of mode * @param $args array of args of do method * @param $result mixed switch */ protected function onDone($mode, $args, $result){ if($this->isScaffoldAction($mode) && $result == self::MODE_TEMPLATE){ $this->buildScaffold(); $mode = $this->foreperson; $template = $this->getModeTemplate($mode); if(Ficus_PageComponentFactory::getSmarty() ->isTemplateExists($template)){ return parent::onDone($mode, $args, $template); }else{ return parent::onDone($mode, $args, self::DEFAULT_SCAFFOLD_TEMPLATE); } } return parent::onDone($mode, $args, $result); } /** * scaffold */ protected function execScaffoldAction($arg){ $result = $this->dispatchScaffoldEvent($args); if(is_null($result)){ return self::MODE_TEMPLATE; } } /** * do new */ public function __call($name, $args){ if($this->methodExists($name) && preg_match('/^doScaffold.*$/', $name)){ return $this->execScaffoldAction($args); } return parent::__call($name, $args); } /** * check for method existance */ protected function methodExists($method){ if(preg_match('/^doScaffold(.*)$/', $method, $regs)){ $action = strtolower($regs[1]); if($action == self::ACTION_NEW || $action == self::ACTION_EDIT || $action == self::ACTION_LIST || $action == self::ACTION_VIEW || $action == self::ACTION_DELETE){ return true; } } return parent::methodExists($method); } /** * get modes */ public function getModes(){ $modes = parent::getModes(); $modes[] = $this->getScaffoldAction(self::ACTION_NEW); $modes[] = $this->getScaffoldAction(self::ACTION_EDIT); $modes[] = $this->getScaffoldAction(self::ACTION_DELETE); $modes[] = $this->getScaffoldAction(self::ACTION_VIEW); $modes[] = $this->getScaffoldAction(self::ACTION_LIST); return $modes; } /** * get action */ protected function getScaffoldAction($action){ return self::ACTION_PREFIX . ucfirst($action); } /** * is scaffold action */ protected function isScaffoldAction($mode){ if(preg_match('/^' . self::ACTION_PREFIX . '(.*)$/', $mode, $regs)){ return $regs[1]; } return false; } /** * call event handler */ protected function dispatchScaffoldEvent($args){ $do = $this->manager->formBean()->do(); $methodDefault = "onDoScaffold" . ucfirst($this->foreperson); $method = $methodDefault . ucfirst($do); if(method_exists($this, $method)){ return $this->{$method}($args); } if(method_exists($this, $methodDefault)){ return $this->{$methodDefault}($args); } return null; } } ?> ficus/pages/scaffold/ScaffoldComponentFactory.php100644 1751 144 5731 10647426442 15732 ISHITOYA Kentaro * @version $Id: ScaffoldComponentFactory.php 15 2007-07-18 15:02:48Z ishitoya $ * * Scaffold component factory */ require_once("ficus/io/File.php"); require_once("ficus/config/Registry.php"); /** * @class Ficus_ScaffoldComponentFactory */ class Ficus_ScaffoldComponentFactory extends Ficus_S2ContainerComponentFactory{ const KEY_SMARTY = "scaffoldSmarty"; /** * dicon file name registry key */ const REGISTRY_DICON_FILENAME = "scaffold.dicon"; /** * dicon namespace registry key */ const REGISTRY_DICON_NAMESPACE = "scaffold.namespace"; /** * Default dicon file name. */ const DEFAULT_DICON_FILENAME = 'scaffold.dicon'; /** * dicon namespace. */ const DEFAULT_DICON_NAMESPACE = 'scaffold.scheme'; /** * get Dicon file name from registry * @return string dicon filename */ protected function getDiconFileNameRegistry(){ return self::REGISTRY_DICON_FILENAME; } /** * get Dicon namespace from registry * @return string dicon namespace */ protected function getDiconNameSpaceRegistry(){ return self::REGISTRY_DICON_NAMESPACE; } /** * get dicon file name * @return string dicon file name */ protected function getDefaultDiconFileName(){ return Ficus_File::currentDir() ->resolve(self::DEFAULT_DICON_FILENAME)->getPath(); } /** * get defoult dicon namespace * @return string dicon namespace */ protected function getDefaultDiconNameSpace(){ return self::DEFAULT_DICON_NAMESPACE; } /** * get component * @param $name string name of component * @param $class string class name * @return Ficus_ScaffoldComponentFactory */ public static function getComponent($name, $class = __CLASS__){ return parent::getComponent($name, $class); } /** * Get smarty * * @param $name string component name. * @return mixed component. */ public static function getSmarty() { return self::getComponent(self::KEY_SMARTY); } } ?> ficus/pages/scaffold/container/ScaffoldPart.php100644 1751 144 2264 10645132217 15316 ISHITOYA Kentaro * @version $Id: ScaffoldPart.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_ScaffoldPart */ interface Ficus_ScaffoldPart{ /** * organize * @param $organizer Ficus_ScaffoldOrganizer organizer */ public function accept($organizer); } ?>ficus/pages/scaffold/container/ScaffoldPartsContainer.php100644 1751 144 2346 10645132217 17345 ISHITOYA Kentaro * @version $Id: ScaffoldPartsContainer.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/beans/Bean.php"); require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_ScaffoldPartsContainer */ interface Ficus_ScaffoldPartsContainer extends Ficus_ScaffoldPart{ /** * organize */ public function build(); } ?> ficus/pages/scaffold/container/ConcreteScaffoldPartsContainer.php100644 1751 144 6705 10645132217 21033 ISHITOYA Kentaro * @version $Id: ConcreteScaffoldPartsContainer.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/beans/Bean.php"); require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_ConcreteScaffoldPartsContainer */ class Ficus_ConcreteScaffoldPartsContainer extends Ficus_Bean implements Ficus_S2DaoModelConstants, Ficus_ScaffoldPartsContainer{ /** * entity */ protected $entity = null; /** * @var organizers */ protected $organizers = array(); /** * @var parts */ protected $parts = array(); /** * constructor */ public function __construct($entity){ $this->entity = $entity; } /** * organize */ public function build(){ $result = ""; foreach($this->organizers as $organizer){ $organizer->startVisit($this); $this->accept($organizer); $organizer->endVisit($this); $result .= $organizer->result(); } return $result; } /** * organize * @param $organizer Ficus_ScaffoldOrganizer organizer */ public function accept($organizer){ foreach($this->parts as $part){ $organizer->visit($part); } } /** * returns part * @param $property string name to get * @return Ficus_ScaffoldPart part */ public function get($property){ if($this->has($property)){ return $this->parts[$property]; }else{ throw new Ficus_PropertyNotFoundException("property $property is not found"); } } /** * has * @params $property string property name to check * @return boolean true if exists */ public function has($property){ if(array_key_exists($property, $this->parts)){ return true; } return parent::has($property); } const METHOD_SIGNATURE = '/^(get|has)(.*?)$/'; /** * get property * @param $name string method name * @param $arguments array of arguments */ public function __call($name, $arguments){ if(preg_match(self::METHOD_SIGNATURE, $name, $regs)){ $property = trim($regs[2]); if(empty($regs[1]) == false){ $operation = trim($regs[1]); } if($operation == "get"){ return $this->get($property); }else if($operation == "has"){ return $this->has($property); } } return parent::__call($name, $arguments); } } ?> ficus/pages/scaffold/container/ScaffoldPartsContainerList.php100644 1751 144 5247 10645132217 20204 ISHITOYA Kentaro * @version $Id: ScaffoldPartsContainerList.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/beans/Bean.php"); require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_ScaffoldPartsContainerList */ class Ficus_ScaffoldPartsContainerList extends Ficus_Bean implements Ficus_S2DaoModelConstants, Ficus_ScaffoldPartsContainer{ /** * @var container */ protected $organizers = array(); /** * @var parts */ protected $containers = array(); /** * organize */ public function build(){ $result = ""; foreach($this->organizers as $organizer){ $organizer->startVisit($this); $this->accept($organizer); $organizer->endVisit($this); $result .= $organizer->result(); } return $result; } /** * organize * @param $organizer Ficus_ScaffoldOrganizer organizer */ public function accept($organizer){ foreach($this->containers as $container){ $container->addOrganizers($organizer); $container->build($organizer); $container->clearOrganizers(); } } /** * returns part * @param $name string name to get * @return Ficus_ScaffoldPart part */ public function get($index){ if($this->has($index)){ return $this->containers[$index]; }else{ throw new Ficus_PropertyNotFoundException("property $property is not found"); } } /** * has * @params $property string property name to check * @return boolean true if exists */ public function has($index){ if(array_key_exists($index, $this->containers)){ return true; } return parent::has($index); } } ?> ficus/pages/scaffold/container/ScaffoldPartsFactory.php100644 1751 144 3127 10645132217 17030 ISHITOYA Kentaro * @version $Id: ScaffoldPartsFactory.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_ScaffoldPartsFactory */ class Ficus_ScaffoldPartsFactory implements Ficus_S2DaoModelConstants{ const SUFFIX = "ScaffoldPart"; const PACKAGE = "interface."; /** * create part * @param $context string context * @param $property string property name * @param $type string type of part * @param $datatype string datatype of part * @return Ficus_ScaffoldPart part */ public static function create($property, $type, $datatype){ $component = self::PACKAGE . "Ficus_Concrete" . self::SUFFIX; $component = Ficus_ClassLoader::load($component); return $component; } } ?>ficus/pages/scaffold/container/AbstractScaffoldPart.php100644 1751 144 5036 10645132217 17002 ISHITOYA Kentaro * @version $Id: AbstractScaffoldPart.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/beans/Bean.php"); require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_AbstractScaffoldPart */ abstract class Ficus_AbstractScaffoldPart extends Ficus_Bean implements Ficus_S2DaoModelConstants, Ficus_ScaffoldPart{ const TEMPLATE_PREFIX = "common/scaffold/"; const TEMPLATE_EXTENSION = ".tpl"; protected $name; protected $type; protected $value; protected $label; protected $remark; protected $template = null; protected $parts = array(); protected static $smarty = null; protected function prefix(){ return self::TEMPLATE_PREFIX; } protected function template(){ if(is_null($this->template)){ $classname = get_class($this); $tempalte = substr($classname, strpos($classname, _)); return $this->prefix() . $template . self::TEMPLATE_EXTENSION; }else{ return $this->prefix() . $this->template . self::TEMPLATE_EXTENSION; } } public function onBuild(){ if(is_null(self::$smarty)){ self::$smarty = Ficus_PageComponentFactory::getSmarty(); } self::$smarty->assign("part", $this); } public function fetch(){ $this->onDisplay(); return self::$smarty->fetch($this->template()); } public function display(){ $this->onDisplay(); self::$smarty->display($this->template()); } public function isComposite(){ if(empty($this->parts)){ return false; } return true; } } ?> ficus/pages/scaffold/container/ConcreteScaffoldPart.php100644 1751 144 5454 10647425603 17013 ISHITOYA Kentaro * @version $Id: ConcreteScaffoldPart.php 14 2007-07-18 14:55:12Z ishitoya $ * */ require_once("ficus/beans/Bean.php"); require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); /** * @class Ficus_ConcreteScaffoldPart */ class Ficus_ConcreteScaffoldPart extends Ficus_Bean implements Ficus_S2DaoModelConstants, Ficus_ScaffoldPart{ /** * parent */ protected $parent; /** * entity name */ protected $entity; /** * name of part */ protected $name; /** * type of part */ protected $type; /** * validators */ protected $validators = array(); /** * constraint */ protected $constraint = array(); /** * value of the part */ protected $value; /** * label of the part */ protected $label; /** * remark of the part */ protected $remark; /** * settings */ protected $settings; /** * composite parts */ protected $parts = array(); /** * organize * @param $organizer Ficus_ScaffoldOrganizer organizer */ public function accept($organizer){ $organizer->visit($this); } /** * check is composite part * @return boolean true if composite */ public function isComposite(){ if(empty($this->parts)){ return false; } return true; } /** * returns qualified name * @return string name */ public function qname(){ if($this->hasParent()){ return $this->parent->qname() . "__" . get_class($this->entity) . "_" . $this->name; }else{ return get_class($this->entity) . "_" . $this->name; } } /** * check has parent * @return boolean true if has parent */ public function hasParent(){ if(is_null($this->parent)){ return false; } return true; } } ?> ficus/pages/scaffold/ScaffoldConfiguration.php100644 1751 144 7310 10647426442 15242 ISHITOYA Kentaro * @version $Id: ScaffoldConfiguration.php 15 2007-07-18 15:02:48Z ishitoya $ * */ /** * @class Ficus_ScaffoldConfiguration */ class Ficus_ScaffoldConfiguration implements Ficus_ScaffoldConstants{ /** * $settings array scaffold settings */ protected $settings = array(); /** * $tables Ficus_ScaffoldTableConfiguration */ protected $tables = array(); /** * constructor */ public function __construct($settings){ if(isset($settings[self::REGISTRY_TABLESETTINGS]) == false){ throw new Ficus_IllegalArgumentException("settings must have TableSettings field"); } foreach($settings[self::REGISTRY_TABLESETTINGS] as $name => $setting){ $this->tables[$name] = $this->createTableConfiguration($setting); } } /** * get table settings * @param $name string name of table * @return Ficus_ScaffoldTableConfiguration */ public function table($name){ if(isset($this->tables[$name])){ return $this->tables[$name]; }else{ throw new Ficus_IllegalArgumentException("table $name is not found"); } } /** * create Ficus_ScaffoldTableConfiguration from array * @param $settings array of settings * @return Ficus_ScaffoldTableConfiguration configuration */ protected function createTableConfiguration($settings){ $config = new Ficus_ScaffoldTableConfiguration(); if(isset($settings[self::REGISTRY_EXCLUDES])){ foreach($settings[self::REGISTRY_EXCLUDES] as $table => $column){ if(is_array($column)){ foreach($column as $prop){ $config->addExcludeProperty($table, $prop); } }else{ $config->addExcludeProperty($table, $column); } } } if(isset($settings[self::REGISTRY_NOLABELS])){ foreach($settings[self::REGISTRY_NOLABELS] as $table => $column){ $config->addNoLabelProperty($table, $column); } } if(isset($settings[self::REGISTRY_DEFAULTS])){ foreach($settings[self::REGISTRY_DEFAULTS] as $column => $value){ $config->addDefaultValues($column, $value); } } if(isset($settings[self::REGISTRY_PARENT])){ $config->setParentPart($settings[self::REGISTRY_PARENT]); } if(isset($settings[self::REGISTRY_TRANSITION])){ $config->setTransitions($settings[self::REGISTRY_TRANSITION]); } if(isset($settings[self::REGISTRY_PROPERTIES])){ $config->setProperties($settings[self::REGISTRY_PROPERTIES]); } if(isset($settings[self::REGISTRY_NOCHILDREN])){ $config->setNoChildren(true); } return $config; } } ?> ficus/pages/scaffold/ViewScaffoldForeperson.php100644 1751 144 3433 10647425604 15411 ISHITOYA Kentaro * @version $Id: ViewScaffoldForeperson.php 14 2007-07-18 14:55:12Z ishitoya $ */ require_once("ficus/pages/AbstractPage.php"); require_once("ficus/config/Registry.php"); require_once("common/AbstractPage.php"); /** * @class Ficus_ViewScaffoldForeperson */ class Ficus_ViewScaffoldForeperson extends Ficus_AbstractScaffoldForeperson{ /** * view * @param $args array of arguments */ public function doDefault(){ $id = $this->mediator->request()->extractAsInt(self::KEY_ID); $entity = $this->mediator->daoManager()->getSingleEntity($id); $container = $this->mediator->getContainer($entity); $organizer = $this->mediator->organizerFactory()->createViewOrganizer(); $organizer->setItemTemplate("row"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); return $container->build(); } } ?> ficus/pages/scaffold/ScaffoldForeperson.php100644 1751 144 2236 10647426442 14557 ISHITOYA Kentaro * @version $Id: ScaffoldForeperson.php 15 2007-07-18 15:02:48Z ishitoya $ */ require_once("ficus/config/Registry.php"); /** * @interface ScaffoldForeperson */ interface Ficus_ScaffoldForeperson{ /** * organaize scaffold * @return string organized result */ public function organize(); } ?> ficus/pages/scaffold/DeleteScaffoldForeperson.php100644 1751 144 4513 10647425604 15701 ISHITOYA Kentaro * @version $Id: DeleteScaffoldForeperson.php 14 2007-07-18 14:55:12Z ishitoya $ */ require_once("ficus/pages/AbstractPage.php"); require_once("ficus/config/Registry.php"); /** * @class Ficus_DeleteScaffoldForeperson */ class Ficus_DeleteScaffoldForeperson extends Ficus_AbstractScaffoldForeperson{ /** * delete */ public function doDefault(){ $ids = $this->mediator->request()->extractAsInt(self::KEY_IDS); $entities = $this->mediator->daoManager()->getEntities($ids); $container = $this->mediator->getContainer($entities); $organizer = $this->mediator->organizerFactory()->createListOrganizer(); $organizer->setItemTemplate("item"); $organizer->setRowTemplate("row"); $organizer->setHeaderTemplate("header"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); $this->mediator->smarty()->assign(self::KEY_IDS, $ids); $this->mediator->formBean()->setDo(self::DO_SUBMIT); return $container->build(); } /** * delete submit */ public function doSubmit(){ $ids = $this->mediator->request()->extractAsString(self::KEY_IDS); $dao = $this->mediator->daoManager()->dao(); $entity = $dao->entity(); foreach($ids as $id){ $entity->setId($id); $dao->delete($entity); } $this->mediator->smarty()->assign(self::KEY_IDS, $ids); return ""; } } ?> ficus/pages/scaffold/ScaffoldFormBean.php100644 1751 144 3741 10647426442 14130 ISHITOYA Kentaro * @version $Id: ScaffoldFormBean.php 15 2007-07-18 15:02:48Z ishitoya $ * */ require_once("ficus/db/s2dao/models/S2DaoModelConstants.php"); require_once("ficus/db/s2dao/models/S2DaoDataAccessObject.php"); /** * @class Ficus_ScaffoldFormBean */ class Ficus_ScaffoldFormBean extends Ficus_Bean implements Ficus_ScaffoldConstants{ /** * $page string form action */ protected $page = null; /** * $method string form method post or get */ protected $method = self::METHOD_POST; /** * $action string page's action, not a scaffold action */ protected $action = null; /** * $target string target table name */ protected $target = null; /** * $do string scaffold's action. */ protected $do = null; /** * $submitTitle string submit button value */ protected $submitTitle = self::SUBMIT_TITLE; /** * $transition string transition */ protected $transition = null; /** * $foreperson string foreperson */ protected $foreperson = null; /** * $message string message */ protected $message = null; } ?> ficus/pages/scaffold/components21.dtd100644 1751 144 2773 10645120161 13300 ficus/pages/scaffold/NewScaffoldForeperson.php100644 1751 144 7565 10647425604 15242 ISHITOYA Kentaro * @version $Id: NewScaffoldForeperson.php 14 2007-07-18 14:55:12Z ishitoya $ */ require_once("ficus/config/Registry.php"); /** * @class Ficus_NewScaffoldForeperson */ class Ficus_NewScaffoldForeperson extends Ficus_AbstractScaffoldForeperson{ /** * new * @param $args array of arguments */ public function doDefault(){ if(is_null($this->mediator->entity())){ $entity = $this->mediator->daoManager()->entity(); }else{ $entity = $this->mediator->entity(); } return $this->buildNew($entity); } /** * new * @param $args array of arguments */ public function doChildren(){ $entity = $this->mediator->getEntityFromRequest(); return $this->buildNew($entity); } /** * new * @param $args array of arguments */ public function doConfirm(){ $entity = $this->mediator->getEntityFromRequest(); $container = $this->mediator->getContainer($entity); $organizer = $this->mediator->organizerFactory()->createViewOrganizer(); $organizer->setItemTemplate("row"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); $container->addOrganizers( $this->mediator->organizerFactory()->createHiddenOrganizer()); $this->mediator->formBean()->setDo(self::DO_SUBMIT); return $container->build(); } /** * new * @param $args array of arguments */ public function doSubmit(){ $entity = $this->mediator->getEntityFromRequest(); $container = $this->mediator->getContainer($entity); $organizer = $this->mediator->organizerFactory()->createViewOrganizer(); $organizer->setItemTemplate("row"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); $entity->insert(); return $container->build(); } /** * buildNew */ protected function buildNew($entity){ $transition = null; if($this->mediator->request()->has(self::KEY_TRANSITION)){ $transition = $this->mediator->request()->extractAsString( self::KEY_TRANSITION); $this->mediator->table()->setCurrentTransition($transition); } $container = $this->mediator->getContainer($entity); $organizer = $this->mediator->organizerFactory()->createNewOrganizer(); $organizer->setItemTemplate("row"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); $transition = $this->mediator->table()->getNextTransition($transition); if($transition == null){ $this->mediator->formBean()->setDo(self::DO_CONFIRM); }else{ $this->mediator->formBean()->setDo(self::DO_CHILDREN); $this->mediator->formBean()->setTransition($transition); } return $container->build(); } } ?> ficus/pages/scaffold/AbstractScaffoldForeperson.php100644 1751 144 3725 10645132217 16237 ISHITOYA Kentaro * @version $Id: AbstractScaffoldForeperson.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/config/Registry.php"); /** * @class Ficus_AbstractScaffoldForeperson */ abstract class Ficus_AbstractScaffoldForeperson implements Ficus_ScaffoldForeperson, Ficus_ScaffoldConstants{ protected $mediator = null; /** * constructor */ public function __construct($mediator){ $this->mediator = $mediator; } /** * invoke */ protected function invoke(){ if($this->mediator->request()->has(self::KEY_DO)){ $key = $this->mediator->request()->extractAsString(self::KEY_DO); }else{ $key = self::DO_DEFAULT; } $method = self::METHOD_PREFIX . ucfirst($key); if(method_exists($this, $method) == false){ throw new Ficus_IllegalArgumentException("method $method is not implemented"); } return $this->{$method}(); } /** * organaize scaffold * @return string organized result */ public function organize(){ return $this->invoke(); } } ?> ficus/pages/scaffold/organizer/ScaffoldOrganizer.php100644 1751 144 2172 10645132217 16364 ISHITOYA Kentaro * @version $Id: ScaffoldOrganizer.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_ScaffoldOrganizer */ interface Ficus_ScaffoldOrganizer{ /** * visit part * @param $part Ficus_ScaffoldPart part */ public function visit($part); } ?>ficus/pages/scaffold/organizer/ListScaffoldOrganizer.php100644 1751 144 12770 10646126775 17262 ISHITOYA Kentaro * @version $Id: ListScaffoldOrganizer.php 7 2007-07-14 10:55:18Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_ListScaffoldOrganizer */ class Ficus_ListScaffoldOrganizer extends Ficus_AbstractScaffoldOrganizer{ const TEMPLATE_PREFIX = "list/"; protected $rowTemplate = ""; protected $headerTemplate = ""; protected $header = ""; protected $rows = array(); /** * prefix * @return string template prefix */ public function prefix(){ return parent::prefix() . self::TEMPLATE_PREFIX; } /** * on visit * @param $part Ficus_ScaffoldPart part */ protected function onVisit($part){ $config = $this->mediator->table(); $entityName = $part->entity()->getEntityName(); if($part->type() == self::TYPE_DIRECT){ return; } if($config->isExcludeProperty($part)){ return; } $value = null; if($part->value() instanceof Ficus_S2DaoEntity){ if($part->type() == self::TYPE_LIST){ $key = $part->value()->name(); if(is_null($key)){ $value = ""; }else{ $value = $part->value()->names($part->value()->name()); } }else if($template = Ficus_ScaffoldTemplateParser::getTemplate($part)){ $value = Ficus_ScaffoldTemplateParser::parse($template, $part); }else{ $value = $this->getChildren($part); } }else{ $value = $part->value(); } $this->assign("part", $part); $this->assign("value", $value); return $this->fetch($this->itemTemplate); } /** * start visit * @param $container Ficus_ScaffoldPartsContainer */ public function startVisit($container){ if($container instanceof Ficus_ScaffoldPartsContainerList){ if($container->isEmptyContainers()){ return; } $container = $container->get(0); $parts = $container->parts(); $this->assign("delete", "delete"); $this->header = $this->createHeader($parts); $this->clear("delete"); } } /** * end visit * @param $container Ficus_ScaffoldPartsContainer */ public function endVisit($container){ if($container instanceof Ficus_ConcreteScaffoldPartsContainer){ $this->assign("entity", $container->entity()); $this->assign("result", $this->result); $result = $this->fetch($this->rowTemplate); $this->rows[] = $result; $this->result = ""; }else if($container instanceof Ficus_ScaffoldPartsContainerList){ $this->assign("header", $this->header); $this->assign("rows", $this->rows); $this->addResult($this->fetch($this->entityTemplate)); } } /** * create header * @param $parts array of interface part * @return string header */ protected function createHeader($parts){ $labels = array(); $config = $this->mediator->table(); foreach($parts as $part){ if($config->isExcludeProperty($part)){ continue; } if($part->type() == self::TYPE_DIRECT){ continue; } $labels[] = $part->label(); } $this->assign("labels", $labels); return $this->fetch($this->headerTemplate); } /** * get child */ protected function getChildren($part){ $input = ""; foreach($part->parts() as $child){ $result = $this->result; $this->result = ""; $child->accept($this); $input .= $this->result; $this->result = $result; $this->assign("nolabel", false); } $this->clear("entity"); $this->assign("result", $input); $row = $this->fetch($this->rowTemplate); $rows = array(); $rows[] = $row; $this->assign("header", $this->createHeader($part->parts())); $this->assign("rows", $rows); return $this->fetch($this->entityTemplate); } /* * set header template * @param $headerTemplate string template file name */ public function setHeaderTemplate($headerTemplate){ $this->headerTemplate = $headerTemplate; } /* * set row template * @param $headerTemplate string template file name */ public function setRowTemplate($rowTemplate){ $this->rowTemplate = $rowTemplate; } } ?>ficus/pages/scaffold/organizer/NewScaffoldOrganizer.php100644 1751 144 11342 10647425604 17064 ISHITOYA Kentaro * @version $Id: NewScaffoldOrganizer.php 14 2007-07-18 14:55:12Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_NewScaffoldOrganizer */ class Ficus_NewScaffoldOrganizer extends Ficus_AbstractScaffoldOrganizer{ const TEMPLATE_PREFIX = "form/"; /** * @var $hiddens array hidden parts */ protected $hiddens = array(); /** * prefix * @return string template prefix */ public function prefix(){ return parent::prefix() . self::TEMPLATE_PREFIX; } /** * on visit * @param $part Ficus_ScaffoldPart part */ protected function onVisit($part){ $config = $this->mediator->table(); $entityName = $part->entity()->getEntityName(); if($part->type() == self::TYPE_DIRECT && $part->value() == null){ if(($value = $config->getDefaultValue($part)) !== null){ $part->setValue($value); } $this->hiddens[] = $part; return; } if($config->isExcludeProperty($part) && $config->isTransitionParentProperty($part) == false){ $this->hiddens[] = $part; return; } $input = null; if($config->isTransitionParentProperty($part)){ $input = $this->getChildren($part); }else if($part->value() instanceof Ficus_S2DaoEntity){ if($part->type() == self::TYPE_LIST){ $key = $part->value()->name(); if(is_null($key)){ $key = $config->getDefaultValue($part); } $this->assign("qname", $part->qname()); $this->assign("items", $part->value()->names()); $this->assign("selected", $key); $input = $this->fetch("select"); }else if($config->isNoChildren()){ return; }else{ $input = $this->getChildren($part); } }else{ $this->assign("qname", $part->qname()); $this->assign("value", $part->value()); $this->assign("validators", $part->validators()); $input = $this->fetch("input"); } if($config->isTransitionProperty($part) == false && $config->isTransitionParentProperty($part) == false){ $this->hiddens[] = $part; return; } if($config->isNoLabelProperty($part)){ $this->assign("nolabel", true); } $this->assign("qname", $part->qname()); $this->assign("label", $part->label()); $this->assign("validators", $part->validators()); $this->assign("input", $input); return $this->fetch($this->itemTemplate); } /** * get child */ protected function getChildren($part){ $input = ""; $result = $this->result; foreach($part->parts() as $child){ $this->result = ""; $child->accept($this); $input .= $this->result; $this->assign("nolabel", false); } $this->result = $result; $this->assign("result", $input); return $this->fetch($this->entityTemplate); } /** * on end visit * @param $container Ficus_ScaffoldPartsContainer */ protected function onEndVisit($container){ foreach($this->hiddens as $hidden){ $this->showHidden($hidden); } } /** * show hidden */ protected function showHidden($hidden){ if($hidden->value() instanceof Ficus_S2DaoEntity){ foreach($hidden->parts() as $part){ $this->addResult($this->showHidden($part)); } return; } $this->assign("qname", $hidden->qname()); $this->assign("value", $hidden->value()); $this->addResult($this->fetch("hidden")); } } ?>ficus/pages/scaffold/organizer/ScaffoldOrganizerFactory.php100644 1751 144 5242 10645132217 17715 ISHITOYA Kentaro * @version $Id: ScaffoldOrganizerFactory.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_ScaffoldOrganizerFactory */ class Ficus_ScaffoldOrganizerFactory implements Ficus_S2DaoModelConstants{ const SUFFIX = "ScaffoldPart"; const PACKAGE = "interface."; /** * mediator */ protected $mediator = null; /** * constructor * @param $mediator Ficus_ScaffoldMediator mediator */ public function __construct($mediator){ $this->mediator = $mediator; } /** * get Organizer */ public function create($context){ $classname = "Ficus_" . $context . "ScaffoldOrganizer"; $organizer = new $classname($this->mediator); return $organizer; } /** * get View Organizer * @return Ficus_ViewInterfaceOrganizer view organizer */ public function createViewOrganizer(){ return $this->create("View"); } /** * create List Organizer * @return Ficus_ListInterfaceOrganizer list organizer */ public function createListOrganizer(){ return $this->create("List"); } /** * create Edit Organizer * @return Ficus_EditInterfaceOrganizer edit organizer */ public function createEditOrganizer(){ return $this->create("Edit"); } /** * create New Organizer * @return Ficus_NewInterfaceOrganizer new organizer */ public function createNewOrganizer(){ $organizer = $this->create("New"); $organizer->mediator()->table()->addExcludeProperty("*", "id"); return $organizer; } /** * create Hidden Organizer * @return Ficus_HiddenInterfaceOrganizer hidden organizer */ public function createHiddenOrganizer(){ return $this->create("Hidden"); } } ?>ficus/pages/scaffold/organizer/ViewScaffoldOrganizer.php100644 1751 144 6154 10645132217 17223 ISHITOYA Kentaro * @version $Id: ViewScaffoldOrganizer.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_ViewScaffoldOrganizer */ class Ficus_ViewScaffoldOrganizer extends Ficus_AbstractScaffoldOrganizer{ const TEMPLATE_PREFIX = "view/"; /** * prefix * @return string template prefix */ public function prefix(){ return parent::prefix() . self::TEMPLATE_PREFIX; } /** * on visit * @param $part Ficus_ScaffoldPart part */ protected function onVisit($part){ $config = $this->mediator->table(); $entityName = $part->entity()->getEntityName(); if($part->type() == self::TYPE_DIRECT){ return; } if($config->isExcludeProperty($part)){ return; } $value = null; if($part->value() instanceof Ficus_S2DaoEntity){ if($part->type() == self::TYPE_LIST){ $key = $part->value()->name(); if(is_null($key)){ $value = ""; }else{ $value = $part->value()->names($part->value()->name()); } }else if($template = Ficus_ScaffoldTemplateParser::getTemplate($part)){ $value = Ficus_ScaffoldTemplateParser::parse($template, $part); }else{ $value = $this->getChildren($part); } }else{ $value = $part->value(); } if($config->isNoLabelProperty($part)){ $this->assign("nolabel", true); } $this->assign("label", $part->label()); $this->assign("value", $value); $result = $this->fetch($this->itemTemplate); $this->addResult($result); } /** * get child */ protected function getChildren($part){ $input = ""; foreach($part->parts() as $child){ $result = $this->result; $this->result = ""; $child->accept($this); $input = $this->result; $this->result = $result; $this->assign("nolabel", false); } $this->assign("result", $input); return $this->fetch($this->entityTemplate); } } ?>ficus/pages/scaffold/organizer/HiddenScaffoldOrganizer.php100644 1751 144 4104 10645132217 17475 ISHITOYA Kentaro * @version $Id: HiddenScaffoldOrganizer.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_HiddenScaffoldOrganizer */ class Ficus_HiddenScaffoldOrganizer extends Ficus_AbstractScaffoldOrganizer{ const TEMPLATE_PREFIX = "form/"; /** * prefix * @return string template prefix */ public function prefix(){ return parent::prefix() . self::TEMPLATE_PREFIX; } /** * on visit * @param $part Ficus_ScaffoldPart part */ protected function onVisit($part){ $entityName = $part->entity()->getEntityName(); $this->showHidden($part); } /** * end visit * @param $container Ficus_ScaffoldPartsContainer */ public function endVisit($container){ } /** * show hidden */ protected function showHidden($hidden){ if($hidden->value() instanceof Ficus_S2DaoEntity){ foreach($hidden->parts() as $part){ $this->showHidden($part); } return; } $this->assign("qname", $hidden->qname()); $this->assign("value", $hidden->value()); $this->addResult($this->fetch("hidden")); } } ?>ficus/pages/scaffold/organizer/EditScaffoldOrganizer.php100644 1751 144 10250 10647425604 17215 ISHITOYA Kentaro * @version $Id: EditScaffoldOrganizer.php 14 2007-07-18 14:55:12Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_EditScaffoldOrganizer */ class Ficus_EditScaffoldOrganizer extends Ficus_AbstractScaffoldOrganizer{ const TEMPLATE_PREFIX = "form/"; /** * @var $hiddens array hidden parts */ protected $hiddens = array(); /** * prefix * @return string template prefix */ public function prefix(){ return parent::prefix() . self::TEMPLATE_PREFIX; } /** * on visit * @param $part Ficus_ScaffoldPart part */ protected function onVisit($part){ $config = $this->mediator->table(); $entityName = $part->entity()->getEntityName(); if($part->type() == self::TYPE_DIRECT){ $this->hiddens[] = $part; return; } if($config->isExcludeProperty($part)){ $this->hiddens[] = $part; return; } $input = null; if($part->value() instanceof Ficus_S2DaoEntity){ if($part->type() == self::TYPE_LIST){ $this->assign("qname", $part->qname()); $this->assign("items", $part->value()->names()); $this->assign("selected", $part->value()->name()); $input = $this->fetch("select"); }else if($config->isNoChildren()){ return; }else{ $input = $this->getChildren($part); } }else{ $this->assign("qname", $part->qname()); $this->assign("value", $part->value()); $this->assign("validators", $part->validators()); $input = $this->fetch("input"); } if($config->isTransitionProperty($part) == false){ $this->hiddens[] = $part; return; } if($config->isNoLabelProperty($part)){ $this->assign("nolabel", true); } $this->assign("qname", $part->qname()); $this->assign("label", $part->label()); $this->assign("validators", $part->validators()); $this->assign("input", $input); $this->addResult($this->fetch($this->itemTemplate)); } /** * get child */ protected function getChildren($part){ $input = ""; $result = $this->result; foreach($part->parts() as $child){ $this->result = ""; $child->accept($this); $input .= $this->result; $this->assign("nolabel", false); } $this->result = $result; $this->assign("result", $input); return $this->fetch($this->entityTemplate); } /** * on end visit * @param $container Ficus_ScaffoldPartsContainer */ protected function onEndVisit($container){ foreach($this->hiddens as $hidden){ $this->showHidden($hidden); } } /** * show hidden */ protected function showHidden($hidden){ if($hidden->value() instanceof Ficus_S2DaoEntity){ foreach($hidden->parts() as $part){ $this->showHidden($part); } return; } $this->assign("qname", $hidden->qname()); $this->assign("value", $hidden->value()); $this->addResult($this->fetch("hidden")); } } ?>ficus/pages/scaffold/organizer/AbstractScaffoldOrganizer.php100644 1751 144 11674 10645132217 20077 ISHITOYA Kentaro * @version $Id: AbstractScaffoldOrganizer.php 2 2007-07-11 10:37:48Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_AbstractScaffoldOrganizer */ abstract class Ficus_AbstractScaffoldOrganizer implements Ficus_ScaffoldOrganizer, Ficus_S2DaoModelConstants{ const TEMPLATE_SUFFIX = ".tpl"; /** * itemtemplate */ protected $itemTempalte = ""; /** * entity template */ protected $entityTemplate = ""; /** * result */ protected $result = ""; /** * mediator */ protected $mediator = null; /** * constructor * @param $mediator Ficus_ScaffoldMediator mediator */ public function __construct($mediator){ $this->mediator = $mediator; } /** * prefix * @return string template prefix */ public function prefix(){ return ""; } /** * get template file name * @param $type string type of template * @return string template filename */ public function template($type){ return $this->prefix() . $type . self::TEMPLATE_SUFFIX; } /** * item template * @param $template string template */ public function setItemTemplate($itemTemplate){ $this->itemTemplate = $itemTemplate; } /** * entity template * @param $template string template */ public function setEntityTemplate($entityTemplate){ $this->entityTemplate = $entityTemplate; } /** * get mediator */ public function mediator(){ return $this->mediator; } /** * visit part * @param $part Ficus_ScaffoldPart part */ public function visit($part){ Ficus_Assert::isInstanceOf($part, "Ficus_ScaffoldPart"); $this->mediator->smarty()->clear("value"); $this->mediator->smarty()->clear("qname"); $this->mediator->smarty()->clear("nolabel"); $result = $this->onVisit($part); $this->addResult($result); } /** * start visit * @param $container Ficus_ScaffoldPartsContainer */ public function startVisit($container){ Ficus_Assert::isInstanceOf($container, "Ficus_ScaffoldPartsContainer"); $this->onStartVisit($container); } /** * end visit * @param $container Ficus_ScaffoldPartsContainer */ public function endVisit($container){ Ficus_Assert::isInstanceOf($container, "Ficus_ScaffoldPartsContainer"); $this->onEndVisit($container); $this->mediator->smarty()->assign("result", $this->result); $this->result = $this->fetch($this->entityTemplate); } /** * result */ public function result(){ return $this->result; } /** * on visit * @param $part Ficus_ScaffoldPart part */ abstract protected function onVisit($part); /** * on start visit * @param $container Ficus_ScaffoldPartsContainer */ protected function onStartVisit($container){ //do nothing } /** * on end visit * @param $container Ficus_ScaffoldPartsContainer */ protected function onEndVisit($container){ //do nothing } /** * add result */ protected function addResult($result){ $this->result .= $result; } /** * assign * @param $name name of variable * @param $var mixed variable */ protected function assign($name, $var){ $this->mediator->smarty()->assign($name, $var); } /** * fetch * @param $template string template * @return string result */ protected function fetch($type){ return $this->mediator->smarty()->fetch($this->template($type)); } /** * display * @param $template string template */ protected function display($type){ $this->mediator->smarty()->fetch($this->display($type)); } /** * clear * @param $name string name of property */ protected function clear($name){ $this->mediator->smarty()->clear($name); } } ?>ficus/pages/scaffold/EditScaffoldForeperson.php100644 1751 144 7624 10647425604 15372 ISHITOYA Kentaro * @version $Id: EditScaffoldForeperson.php 14 2007-07-18 14:55:12Z ishitoya $ */ require_once("ficus/pages/AbstractPage.php"); require_once("ficus/config/Registry.php"); /** * @class Ficus_EditScaffoldForeperson */ class Ficus_EditScaffoldForeperson extends Ficus_AbstractScaffoldForeperson{ /** * edit * @param $args array of arguments */ public function doDefault(){ $id = $this->mediator->request()->extractAsInt(self::KEY_ID); $entity = $this->mediator->daoManager()->getSingleEntity($id); return $this->buildEdit($entity); } /** * new * @param $args array of arguments */ public function doChildren(){ $entity = $this->mediator->getEntityFromRequest(); return $this->buildNew($entity); } /** * edit confirm * @param $args array of arguments */ public function doConfirm(){ $entity = $this->mediator->getEntityFromRequest(); $container = $this->mediator->getContainer($entity); $organizer = $this->mediator->organizerFactory()->createViewOrganizer(); $organizer->setItemTemplate("row"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); $container->addOrganizers( $this->mediator->organizerFactory()->createHiddenOrganizer()); $this->mediator->formBean()->setDo(self::DO_SUBMIT); return $container->build(); } /** * edit submit * @param $args array of arguments */ public function doSubmit(){ $entity = $this->mediator->getEntityFromRequest(); $container = $this->mediator->getContainer($entity); $organizer = $this->mediator->organizerFactory()->createViewOrganizer(); $organizer->setItemTemplate("row"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); $entity->update(); return $container->build(); } /** * buildNew */ protected function buildEdit($entity){ $transition = null; if($this->mediator->request()->has(self::KEY_TRANSITION)){ $transition = $this->mediator->request()->extractAsString( self::KEY_TRANSITION); $this->mediator->table()->setCurrentTransition($transition); } $container = $this->mediator->getContainer($entity); $organizer = $this->mediator->organizerFactory()->createEditOrganizer(); $organizer->setItemTemplate("row"); $organizer->setEntityTemplate("table"); $container->addOrganizers($organizer); $transition = $this->mediator->table()->getNextTransition($transition); if($transition == null){ $this->mediator->formBean()->setDo(self::DO_CONFIRM); }else{ $this->mediator->formBean()->setDo(self::DO_CHILDREN); $this->mediator->formBean()->setTransition($transition); } return $container->build(); } } ?> ficus/pages/scaffold/scaffold.dicon100644 1751 144 532 10645120256 13026 Ficus_Registry::search(Ficus_ScaffoldConstants::REGISTRY_SMARTYCACHE) ficus/pages/scaffold/builder/ConcreteScaffoldBuilder.php100644 1751 144 10617 10647425603 17154 ISHITOYA Kentaro * @version $Id: ConcreteScaffoldBuilder.php 14 2007-07-18 14:55:12Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_AbstractScaffoldBuilder */ class Ficus_ConcreteScaffoldBuilder implements Ficus_ScaffoldBuilder, Ficus_ScaffoldConstants{ /** * mediator */ protected $mediator = null; /** * constructor * @param $mediator Ficus_ScaffoldMediator mediator */ public function __construct($mediator){ $this->mediator = $mediator; } /** * build interface from entity * @param $entity Ficus_S2DaoEntity entity */ public function build($entity){ if($entity instanceof S2Dao_ArrayList){ $list = new Ficus_ScaffoldPartsContainerList(); foreach($entity as $target){ $list->addContainers($this->createContainer($target)); } return $list; }else{ return $this->createContainer($entity); } } /** * create container * @param $parts array of parts * @return Ficus_ConcreateScaffoldPartsContainer */ protected function createContainer($entity){ Ficus_Assert::isInstanceOf($entity, "Ficus_S2DaoEntity"); $parts = $this->buildParts($entity); $container = new Ficus_ConcreteScaffoldPartsContainer($entity); $container->setParts($parts); return $container; } /** * build parts array * @param $entity Ficus_S2DaoEntity target entity * @return array of parts */ protected function buildParts($entity){ $reader = new Ficus_S2DaoEntityAnnotationReader($entity); $settings = $this->mediator->table($entity->getEntityName()); if($settings->isEmptyParentPart("parent") == false){ $settings = $this->mediator->table($settings->parentPart()); } $settings = $settings->properties(); $reader->sort($settings); $parts = array(); $properties = $reader->properties(); foreach($properties as $property){ $value = $entity->get($property); $setting = $settings[$property]; $part = $this->buildPart($reader, $property, $value, $setting); $parts[$property] = $part; } return $parts; } /** * build part * @param $reader Ficus_S2DaoEntityAnnotationReader reader * @param $property string property name * @param $value mixed value * @return Ficus_ScaffoldPart part */ protected function buildPart($reader, $property, $value, $setting){ $type = $reader->type($property); $label = $reader->label($property); $remark = $reader->remark($property); $datatype = $reader->datatype($property); $validators = $setting[self::REGISTRY_VALIDATORS]; $constraint = $setting[self::REGISTRY_CONSTRAINT]; $part = Ficus_ScaffoldPartsFactory::create( $property, $type, $datatype); $part->setEntity($reader->getTarget()); $part->setName($property); $part->setType($type); $part->setLabel($label); $part->setRemark($remark); $part->setValidators($validators); $part->setConstraint($constraint); if($value instanceof Ficus_S2DaoEntity){ $parts = $this->buildParts($value); foreach($parts as $child){ $child->setParent($part); } $part->setParts($parts); } $part->setValue($value); return $part; } } ?>ficus/pages/scaffold/builder/ScaffoldBuilder.php100644 1751 144 2204 10645132217 15434 ISHITOYA Kentaro * @version $Id: ScaffoldBuilder.php 2 2007-07-11 10:37:48Z ishitoya $ * */ /** * @class Ficus_ScaffoldBuilder */ interface Ficus_ScaffoldBuilder{ /** * build interface from entity * @param $entity Ficus_S2DaoEntity entity */ public function build($entity); } ?>ficus/pages/scaffold/ScaffoldTableConfiguration.php100644 1751 144 16016 10647426442 16235 ISHITOYA Kentaro * @version $Id: ScaffoldTableConfiguration.php 15 2007-07-18 15:02:48Z ishitoya $ * */ /** * @class Ficus_ScaffoldTableConfiguration */ class Ficus_ScaffoldTableConfiguration extends Ficus_Bean implements Ficus_ScaffoldConstants, Ficus_S2DaoModelConstants{ /** * exclude pattern */ protected $excludes = array(); /** * no label */ protected $nolabels = array(); /** * no children */ protected $noChildren = true; /** * transitions */ protected $transitions = array(); /** * current Transition */ protected $currentTransition = array(); /** * default values */ protected $defaultValues = array(); /** * property settings */ protected $properties = array(); /** * parent Part */ protected $parentPart = null; /** * check for exclude * @param $part Ficus_ScaffoldPart part to check */ public function isExcludeProperty($part){ $entityName = $this->getQname($part); if((isset($this->excludes["*"]) && in_array($part->name(), $this->excludes["*"])) || (isset($this->excludes[$entityName]) && in_array($part->name(), $this->excludes[$entityName])) || (isset($this->excludes[$entityName]) && $this->excludes[$entityName][0] == "*")){ return true; } return false; } /** * check for exclude * @param $part Ficus_ScaffoldPart part to check */ public function isNoLabelProperty($part){ $entityName = $this->getQname($part); if(array_key_exists($entityName, $this->nolabels) && $this->nolabels[$entityName] == $part->name()){ return true; } return false; } /** * check for transition property * @param $part Ficus_ScaffoldPart part to check */ public function isTransitionProperty($part){ $entityName = $this->getQname($part); if(empty($this->currentTransition)){ return true; } if($part->value() instanceof Ficus_S2DaoEntity && in_array($this->getEntityQname($part), $this->currentTransition)){ return true; } if(in_array($entityName, $this->currentTransition) == false){ return false; } return true; } /** * check is parent of transition property */ public function isTransitionParentProperty($part){ if($part->type() == self::TYPE_FOREIGN){ $parent = $this->getEntityQname($part); foreach($this->currentTransition as $transition){ if(strpos($transition, $parent) === 0){ return true; } } } return false; } /** * get default value * @param $part Ficus_ScaffoldPart part to check */ public function getDefaultValue($part){ if($part->type() != self::TYPE_LIST && $part->type() != self::TYPE_DIRECT){ return null; } $qname = $this->getQname($part) . "." . $part->name(); if(preg_match('/Direct$/', $qname) == false){ $qname .= "Direct"; } if(isset($this->defaultValues[$qname])){ return $this->defaultValues[$qname]; } return null; } /** * is no children */ public function isNoChildren(){ return $this->noChildren; } /** * ignore parts pattern * @param $entityname string ignore entity name * @param $property string when null, ignore class */ public function addExcludeProperty($entityname, $property = null){ $this->excludes[$entityname][] = $property; } /** * no label pattern */ public function addNoLabelProperty($entityname, $property = null){ $this->nolabels[$entityname] = $property; } /** * set no children * @param $noChildren boolean set to true, ignore child entities */ public function setNoChildren($noChildren){ $this->noChildren = $noChildren; } /** * set transition * @param $transition string transition */ public function setCurrentTransition($transition){ $transition = explode(",", $transition); $this->currentTransition = array(); foreach($transition as $trans){ $this->currentTransition[] = trim($trans); } } /** * set transitions * @param $transitions array transitions */ public function setTransitions($transitions){ $this->transitions = $transitions; } /** * set default values */ public function addDefaultValues($column, $value){ $this->defaultValues[$column] = $value; } /** * get qname */ protected function getQname($part){ $entityName = $part->entity()->getEntityName(); if($part->hasParent()){ $entityName = $this->getQname($part->parent()) . "." . $entityName; } return $entityName; } /** * get Entity qname */ protected function getEntityQname($part){ if(($part->value() instanceof Ficus_S2DaoEntity) == false){ return ""; } $entityName = $part->value()->getEntityName(); $qname = $this->getQname($part); return $qname . "." . $entityName; } /** * get Next transition * @param $key string current transition, if ommited, return first one * @return string next transition */ public function getNextTransition($key = null){ $transitions = $this->transitions; if(empty($transitions)){ return false; } if(is_null($key)){ return array_shift($transitions); }else{ reset($transitions); while($value = each($transitions)){ if($value["value"] == $key){ $next = each($transitions); if($next == false){ return false; } return $next["value"]; } } } return false; } } ?> ficus/pages/scaffold/templates/ScaffoldView.tpl100644 1751 144 47 10646126775 15320 {$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/form/row.tpl100644 1751 144 122 10645120161 14506 {if $nolabel == false} {$label} {/if} {$input} ficus/pages/scaffold/templates/form/select.tpl100644 1751 144 517 10645120161 15166 ficus/pages/scaffold/templates/form/input.tpl100644 1751 144 377 10647425603 15065 ficus/pages/scaffold/templates/form/table.tpl100644 1751 144 36 10645120161 14752 {$result}
ficus/pages/scaffold/templates/form/hidden.tpl100644 1751 144 72 10645120161 15116 ficus/pages/scaffold/templates/list/itemWithMenu.tpl100644 1751 144 332 10646126775 16353 {if $part->name() == "id"} {assign var="entity" value=$part->entity()} {$value} {else} {$value} {/if} ficus/pages/scaffold/templates/list/rowWithMenu.tpl100644 1751 144 372 10646126775 16230 {$result} {if $entity !== null} 編集 {/if} ficus/pages/scaffold/templates/list/headerWithMenu.tpl100644 1751 144 206 10645120161 16623 {foreach from=$labels item=label} {$label} {/foreach} {if $delete} 編集 削除 {/if} ficus/pages/scaffold/templates/list/row.tpl100644 1751 144 24 10645120161 14477 {$result} ficus/pages/scaffold/templates/list/item.tpl100644 1751 144 23 10645120161 14625 {$value} ficus/pages/scaffold/templates/list/header.tpl100644 1751 144 117 10645120161 15143 {foreach from=$labels item=label} {$label} {/foreach} ficus/pages/scaffold/templates/list/table.tpl100644 1751 144 121 10645120161 14775 {$header} {foreach from=$rows item=row} {$row} {/foreach}
ficus/pages/scaffold/templates/view/row.tpl100644 1751 144 122 10645120161 14515 {if $nolabel == false} {$label} {/if} {$value} ficus/pages/scaffold/templates/view/table.tpl100644 1751 144 36 10645120161 14761 {$result}
ficus/pages/scaffold/templates/ScaffoldSubmit.tpl100644 1751 144 47 10645120161 15627 {$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/ScaffoldNewSubmit.tpl100644 1751 144 47 10645120161 16301 {$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/ScaffoldEdit.tpl100644 1751 144 562 10647425604 15307
{$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/ScaffoldList.tpl100644 1751 144 2406 10647425604 15354

æ–°è¦ä½œæˆ

{if $scaffold_helper->getDisplayPageIndexEnd()} {if $scaffold_helper->isPrev()} å‰ã®{$scaffold_helper->getLimit()}件 {/if} {section name="scaffold_page" loop=$scaffold_helper->getDisplayPageIndexEnd()+1 start=$scaffold_helper->getDisplayPageIndexBegin()} {if $smarty.section.scaffold_page.index == $scaffold_helper->getPageIndex()} {$smarty.section.scaffold_page.index+1} {else} {$smarty.section.scaffold_page.index+1} {/if} {/section} {if $scaffold_helper->isNext()} 次ã®{$scaffold_helper->getLimit()}件 {/if} {/if}
{$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/Scaffold.tpl100644 1751 144 176 10646126775 14510 {include file="header.tpl" title="$scaffold_title"}

管ç†ãƒ¡ãƒ‹ãƒ¥ãƒ¼

{$scaffold} {include file="footer.tpl"} ficus/pages/scaffold/templates/exception.tpl100644 1751 144 102 10645120161 14730

{$exception}

{$exception->getTraceAsString()}
ficus/pages/scaffold/templates/ScaffoldDeleteSubmit.tpl100644 1751 144 33 10645120161 16745

{$scaffold_message}

ficus/pages/scaffold/templates/ScaffoldEditSubmit.tpl100644 1751 144 47 10645120161 16435 {$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/ScaffoldNew.tpl100644 1751 144 1026 10647425604 15167
{$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/ScaffoldConfirm.tpl100644 1751 144 562 10647425604 16017
{$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/ScaffoldNewConfirm.tpl100644 1751 144 562 10647425604 16471
{$scaffold}

{$scaffold_message}

ficus/pages/scaffold/templates/footer.tpl100644 1751 144 20 10645120161 14207 ficus/pages/scaffold/templates/header.tpl100644 1751 144 421 10645120161 14166 {$scaffold_title}

{$scaffold_title}

ficus/pages/scaffold/templates/ScaffoldDelete.tpl100644 1751 144 760 10647425604 15624
{$scaffold} {foreach from=$scaffold_ids item=scaffold_id} {/foreach}

{$scaffold_message}

ficus/pages/PageLoader.php100644 1751 144 12240 10646126776 11237 ISHITOYA Kentaro * @version $Id: PageLoader.php 7 2007-07-14 10:55:18Z ishitoya $ */ require_once("ficus/pages/ConcretePage.php"); require_once("ficus/pages/PageModeExtractor.php"); require_once("ficus/lang/ClassLoader.php"); require_once("ficus/exception/ClassNotFoundException.php"); require_once("ficus/exception/PageNotFoundException.php"); require_once("ficus/lang/Class.php"); require_once("ficus/lang/String.php"); /** * @class Ficus_PageLoader */ class Ficus_PageLoader implements Ficus_PageConstants{ /** * page dir */ protected $pageDir = null; /** * default page */ protected $defaultPage = null; /** * prefixes */ protected $prefixes = array(); /** * suffix */ protected $suffix = self::PAGE_SUFFIX; /** * set base dir */ public function setBaseDir($base){ $this->setPageDir($base . "/" . self::PAGES_DIR); } /** * set default page * @param $pagename string default page */ public function setDefaultPage($pagename){ $this->defaultPage = $pagename; } /** * set prefixes * @param $prefixes array page class prefixes */ public function setPrefixes($prefixes){ if(is_string($prefixes)){ $prefixes = array($prefixes); } $this->prefixes = $prefixes; } /** * set suffix * @param $suffix String to set */ public function setSuffix($suffix){ $this->suffix = $suffix; } /** * load page * @param $request array of request * @return string name of found page */ public function dispatch($request){ $request = $request->requests(); foreach($request as $key => $value){ if(empty($value)){ try{ $page = $this->load($key); return $key; }catch(Ficus_PageNotFoundException $e){ } } } return $this->defaultPage; } /** * get class name * @param $prefix String prefix * @param $name String name of page * @return string classname */ protected function getClassName($prefix, $name){ $class = new Ficus_Class($name); $qname = $class->qname($prefix); return $qname . $this->getSuffix(); } /** * load page * @param $name string classname of page * @return Ficus_Page instance of page */ public function load($name){ if(empty($name)){ throw new Ficus_IllegalArgumentException("template name is empty"); } $name = str_replace("_", ".", $name); foreach($this->prefixes as $prefix){ $classname = $this->getClassName($prefix, $name); try{ $class = new Ficus_Class($classname); $package = $class->package(); $page = Ficus_ClassLoader::load($classname, array($package, $name)); }catch(Ficus_ClassNotFoundException $e){ continue; } if($page instanceof Ficus_Page){ return $page; } } $template = Ficus_PageComponentFactory::getTemplateResolver()->resolve($name); if(Ficus_PageComponentFactory::getSmarty()-> isTemplateExists($template)){ return new Ficus_ConcretePage($template, $name); } throw new Ficus_PageNotFoundException("page, $name is not found in class path"); } /** * set Pages dir * @param $pageDir string page dir */ protected function setPageDir($pageDir){ $this->pageDir = $pageDir; Ficus_ClassPath::add(new Ficus_ClassPathElement($pageDir), "pages"); Ficus_FicusPathInitializer::addIncludePath($pageDir); } /** * get suffix * @return string suffix of the page */ public function getSuffix(){ return $this->suffix; } /** * get Page name * @param $page Ficus_Page * @return string page name */ public function getPageName($page){ $classname = get_class($page); $pattern = '/(.+?)_([^_]+)' . $this->getSuffix() . '/'; if(preg_match($pattern, $classname, $regs)){ return $regs[2]; } return ""; } } ?>ficus/pages/InlinePageController.php100644 1751 144 4001 10645132217 13251 ISHITOYA Kentaro * @version $Id: InlinePageController.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/pages/PageComponentFactory.php"); /** * @class Ficus_InlinePageController */ class Ficus_InlinePageController{ /** * pages */ protected $pages = array(); /** * call function */ public function __call($name, $arguments){ $page = $this->load($name); call_user_func_array(array($page, "action"), $arguments); } /** * add pages */ protected function load($name){ if(array_key_exists($name, $this->pages) === false){ $loader = Ficus_PageComponentFactory::getInlinePageLoader(); try{ $page = $loader->load($name); if($page instanceof Ficus_InlinePage == false){ throw new Ficus_TypeMismatchException("page, $name is not instance of InlinePage"); } $this->pages[$name] = $page; }catch(Ficus_PageNotFoundException $e){ throw new Ficus_PageNotFoundException("inline page, $name is not found in class path."); } } return $this->pages[$name]; } } ?>ficus/pages/InlinePage.php100644 1751 144 2554 10645132217 11220 ISHITOYA Kentaro * @version $Id: InlinePage.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/pages/Page.php"); /** * @class Ficus_InlinePage */ abstract class Ficus_InlinePage extends Ficus_Page{ const DEFAULT_MODE = "action"; /** * get default mode * @return string default mode name */ public function getDefaultMode(){ return self::DEFAULT_MODE; } /** * on authorization */ protected function onAuthorization(){ return self::AUTHORIZATION_NOT_REQUIRED; } } ?> ficus/pages/PageConstants.php100644 1751 144 11632 10646126776 12011 ISHITOYA Kentaro * @version $Id: PageConstants.php 7 2007-07-14 10:55:18Z ishitoya $ * * Page component factory */ /** * @interface Ficus_PageConstants */ interface Ficus_PageConstants { /** * component smarty */ const COMPONENT_SMARTY = "pagesSmarty"; /** * component template resolver */ const COMPONENT_TEMPLATERESOLVER = "templateResolver"; /** * component pageLoader */ const COMPONENT_PAGELOADER = "pageLoader"; /** * component pageController */ const COMPONENT_PAGECONTROLLER = "controller"; /** * component inline page loader */ const COMPONENT_INLINEPAGELOADER = "inlinePageLoader"; /** * component inline page controller */ const COMPONENT_INLINEPAGECONTROLLER = "inlineController"; /** * component environment bean */ const COMPONENT_ENVBEAN = "envBean"; /** * component visit bean */ const COMPONENT_VISITBEAN = "visitBean"; /** * smarty cache */ const REGISTRY_SMARTY = "pages.smarty"; /** * assign name of properties */ const REGISTRY_SMARTY_PROPERTIES = "pages.smarty.properties"; /** * assign name of plugins */ const REGISTRY_SMARTY_PLUGINS = "pages.smarty.plugins"; /** * assign name of env */ const REGISTRY_SMARTY_ENV = "pages.smarty.env"; /** * assign name of visit */ const REGISTRY_SMARTY_VISIT = "pages.smarty.visit"; /** * base dir */ const REGISTRY_BASE = "pages.base"; /** * prefixes */ const REGISTRY_PREFIXES = "pages.prefixes"; /** * suffix */ const REGISTRY_SUFFIX = "pages.suffix"; /** * inline suffix */ const REGISTRY_INLINE_SUFFIX = "pages.inline.suffix"; /** * default page */ const REGISTRY_DEFAULT = "pages.default"; /** * default smarty plugins */ const DEFAULT_SMARTY_PLUGINS = "plugins"; /** * default smarty properties */ const DEFAULT_SMARTY_PROPERTIES = "properties"; /** * default smarty env */ const DEFAULT_SMARTY_ENV = "env"; /** * default smarty visit */ const DEFAULT_SMARTY_VISIT = "visit"; /** * default suffix */ const DEFAULT_SUFFIX = "Page"; /** * default inline suffix */ const DEFAULT_INLINE_SUFFIX = "InlinePage"; /** * default default page */ const DEFAULT_DEFAULT = "Index"; /** * default mode */ const PAGE_DEFAULT_MODE = "default"; /** * page exception */ const PAGE_ERROR = "error"; /** * page exception */ const PAGE_EXCEPTION = "exception"; /** * page exception template */ const REGISTRY_EXCEPTION_TEMPLATE = "exception.tpl"; /** * page exception template */ const DEFAULT_EXCEPTION_TEMPLATE = "exception.tpl"; /** * pagename */ const PAGENAME = "pagename"; /** * actionname */ const ACTIONNAME= "actioname"; /** * not display */ const NODISPLAY = "nodisplay"; /** * get template as mode template */ const MODE_TEMPLATE = "modetemplate"; /** * current page name */ const CURRENT_PAGENAME = "currentPage"; /** * fowarded */ const FORWARDED = "forwarded"; /** * authorization not required */ const AUTHORIZATION_NOT_REQUIRED = "authorization not required"; /** * auth user name */ const KEY_USER = "PHP_AUTH_USER"; /** * auth password */ const KEY_PASSWORD = "PHP_AUTH_PW"; /** * fail counts */ const AUTH_FAILUER_COUNT = "auth_failuer_count"; /** * guest user */ const USER_GUEST = "__guest"; /** * pages dir */ const PAGES_DIR = "pages"; /** * page class suffix */ const PAGE_SUFFIX = "Page"; /** * template dir */ const TEMPLATES_DIR = "templates"; /** * template name */ const TEMPLATE_NAME = "pages"; } ?> ficus/pages/PageTemplateResolver.php100644 1751 144 4673 10646126776 13321 ISHITOYA Kentaro * @version $Id: PageTemplateResolver.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/pages/ConcretePage.php"); require_once("ficus/pages/PageController.php"); /** * @class Ficus_PageTemplateResolver */ class Ficus_PageTemplateResolver{ /** * get full path of the template * @param $template string template name * @return string fullpath of the template */ public function getFullPath($template){ $path = $this->templateDir . "/" . $template; return Ficus_Dir::normalize($path); } /** * search template * @param $page Ficus_Page page object * @param $mode string mode * @return String filename */ public function resolve($page, $mode = null){ if($page instanceof Ficus_Page){ $class = new Ficus_Class($page); $package = str_replace(".", "/", $page->getPackage()); $template = $class->shortname(); $suffix = Ficus_PageComponentFactory::getPageLoader()->getSuffix(); $template = substr($template, 0, strpos($template, $suffix)); }else if(is_string($page)){ $class = new Ficus_Class($page); $package = $class->package(); $template = $class->shortname(); }else{ throw new Ficus_IllegalArgumentException("page is not Ficus_Page nor string"); } if(is_null($mode) == false){ $template .= ucfirst($mode); } if(empty($package)){ return $template; }else{ return str_replace(".", "/", $package) . "/" . $template; } } } ?>ficus/pages/BufferedPage.php100644 1751 144 5614 10645132217 11524 ISHITOYA Kentaro * @version $Id: BufferedPage.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/pages/PageConstants.php"); require_once("ficus/pages/PageComponentFactory.php"); require_once("ficus/exception/PropertyNotFoundException.php"); require_once("ficus/exception/MethodNotFoundException.php"); require_once("ficus/pages/AbstractPage.php"); /** * @class Ficus_Page */ abstract class Ficus_BufferedPage extends Ficus_AbstractPage{ /** * @var $fetchOutput boolean */ protected $outputBuffering = false; /** * @var $buffer string */ protected $buffer = ""; /** * caller method * @param $name string name of method * @param $args array array of parameter * @return mixed method result */ public function __call($name, $args){ $result = parent::__call($name, $args); if($this->outputBuffering){ return $this->buffer; } return $result; } /** * fetch template * @param $template string template name * @return string fetched string */ protected function fetch($template = null){ $result = parent::fetch($template); if($this->outputBuffering){ $this->buffer .= $result; } return $result; } /** * display template * @param $template string template name * @return mixed return value of display */ protected function display($template = null){ if($this->outputBuffering){ return $this->fetch($template); } return parent::display($template); } /** * set output buffering */ public function enableOutputBuffering(){ $this->outputBuffering = true; } /** * disable output buffering */ public function disableOutputBuffering(){ $this->outputBuffering = false; } /** * get buffer */ public function getBuffer(){ return $this->buffer; } /** * clear buffer */ public function clearBuffer(){ $this->buffer = ""; } } ?> ficus/pages/PageRequest.php100644 1751 144 6705 10647426442 11444 ISHITOYA Kentaro * @version $Id: PageRequest.php 15 2007-07-18 15:02:48Z ishitoya $ */ /** * @class Ficus_PageRequest */ class Ficus_PageRequest extends Ficus_Bean{ protected $post = array(); protected $get = array(); protected $requests = array(); /** * construct */ public function __construct($args = array()){ $this->post = $_POST; $this->get = $_GET; $this->requests = $this->createArguments($args); } /** * create args * merge post, get and drop filename * @param $args array of argument * @return Array of arguments */ protected function createArguments($args){ $request = array_merge($_POST, $_GET); array_shift($args); array_shift($args); array_shift($args); $result = array(); foreach($args as $arg){ if(is_array($arg)){ $result[key($arg)] = $arg[key($arg)]; } } foreach($request as $key => $arg){ $result[$key] = $arg; } return $result; } /** * extract * @param $args array of arguments * @param $name string name of the argument * @param $type string type of the argument * @return integer id */ protected function extract($name, $type = "int"){ $args = $this->requests; if(isset($args[$name]) == false){ return null; } $argument = $args[$name]; if(is_string($argument)){ $argument = trim($argument); $argument = Ficus_Types::cast($argument, $type); Ficus_Assert::isPrimitiveType($argument, $type); }else if(is_array($argument)){ foreach($argument as $key => $value){ $value = trim($value); $value = Ficus_Types::cast($value, $type); Ficus_Assert::isPrimitiveType($value, $type); $argument[$key] = $value; } } return $argument; } /** * has */ public function has($name){ return isset($this->requests[$name]); } /** * call */ public function __call($name, $arguments){ if(preg_match('/^extractAs(.*)$/', $name, $regs)){ $type = strtolower(trim($regs[1])); return $this->extract($arguments[0], $type); }else if(preg_match('/^has(.*?)$/', $name, $regs)){ $string = new Ficus_String($regs[1]); $name = $string->lowerCaseFirst(); $name = $name->__toString(); return $this->has($name); } return parent::__call($name, $arguments); } } ?> ficus/pages/components21.dtd100644 1751 144 2773 10645120161 11517 ficus/pages/ConcretePage.php100644 1751 144 4407 10645132217 11543 ISHITOYA Kentaro * @version $Id: ConcretePage.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/pages/BufferedPage.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Soya_ConcretePage */ class Ficus_ConcretePage extends Ficus_BufferedPage{ const DEFAULT_MODE = "default"; /** * @var $template template */ protected $template = ""; /** * constructor * @param $template string template name * @param $name string page name */ public function __construct($template, $name){ $this->template = $template; parent::__construct("", $name); } /** * get default mode * @return string default mode name */ public function getDefaultMode(){ return self::DEFAULT_MODE; } /** * on called * @param $mode string name of mode * @param $args array of args of do method */ protected function onDo($mode, $args){ } /** * on exception * @param $mode string name of mode * @param $args array of args of do method * @param $exception Exception exception */ protected function onException($mode, $args, $exception){ $this->assign("exception", $exception); $this->display($this->template); } /** * show default */ public function doDefault(){ $this->display($this->template); return self::NODISPLAY; } } ?>ficus/pages/pages.dicon100644 1751 144 6025 10646126776 10624 Ficus_Registry::search(Ficus_PageConstants::REGISTRY_SMARTY) Ficus_Registry::search(Ficus_PageConstants::REGISTRY_SMARTY_PROPERTIES) Ficus_Registry::getInstance() Ficus_Registry::search(Ficus_PageConstants::REGISTRY_SMARTY_PLUGINS) Ficus_PageComponentFactory::getInlinePageController() Ficus_Registry::search(Ficus_PageConstants::REGISTRY_SMARTY_ENV) envBean Ficus_Registry::search(Ficus_PageConstants::REGISTRY_SMARTY_VISIT) visitBean Ficus_Registry::search(Ficus_PageComponentFactory::REGISTRY_BASE) Ficus_Registry::search(Ficus_PageConstants::REGISTRY_DEFAULT) Ficus_Registry::search(Ficus_PageConstants::REGISTRY_SUFFIX) Ficus_Registry::search(Ficus_PageComponentFactory::REGISTRY_BASE) Ficus_Array::stringToArray( Ficus_Registry::search( Ficus_PageComponentFactory::REGISTRY_PREFIXES)) Ficus_Registry::search(Ficus_PageConstants::REGISTRY_INLINE_SUFFIX) Ficus_Registry::search(Ficus_PageComponentFactory::REGISTRY_BASE) Ficus_Array::stringToArray( Ficus_Registry::search( Ficus_PageComponentFactory::REGISTRY_PREFIXES)) ficus/pages/PageModeExtractor.php100644 1751 144 5267 10646126776 12604 ISHITOYA Kentaro * @version $Id: PageModeExtractor.php 7 2007-07-14 10:55:18Z ishitoya $ */ require_once("ficus/lang/ClassLoader.php"); /** * @class Ficus_PageModeExtractor */ class Ficus_PageModeExtractor{ /** * modes */ private $modes = array(); /** * default mode */ private $defaultMode = null; /** * construct with modes * @param $modes Ficus_Page of modes */ public function __construct($page){ $modes = $this->extractModes($page); foreach($modes as $mode){ $this->addMode($mode); } } /** * add mode * @param $mode string name of mode */ public function addMode($mode){ $this->modes[trim($mode)] = trim($mode); } /** * set default mode * @param $defaultMode string default mode name */ public function setDefaultMode($defaultMode){ $this->defaultMode = $defaultMode; } /** * get mode * @return string mode */ public function getMode(){ if(empty($_REQUEST)){ return $this->defaultMode; }else{ $keys = array_keys($_REQUEST); foreach($keys as $key){ if(preg_match('/^(.*)_([^_]+)$/', $key, $matches)){ $prefix = $matches[1]; if(array_key_exists($prefix, $this->modes)){ return $this->modes[$prefix]; } } if(array_key_exists($key, $this->modes)){ return $this->modes[$key]; } } } return $this->defaultMode; } /** * extract mode from $_REQUEST * @param $page Ficus_Page target page * @return array array of modes */ private function extractModes($page){ $modes = array(); return $page->getModes(); } } ?>ficus/pages/PageComponentFactory.php100644 1751 144 16423 10647425604 13323 ISHITOYA Kentaro * @version $Id: PageComponentFactory.php 14 2007-07-18 14:55:12Z ishitoya $ * * Page component factory */ require_once("ficus/io/File.php"); require_once("ficus/config/Registry.php"); require_once("ficus/lang/AutoLoad.php"); require_once("ficus/lang/S2ContainerAutoLoad.php"); require_once("ficus/lang/ClassLoaderAutoLoad.php"); require_once("ficus/pages/PageController.php"); require_once("ficus/pages/InlinePageController.php"); require_once("ficus/pages/PageLoader.php"); require_once("ficus/pages/PageTemplateResolver.php"); require_once("ficus/pages/PageConstants.php"); require_once("ficus/pages/beans/PageEnvironmentsBean.php"); require_once("ficus/pages/beans/PageVisitBean.php"); require_once("ficus/lang/Array.php"); /** * @class Ficus_PageComponentFactory */ class Ficus_PageComponentFactory extends Ficus_S2ContainerComponentFactory implements Ficus_PageConstants{ /** * dicon file name registry key */ const REGISTRY_DICON_FILENAME = "pages.dicon"; /** * dicon namespace registry key */ const REGISTRY_DICON_NAMESPACE = "pages.namespace"; /** * Default dicon file name. */ const DEFAULT_DICON_FILENAME = 'pages.dicon'; /** * dicon namespace. */ const DEFAULT_DICON_NAMESPACE = 'pages.scheme'; /** * get Dicon file name from registry * @return string dicon filename */ protected function getDiconFileNameRegistry(){ return self::REGISTRY_DICON_FILENAME; } /** * get Dicon namespace from registry * @return string dicon namespace */ protected function getDiconNameSpaceRegistry(){ return self::REGISTRY_DICON_NAMESPACE; } /** * get dicon file name * @return string dicon file name */ protected function getDefaultDiconFileName(){ return Ficus_File::currentDir() ->resolve(self::DEFAULT_DICON_FILENAME)->getPath(); } /** * get defoult dicon namespace * @return string dicon namespace */ protected function getDefaultDiconNameSpace(){ return self::DEFAULT_DICON_NAMESPACE; } /** * get component * @param $name string name of component * @param $class string class name * @return Ficus_ScaffoldComponentFactory */ public static function getComponent($name, $class = __CLASS__){ return parent::getComponent($name, $class); } /** * check registry */ protected function checkForRegistry(){ if(Ficus_Registry::search(self::REGISTRY_SMARTY) == false){ throw new Ficus_PropertyNotFoundException("property " . self::REGISTRY_SMARTY . " must be loaded before ComponentFactory initialization"); }else if(Ficus_Registry::search(self::REGISTRY_BASE) == false){ throw new Ficus_PropertyNotFoundException("property " . self::REGISTRY_BASE . " must be loaded before ComponentFactory initialization"); }else if(Ficus_Registry::search(self::REGISTRY_PREFIXES) == false){ throw new Ficus_PropertyNotFoundException("property " . self::REGISTRY_PREFIXES . " must be loaded before ComponentFactory initialization"); } if(Ficus_Registry::search(self::REGISTRY_SMARTY_PROPERTIES) == false){ Ficus_Registry::regist(self::REGISTRY_SMARTY_PROPERTIES, self::DEFAULT_SMARTY_PROPERTIES); } if(Ficus_Registry::search(self::REGISTRY_SMARTY_PLUGINS) == false){ Ficus_Registry::regist(self::REGISTRY_SMARTY_PLUGINS, self::DEFAULT_SMARTY_PLUGINS); } if(Ficus_Registry::search(self::REGISTRY_SMARTY_ENV) == false){ Ficus_Registry::regist(self::REGISTRY_SMARTY_ENV, self::DEFAULT_SMARTY_ENV); } if(Ficus_Registry::search(self::REGISTRY_SMARTY_VISIT) == false){ Ficus_Registry::regist(self::REGISTRY_SMARTY_VISIT, self::DEFAULT_SMARTY_VISIT); } if(Ficus_Registry::search(self::REGISTRY_DEFAULT) == false){ Ficus_Registry::regist(self::REGISTRY_DEFAULT, self::DEFAULT_DEFAULT); } if(Ficus_Registry::search(self::REGISTRY_SUFFIX) == false){ Ficus_Registry::regist(self::REGISTRY_SUFFIX, self::DEFAULT_SUFFIX); } if(Ficus_Registry::search(self::REGISTRY_INLINE_SUFFIX) == false){ Ficus_Registry::regist(self::REGISTRY_INLINE_SUFFIX, self::DEFAULT_INLINE_SUFFIX); } } /** * get Smarty * @return Smarty smarty view controller */ public static function getSmarty(){ return self::getComponent(self::COMPONENT_SMARTY); } /** * get template resolver * @return Ficus_PageTemplateResolver template resolver */ public static function getTemplateResolver(){ return self::getComponent(self::COMPONENT_TEMPLATERESOLVER); } /** * get page loader * @return Ficus_PageLoader page loader */ public static function getPageLoader(){ return self::getComponent(self::COMPONENT_PAGELOADER); } /** * get page controller * @return Ficus_PageController controller */ public static function getPageController(){ return self::getComponent(self::COMPONENT_PAGECONTROLLER); } /** * get page loader * @return Ficus_PageLoader page loader */ public static function getInlinePageLoader(){ return self::getComponent(self::COMPONENT_INLINEPAGELOADER); } /** * get inline page controller * @return Ficus_InlinePageController controller */ public static function getInlinePageController(){ return self::getComponent(self::COMPONENT_INLINEPAGECONTROLLER); } /** * get environment bean * @return Ficus_PageEnvironmentsBean */ public static function getEnvBean(){ return self::getComponent(self::COMPONENT_ENVBEAN); } /** * get visit bean * @return Ficus_PageVisitBean */ public static function getVisitBean(){ return self::getComponent(self::COMPONENT_VISITBEAN); } /** * Get Authentication */ public static function getAuthorization($page){ Ficus_Assert::isInstanceOf($page, "Ficus_Page"); $name = $page->getPagename() . "PageAuthorization"; return self::getComponent($name); } } ?> ficus/pages/Page.php100644 1751 144 22752 10646126776 10121 ISHITOYA Kentaro * @version $Id: Page.php 7 2007-07-14 10:55:18Z ishitoya $ */ require_once("ficus/pages/PageConstants.php"); require_once("ficus/pages/PageComponentFactory.php"); require_once("ficus/exception/PropertyNotFoundException.php"); require_once("ficus/exception/MethodNotFoundException.php"); /** * @class Ficus_Page */ abstract class Ficus_Page extends Ficus_Bean implements Ficus_PageConstants{ /** * @var $package string package */ protected $package = null; /** * @var $pagename string pagename */ protected $pagename = null; /** * @var $request Ficus_PageRequest */ protected $request = null; /** * @var $currentAction string action */ protected $currentAction = null; /** * @var $nextAction string next action */ protected $nextAction = null; /** * constructor * @param $package string package name * @param $pagename string pagename */ public function __construct($package, $pagename){ $this->package = $package; $this->pagename = $pagename; $this->onConstruct(); } /** * check for method existance */ protected function methodExists($method){ return method_exists($this, $method); } /** * caller method * @param $name string name of method * @param $args array array of parameter * @return mixed method result */ public function __call($name, $args){ $method = "do" . ucfirst($name); if($this->methodExists($method) == false){ return parent::__call($name, $args); } $this->currentAction = $name; try{ $this->assign(self::CURRENT_PAGENAME, $this->pagename); $args = $args[0]; Ficus_Assert::isInstanceOf($args, "Ficus_PageRequest"); $this->request = $args; $this->onDo($name, $args); $result = call_user_func(array($this, $method), $args); $this->onDone($name, $args, $result); }catch(Exception $e){ $this->assign(self::PAGE_EXCEPTION, $e); $this->onException($name, $args, $e); $result = ""; } return $result; } /** * get default mode * @return string default mode name */ abstract public function getDefaultMode(); /** * on construct */ abstract protected function onConstruct(); /** * on exception * @param $mode string name of mode * @param $args array of args of do method * @param $exception Exception exception */ abstract protected function onException($mode, $args, $exception); /** * on called * @param $mode string name of mode * @param $args array of args of do method */ abstract protected function onDo($mode, $args); /** * on execute finished * @param $mode string name of mode * @param $args array of args of do method * @param $result mixed switch */ protected function onDone($mode, $args, $result){ if($result == self::NODISPLAY){ return; }else if($result == self::MODE_TEMPLATE){ $this->display($this->getModeTemplate($mode)); }else if(is_string($result)){ $this->display($result); }else if(is_array($result) && isset($result[self::PAGENAME])){ if(isset($result[self::ACTIONNAME])){ $this->forward($result[self::PAGENAME], $result[self::ACTIONNAME]); }else{ $this->forward($result[self::PAGENAME]); } }else{ $this->display(); } } /** * authorization */ public function authorization(){ $retval = $this->onAuthorization(); if($retval !== self::FORWARDED && $retval !== self::AUTHORIZATION_NOT_REQUIRED){ throw new Ficus_InvalidImplementationException(get_class($this) . "::onAuthorization not valid. please check out it returns FORWARDED or AUTHORIZATION_NOT_REQUIRED."); } return $retval; } /** * on authorization */ abstract protected function onAuthorization(); /** * get modes */ public function getModes(){ $class = new ReflectionClass(get_class($this)); $methods = $class->getMethods(); foreach($methods as $method){ if(preg_match('/^do(.+)$/', $method->getName(), $matches)){ $mode = $matches[1]; $mode = strtolower(substr($mode, 0, 1)) . substr($mode, 1); $modes[] = $mode; } } return $modes; } /** * forward * @param $pagename string target pagename * @param $actionname string actionname */ protected function forward($pagename, $actionname = null, $buffering = false){ $controller = Ficus_PageComponentFactory::getPageController(); return $controller->execute($pagename, $actioname, $buffering); } /** * move * @param $pagename string target pagename * @param $actionname string actionname */ protected function move($pagename = "", $actionname = null){ $self = $_SERVER["PHP_SELF"]; if(preg_match('/(.*?)index.php$/', $self, $regs)){ $self = $regs[1]; } if($pagename == ""){ header("Location: $self"); }else{ header("Location: $self?$pagename"); } } /** * fetch template * @param $template string template name * @return string fetched string */ protected function fetch($template = null){ if(is_null($template)){ $template = Ficus_PageComponentFactory::getTemplateResolver()->resolve($this); } return Ficus_PageComponentFactory::getSmarty()->fetch($template); } /** * display template * @param $template string template name * @return mixed return value of display */ protected function display($template = null){ if(is_null($template)){ $template = Ficus_PageComponentFactory::getTemplateResolver()->resolve($this); } return Ficus_PageComponentFactory::getSmarty()->display($template); } /** * assign value to name * @param $name string name to assign * @param $value string value to assign * @return string return value of assign */ protected function assign($name, $value){ return Ficus_PageComponentFactory::getSmarty()->assign($name, $value); } /** * assign reference to name * @param $name string name to assign * @param $value string value to assign * @return string return value of assign */ protected function assignReference($name, $value){ return Ficus_PageComponentFactory::getSmarty()->assign_by_ref($name, $value); } /** * show error * @param $message string error message */ public function error($message){ $this->assign(self::PAGE_ERROR, $message); } /** * get property from registry * @param $name string name of key * @return string value */ protected function property($name){ $property = Ficus_Registry::search($name); if($property === false){ throw new Ficus_PropertyNotFoundException("property $name is not registered in Ficus_Registry"); } return $property; } /** * get env bean * @param $name string name of key * @return string value, if null specified in name then return whole values */ protected function env($name = null){ $env = Ficus_PageComponentFactory::getEnvBean()->values(); if(is_null($name)){ return $env; } if(isset($env[$name]) == false){ throw new Ficus_PropertyNotFoundException("property $name is not found in _ENV and _SERVER"); } return $env[$name]; } /** * get visit bean * @return Ficus_PageVisitBean session information */ protected function visit(){ return Ficus_PageComponentFactory::getVisitBean(); } /** * set next action * @param $action string mode name */ protected function setNextAction($action){ $this->assign("nextAction", $action); $this->nextAction = $action; } /** * get mode template * @param $mode string mode * @return string template name */ protected function getModeTemplate($mode){ return Ficus_PageComponentFactory::getTemplateResolver()->resolve($this, $mode); } } ?> ficus/pages/AuthorizationComponent.php100644 1751 144 2240 10647426442 13730 ISHITOYA Kentaro * @version $Id: AuthorizationComponent.php 15 2007-07-18 15:02:48Z ishitoya $ */ /** * @class Ficus_AuthorizationComponent */ class Ficus_AuthorizationComponent{ /** * check authorization */ public function check(){ //do nothing, to run intercepter to check authority } } ?>ficus/pages/templates/exception.tpl100644 1751 144 102 10645120161 13147

{$exception}

{$exception->getTraceAsString()}
ficus/exception/PageNotFoundException.php100644 1751 144 2314 10645132217 14306 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: PageNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * * Class not Found Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_PageNotFoundException */ class Ficus_PageNotFoundException extends Ficus_Exception { } ?> ficus/exception/URISyntaxException.php100644 1751 144 2244 10645132217 13625 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: URISyntaxException.php 2 2007-07-11 10:37:48Z ishitoya $ * * URI Syntax Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_URISyntaxException */ class Ficus_URISyntaxException extends Ficus_Exception { } ?> ficus/exception/AssertException.php100644 1751 144 2220 10645132217 13212 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: AssertException.php 2 2007-07-11 10:37:48Z ishitoya $ * * Assert Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_AssertException */ class Ficus_AssertException extends Ficus_Exception { } ?> ficus/exception/SQLException.php100644 1751 144 2176 10645132217 12422 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: SQLException.php 2 2007-07-11 10:37:48Z ishitoya $ * * SQL Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_SQLException */ class Ficus_SQLException extends Ficus_Exception { } ?> ficus/exception/MultipleFileFoundException.php100644 1751 144 2216 10645132217 15345 SUMI Masafumi * @version $Id: MultipleFileFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * File not Found Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_MultipleFileFoundException */ class Ficus_MultipleFileFoundException extends Ficus_Exception { } ?> ficus/exception/IllegalAccessException.php100644 1751 144 2076 10645120256 14455 SUMI Masafumi * @version $Id: * Illegal access exception class. */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_IllegalAccessException */ class Ficus_IllegalAccessException extends Ficus_Exception { } ?> ficus/exception/PropertyNotFoundException.php100644 1751 144 2142 10645132217 15255 ISHITOYA Kentaro * @version $Id: PropertyNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_PropertyNotFoundException */ class Ficus_PropertyNotFoundException extends Ficus_Exception { } ?> ficus/exception/ConstantNotFoundException.php100644 1751 144 2142 10645132217 15222 ISHITOYA Kentaro * @version $Id: ConstantNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_ConstantNotFoundException */ class Ficus_ConstantNotFoundException extends Ficus_Exception { } ?> ficus/exception/IllegalTypeException.php100644 1751 144 2355 10645132217 14175 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: IllegalTypeException.php 2 2007-07-11 10:37:48Z ishitoya $ * * this Exception will thrown when type is invalid * @see ficus/primitive/Parameter.php */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_IllegalTypeException */ class Ficus_IllegalTypeException extends Ficus_Exception { } ?> ficus/exception/FileNotFoundException.php100644 1751 144 2172 10645132217 14313 SUMI Masafumi * @version $Id: FileNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * File not Found Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_FileNotFoundException */ class Ficus_FileNotFoundException extends Ficus_Exception { } ?> ficus/exception/Exception.php100644 1751 144 6254 10645132217 12043 SUMI Masafumi * @version $Id: Exception.php 2 2007-07-11 10:37:48Z ishitoya $ * * Soya base exception. */ /** * @class Ficus_Exception */ class Ficus_Exception extends Exception { /** * Cause of exception. */ protected $cause = null; /** * Constructor. */ public function __construct() { $message = null; $code = 0; foreach (func_get_args() as $arg) { if ($arg instanceof Ficus_Exception) { $this->cause = $arg; } else if (is_string($arg)) { $message = $arg; } else if (is_numeric($arg)) { $code = $arg; } else { assert(false, "Invalid argument in exception."); } } parent::__construct($message, $code); } /** * Set cause of exception. * * Set cause of exception. * * @param $cause Exception cause of exception. * @return Ficus_Exception $this */ public function initCause($cause) { $this->cause = $cause; return $this; } /** * Cause of exception. * * Cause of exception. * * @return Exception cause of exception. */ public final function getCause() { return $this->cause; } /** * Get stack trace. * * @return array stack trace. */ public function getStackTraceArray() { if ($this->getCause()) { return array_merge(array(get_class($this) . ': "' . $this->getMessage() . '"'), $this->getCause()->getStackTraceArray()); } else { return array(get_class($this) . ': "' . $this->getMessage() . '"'); } } /** * Get stack trace string. * * @return string stack trace. */ public function getStackTrace() { return join(" \n", $this->getStackTraceArray()); } /** * create exception string * * @return string error string */ public function toString(){ $file = basename($this->getFile()) . ":" . $this->getLine(); return $file . " : " . $this->getStackTrace(); } /** * create exception string * * @return string error string */ public function __toString(){ $file = basename($this->getFile()) . ":" . $this->getLine(); return $file . " : " . $this->getStackTrace(); } } ?> ficus/exception/ClassCastException.php100644 1751 144 2135 10645132217 13636 ISHITOYA Kentaro * @version $Id: ClassCastException.php 2 2007-07-11 10:37:48Z ishitoya $ * * class cast exception. */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_ClassCastException */ class Ficus_ClassCastException extends Ficus_Exception { } ?> ficus/exception/AlgorithmNotFoundException.php100644 1751 144 2251 10645132217 15360 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: AlgorithmNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_AlgorithmNotFoundException */ class Ficus_AlgorithmNotFoundException extends Ficus_Exception { } ?> ficus/exception/SoapFaultException.php100644 1751 144 2204 10645132217 13651 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: SoapFaultException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_SoapFaultException */ class Ficus_SoapFaultException extends Ficus_Exception { } ?> ficus/exception/MethodNotFoundException.php100644 1751 144 2326 10645132217 14655 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: MethodNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * * Method not Found Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_MethodNotFoundException */ class Ficus_MethodNotFoundException extends Ficus_Exception { } ?> ficus/exception/InvalidImplementationException.php100644 1751 144 2363 10645132217 16255 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: InvalidImplementationException.php 2 2007-07-11 10:37:48Z ishitoya $ * * this Exception will thrown when argument is invalid */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_InvalidImplementationException */ class Ficus_InvalidImplementationException extends Ficus_Exception { } ?> ficus/exception/IllegalArgumentException.php100644 1751 144 2333 10645132217 15032 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: IllegalArgumentException.php 2 2007-07-11 10:37:48Z ishitoya $ * * this Exception will thrown when argument is invalid */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_IllegalArgumentException */ class Ficus_IllegalArgumentException extends Ficus_Exception { } ?> ficus/exception/CommandNotFoundException.php100644 1751 144 2236 10645132217 15013 ISHITOYA Kentaro * @version $Id: CommandNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * * Command not Found Exception Command */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_CommandNotFoundException */ class Ficus_CommandNotFoundException extends Ficus_Exception { } ?> ficus/exception/ValidationException.php100644 1751 144 2353 10645132217 14052 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ValidationException.php 2 2007-07-11 10:37:48Z ishitoya $ * * this Exception will thrown when validation failed * @see ficus/validator/Validator.php */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_ValidationException */ class Ficus_ValidationException extends Ficus_Exception { } ?> ficus/exception/IllegalRDFSchemaException.php100644 1751 144 2334 10645132217 15005 OOTA Ikito * @author SUMI Masafumi * @version $Id: IllegalRDFSchemaException.php 2 2007-07-11 10:37:48Z ishitoya $ * * this Exception will thrown when argument is invalid */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_IllegalRDFSchemaException */ class Ficus_IllegalRDFSchemaException extends Ficus_Exception { } ?> ficus/exception/BeanNotFoundException.php100644 1751 144 2225 10645132217 14300 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: BeanNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_BeanNotFoundException */ class Ficus_BeanNotFoundException extends Ficus_Exception { } ?> ficus/exception/TokenNotFoundException.php100644 1751 144 2275 10645132217 14520 OOTA Ikito * @author SUMI Masafumi * @version $Id: TokenNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * Token not Found Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_TokenNotFoundException */ class Ficus_TokenNotFoundException extends Ficus_Exception { } ?> ficus/exception/DirException.php100644 1751 144 2074 10645132217 12476 SUMI Masafumi * @version $Id: DirException.php 2 2007-07-11 10:37:48Z ishitoya $ * Dir Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_DirException */ class Ficus_DirException extends Ficus_Exception { } ?> ficus/exception/MultipleClassDefinitionFoundException.php100644 1751 144 2403 10645132217 17542 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: MultipleClassDefinitionFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * * Class not Found Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_MultipleClassDefinitionFoundException */ class Ficus_MultipleClassDefinitionFoundException extends Ficus_Exception { } ?> ficus/exception/GeneratorNotFoundException.php100644 1751 144 2335 10645132217 15363 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: GeneratorNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * * Generator not Found Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_GeneratorNotFoundException */ class Ficus_GeneratorNotFoundException extends Ficus_Exception { } ?> ficus/exception/ClassNotFoundException.php100644 1751 144 2320 10645132217 14474 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ClassNotFoundException.php 2 2007-07-11 10:37:48Z ishitoya $ * * Class not Found Exception Class */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_ClassNotFoundException */ class Ficus_ClassNotFoundException extends Ficus_Exception { } ?> ficus/exception/NotImplementedException.php100644 1751 144 2233 10645132217 14701 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NotImplementedException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_NotImplementedException */ class Ficus_NotImplementedException extends Ficus_Exception { } ?> ficus/exception/NotReadyException.php100644 1751 144 2203 10645132217 13477 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NotReadyException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_NotReadyException */ class Ficus_NotReadyException extends Ficus_Exception { } ?> ficus/exception/IllegalBeanException.php100644 1751 144 2217 10645132217 14116 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: IllegalBeanException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_IllegalBeanException */ class Ficus_IllegalBeanException extends Ficus_Exception { } ?> ficus/exception/IllegalAnnotationException.php100644 1751 144 2243 10645132217 15362 ISHITOYA Kentaro * @version $Id: IllegalAnnotationException.php 2 2007-07-11 10:37:48Z ishitoya $ * * this Exception will thrown when argument is invalid */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_IllegalAnnotationException */ class Ficus_IllegalAnnotationException extends Ficus_Exception { } ?> ficus/exception/TypeMismatchException.php100644 1751 144 2144 10645132217 14365 SUMI Masafumi * @version $Id: TypeMismatchException.php 2 2007-07-11 10:37:48Z ishitoya $ * * Type mismatch. */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_TypeMismatchException */ class Ficus_TypeMismatchException extends Ficus_Exception { } ?> ficus/exception/NotSupportedException.php100644 1751 144 2223 10645132217 14422 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NotSupportedException.php 2 2007-07-11 10:37:48Z ishitoya $ */ require_once("ficus/exception/Exception.php"); /** * @class Ficus_NotSupportedException */ class Ficus_NotSupportedException extends Ficus_Exception { } ?> ficus/template/smarty/smarty.dicon100644 1751 144 346 10645120161 13034 ficus/template/smarty/Smarty.php100644 1751 144 11404 10647426442 12541 ISHITOYA Kentaro * @version $Id: Smarty.php 15 2007-07-18 15:02:48Z ishitoya $ * */ require_once("ficus/lang/Assert.php"); /** * @class Ficus_Smarty */ class Ficus_Smarty{ const TEMPLATE_SUFFIX = ".tpl"; /** * smarty */ protected $smarty = null; /** * system paths */ protected $paths = array(); /** * user paths */ protected $userPaths = array(); /** * constructor * @param $templateDir string template Dir * @param $cacheDir string cache Dir */ public function __construct($cacheDir = null){ $this->smarty = Ficus_SmartyComponentFactory::getSmarty(); $this->setCacheDir($cacheDir); } /** * set template dir * default load path for smarty include */ public function setTemplateDir($dir){ $this->smarty->template_dir = $dir; } /** * add path */ public function addPath($name, $path){ if(is_dir($path) == false){ throw new Ficus_IllegalArgumentException("$path is not readable"); } $this->paths[$name] = new Ficus_ClassPathElement($path); } /** * add user dir */ public function addUserPath($name, $path){ if(is_dir($path) == false){ throw new Ficus_IllegalArgumentException("$path is not a directory"); } $this->userPaths[$name] = new Ficus_ClassPathElement($path); } /** * set cache dir */ public function setCacheDir($cacheDir){ $this->smarty->compile_dir = $cacheDir; } /** * set id */ public function setCompileId($id){ $this->smarty->compile_id = $id; } /** * search for template */ protected function search($template){ $template = new Ficus_File($template); if(is_null($template->getExtension())){ $template->add(self::TEMPLATE_SUFFIX); } $template = $template->normalize(); $template = $template->getPath(); $paths = array(); foreach($this->userPaths as $path){ $paths = array_merge($path->search($template), $paths); } if(empty($paths)){ foreach($this->paths as $path){ $paths = array_merge($path->search($template), $paths); } } if(empty($paths)){ throw new Ficus_FileNotFoundException("template $template is not found in " . implode(",", $this->paths) . "," . implode(",", $this->userPaths)); } if(count($paths) >= 2){ throw new Ficus_MultipleFileFoundException("multiple template named $template found in " . explode(",", $paths)); } $path = $paths[0]; $this->assign("smarty_AbsolutePath", dirname($path)); return "file:" . $path; } /** * is template exists */ public function isTemplateExists($template){ try{ $this->search($template); }catch(Exception $e){ return false; } return true; } /** * assign * @param $name name of variable * @param $var mixed variable */ public function assign($name, $var){ $this->smarty->assign($name, $var); } /** * assign by ref * @param $name name of variable * @param $var mixed variable */ public function assignByReference($name, $var){ $this->smarty->assign_by_ref($name, $var); } /** * fetch * @param $template string template * @return string result */ public function fetch($template){ return $this->smarty->fetch($this->search($template)); } /** * display * @param $template string template */ public function display($template){ $this->smarty->display($this->search($template)); } /** * clear * @param $name string name of property */ public function clear($name){ $this->smarty->clear_assign($name); } } ?> ficus/template/smarty/SmartyComponentFactory.php100644 1751 144 5663 10647425604 15745 ISHITOYA Kentaro * @version $Id: SmartyComponentFactory.php 14 2007-07-18 14:55:12Z ishitoya $ * * Smarty component factory */ require_once("ficus/io/File.php"); require_once("ficus/config/Registry.php"); /** * @class Ficus_SmartyComponentFactory */ class Ficus_SmartyComponentFactory extends Ficus_S2ContainerComponentFactory{ const KEY_SMARTY = "Smarty"; /** * dicon file name registry key */ const REGISTRY_DICON_FILENAME = "smarty.dicon"; /** * dicon namespace registry key */ const REGISTRY_DICON_NAMESPACE = "smarty.namespace"; /** * Default dicon file name. */ const DEFAULT_DICON_FILENAME = 'ssmarty.dicon'; /** * dicon namespace. */ const DEFAULT_DICON_NAMESPACE = 'smarty.scheme'; /** * get Dicon file name from registry * @return string dicon filename */ protected function getDiconFileNameRegistry(){ return self::REGISTRY_DICON_FILENAME; } /** * get Dicon namespace from registry * @return string dicon namespace */ protected function getDiconNameSpaceRegistry(){ return self::REGISTRY_DICON_NAMESPACE; } /** * get dicon file name * @return string dicon file name */ protected function getDefaultDiconFileName(){ return Ficus_File::currentDir() ->resolve(self::DEFAULT_DICON_FILENAME)->getPath(); } /** * get defoult dicon namespace * @return string dicon namespace */ protected function getDefaultDiconNameSpace(){ return self::DEFAULT_DICON_NAMESPACE; } /** * get component * @param $name string name of component * @param $class string class name * @return Ficus_SmartyComponentFactory */ public static function getComponent($name, $class = __CLASS__){ return parent::getComponent($name, $class); } /** * Get smarty * * @param $name string component name. * @return mixed component. */ public static function getSmarty() { return self::getComponent(self::KEY_SMARTY); } } ?> ficus/template/smarty/components21.dtd100644 1751 144 2773 10645120161 13552 ficus/logging/Logger.php100644 1751 144 16455 10645132217 11000 ISHITOYA Kentaro * @version $Id: Logger.php 2 2007-07-11 10:37:48Z ishitoya $ * * Util Ficus_Logger */ require_once("Log/Log.php"); require_once("ficus/lang/ClassPath.php"); require_once("ficus/io/PropertyFileReader.php"); require_once("ficus/exception/NotReadyException.php"); /** * @class Ficus_Logger */ class Ficus_Logger{ //config file name const CONFIG_FILE = "logger"; /** * log level * @see Log/Log.php */ const LOG_EMERG = "ficus_logger_emerg"; const LOG_ALERT = "ficus_logger_alert"; const LOG_CRIT = "ficus_logger_crit"; const LOG_ERR = "ficus_logger_err"; const LOG_WARNING = "ficus_logger_warning"; const LOG_NOTICE = "ficus_logger_notice"; const LOG_INFO = "ficus_logger_info"; const LOG_DEBUG = "ficus_logger_debug"; const LOG_ALL = "ficus_logger_all"; const LOG_NONE = "ficus_logger_none"; /* const LOG_TYPE_SYSTEM = "system"; const LOG_TYPE_MAIL = "mail"; const LOG_TYPE_DEBUG ="debug"; const LOG_TYPE_FILE = "file"; */ /** * @var $log Log log object */ private static $log = null; /** * $handler */ private static $handler = null; /** * $logLevel */ private static $logLevel = PEAR_LOG_NOTICE; /** * $logLevels string log levels */ private static $logLevels = array(self::LOG_EMERG => PEAR_LOG_EMERG, self::LOG_ALERT => PEAR_LOG_ALERT, self::LOG_CRIT => PEAR_LOG_CRIT, self::LOG_ERR => PEAR_LOG_ERR, self::LOG_WARNING => PEAR_LOG_WARNING, self::LOG_NOTICE => PEAR_LOG_NOTICE, self::LOG_INFO => PEAR_LOG_INFO, self::LOG_DEBUG => PEAR_LOG_DEBUG, self::LOG_ALL => PEAR_LOG_ALL, self::LOG_NONE => PEAR_LOG_NONE); /** * constructor * @param $base string directory */ public static function initialize($base){ if(empty(self::$log)){ $ini = Ficus_PropertyFileReader::read(self::CONFIG_FILE); //ignore mode. because its not work properly $conf = array('timeFormat' => $ini["timeformat"]); $file = $base . "/" . $ini["file"]; self::$log = &Log::singleton( $ini["handler"], $file, $ini["ident"], $conf, $ini["level"]); self::$handler = $ini["handler"]; self::$log->_timeFormat = "[" . self::$log->_timeFormat . "]"; } } /** * flush log */ public static function flush(){ self::$log->flush(); } /** * clean log file */ public static function clean(){ file_put_contents(self::$log->_filename, ""); } /** * log specific message to logger * @param $msg+ string message to log. * @param $level integer LOG_LEVEL * @throw Ficus_NotReadyException log is not ready. */ public static function log(){ if(is_null(self::$log)){ throw new Ficus_NotReadyException("Log is not ready. please call initialize() function before call log()."); } $args = func_get_args(); $count = func_num_args(); $level = null; if($count == 0){ throw new Ficus_IllegalArgumentException("There are no argument."); }else if($count >= 2){ if(array_key_exists(end($args), self::$logLevels)){ $level = self::$logLevels[array_pop($args)]; } } foreach($args as $key => $arg){ $args[$key] = self::convertVariableToString($arg); } $msg = implode($args, " , "); $location = self::getLocation(); self::writeToFile($msg, $location, $level); } /** * log and flush atonce * @param $msg string message to log; * @param $level integer log level */ public static function logAtOnce($msg, $level = null){ if(is_null($level)){ self::log($msg); }else{ self::log($msg, $level); } self::flush(); } /** * set mask */ public static function setMask($level){ $level = self::$logLevels[$level]; self::$log->setMask(self::LOG_NONE | self::$log->UPTO($level)); } /** * write to file * @param $msg misc argument to log * @param $location location where log method called * @param $level string log level */ private static function writeToFile($msg, $location, $level = null){ $msg .= $location; self::$log->log($msg, $level); } /** * get location */ private static function getLocation(){ $trace = debug_backtrace(); $locate = " at "; if ($trace[2]["class"] != null) { $locate .= $trace[2]["class"] . "::"; } if ($trace[2]["function"] != null) { $locate .= $trace[2]["function"] . "()"; } $locate .= " in " . $trace[1]["file"] . "#" . $trace[0]["line"]; return $locate; } /** * Convert variable to string * @param $arg mixed argument to convert * @return string converted string */ private static function convertVariableToString($arg){ if(is_null($arg)){ $arg = "NULL"; }else if(is_bool($arg)){ $arg = $arg ? "true" : "false"; }else if(is_integer($arg) && $arg === 0){ $arg = "0"; }else if(is_string($arg) && $arg === ""){ $arg = "empty string"; }else if(is_string($arg) == false){ $arg = self::$log->_extractMessage($arg); } return $arg; } /** * aliases of log level */ public static function emerg(){ self::log(func_get_args(), "ficus_logger_" . __FUNCTION__); } public static function alert(){ self::log(func_get_args(), "ficus_logger_" . __FUNCTION__); } public static function crit(){ self::log(func_get_args(), "ficus_logger_" . __FUNCTION__); } public static function err(){ self::log(func_get_args(), "ficus_logger_" . __FUNCTION__); } public static function warning(){ self::log(func_get_args(), "ficus_logger_" . __FUNCTION__); } public static function notice(){ self::log(func_get_args(), "ficus_logger_" . __FUNCTION__); } public static function info(){ self::log(func_get_args(), "ficus_logger_" . __FUNCTION__); } public static function debug(){ self::log(func_get_args(), "ficus_logger_" . __FUNCTION__); } } ?> ficus/validators/RDFValidator.php100644 1751 144 3277 10645132217 12542 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: RDFValidator.php 2 2007-07-11 10:37:48Z ishitoya $ * * validate parameter that */ require_once("ficus/validators/Validatable.php"); require_once("ficus/exception/ValidationException.php"); /** * @interface Ficus_RDFValidator */ class Ficus_RDFValidator implements Ficus_Validatable { /** * validate parameter * @param $param array parameter to validate */ public function validate($param){ /* try{ Ficus_Resource::RdfValidate($param["value"]); }catch(Exception $e){ $ve = new Ficus_ValidationException("Parameter {$param['key']} is not a legal RDF form."); $ve->initCause($e); throw $ve; } */ } /** * get String form validator * @return string definition of this validator */ public function __toString(){ return "RDF"; } } ?> ficus/validators/PerlRegexValidator.php100644 1751 144 6131 10645132217 14014 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: PerlRegexValidator.php 2 2007-07-11 10:37:48Z ishitoya $ * * validate parameter that */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @interface Ficus_PerlRegexValidator */ class Ficus_PerlRegexValidator implements Ficus_RegexValidator { /** * @var $pattern string regular expression */ private $pattern = ""; /** * @var $errorIndicator boolean indicates regex error occurance */ private $errorIndicator = false; /** * constructor * @param $pattern string regular expression */ public function __construct($pattern){ $this->pattern($pattern); } /** * validate parameter * @param $param array parameter to validate * @throw Ficus_ValidationException invalidate. */ public function validate($param){ set_error_handler(array($this, "errorHandler")); $result = preg_match($this->pattern, $param["value"]); restore_error_handler(); if($this->errorIndicator || $result === 0){ $this->errorIndicator = false; if(isset($param['key'])){ throw new Ficus_ValidationException("Parameter {$param['key']} does not match pattern : {$this->pattern}"); }else{ throw new Ficus_ValidationException("Parameter index key was not exist"); } } } /** * error Handler for regex validator * * @param $errno string error number. * @param $errmsg string error message. * @param $filename string file name. * @param $linenum string line number. * @param $vars string vars. */ public function errorHandler($errno, $errmsg, $filename, $linenum, $vars){ if($filename === __FILE__){ $this->errorIndicator = true; } } /** * set regular pattern * @param $pattern string reqular expression * @throw Ficus_IllegalArgumentException pattern is empty. */ public function pattern($pattern){ if(empty($pattern)){ throw new Ficus_IllegalArgumentException("pattern is empty"); } $this->pattern = $pattern; } /** * get String form validator * @return string definition of this validator */ public function __toString(){ return "perlRegex('{$this->pattern}')"; } } ?> ficus/validators/PostfixRegexValidator.php100644 1751 144 7645 10645132217 14561 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: PostfixRegexValidator.php 2 2007-07-11 10:37:48Z ishitoya $ * * validate parameter that */ require_once("ficus/validators/RegexValidator.php"); require_once("ficus/exception/ValidationException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @interface Ficus_PostfixRegexValidator */ class Ficus_PostfixRegexValidator implements Ficus_RegexValidator { ///case sensitive function name const SENSITIVE = "ereg"; ///case insensitive function name const INSENSITIVE = "eregi"; /** * @var $pattern string regular expression */ private $pattern = ""; /** * @var $fanctionName string function name * default self::SENSITIVE */ private $fanctionName = ""; /** * @var $errorIndicator boolean indicates that regex had error */ private $errorIndicator = false; /** * constructor * @param $pattern string regular expression * @param $caseSensitive boolean case sensitive */ public function __construct($pattern, $caseSensitive = true){ $this->pattern($pattern); $this->caseSensitive($caseSensitive); } /** * validate parameter * @param $param array parameter to validate * @throw Ficus_ValidationException invalidate. */ public function validate($param){ set_error_handler(array($this, "errorHandler")); $func = $this->functionName; $result = $func($this->pattern, $param["value"]); restore_error_handler(); if($this->errorIndicator || $result === false){ $this->errorIndicator = false; if(isset($param['key'])){ throw new Ficus_ValidationException("Parameter {$param['key']} does not match pattern : {$this->pattern}"); }else{ throw new Ficus_ValidationException("Parameter index key was not exist"); } } } /** * error Handler for regex validator * * @param $errno string error number. * @param $errmsg string error message. * @param $filename string file name. * @param $linenum string line number. * @param $vars string vars. */ public function errorHandler($errno, $errmsg, $filename, $linenum, $vars){ if($filename === __FILE__){ $this->errorIndicator = true; } } /** * set regular pattern * @param $pattern string reqular expression * @throw Ficus_IllegalArgumentException pattern is empty. */ public function pattern($pattern){ if(empty($pattern)){ throw new Ficus_IllegalArgumentException("pattern is empty"); } $this->pattern = $pattern; } /** * set caseSensitive * @param $caseSensitive boolean true caseSensitive */ public function caseSensitive($caseSensitive){ if($caseSensitive === true){ $this->functionName = self::SENSITIVE; }else{ $this->functionName = self::INSENSITIVE; } } /** * get String form validator * @return string definition of this validator */ public function __toString(){ if($this->functionName == self::SENSITIVE){ return "multibyteRegex('{$this->pattern}',true)"; }else{ return "postfixRegex('{$this->pattern}',false)"; } } } ?> ficus/validators/SimpleTypeValidator.php100644 1751 144 2247 10645132217 14216 ISHITOYA Kentaro * @version $Id: SimpleTypeValidator.php 2 2007-07-11 10:37:48Z ishitoya $ * * regex validator interface */ /** * @interface Ficus_RegexValidator */ interface Ficus_RegexValidator extends Ficus_Validator { /** * set reqular expression * @param $pattern string reqular expression */ public function pattern($pattern); } ?> ficus/validators/Validatable.php100644 1751 144 2177 10645132217 12467 ISHITOYA Kentaro * @version $Id: Validatable.php 2 2007-07-11 10:37:48Z ishitoya $ * * Validatable interface for php */ /** * @interface Ficus_Validatable */ interface Ficus_Validatable{ /** * validate param * @param $param array param to validate */ public function validate($param); } ?> ficus/validators/RegexValidator.php100644 1751 144 2333 10645132217 13171 ISHITOYA Kentaro * @version $Id: RegexValidator.php 2 2007-07-11 10:37:48Z ishitoya $ * * regex validator interface */ require_once("ficus/validators/Validatable.php"); /** * @interface Ficus_RegexValidator */ interface Ficus_RegexValidator extends Ficus_Validatable { /** * set reqular expression * @param $pattern string reqular expression */ public function pattern($pattern); } ?> ficus/validators/URIValidator.php100644 1751 144 3322 10645132217 12555 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: URIValidator.php 2 2007-07-11 10:37:48Z ishitoya $ * * validate parameter that is URI */ require_once("ficus/net/URI.php"); require_once("ficus/validators/Validatable.php"); require_once("ficus/exception/ValidationException.php"); /** * @interface Ficus_URIValidator */ class Ficus_URIValidator implements Ficus_Validatable { /** * validate parameter * @param $param array parameter to validate * @throw Ficus_ValidationException invalidate. */ public function validate($param){ $uri = $param['value']; if ($uri instanceof Ficus_URI) { return; } try { Ficus_URI::create($uri); } catch (Ficus_URISyntaxException $e) { throw new Ficus_ValidationException("{$param['key']} is not a legal uri.", $e); } } } ?> ficus/validators/RequiredValidator.php100644 1751 144 3337 10645132217 13704 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: RequiredValidator.php 2 2007-07-11 10:37:48Z ishitoya $ * * validate parameter that is required */ require_once("ficus/validators/Validatable.php"); require_once("ficus/exception/ValidationException.php"); /** * @interface Ficus_RequiredValidator */ class Ficus_RequiredValidator implements Ficus_Validatable { /** * validate parameter * parameter must not empty * @param $param array parameter to validate * @throw Ficus_ValidationException invalidate. */ public function validate($param){ if(empty($param["value"])){ throw new Ficus_ValidationException("Parameter {$param['key']} is required : must exist and must not empty"); } } /** * get String form validator * @return string definition of this validator */ public function __toString(){ return "required"; } } ?> ficus/config/PropertyRegister.php100644 1751 144 3641 10645132217 12702 ISHITOYA Kentaro * @version $Id: PropertyRegister.php 2 2007-07-11 10:37:48Z ishitoya $ * * PropertyRegister pattern. */ require_once("ficus/config/Registry.php"); require_once("ficus/io/PropertyFileReader.php"); require_once("ficus/io/YAMLFileReader.php"); /** * @class Ficus_PropertyRegister */ class Ficus_PropertyRegister { const YAML = "yaml"; const INI = "ini"; /** * register properties * @param $filename string file name of the property file * @param $filetype string yaml or ini */ public function regist($filename, $filetype = self::INI){ if($filetype == self::YAML){ $properties = Ficus_YAMLFileReader::read($filename); }else{ $properties = Ficus_PropertyFileReader::read($filename); } foreach($properties as $key => $value){ if(($old = Ficus_Registry::search($key)) && is_array($old) && is_array($value)){ $value = array_merge_recursive($old, $value); } Ficus_Registry::regist($key, $value); } } } ?> ficus/config/Registry.php100644 1751 144 4460 10645132217 11161 SUMI Masafumi * @version $Id: Registry.php 2 2007-07-11 10:37:48Z ishitoya $ * * Registry pattern. */ /** * @class Ficus_Registry */ class Ficus_Registry { /** * @var registry. */ private static $registry; /** * @var regist values. */ private $values; /** * Constructor. */ protected function __construct() { $this->values = array(); } /** * */ public static function getInstance() { if (is_null(self::$registry)) { self::$registry = new Ficus_Registry(); } return self::$registry; } /** * Regist value. * * @param $key string key. * @param $value mixed value. */ public static function regist($key, $value) { self::getInstance()->values[$key] = $value; } /** * Search registry. * * @param $key string registry key. * @return mixed value if novalue then return false. */ public static function search($key) { if (isset(self::getInstance()->values[$key])) { return self::getInstance()->values[$key]; } else { return false; } } /** * Remove registry. * * @param $key string registry key. */ public static function remove($key) { $values = self::getInstance()->values; if (isset($values[$key])) { $values[$key] = null; self::getInstance()->values = array_filter($values); } } } ?> ficus/crypto/DSAKeyGenerator.php100644 1751 144 2451 10645132217 12351 ISHITOYA Kentaro * @version $Id: DSAKeyGenerator.php 2 2007-07-11 10:37:48Z ishitoya $ * * dsa key generator. */ require_once "ficus/exception/NotImplementedException.php"; /** * @class Ficus_DSAKeyGenerator */ class Ficus_DSAKeyGenerator extends Ficus_KeyGenerator { /** * Generate key * @return Ficus_Key generated key */ public function generate(){ throw new Ficus_NotImplementedException("DSA algorithm is not implemented yet."); } } ?> ficus/crypto/SHA1KeyGenerator.php100644 1751 144 2535 10645132217 12441 ISHITOYA Kentaro * @version $Id: SHA1KeyGenerator.php 2 2007-07-11 10:37:48Z ishitoya $ * * adhoc key generator. */ require_once "ficus/crypto/KeyGenerator.php"; require_once "ficus/lang/Random.php"; /** * @class Ficus_SHA1KeyGenerator */ class Ficus_SHA1KeyGenerator extends Ficus_KeyGenerator { /** * Generate key * @return Ficus_Key generated key */ public function generate(){ $random = new Ficus_Random(); return new Ficus_Key(self::KEY_SHA1, sha1($random->nextString())); } } ?> ficus/crypto/RSAKeyGenerator.php100644 1751 144 2451 10645132217 12367 ISHITOYA Kentaro * @version $Id: RSAKeyGenerator.php 2 2007-07-11 10:37:48Z ishitoya $ * * rsa key generator. */ require_once "ficus/exception/NotImplementedException.php"; /** * @class Ficus_RSAKeyGenerator */ class Ficus_RSAKeyGenerator extends Ficus_KeyGenerator { /** * Generate key * @return Ficus_Key generated key */ public function generate(){ throw new Ficus_NotImplementedException("RSA algorithm is not implemented yet."); } } ?> ficus/crypto/CryptoConstants.php100644 1751 144 2316 10645132217 12577 ISHITOYA Kentaro * @version $Id: CryptoConstants.php 2 2007-07-11 10:37:48Z ishitoya $ * * */ /** * @interface Ficus_CryptoConstants */ interface Ficus_CryptoConstants { const KEY_DSA = "DSA"; const KEY_RSA = "RSA"; const KEY_SHA1 = "SHA1"; const CIPHER_HMACSHA1 = "HMACSHA1"; const DIGEST_SHA1 = "SHA1"; const DIGEST_MD2 = "MD2"; const DIGEST_MD5 = "MD5"; } ?> ficus/crypto/Key.php100644 1751 144 3677 10645132217 10165 ISHITOYA Kentaro * @version $Id: Key.php 2 2007-07-11 10:37:48Z ishitoya $ * * */ require_once("ficus/crypto/CryptoConstants.php"); /** * @class Ficus_Key */ class Ficus_Key implements Ficus_CryptoConstants { /** * @var string algorithm */ protected $algorithm = null; /** * @var string key */ protected $key = null; /** * constructor * @param $algorithm string algorithm * @param $key generated key */ public function __construct($algorithm, $key){ $this->algorithm = $algorithm; $this->key = $key; } /** * get algorithm * @return string algorithm */ public function getAlgorithm(){ return $this->algorithm; } /** * get raw key * @return string raw key */ public function getRaw(){ return $this->key; } /** * get encoded key * @return string encoded key */ public function getEncoded(){ return $this->getRaw(); } /** * to string * @return string string form of key */ public function __toString(){ return $this->getEncoded(); } } ?> ficus/crypto/Cipher.php100644 1751 144 4106 10645132217 10633 * @version $Id: Cipher.php 2 2007-07-11 10:37:48Z ishitoya $ * * cipher class */ require_once "ficus/crypto/Key.php"; require_once "ficus/crypto/CryptoConstants.php"; require_once "ficus/lang/ClassLoader.php"; require_once "ficus/exception/AlgorithmNotFoundException.php"; /** * @class Ficus_Cipher */ abstract class Ficus_Cipher implements Ficus_CryptoConstants { const SIGNATURE = "ficus.crypto.Ficus_%sCipher"; /** * get instance * @param $algorithm string algorithm * @return Ficus_Cipher instance */ public static function getInstance($algorithm){ $classname = sprintf(self::SIGNATURE, $algorithm); try{ $cipher = Ficus_ClassLoader::load($classname); return $cipher; }catch(Exception $e){ throw new Ficus_AlgorithmNotFoundException($e->getMessage(), $e); } } /** * crypt data with key * @param $data string data to crypt * @param $key Ficus_Key to use cryption * @return crypted data */ public abstract function encrypt($data, $key); /** * decrypt data from crypted data. * @param $data string crypted data * @param $key Ficus_Key to use decrypt * @return decripted data */ public abstract function decrypt($data, $key); } ?> ficus/crypto/HMACSHA1Cipher.php100644 1751 144 5001 10645132217 11674 * @version $Id: HMACSHA1Cipher.php 2 2007-07-11 10:37:48Z ishitoya $ * * cipher class */ require_once "ficus/crypto/Cipher.php"; require_once "ficus/exception/NotSupportedException.php"; require_once "ficus/lang/Bytes.php"; /** * @class Ficus_HMACSHA1Cipher */ class Ficus_HMACSHA1Cipher extends Ficus_Cipher { const PADDING_KEY = 0x00; const PADDING_INNER = 0x36; const PADDING_OUTER = 0x5C; const KEY_LENGTH = 64; /** * ipad */ protected $ipad = null; /** * opad */ protected $opad = null; /** * */ public function __construct(){ $bytes = new Ficus_Bytes(); $this->ipad = $bytes->fill(self::KEY_LENGTH, self::PADDING_INNER); $this->opad = $bytes->fill(self::KEY_LENGTH, self::PADDING_OUTER); } /** * crypt data with key * @param $data string data to crypt * @param $key Ficus_Key to use cryption * @return crypted data */ public function encrypt($data, $key){ if(is_string($key)){ $key = new Ficus_Key(self::DIGEST_SHA1, $key); } $key = new Ficus_Bytes($key->getEncoded()); $key = $key->padding(self::KEY_LENGTH, self::PADDING_KEY); $inner = $key->xorWith($this->ipad); $inner = sha1($inner . $data); $outer = $key->xorWith($this->opad); $outer = sha1($outer . $inner); return $outer; } /** * decrypt data from crypted data. * @param $data string crypted data * @param $key Ficus_Key to use decrypt * @return decripted data */ public function decrypt($data, $key){ throw new Ficus_NotSupportedException("HMACSHA1Ciper is not able to decrypt."); } } ?> ficus/crypto/KeyGenerator.php100644 1751 144 3522 10645132217 12021 ISHITOYA Kentaro * @version $Id: KeyGenerator.php 2 2007-07-11 10:37:48Z ishitoya $ * * generator factory class */ require_once "ficus/crypto/CryptoConstants.php"; require_once "ficus/lang/ClassLoader.php"; require_once "ficus/exception/AlgorithmNotFoundException.php"; /** * @abstract Ficus_KeyGenerator */ abstract class Ficus_KeyGenerator implements Ficus_CryptoConstants { const SIGNATURE = "ficus.crypto.Ficus_%sKeyGenerator"; /** * get instance * @param $algorithm string algorithm * @return Ficus_KeyGenerator instance */ public static function getInstance($algorithm){ $classname = sprintf(self::SIGNATURE, $algorithm); try{ $generator = Ficus_ClassLoader::load($classname); return $generator; }catch(Exception $e){ throw new Ficus_AlgorithmNotFoundException($e->getMessage(), $e); } } /** * Generate key * @return Ficus_Key generated key */ public abstract function generate(); } ?> ficus/parameters/ArrayParameter.php100644 1751 144 11534 10645132217 13206 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ArrayParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ComplexParameter with Validator. */ require_once("ficus/lang/Assert.php"); require_once("ficus/parameters/ValidatableComplexParameter.php"); require_once("ficus/exception/IllegalTypeException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_ArrayParameter */ class Ficus_ArrayParameter extends Ficus_ValidatableComplexParameter implements Iterator { const TEMPLATE = "template"; const ITEM = "item"; const PATTERN = '/^([a-zA-Z0-9_:.]+)\[\]$/'; /** * type of this array contents */ private $arrayType = null; /** * value parameters */ private $arrayValues = array(); /** * construct validiatable Parameter. * @param $name string name * @param $typename string name of type * @param $value mixed value of this param * @param $validator Ficus_Validator validator for validate parameter */ function __construct($name, $typename, $value = null, $validator = array()){ parent::__construct($name, $typename, $value); $this->setArrayType($typename); $this->setValidator($validator); } /** * set array type * @param $typename string type of Parameter * @throw Ficus_IllegalTypeException illegal type. */ private function setArrayType($typename){ if(preg_match(self::PATTERN, $typename, $matches) === false){ throw new Ficus_IllegalTypeException("{$matches[1]} is not exist"); } $this->arrayType = $matches[1]; } /** * set Value * @param $parameter Ficus_Parameter must be same type as $this->arrayType */ public function setValue($parameter){ if(is_null($parameter)){ return; } $this->append($parameter); } /** * return value parameters * @return array array of Ficus_ComplexParameter */ public function value(){ return $this->arrayValues; } /** * return index parameter * @param $index integer index * @throw Ficus_IllegalArgumentException illegal index. */ public function at($index){ if(count($this->arrayValues) > $index && $index >= 0){ return $this->arrayValues[$index]; }else{ throw new Ficus_IllegalArgumentException("index $index is illegal index"); } } /** * return array count * @return integer index length */ public function length(){ return count($this->arrayValues); } /** * append parameter * @param $parameter Ficus_Parameter type of this parameter * @throw Ficus_IllegalTypeException no array. */ public function append($parameter){ Ficus_Assert::TypeHinting("Ficus_Parameter", $parameter); if($parameter->typeName() == $this->arrayType){ if(parent::getParameters()){ $parameter->setName(self::ITEM); array_push($this->arrayValues, clone $parameter); }else{ $parameter->setName(self::TEMPLATE); parent::append($parameter); } }else{ throw new Ficus_IllegalTypeException("method parameter must be same type as {$this->arrayType}."); } } /** * iteration function reset array pointer */ public function rewind() { reset($this->arrayValues); } /** * iteration function returns current value */ public function current() { $var = current($this->arrayValues); return $var; } /** * iteration function returns key of current array pointer */ public function key() { $var = key($this->arrayValues); return $var; } /** * iteration function get next array value */ public function next() { $var = next($this->arrayValues); return $var; } /** * iteration function validate array pointer */ public function valid() { return (is_null(key($this->arrayValues)) === false); } /** * clone method */ public function __clone(){ $parameters = array(); $arrayValues = array(); foreach($this->parameters as $parameter){ array_push($parameters, clone $parameter); } foreach($this->arrayValues as $value){ array_push($arrayValues, clone $value); } $this->parameters = $parameters; $this->arrayValues = $arrayValues; } } ?> ficus/parameters/visitors/ParameterToWSDLConverter.php100644 1751 144 16571 10645132217 16764 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ParameterToWSDLConverter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ParameterToWSDLConverter. */ require_once("ficus/lang/Assert.php"); require_once("ficus/net/WSDL.php"); require_once("ficus/parameters/visitors/Acceptor.php"); require_once("ficus/parameters/visitors/Visitor.php"); require_once("ficus/validators/Validatable.php"); require_once("ficus/parameters/ValidatableComplexParameter.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); require_once("ficus/exception/IllegalTypeException.php"); /** * @class Ficus_ParameterToWSDLConverter */ class Ficus_ParameterToWSDLConverter extends Ficus_Visitor { /** * @var $wsdl Ficus_WSDL */ private $wsdl = null; /** * @var $dom DomDocument */ private $dom = null; /** * @var $messages array array of message that DOMElement presentation */ private $messages = array(); /** * @var $types array array of types that DOMElement presentation */ private $types = array(); /** * constructor * @param $wsdl Ficus_WSDL intstance of Util DSDL * @param $dom array array of parameters to validate */ public function __construct($wsdl, $dom){ $this->setWSDL($wsdl); $this->setDOMDocument($dom); } /** * set WSDL class * @param $wsdl Ficus_WSDL set WSDL class * @throw Ficus_IllegalTypeException no WSDL. */ private function setWSDL($wsdl){ if($wsdl instanceof Ficus_WSDL){ $this->wsdl = $wsdl; }else{ throw new Ficus_IllegalTypeException("wsdl is not instance of Ficus_WSDL"); } } /** * set DOMDocument * @param $dom DOMDocument set DOMDocument * @throw Ficus_IllegalTypeException no DOMDocument. */ private function setDOMDocument($dom){ if($dom instanceof DOMDocument){ $this->dom = $dom; }else{ throw new Ficus_IllegalTypeException("dom is not instance of DOMDocument."); } } /** * visit parameters and validate * @param $parameter Ficus_Acceptor validatables */ public function visit($parameter){ Ficus_Assert::isInstanceOf($parameter, "Ficus_Acceptor"); if($parameter instanceof Ficus_ValidatableComplexParameter){ //if type is null, the parameter is name of parameter if($parameter->typeName() === ""){ $name = preg_replace("/\[\]/", "Array", $parameter->name()); $this->messages[$name] = $this->createMessageElement($parameter, $name); }else if($parameter instanceof Ficus_ArrayParameter){ $typename = preg_replace("/\[\]/", "Array", $parameter->typeName()); $this->types[$typename] = $this->createArrayTypesElement($parameter, $typename); }else{ $this->types[$parameter->typeName()] = $this->createTypesElement($parameter); } //check for child parameters $children = $parameter->getParameters(); foreach($children as $child){ if($child instanceof Ficus_ValidatableComplexParameter && isset($types[$child->name()]) === false){ $child->accept($this); } } } } /** * create Types Element * @param $parameter Ficus_ValidatableComplexParameter target parameter * @return DOMElement */ private function createTypesElement($parameter){ $complexType = $this->dom->createElementNS(Ficus_WSDL::XMLNS_XSD, "xsd:complexType"); $complexType->setAttribute("name", $parameter->typeName()); $all = $this->dom->createElementNS(Ficus_WSDL::XMLNS_XSD, "xsd:all"); $params = $parameter->getParameters(); foreach($params as $param){ $element = $this->dom->createElementNS(Ficus_WSDL::XMLNS_XSD, "xsd:element"); $element->setAttribute("name", $param->name()); $element->setAttribute("type", $param->typeName()); $all->appendChild($element); } $complexType->appendChild($all); return $complexType; } /** * create Types Element for Array * @param $parameter Ficus_ValidatableComplexParameter target parameter * @param $arrayName string array name * @return DOMElement created types element for array */ private function createArrayTypesElement($parameter, $arrayName){ $params = $parameter->getParameters(); $checkparam = current($params); $complexType = $this->dom->createElementNS(Ficus_WSDL::XMLNS_XSD, "xsd:complexType"); $complexType->setAttribute("name", $arrayName); $complexContent = $this->dom->createElementNS(Ficus_WSDL::XMLNS_XSD, "xsd:complexContent"); $restriction = $this->dom->createElementNS(Ficus_WSDL::XMLNS_XSD, "xsd:restriction"); $restriction->setAttribute("base", Ficus_WSDL::P_SOAPENC . "Array"); $attribute = $this->dom->createElementNS(Ficus_WSDL::XMLNS_XSD, "xsd:attribute"); $attribute->setAttribute("ref", Ficus_WSDL::P_SOAPENC . "arrayType"); $typename = $parameter->typeName(); if($checkparam instanceof Ficus_ComplexParameter){ $typename = Ficus_WSDL::P_TYPENS . $typename; }else{ $typename = Ficus_WSDL::P_XSD . $typename; } $attribute->setAttributeNS(Ficus_WSDL::XMLNS_WSDL, "wsdl:arrayType", $typename); $restriction->appendChild($attribute); $complexContent->appendChild($restriction); $complexType->appendChild($complexContent); return $complexType; } /** * create Message Element * @param $parameter Ficus_ValidatableComplexParameter target parameter * @return DOMElement created message element */ private function createMessageElement($parameter){ $messageName = $parameter->name(); $params = $parameter->getParameters(); $message = $this->dom->createElement("message"); $message->setAttribute("name", $messageName); foreach($params as $param){ $part = $this->dom->createElement("part"); $part->setAttribute("name", $param->name()); $typename = preg_replace('/\[\]/', "Array", $param->typeName()); if($param instanceof Ficus_ValidatableSimpleParameter){ $part->setAttribute("type", Ficus_WSDL::P_XSD . $typename); }else{ $part->setAttribute("type", Ficus_WSDL::P_TYPENS . $typename); } $message->appendChild($part); } return $message; } /** * return array of messages * @return array of DOMElement */ public function getConvertedMessages(){ return $this->messages; } /** * return type Element * @return DOMElement type Element */ public function getConvertedTypes(){ $types = $this->dom->createElement("types"); $schema = $this->dom->createElementNS(Ficus_WSDL::XMLNS_XSD, "xsd:schema"); $schema->setAttribute("targetNamespace", $this->wsdl->targetNameSpace()); foreach($this->types as $type){ $types->appendChild($type); } return $types; } } ?> ficus/parameters/visitors/Visitor.php100644 1751 144 2241 10645132217 13563 ISHITOYA Kentaro * @version $Id: Visitor.php 2 2007-07-11 10:37:48Z ishitoya $ * * Visitor. */ require_once("ficus/parameters/visitors/Acceptor.php"); /** * @class Ficus_Visitor */ abstract class Ficus_Visitor{ /** * * @param $host string hostname. * @return name of parameter */ abstract public function visit($host); } ?> ficus/parameters/visitors/ParameterValidator.php100644 1751 144 6157 10645132217 15724 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ParameterValidator.php 2 2007-07-11 10:37:48Z ishitoya $ * * ParameterValidator. */ require_once("ficus/lang/Assert.php"); require_once("ficus/parameters/Parameter.php"); require_once("ficus/parameters/visitors/Acceptor.php"); require_once("ficus/parameters/visitors/Visitor.php"); require_once("ficus/validators/Validatable.php"); require_once("ficus/exception/IllegalTypeException.php"); /** * @class Ficus_ParameterValidator */ class Ficus_ParameterValidator extends Ficus_Visitor { /* * @var array array of parameters that passed to module */ private $parameters = array(); /** * constructor * * @param $parameters array array of parameters to validate */ public function __construct($parameters){ $this->setParameters($parameters); } /** * visit parameters and validate * @param $parameter Ficus_Acceptor validatables */ public function visit($parameter){ Ficus_Assert::isInstanceOf($parameter, "Ficus_Acceptor"); if($parameter instanceof Ficus_Validatable && $parameter instanceof Ficus_Parameter){ $name = $parameter->name(); if(array_key_exists($name, $this->parameters)){ if(is_string($this->parameters[$name])){ $this->parameters[$name] = trim($this->parameters[$name]); } $param = array("key" => trim($name), "value" => $this->parameters[$name]); $parameter->validate($param); }else{ $parameter->validate(array("key" => $name, "value" => null)); } //check for child parameters if($parameter instanceof Ficus_ComplexParameter){ $children = $parameter->getParameters(); foreach($children as $child){ if($child instanceof Ficus_Acceptor){ $child->accept($this); } } } } } /** * Set parameter. * * @param $parameters array array of parameters that passed to module * @throw Ficus_IllegalTypeException no array argument. */ public function setParameters($parameters){ if(is_array($parameters)){ $this->parameters = $parameters; }else{ throw new Ficus_IllegalTypeException("argument 1 must be array"); } } } ?> ficus/parameters/visitors/Acceptor.php100644 1751 144 2242 10645132217 13665 ISHITOYA Kentaro * @version $Id: Acceptor.php 2 2007-07-11 10:37:48Z ishitoya $ * * Acceptor interface. */ require_once("ficus/parameters/visitors/Visitor.php"); /** * @interface Ficus_Acceptor */ interface Ficus_Acceptor{ /** * @param $visitor Ficus_Visitor visitor */ public function accept(Ficus_Visitor $visitor); } ?> ficus/parameters/visitors/ParameterAccessor.php100644 1751 144 22633 10645132217 15556 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ParameterAccessor.php 2 2007-07-11 10:37:48Z ishitoya $ * * ParameterAccessor. */ require_once("ficus/lang/Assert.php"); require_once("ficus/parameters/Parameter.php"); require_once("ficus/parameters/ComplexParameter.php"); require_once("ficus/parameters/visitors/Acceptor.php"); require_once("ficus/parameters/visitors/Visitor.php"); require_once("ficus/validators/Validatable.php"); require_once("ficus/exception/IllegalArgumentException.php"); require_once("ficus/exception/PropertyNotFoundException.php"); /** * @class Ficus_ParameterAccessor */ class Ficus_ParameterAccessor extends Ficus_Visitor implements Iterator { /** * @var $parameters array array of parameters that passed to module */ private $parameters = array(); /** * @var $root Ficus_Parameter root parameter; */ private $root = null; /** * constructor * @param $parameter array array of parameters to validate */ public function __construct($parameter){ if($parameter instanceof Ficus_ComplexParameter){ $parameter->accept($this); } } /** * visit parameters and sets parameters. * @param $parameter Ficus_Acceptor validatables */ public function visit($parameter){ Ficus_Assert::typeHinting("Ficus_Acceptor" , $parameter); Ficus_Assert::typeHinting("Ficus_Parameter", $parameter); if(empty($this->root) && $parameter instanceof Ficus_ComplexParameter){ $this->root = $parameter; }else{ $name = strtolower($parameter->name()); $this->parameters[$name] = $parameter; } //check for child parameters if($parameter instanceof Ficus_ComplexParameter){ $children = $parameter->getParameters(); foreach($children as $child){ $this->parameters[$child->name()] = $child; } } } /** * get Root Parameter * @return Ficus_ComplexParameter rootParameter */ public function getRootParameter(){ return $this->root; } /** * get parameters * @param $name string name of this parameter * @throw Ficus_PropertyNotFoundException property not found. */ function __get($name){ if(array_key_exists($name, $this->parameters) === false){ throw new Ficus_PropertyNotFoundException("Property $name is not found in this parameter"); } $result = $this->parameters[$name]; //for nested parameter //$accessor->resource->id() if($result instanceof Ficus_ComplexParameter){ $accessor = new Ficus_ParameterAccessor($result); return $accessor; } return $result->value(); } /** * get parameter value by name * @param $name string name of this parameter * @return mixed parameter value */ function get($name){ return $this->callGetMethod($name); } /** * set parameter value by name * @param $name string name of target parameter * @param $argument array argument of this param * @return mixed result */ function set($name, $argument){ return $this->__call($name, array($argument)); } /** * php magic method to get and set parameters like below * $accessor->resource->id() * $accessor->getResource->getId(); * $accessor->resource->setId("urn:soya:resource:1"); * $accessor->setResource($obj); * @param $function string function name * @param $arguments mixed arguments of this function * @return mixed result * @throw Ficus_IllegalArgumentException illegal argument. */ function __call($function, $arguments){ if(count($arguments) == 1){ if(is_object($arguments[0])){ return $this->callSetMethodWithObject( $function, $arguments[0]); }else{ return $this->callSetMethod($function, $arguments[0]); } }else if(count($arguments) == 0){ return $this->callGetMethod($function); }else{ throw new Ficus_IllegalArgumentException("if argument specified, count must be 1, not specified then must be 0."); } } /** * get method handler. * @param $name string property name * @return Ficus_ValidatableParameter * @throw Ficus_PropertyNotFoundException property not found. */ function callGetMethod($name){ if(preg_match('/(?:get_?)([A-Z0-9_][a-zA-Z0-9_]+)/', $name, $match)){ $name = strtolower($match[1]); } if(array_key_exists($name, $this->parameters) === false){ throw new Ficus_PropertyNotFoundException("Property $name is not found in this parameter"); } $param = $this->parameters[$name]; if($name == Ficus_ArrayParameter::TEMPLATE){ if($param instanceof Ficus_ComplexParameter){ return new Ficus_ParameterAccessor(clone $param); }else{ return $param; } }else if($param instanceof Ficus_ArrayParameter){ return $param; } return $param->value(); } /** * set property * @param $function string property name * @param $argument mixed property value * @throw Ficus_PropertyNotFoundException property not found. */ private function callSetMethod($function, $argument){ if(preg_match('/(?:set_?)([a-zA-Z0-9_]+)/', $function, $match)){ $name = strtolower($match[1]); } if(array_key_exists($name, $this->parameters) === false){ throw new Ficus_PropertyNotFoundException("Property $name is not found in this parameter"); } $param = $this->parameters[$name]; if($param instanceof Ficus_ArrayParameter){ $this->callSetMethodForArray($name, $argument); }else{ $this->parameters[$name]->setValue($argument); } } /** * set property * @param $name string name of parameter * @param $argument mixed value of parameter * @throw Ficus_PropertyNotFoundException property not found. */ private function callSetMethodWithObject($name, $argument){ if(preg_match('/(?:set_?)([a-zA-Z0-9_]+)/i', $name, $match)){ $name = strtolower($match[1]); } if(array_key_exists($name, $this->parameters) === false){ throw new Ficus_PropertyNotFoundException("Property $name is not found in this parameter"); } $param = $this->parameters[$name]; if($param instanceof Ficus_ArrayParameter){ $this->callSetMethodForArray($name, $argument); return; } if($param instanceof Ficus_ComplexParameter){ $children = $param->getParameters(); $class = new ReflectionClass($argument); foreach($children as $child){ $childName = $child->name(); $getMethod = "get" . ucfirst($childName); if(method_exists($argument, $getMethod)){ $method = $class->getMethod($getMethod); }else if(method_exists($argument, $childName)){ $method = $class->getMethod($childName); }else{ continue; } $value = $method->invoke($argument); $accessor = new Ficus_ParameterAccessor(null); $child->accept($accessor); $accessor->{"set" . ucfirst($childName)}($value); } } $param->setValue($argument); } /** * set value to ArrayParameter * @param $name string name * @param $argument mixed argument to set array */ private function callSetMethodForArray($name, $argument){ $param = $this->parameters[$name]; if($argument instanceof Ficus_ParameterAccessor){ $value = clone $argument->getRootParameter(); }else if($argument instanceof Ficus_Parameter){ $value = clone $argument; } $param->append(clone($value)); } /** * if target parameter is array, then get index parameter * * @param $index int index. */ public function at($index){ $target = $this->getRootParameter(); if($target instanceof Ficus_ArrayParameter){ try{ $param = $target->at($index); if($param instanceof Ficus_ComplexParameter){ return new Ficus_ParameterAccessor($param); }else{ return $param->value(); } }catch(Ficus_IllegalArgumentException $e){ //do nothing, return null } } return null; } /** * iteration function reset array pointer */ public function rewind() { reset($this->parameters); } /** * iteration function returns current value */ public function current() { $var = current($this->parameters); if($var instanceof Ficus_ArrayParameter){ return $var; }else if($var instanceof Ficus_ComplexParameter){ $accessor = new Ficus_ParameterAccessor($var); return $accessor; } return $var; } /** * iteration function returns key of current array pointer */ public function key() { $var = key($this->parameters); return $var; } /** * iteration function get next array value */ public function next() { $var = next($this->parameters); if($var instanceof Ficus_ArrayParameter){ return $var; }else if($var instanceof Ficus_ComplexParameter){ $accessor = new Ficus_ParameterAccessor($var); return $accessor; } return $var; } /** * iteration function validate array pointer */ public function valid() { return (is_null(key($this->parameters)) === false); } } ?> ficus/parameters/visitors/ParameterValueSetter.php100644 1751 144 7626 10645132217 16244 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ParameterValueSetter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ParameterValueSetter. */ require_once("ficus/lang/Assert.php"); require_once("ficus/lang/Types.php"); require_once("ficus/parameters/Parameter.php"); require_once("ficus/parameters/visitors/Acceptor.php"); require_once("ficus/parameters/visitors/Visitor.php"); require_once("ficus/validators/Validatable.php"); /** * @class Ficus_ParameterValueSetter */ class Ficus_ParameterValueSetter extends Ficus_Visitor { /** * @var $parameter Ficus_Parameter Parameter to set Value */ private $parameter = null; /** * @var $values array array of values */ private $values = array(); /** * set values * @param $parameter Ficus_Parameter target Parameter * @param $values array array of values to set */ public function __construct($parameter = null, $values = array()){ if(is_null($parameter) === false){ $this->set($parameter, $values); } } /** * set values * @param $parameter Ficus_Parameter target Parameter * @param $values array array of values to set */ public function set($parameter, $values){ Ficus_Assert::TypeHinting("Ficus_Parameter", $parameter); Ficus_Assert::isPrimitiveType($values, "array"); $this->parameter = null; $this->values = array(); $this->parameter = $parameter; $this->values = $values; $this->parameter->accept($this); } /** * visit parameters and validate * @param $parameter Ficus_Acceptor validatables */ public function visit($parameter){ Ficus_Assert::isInstanceOf($parameter, "Ficus_Acceptor"); Ficus_Assert::isInstanceOf($parameter, "Ficus_Parameter"); $name = $parameter->name(); if(array_key_exists($name, $this->values)){ $value = $this->values[$name]; if(is_object($value)){ $value = Ficus_Types::toArrayOf($value); $this->values = array_merge($this->values, $value); }else if(is_array($value) && $parameter instanceof Ficus_ArrayParameter){ $setter = new Ficus_ParameterValueSetter(); $parameters = $parameter->getParameters(); $template = current($parameters); foreach($value as $v){ $t = clone $template; if(is_array($v)){ $setter->set($t, $v); }else{ $t->setValue($v); } $parameter->setValue($t); } }else{ $parameter->setValue($value); } }else{ $parameter->setValue(null); } //check for child parameters if($parameter instanceof Ficus_ComplexParameter && ($parameter instanceof Ficus_ArrayParameter) === false){ $children = $parameter->getParameters(); foreach($children as $child){ if($child instanceof Ficus_Acceptor){ $child->accept($this); } } } } /** * return filled parameter * @return Ficus_Parameter value filled parameter */ public function getParameter(){ return $this->parameter; } /** * return parameter with in accessor * @return Ficus_ParameterAccessor accessor */ public function getAccessor(){ return new Ficus_ParameterAccessor($this->parameter); } } ?> ficus/parameters/visitors/ParameterToDefinitionConverter.php100644 1751 144 5464 10645132217 20262 ISHITOYA Kentaro * @version $Id: ParameterToDefinitionConverter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ParameterToDefinitionConverter. */ require_once("ficus/lang/Assert.php"); require_once("ficus/parameters/visitors/Acceptor.php"); require_once("ficus/parameters/visitors/Visitor.php"); require_once("ficus/parameters/ParameterBuilder.php"); /** * @class Ficus_ParameterToDefinitionConverter */ class Ficus_ParameterToDefinitionConverter extends Ficus_Visitor { /** * @var $definition string definition string */ private $definition = ""; /** * constructor * @param $param Ficus_Parameter target parameter */ public function __construct($param){ Ficus_Assert::typeHinting("Ficus_Parameter", $param); $param->accept($this); } /** * visit parameters and validate * @param $parameter Ficus_Acceptor validatables */ public function visit($parameter){ static $depth = 0; Ficus_Assert::isInstanceOf($parameter, "Ficus_Acceptor"); if($parameter instanceof Ficus_Parameter){ //if type is null, the parameter is name of parameter if($parameter->typeName() === ""){ $this->definition .= $parameter->name() . "\n"; }else{ $this->definition .= $this->createDefinition($parameter, $depth); } if($parameter instanceof Ficus_ComplexParameter){ $depth++; //check for child parameters $children = $parameter->getParameters(); foreach($children as $child){ $child->accept($this); } $depth--; } } } /** * get converted definition * @return string definition */ public function getConvertedDefinition(){ return $this->definition; } /** * create definition from parameter * @param $param Ficus_Parameter target parameter * @param $depth integer multiplier * @return string definition of parameter */ private function createDefinition($param, $depth){ $level = str_repeat(Ficus_ParameterBuilder::T_LEVEL, $depth); return $level . $param->__toString() . "\n"; } } ?> ficus/parameters/ComplexParameter.php100644 1751 144 4105 10645132217 13513 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ComplexParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * Complex Type class */ require_once("ficus/parameters/Parameter.php"); require_once("ficus/exception/IllegalTypeException.php"); /** * @class Ficus_ComplexParameter */ class Ficus_ComplexParameter extends Ficus_Parameter { /** * @var $parameters array of Ficus_Parameter */ protected $parameters = array(); /** * constructor * @param $name string name of parameter * @param $typeName string typename of parameter * @param $value mixed complex parameter */ function __construct($name, $typeName, $value = null){ parent::__construct($name, $typeName, $value); } /** * append parameter * @param $parameter Ficus_Parameter type of this parameter * @throw Ficus_IllegalTypeException no Ficus_Parameter. */ public function append($parameter){ if($parameter instanceof Ficus_Parameter){ array_push($this->parameters, $parameter); }else{ throw new Ficus_IllegalTypeException("method parameter must be Ficus_Parameter"); } } /** * get parameter * @return array array of Ficus_Parameter */ public function getParameters(){ return $this->parameters; } } ?> ficus/parameters/datatypes/ShortParameter.php100644 1751 144 4415 10645132217 15205 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ShortParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as short */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_ShortParameter */ class Ficus_ShortParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "short"; const PATTERN = '^[+\-]?[0-9]+$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (ereg(self::PATTERN, $value) && (integer)$value <= 32767 && (integer)$value >= -32768)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a short value"); } } } ?> ficus/parameters/datatypes/Base64BinaryParameter.php100644 1751 144 5536 10645132217 16304 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: Base64BinaryParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as base64Binary */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_Base64BinaryParameter */ class Ficus_Base64BinaryParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "base64Binary"; const PATTERN = '/^[a-z0-9+\/=+]+$/i'; const LENGTH = "200"; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * set value * @param $value mixed value */ public function setValue($value){ if(preg_match(self::PATTERN, trim(substr($value, 0, self::LENGTH))) && strlen($value) % 4 == 0){ $this->value = base64_decode($value); }else{ $this->value = $value; } } /** * normalize parameter to base64Binary * @param $param string decoded value */ public function normalize($param){ return base64_encode($param); } /** * check param that associated with simple parameter * must be binary64 encoded string * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = $parameter["value"]; if(empty($value) || (preg_match(self::PATTERN, trim(substr($value, 0, self::LENGTH))) && strlen($value) % 4 == 0)){ $parameter["value"] = base64_decode($value); parent::validate($parameter); }else{ throw new Ficus_ValidationException("failed base64 decoding {$this->name()}."); } } } ?> ficus/parameters/datatypes/DateTimeParameter.php100644 1751 144 12153 10645132217 15620 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: DateTimeParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as datetime */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_DateTimeParameter */ class Ficus_DateTimeParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "dateTime"; const PATTERN = '^(-?[0-9]{4})-?(0[1-9]|1[0-2])-?(0[1-9]|[1-2][0-9]|3[0-1])T([0-1][0-9]|2[0-4]):?([0-5][0-9]):?([0-6][0-9])(\.[0-9]*)?(Z|[+\-][[0-5][0-9]:?[0-5][0-9])?$'; const DATE_W3C = 'Y-m-d\TH:i:sO'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * YYYY-MM-DDThh:mm:ss(Z|mm:ss) or YYYYMMDD * but 1981-11-31 will throw exception, because 11-31 is not exist. * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if (self::match($value)) { parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal dateTime format"); } } public function match($str) { return empty($str) || (ereg(self::PATTERN, $str, $regs) && (integer)$regs[1] !== 0); } /** * Date format of W3C. * * @return string Date format of W3C. */ public static function dateFormatW3C() { return defined('DATE_W3C') ? DATE_W3C: self::DATE_W3C; } /** * Parse date by W3C format. * * The date time formar must be * YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) * @param $str string string of date. * @return int gmt date. * @see http://www.w3.org/TR/NOTE-datetime */ public static function parse($str) { if (!self::match($str)) { throw new Ficus_ValidationException("'$str' is not legal dateTime format."); } if (function_exists('strptime')) { return strtotime($str); } else { $ret = preg_match('/(-?)([0-9]{4})-([0-1][0-9])-([0-3][0-9])T([0-2][0-9]):([0-6][0-9]):([0-6][0-9])(?:([zZ])|([\\-\\+])([0-2][0-9]):?([0-6][0-9]))/', $str, $matches); if ($ret === false || !isset($matches[1])) { throw new Ficus_ValidationException("parameter $str is not legal dateTime format"); } //preg_match('/' . self::PATTERN . '/', $str, $matches); $minus = $matches[1]; $year = intval($matches[2]); $month = intval($matches[3]); $day = intval($matches[4]); $hour = intval($matches[5]); $min = intval($matches[6]); $sec = intval($matches[7]); if (sizeof($matches) >= 9 && strtoupper($matches[8]) == 'Z') { $timezone = 'Z'; $plusminus = 1; $timezoneHour = 0; $timezoneMin = 0; } else { $timezone = null; $plusminus = $matches[9] == '+' ? 1 : -1; $timezoneHour = intval($matches[10]); $timezoneMin = intval($matches[11]); } $tz = date_default_timezone_get(); date_default_timezone_set('utc'); $local = mktime($hour, $min, $sec, $month, $day, $year); date_default_timezone_set($tz); $gmt = $local + -1 * $plusminus * (($timezoneHour * 60 + $timezoneMin) * 60); return $gmt; } } /** * Date format. * * @param $date int Date. * @return string formated date. */ public static function format($date = null) { $formated = is_null($date) ? date(self::dateFormatW3C()) : date(self::dateFormatW3C(), $date); return $formated; } } ?> ficus/parameters/datatypes/QNameParameter.php100644 1751 144 4307 10645132217 15107 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: QNameParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as QName */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_QNameParameter */ class Ficus_QNameParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "QName"; const PATTERN = '^[^:]+([:][^:]*|:)$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not valid QName"); } } } ?> ficus/parameters/datatypes/LongParameter.php100644 1751 144 4541 10645132217 15005 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: LongParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as long */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_LongParameter */ class Ficus_LongParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "long"; const PATTERN = '^[+\-]?([0-9]+)$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (ereg(self::PATTERN, $value, $regs) && (float)$value <= 9223372036854775807 && (float)$value >= -9223372036854775808)){ //bigger enouge integer treat as float in php parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a valid long format"); } } } ?> ficus/parameters/datatypes/AnyURIParameter.php100644 1751 144 4564 10645132217 15222 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: AnyURIParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as anyURI */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/net/URI.php"); require_once("ficus/net/URIBuilder.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_AnyURIParameter */ class Ficus_AnyURIParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "anyURI"; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); try { $uri = Ficus_URIBuilder::create($value); } catch (Ficus_URISyntaxException $e) { $uri = null; } if(empty($value) || $uri){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not valid URI"); } } } ?> ficus/parameters/datatypes/DoubleParameter.php100644 1751 144 4526 10645132217 15323 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: DoubleParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as double */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_DoubleParameter */ class Ficus_DoubleParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "double"; const PATTERN = '^(([0-9]+)|([+\-]?(([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*)))|([+\-]?((([0-9]+|([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*))[eE][+\-]?[0-9]+)))|(NaN|[-]?INF))$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$this->name()}: is not double value"); } } } ?> ficus/parameters/datatypes/ByteParameter.php100644 1751 144 4417 10645132217 15013 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ByteParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as byte */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_ByteParameter */ class Ficus_ByteParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "byte"; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * -128 <= x <= 127 * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (is_numeric($value) && ((integer)$value >= -128 && (integer)$value <= 127))){ $parameter["value"] = $value; parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$this->name()} is not a byte range value"); } } } ?> ficus/parameters/datatypes/GMonthParameter.php100644 1751 144 4520 10645132217 15277 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: GMonthParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as gMonth */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_GMonthParameter */ class Ficus_GMonthParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "gMonth"; const PATTERN = '^[-]{2}(0[1-9]|1[0-2])(Z|[+\-]([0-1][0-9]|2[0-4]):?([0-5][0-9]))?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * MM * but 1981-11-31 will throw exception, because 11-31 is not exist. * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || eregi(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal gMonth"); } } } ?> ficus/parameters/datatypes/IntegerParameter.php100644 1751 144 4325 10645132217 15503 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: IntegerParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as integer */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_IntegerParameter */ class Ficus_IntegerParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "integer"; const PATTERN = '^[+\-]?[0-9]+$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a Integer"); } } } ?> ficus/parameters/datatypes/GMonthDayParameter.php100644 1751 144 4617 10645132217 15744 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: GMonthDayParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as gMonthDay */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_GMonthDayParameter */ class Ficus_GMonthDayParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "gMonthDay"; const PATTERN = '^[-]{2}(0[1-9]|1[0-2])[-](0[1-9]|[1-2][0-9]|3[0-1])(Z|[+\-]([0-1][0-9]|2[0-4]):?([0-5][0-9]))?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * MM-DD or MMDD * but 1981-11-31 will throw exception, because 11-31 is not exist. * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal gMonthDay"); } } } ?> ficus/parameters/datatypes/UnsignedIntParameter.php100644 1751 144 4455 10645132217 16341 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: UnsignedIntParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as unsigned Int */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_UnsignedIntParameter */ class Ficus_UnsignedIntParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "unsignedInt"; const PATTERN = '^[+]?[0-9]+$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (eregi(self::PATTERN, $value) && (float)$value <= 4294967295)) { parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a unsignedInt value"); } } } ?> ficus/parameters/datatypes/LanguageParameter.php100644 1751 144 4620 10645132217 15627 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: LanguageParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as langeage */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_LanguageParameter */ class Ficus_LanguageParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "language"; const PATTERN = '^([a-zA-Z]{2,3}|x|i)(-([a-zA-Z0-9]{2,8})(-[a-zA-Z0-9]+)*)?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @see http://ietfreport.isoc.org/idref/rfc3066/ * @see http://www5d.biglobe.ne.jp/~quia/tech/html/lang.html for japanese * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not valid language format"); } } } ?> ficus/parameters/datatypes/DateParameter.php100644 1751 144 4666 10645132217 14773 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: DateParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as date */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_DateParameter */ class Ficus_DateParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "date"; const PATTERN = '^([-]?[0-9]{3,}[0-9])-?(0[1-9]|1[0-2])-?(0[1-9]|[1-2][0-9]|[3][0-1])(Z|[+\-]([0-1][0-9]|2[0-4]):?([0-5][0-9]))?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * YYYY-MM-DD(+hh:mm) or YYYYMMDD(+hhmm) * but 1981-11-31 will throw exception, because 11-31 is not exist. * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (ereg(self::PATTERN, $value, $regs) && (integer)$regs[1] !== 0)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal date"); } } } ?> ficus/parameters/datatypes/TokenParameter.php100644 1751 144 4307 10645132217 15166 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: TokenParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as token */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_TokenParameter */ class Ficus_TokenParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "token"; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = $parameter["value"]; if(empty($value) || strpbrk($value, "\r\n\t") === false || ereg("\s{2,}", $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$this->name()} is not normalizedString"); } } } ?> ficus/parameters/datatypes/GYearMonthParameter.php100644 1751 144 4602 10645132217 16121 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: GYearMonthParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as gYearMonth */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_GYearMonthParameter */ class Ficus_GYearMonthParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "gYearMonth"; const PATTERN = '^[-]?([0-9]{3,})[-](0[1-9]|1[0-2])(Z|[+\-]([0-1][0-9]|2[0-4]):?([0-5][0-9]))?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * [-]?YYYY-MM[Z|[+|-]hh:ss] or YYYYMM[Z|[+|-]hhss] * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (eregi(self::PATTERN, $value) && (integer)$value !== 0)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal gYearMonth"); } } } ?> ficus/parameters/datatypes/NCNameParameter.php100644 1751 144 4624 10645132217 15211 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NCNameParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as NCName */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_NCNameParameter */ class Ficus_NCNameParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "NCName"; //we have not permit unicode charactor yet const PATTERN = '^([^0-9])|[_])[^:]*$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @todo implement utf functions * @see http://www.koders.com/php/fid688BE37A00E98499C7778DAD8320B06CAEE1D19E.aspx?s=letter digit * * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not valid NCName format."); } } } ?> ficus/parameters/datatypes/GYearParameter.php100644 1751 144 4572 10645132217 15121 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: GYearParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as gYear */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_GYearParameter */ class Ficus_GYearParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "gYear"; const PATTERN = '^[-]?([0-9]{3,})(Z|[+\-]([0-1][0-9]|2[0-4]):?([0-5][0-9]))?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * [-]YYYY[Z|+-hh:mm] * but 1981-11-31 will throw exception, because 11-31 is not exist. * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (ereg(self::PATTERN, $value, $regs) && (integer)$regs[1] !== 0)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal gYear"); } } } ?> ficus/parameters/datatypes/NormalizedStringParameter.php100644 1751 144 4367 10645132217 17407 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NormalizedStringParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as normalizedString */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_NormalizedStringParameter */ class Ficus_NormalizedStringParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "normalizedString"; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = $parameter["value"]; if(empty($value) || strpbrk($value, "\r\n\t") === false){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$this->name()} is not normalizedString"); } } } ?> ficus/parameters/datatypes/TimeParameter.php100644 1751 144 4440 10645132217 15002 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: TimeParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as time */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_TimeParameter */ class Ficus_TimeParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "time"; const PATTERN = '^([0-1][0-9]|2[0-4]):?([0-5][0-9]):?([0-5][0-9])(\.[0-9]*)?(Z|[+\-][[0-5][0-9]:?[0-5][0-9])?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * hh:mm:ss * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal time format"); } } } ?> ficus/parameters/datatypes/NegativeIntegerParameter.php100644 1751 144 4561 10645132217 17170 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NegativeIntegerParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as negativeInteger */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_NegativeIntegerParameter */ class Ficus_NegativeIntegerParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "negativeInteger"; const PATTERN = '^[-]([0-9]+)$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * non 0 negative integer x < 0 * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(ereg('^[+\-]?0+$', $value) === false && (empty($value) || ereg(self::PATTERN, $value))){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a valid NegativeInteger format."); } } } ?> ficus/parameters/datatypes/NonNegativeIntegerParameter.php100644 1751 144 4553 10645132217 17644 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NonNegativeIntegerParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as nonNegativeInteger */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_NonNegativeIntegerParameter */ class Ficus_NonNegativeIntegerParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "nonNegativeInteger"; const PATTERN = '^[+]?(0+|[0-9]+)$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * positive integer includes 0 x >= 0 * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (ereg(self::PATTERN, $value))){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a valid NonNegativeInteger format."); } } } ?> ficus/parameters/datatypes/BooleanParameter.php100644 1751 144 4702 10645132217 15464 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: BooleanParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as boolean */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); require_once("ficus/lang/Assert.php"); /** * @class Ficus_BooleanParameter */ class Ficus_BooleanParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "boolean"; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * must be true or false * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ if(array_key_exists("value", $parameter) == false){ throw new Ficus_ValidationException("parameter value is not specified."); } $value = $parameter["value"]; if(empty($value) || (is_string($value) && eregi("^(true|1|false|0)$", trim($value)))){ }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not boolean value."); } } } ?> ficus/parameters/datatypes/GDayParameter.php100644 1751 144 4420 10645132217 14726 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: GDayParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as gDay */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_GDayParameter */ class Ficus_GDayParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "gDay"; const PATTERN = '^[-]{3}(0[1-9]|[1-2][0-9]|3[0-1])(Z|[+\-]([0-1][0-9]|2[0-4]):?([0-5][0-9]))?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * ---DD[+-hh[:]mm] * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal gDay"); } } } ?> ficus/parameters/datatypes/NameParameter.php100644 1751 144 4603 10645132217 14765 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NameParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as Name */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_NameParameter */ class Ficus_NameParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "Name"; //we have not permit unicode charactor yet const PATTERN = '^([^0-9])|[_:])[^,]*$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @todo implement utf functions * @see http://www.koders.com/php/fid688BE37A00E98499C7778DAD8320B06CAEE1D19E.aspx?s=letter digit * * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not valid name format."); } } } ?> ficus/parameters/datatypes/HexBinaryParameter.php100644 1751 144 7357 10645132217 16007 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: HexBinaryParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as hexBinary */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_HexBinaryParameter */ class Ficus_HexBinaryParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "hexBinary"; //error indicator for pack private $errorIndicator = false; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = $parameter["value"]; $old = set_error_handler(array($this, "errorHandler"), E_WARNING); pack("H*", $value); restore_error_handler(); if(empty($value) || $this->errorIndicator === false){ parent::validate($parameter); }else{ $this->errorIndicator = false; throw new Ficus_ValidationException("failed hex decoding {$this->name()}."); } } /** * error Handler for hexBinary * * @param $errno string error number. * @param $errmsg string error message. * @param $filename string file name. * @param $linenum string line number. * @param $vars string vars. */ private function errorHandler($errno, $errmsg, $filename, $linenum, $vars){ if($filename === __FILE__ && $errno == E_WARNING){ $this->errorIndicator = true; } } /* !!!! function below here is copied from php.net !!!! */ //admin[TAKETHISOUT] at torsoft dot no-ip dot com //22-Apr-2004 04:01 /* here are two functions, some might find them useful (maybe for encoding) converting string to hex and hex to string: */ /** * convert string to hex style string * @param $string string to convert * @return string hex style string */ public static function strhex($string){ $hex=""; for ($i=0;$i ficus/parameters/datatypes/DurationParameter.php100644 1751 144 4434 10645132217 15674 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: DurationParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as duration */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_DurationParameter */ class Ficus_DurationParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "duration"; const PATTERN = '^(-)?P([0-9]+Y)?([0-9]+M)?([0-9]+D)?(T([0-9]+H)?([0-9]+M)?([0-9]+S)?)?$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("parameter {$this->name()} is not legal duration format"); } } } ?> ficus/parameters/datatypes/PositiveIntegerParameter.php100644 1751 144 4570 10645132217 17230 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: PositiveIntegerParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as positiveInteger */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_PositiveIntegerParameter */ class Ficus_PositiveIntegerParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "positiveInteger"; const PATTERN = '^[+]?([0-9]+)$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * positive integer excludes 0 x > 0 * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(ereg('^[+\-]?0+$', $value) === false && (empty($value) || ereg(self::PATTERN, $value))){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a valid PositiveInteger format."); } } } ?> ficus/parameters/datatypes/NonPositiveIntegerParameter.php100644 1751 144 4551 10645132217 17702 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: NonPositiveIntegerParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as nonPositiveInteger */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_NonPositiveIntegerParameter */ class Ficus_NonPositiveIntegerParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "nonPositiveInteger"; const PATTERN = '^[-](0+|[0-9]+)$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * negative integer includes 0 x <= 0 * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (ereg(self::PATTERN, $value))){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a valid NonPositiveInteger format."); } } } ?> ficus/parameters/datatypes/StringParameter.php100644 1751 144 4225 10645132217 15353 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: StringParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as string */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_StringParameter */ class Ficus_StringParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "string"; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = $parameter["value"]; if(empty($value) || is_string($value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$this->name()} is not string"); } } } ?> ficus/parameters/datatypes/UnsignedLongParameter.php100644 1751 144 4515 10645132217 16503 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: UnsignedLongParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as unsignedLong */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_UnsignedLongParameter */ class Ficus_UnsignedLongParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "unsignedLong"; const PATTERN = '^[+]?[0-9]+$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (eregi(self::PATTERN, $value) && (float)$value <= 18446744073709551615 && (integer)$value >= 0)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a unsignedLong value"); } } } ?> ficus/parameters/datatypes/IntParameter.php100644 1751 144 4566 10645132217 14647 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: IntParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as int */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_IntParameter */ class Ficus_IntParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "int"; const PATTERN = '^[+\-]?[0-9]+$'; const MAX_INT = 2147483647; const MIN_INT = -2147483648; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (eregi(self::PATTERN, $value) && (string)(integer)$value == $value) && $value <= self::MAX_INT && $value >= self::MIN_INT) { parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a int value"); } } } ?> ficus/parameters/datatypes/DecimalParameter.php100644 1751 144 4450 10645132217 15443 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: DecimalParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as decimal */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_DecimalParameter */ class Ficus_DecimalParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "decimal"; const PATTERN = '^([+\-]?([0-9]+)|([+\-]?(([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*)))|(NaN|[-]?INF))$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * treat as decimal * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$this->name()} is not a decimal."); } } } ?> ficus/parameters/datatypes/UnsignedByteParameter.php100644 1751 144 4476 10645132217 16515 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: UnsignedByteParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as unsignedByte */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_UnsignedByteParameter */ class Ficus_UnsignedByteParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "unsignedByte"; const PATTERN = '^[+]?[0-9]+$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (eregi(self::PATTERN, $value) && (integer)$value <= 255 && (integer)$value >= 0)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a unsignedByte value"); } } } ?> ficus/parameters/datatypes/UnsignedShortParameter.php100644 1751 144 4510 10645132217 16676 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: UnsignedShortParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as unsignedShort */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_UnsignedShortParameter */ class Ficus_UnsignedShortParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "unsignedShort"; const PATTERN = '^[+]?[0-9]+$'; /** * construct parameter with name, value, and specific validator. * @param $name String name of this parameter. * @param $value String value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || (eregi(self::PATTERN, $value) && (integer)$value <= 65535 && (integer)$value >= 0)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$parameter['key']} is not a unsignedShort value"); } } } ?> ficus/parameters/datatypes/FloatParameter.php100644 1751 144 4520 10645132217 15150 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: FloatParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ValidatableSimpleParameter with normailizer. * treat param as float */ require_once("ficus/exception/ValidationException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); /** * @class Ficus_FloatParameter */ class Ficus_FloatParameter extends Ficus_ValidatableSimpleParameter { const TYPENAME = "float"; const PATTERN = '^(([0-9]+)|([+\-]?(([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*)))|([+\-]?((([0-9]+|([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*))[eE][+\-]?[0-9]+)))|(NaN|[-]?INF))$'; /** * construct parameter with name, value, and specific validator. * @param $name string name of this parameter. * @param $value string value of this parameter. * @param $validator array array of Ficus_Validator. */ public function __construct($name, $value = null, $validator = array()){ parent::__construct($name, self::TYPENAME, $value); $this->setValidator($validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array validated param * @throw Ficus_ValidationException invalidate parameter. */ public function validate($parameter){ $value = trim($parameter["value"]); if(empty($value) || ereg(self::PATTERN, $value)){ parent::validate($parameter); }else{ throw new Ficus_ValidationException("Parameter {$this->name()}: is not float value"); } } } ?> ficus/parameters/ValidatableComplexParameter.php100644 1751 144 7234 10645132217 15652 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ValidatableComplexParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * ComplexParameter with Validator. */ require_once("ficus/validators/Validatable.php"); require_once("ficus/parameters/ComplexParameter.php"); require_once("ficus/parameters/visitors/Visitor.php"); require_once("ficus/parameters/visitors/Acceptor.php"); require_once("ficus/exception/IllegalTypeException.php"); /** * @class Ficus_ValidatableComplexParameter */ class Ficus_ValidatableComplexParameter extends Ficus_ComplexParameter implements Ficus_Validatable, Ficus_Acceptor { /** * @var $validator array array of Ficus_Validator for validate parameter */ private $validator = array(); /** * construct validiatable Parameter. * @param $name string name * @param $typeName string name of type * @param $value mixed value of this param * @param $validator Ficus_Validator validator for validate parameter */ function __construct($name, $typeName = "", $value = null, $validator = array()){ parent::__construct($name, $typeName, $value); $this->setValidator($validator); } /** * validate param * @param $parameter array data */ public function validate($parameter){ foreach($this->validator as $validator){ $validator->validate($parameter); } } /** * accept visitor * @param $visitor Ficus_Visitor visitor */ public function accept(Ficus_Visitor $visitor){ $visitor->visit($this); } /** * set validator * @param $validator Ficus_Validator set validator * @throw Ficus_IllegalTypeException illegal validator type. */ protected function setValidator($validator){ if($validator == null){ $this->validator = array(); }else if(is_array($validator)){ foreach($validator as $v){ if($v instanceof Ficus_Validatable){ array_push($this->validator, $v); }else{ throw new Ficus_IllegalTypeException("validator must be extend Ficus_Validator"); } } }else{ throw new Ficus_IllegalTypeException("validator must be array of Ficus_Validator"); } } /** * clone method */ public function __clone(){ $validator = array(); $parameters = array(); foreach($this->validator as $v){ array_push($validator, clone $v); } foreach($this->parameters as $parameter){ array_push($parameters, clone $parameter); } $this->validator = $validator; $this->parameters = $parameters; } /** * get String form parameter * @return string definition of this parameter */ public function __toString(){ $str = ""; $str .= $this->name() . "|"; $str .= $this->typeName() . "|"; $vstr = array(); foreach($this->validator as $validator){ array_push($vstr, $validator->__toString()); } $str .= implode(",", $vstr); return $str; } } ?> ficus/parameters/Parameter.php100644 1751 144 6263 10645132217 12172 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: Parameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * Parameter class */ require_once("ficus/exception/IllegalTypeException.php"); require_once("ficus/exception/IllegalArgumentException.php"); /** * @class Ficus_Parameter */ class Ficus_Parameter { const PATTERN = '/^([a-zA-Z][a-zA-Z0-9_\-\.:]*|[_\.:]+[a-zA-Z0-9_\-\.:]*[a-zA-Z0-9])$/'; /** * @var $name string name of this Parameter */ protected $name = null; /** * @var $typeName string type name of this Parameter */ protected $typeName = null; /** * @var $value mixed value of this Parameter */ protected $value = null; /** * constructor * @param $name string name * @param $typeName string type * @param $value mixed value mixed */ function __construct($name, $typeName, $value){ $this->setName($name); $this->setTypeName($typeName); $this->setValue($value); } /** * get parameter name * @return string name of this type */ public function name(){ return $this->name; } /** * get parameter type name * @return string typename */ public function typeName(){ return $this->typeName; } /** * get value * @return mixed value */ public function value(){ return $this->value; } /** * set value * @param $value mixed value */ public function setValue($value){ $this->value = $value; } /** * set name * @param $name string name * @throw Ficus_IllegalTypeException no string. * @throw Ficus_IllegalArgumentException illegal format. */ protected function setName($name){ if(is_string($name) === false){ throw new Ficus_IllegalTypeException("name must be string"); }else if(preg_match(self::PATTERN, $name) === false){ throw new Ficus_IllegalArgumentException("illegal format name"); } $this->name = $name; } /** * set typeName * @param $typeName string typeName * @throw Ficus_IllegalTypeException no string. * @throw Ficus_IllegalArgumentException illegal format. */ protected function setTypeName($typeName){ if(is_string($typeName) === false){ throw new Ficus_IllegalTypeException("typename must be string"); }else if(preg_match(self::PATTERN, $typeName) === false){ throw new Ficus_IllegalArgumentException("Illegal format typename"); } $this->typeName = ($typeName === null) ? "" : $typeName; } } ?> ficus/parameters/ResponseSoapnizer.php100644 1751 144 5616 10645132217 13744 ISHITOYA Kentaro * @version $Id: ResponseSoapnizer.php 2 2007-07-11 10:37:48Z ishitoya $ * * ResponseSoapnizer class */ require_once("SOAP/Value.php"); require_once("ficus/parameters/visitors/ParameterAccessor.php"); require_once("ficus/lang/Assert.php"); /** * @class Ficus_ResponseSoapnizer */ class Ficus_ResponseSoapnizer { /** * convert Accessor to SOAP_Value * @param $accessor Ficus_ParameterAccessor Accessor data * @return array array of PEAR::SOAP_Value */ public static function convert($accessor){ Ficus_Assert::typeHinting("Ficus_ParameterAccessor", $accessor); $values = self::soapnize($accessor); $result = self::normalize($values); return $result; } /** * if value is single element array return SoapValue * @param $values array array of PEAR::SOAP_Value * @return mixed Soap_Value or array of Soap_Value */ private static function normalize($values){ if(count($values) == 1){ reset($values); return current($values); } return $values; } /** * get flat structure of soap values * @param $accessor Ficus_ParameterAccessor data * @return array array of PEAR::SOAP_Value */ private static function soapnize($accessor){ $result = array(); foreach($accessor as $parameter){ if($parameter instanceof Ficus_ArrayParameter){ foreach($parameter as $value){ if($value instanceof Ficus_ComplexParameter){ $vacc = new Ficus_ParameterAccessor($value); array_push($result, self::soapnize($vacc)); }else{ array_push($result, self::soapValue($value)); } } }else if($parameter instanceof Ficus_ParameterAccessor){ $result = array_merge($result, self::soapnize($parameter)); }else{ array_push($result, self::soapValue($parameter)); } } return $result; } /** * create soap value from parameter * @param $parameter Ficus_Parameter parameter to convert * @return SOAP_Value converted parameter */ private static function soapValue($parameter){ return new SOAP_Value($parameter->name(), $parameter->typeName(), $parameter->value()); } } ?> ficus/parameters/ValidatableSimpleParameter.php100644 1751 144 10203 10645132217 15502 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ValidatableSimpleParameter.php 2 2007-07-11 10:37:48Z ishitoya $ * * SimpleParameter with Validator. */ require_once("ficus/parameters/Parameter.php"); require_once("ficus/validators/Validatable.php"); require_once("ficus/parameters/visitors/Visitor.php"); require_once("ficus/parameters/visitors/Acceptor.php"); require_once("ficus/exception/IllegalTypeException.php"); /** * @class Ficus_ValidatableSimpleParameter */ class Ficus_ValidatableSimpleParameter extends Ficus_Parameter implements Ficus_Validatable, Ficus_Acceptor { /** * @var $validator array array of validator for validate parameter */ private $validator = array(); /** * construct validatable Parameter with name and typeName * @param $name string name * @param $typeName string name of type * @param $value mixed value of this param * @param $validator Ficus_Validator validator for validate parameter */ public function __construct($name, $typeName, $value = null, $validator = array()){ parent::__construct($name, $typeName, $value); $this->setValidator($validator); } /** * construct validiatable Parameter. * @param $parameter Ficus_Parameter parameter to validate * @param $value string non validate value * @param $validator Ficus_Validator validator for validate parameter */ public static function create( Ficus_Parameter $parameter, $value = null, $validator = array()){ return new Ficus_ValidatableSimpleParameter( $parameter->name(), $parameter->typeName(), $value, $validator); } /** * check param that associated with simple parameter * @param $parameter array data * @return array normalized param */ public function normalize($parameter){ //do nothing return $parameter; } /** * get value * @return mixed value */ public function value(){ return $this->normalize($this->value); } /** * validate param * @param $parameter array data */ public function validate($parameter){ foreach($this->validator as $validator){ $validator->validate($parameter); } //sets value $this->setValue($parameter["value"]); } /** * accept visitor * @param $visitor Ficus_Visitor visitor */ public function accept(Ficus_Visitor $visitor){ $visitor->visit($this); } /** * set validator * @param $validator Ficus_Validator set validator * @throw Ficus_IllegalTypeException illegal validator type. */ protected function setValidator($validator){ if($validator == null){ $this->validator = array(); }else if(is_array($validator)){ foreach($validator as $v){ if($v instanceof Ficus_Validatable){ array_push($this->validator, $v); }else{ throw new Ficus_IllegalTypeException("validator must be extend Ficus_Validator"); } } }else{ throw new Ficus_IllegalTypeException("validator must be array of Ficus_Validator"); } } /** * get String form parameter * @return string definition of this parameter */ public function __toString(){ $str = ""; $str .= $this->name() . "|"; $str .= $this->typeName() . "|"; $vstr = array(); foreach($this->validator as $validator){ array_push($vstr, $validator->__toString()); } $str .= implode(",", $vstr); return $str; } } ?> ficus/parameters/ParameterBuilder.php100644 1751 144 46105 10645132217 13520 ISHITOYA Kentaro * @author SUMI Masafumi * @version $Id: ParameterBuilder.php 2 2007-07-11 10:37:48Z ishitoya $ * * build Parameter from string definition. */ require_once("ficus/exception/ClassNotFoundException.php"); require_once("ficus/exception/IllegalTypeException.php"); require_once("ficus/parameters/ValidatableSimpleParameter.php"); require_once("ficus/parameters/ValidatableComplexParameter.php"); require_once("ficus/parameters/ArrayParameter.php"); require_once("ficus/lang/ClassLoader.php"); /** * @class Ficus_ParameterBuilder */ class Ficus_ParameterBuilder{ //separator token const T_SEPARATOR = "|"; //comma token const T_COMMA = ","; //level token const T_LEVEL = ":"; //comment token const T_COMMENT = "#"; //End of Definition token const T_EOD = "EOD"; //array token const T_ARRAY = '/([a-zA-Z0-9_:\.]+)\[\]/'; //name index const NAME = 0; //typename index const TYPENAME = 1; //validator index const VALIDATOR = 2; //validator class path const VALIDATOR_PATH = "ficus.validators.Ficus_%sValidator"; //parameter class name const DATATYPE_CLASSNAME = "Ficus_%sParameter"; //parameter class path const DATATYPE_PATH = "ficus.parameters.datatypes.Ficus_%sParameter"; /** * @var validator path. */ private static $validatorPath = ''; /** * Set validator path. * * @param $validatorPath string validator path. */ public static function setValidatorPath($validatorPath) { self::$validatorPath = $validatorPath; } /** * create root parameter * @param $name string name * @param $validator Ficus_Validator validator for root param * @return Ficus_ValidatableComplexParameter root parameter */ public static function buildRootParameter($name, $validator = null){ return new Ficus_ValidatableComplexParameter($name, "", null, $validator); } /** * create Simple Parameter with definition line * @param $definition string definition of simple parameter * @param $value mixed value of this param * @return Ficus_ValidatableSimpleParameter simple parameter */ public static function buildSimpleParameter($definition, $value = null){ $array = null; $set = self::parseOneLine($definition); if(preg_match(self::T_ARRAY, $set[self::TYPENAME], $matches)){ $array = new Ficus_ArrayParameter($set[self::NAME], $set[self::TYPENAME], $value, $set[self::VALIDATOR]); $set[self::TYPENAME] = $matches[1]; } $typename = ucfirst($set[self::TYPENAME]); $className = sprintf(self::DATATYPE_CLASSNAME, $typename); $classPath = sprintf(self::DATATYPE_PATH, $typename); try{ Ficus_ClassLoader::import($classPath); $class = new $className($set[self::NAME], $value, $set[self::VALIDATOR]); }catch(Ficus_ClassNotFoundException $e){ $class = new Ficus_ValidatableSimpleParameter( $set[self::NAME], $set[self::TYPENAME], $value, $set[self::VALIDATOR]); } if($value){ $class->validate(); } if($array){ $array->append($class); return $array; } return $class; } /** * create Complex Parameter with definition line * @param $definition string definition of complex parameter * @param $value mixed parameter value * @return Ficus_ValidatableComplexParameter complex parameter */ public static function buildComplexParameter($definition, $value = null){ $set = self::parseOneLine($definition); if(preg_match(self::T_ARRAY, $set[self::TYPENAME], $matches)){ $set[self::TYPENAME] = $matches[1]; } return new Ficus_ValidatableComplexParameter($set[self::NAME], $set[self::TYPENAME], $value, $set[self::VALIDATOR]); } /** * create Array Parameter with definition line * @param $definition string definition of array parameter * @param $value mixed parameter value * @return Ficus_ValidatableComplexParameter array parameter */ public static function buildArrayParameter($definition, $value = null){ $set = self::parseOneLine($definition); if(preg_match(self::T_ARRAY, $set[self::TYPENAME])){ return new Ficus_ArrayParameter($set[self::NAME], $set[self::TYPENAME], $value, $set[self::VALIDATOR]); }else{ return null; } } /** * create Typed Parameter * @param $name string name of this parameter * @param $typename string type * @param $value string parameter value * @param $validators array array of Ficus_Validator * @return Ficus_ValidatableSimpleParameter requested Simple Parameter */ public static function buildSimpleParameterFromTypename( $name, $typename, $value = null, $validators = null){ $typename = ucfirst($typename); $className = sprintf(self::DATATYPE_CLASSNAME, $typename); $classPath = sprintf(self::DATATYPE_PATH, $typename); try{ Ficus_ClassLoader::import($classPath); $class = new $className($name, $value, $validators); }catch(Ficus_ClassNotFoundException $e){ $class = new Ficus_ValidatableSimpleParameter( $name, $typename, $value, $validators); } if($value){ $class->validate(); } return $class; } /** * build parameter from PHP types * @param $name string name of this parameter * @param $value string value * @throw Ficus_IllegalTypeException illegal type. */ public static function buildSimpleParameterFromVariable($name, $value){ $parameter = null; if(is_string($value) && class_exists($value)){ return $this->buildParameterFromClassName($name, $value); }else if(is_array($value)){ return $this->buildParameterFromArray($name, $value); }else if(is_bool($value)){ return new Ficus_BooleanParameter($name, $value); }else if(is_double($value)){ //In php, there are no difference between double and float. //and is_double is aliase of is_float. //so we will never create FloatParameter. return new Ficus_DoubleParameter($name, $value); }else if(is_int($value)){ //same reason as double, we will not create short, byte or any //other subclass of Integer. return new Ficus_IntegerParameter($name, $value); }else if(is_object($value)){ return $this->buildParameterFromObject($name, $value); }else if(is_string($value)){ return new Ficus_StringParameter($name, $value); }else{ throw new Ficus_IllegalTypeException("this function may not accept functions, null or resource variables"); } } /** * build Parameter tree from object * @param $name string name of this parameter * @param $object mixed target object * @throw Ficus_IllegalArgumentException no object. */ public static function buildParameterFromObject($name, $object){ if(is_object($object) === false){ throw new Ficus_IllegalArgumentException("input must be an object"); } ereg('_(.+)$', get_class($object), $matches); $root = new Ficus_ValidatableComplexParameter($name, $matches[1]); $class = new ReflectionClass($object); $props = $class->getProperties(); foreach($props as $prop){ $propName = $prop->getName(); $getMethod = "get" . ucfirst($propName); if(method_exists($object, $getMethod)){ $method = $class->getMethod($getMethod); }else if(method_exists($object, $propName)){ $method = $class->getMethod($propName); }else{ continue; } $value = $object->{$method->getName()}(); // we havent ReflectionClass->hasMethod() yet, it will be // introduce in php 5.1.0. /* if($class->hasMethod($getMethod)){ $value = $object->{$getMethod}(); }else if($class->hasMethod($propName)){ $value = $object->{$propName}(); }else{ continue; } */ $root->append(self::buildParameterFromVariable($propName, $value)); } return $root; } /** * build Parameter tree from object * !!!! this method can not understand class properties when pear doc style * !!!! comment is not specified. * !!!! this problem blongs to PHP language nature. there is no type! * @param $name string name of this parameter * @param $className string class name * @throw Ficus_IllegalArgumentException no object. */ public static function buildParameterFromClassName($name, $className){ if(is_string($className) === false){ throw new Ficus_IllegalArgumentException("input must be an object"); } ereg('([^.]+_[^.]+)$', $className, $matches); $root = new Ficus_ValidatableComplexParameter($name, $matches[1]); $class = new ReflectionClass($className); $props = $class->getProperties(); foreach($props as $prop){ $propName = $prop->getName(); $getMethod = "get" . ucfirst($propName); try{ $method = $class->getMethod($getMethod); }catch(ReflectionException $e){ try{ $method = $class->getMethod($propName); }catch(ReflectionException $e){ continue; } } //get property type infomation from doc comment //I want ReflectionMethod->hasDocComment() ... try{ $comment = $method->getDocComment(); }catch(ReflectionException $e){ continue; } $validators = null; if(preg_match("/@xmltype\s+([^\s\|]+)\|?([^\s]+)?/", $comment, $matches)){ $propClassName = $matches[1]; if(isset($matches[2])){ $validators = self::buildValidators($matches[2]); } }else if(preg_match("/@return\s+([^\s]+)/", $comment, $matches)){ $propClassName = $matches[1]; } if(class_exists($propClassName)){ $root->append(self::buildParameterFromClassName( $propName, $propClassName)); }else{ $root->append(self::buildSimpleParameterFromTypename( $propName, $propClassName, null, $validators)); } } return $root; } /** * build Parameter from array * @param $name string name of this parameter * @param $array array array of parameters. must be an named * @throw Ficus_IllegalArgumentException no object. */ public static function buildParameterFromArray($name, $array){ if(is_array($array) === false){ throw new Ficus_IllegalArgumentException("this function accepts only an array"); } if(is_array($name)){ $set = each($name); $root = new Ficus_ValidatableComplexParameter( $set["key"], $set["value"]); }else{ $root = self::buildRootParameter($name); } foreach($array as $key => $value){ $root->append(self::buildParameterFromVariable($key, $value)); } return $root; } /** * create Parameter Tree from multi line definition * @param $definition string definiton * @return Ficus_ValidatableComplexParameter requested complex parameter */ public static function buildParameterFromDefinition($definition){ $lines = self::explodeNewline($definition); return self::parseMultiLine(null, $lines, 0); } /** * one line parser of parameter definition * * line format is like this * <ValiableName> <SEPARATOR> <TypeName> <SEPARATOR> * (<ValidatorName> (<COMMA> <ValidatorName>)?)? * ValiableName, TypeName and ValidatorName must be legal name * @param $line string definition line * @return array elements * @throw Ficus_IllegalArgumentException no object. */ private function parseOneLine($line){ if(is_string($line) == false){ throw new Ficus_IllegalArgumentException("input must be formated string"); } $line = trim(str_replace(self::T_LEVEL, "", $line)); preg_match('/^([^|]+)\|?((?<=\|)[^\|]+)?\|?((?<=\|).+)?$/', $line, $elements); array_shift($elements); $name = ""; $typeName = ""; if(isset($elements[self::NAME])){ $name = trim($elements[self::NAME]); } if(isset($elements[self::TYPENAME])){ $typeName = trim($elements[self::TYPENAME]); } $validators = null; if(isset($elements[self::VALIDATOR])){ $validators = self::buildValidators($elements[self::VALIDATOR]); } return array(self::NAME => $name, self::TYPENAME => $typeName, self::VALIDATOR => $validators); } /** * load validators * @param $names string validator names * @return array array of Validator classes * @throw Ficus_IllegalArgumentException illegal validator name. */ private function buildValidators($names){ if(is_string($names) === false){ throw new Ficus_IllegalArgumentException("validator names must be string"); } preg_match_all('/[a-zA-Z_]\w*\(.*\)|[a-zA-Z_][^,]*/', $names, $matches); $validatorNames = $matches[0]; $validators = array(); $parameters = array(); foreach($validatorNames as $name){ if(empty($name)){ continue; } ereg("([^\(]+)(.*)", trim($name), $regs); $className = ucfirst($regs[1]); // TODO use seasar. switch ($className) { case 'PerlRegex': case 'PostfixRegex': case 'RDF': case 'Regex': case 'Required': case 'SimpleType': case 'URI': $className = sprintf(self::VALIDATOR_PATH, $className); break; default: $className = sprintf(self::$validatorPath, $className); break; } //create parameter if(preg_match_all( '/(?:[^\\\\]["\'])(.+[^\\\\])(?:["\'])|[^,\)\(]+/', $regs[2], $regs)){ foreach($regs[0] as $key => $reg){ if(preg_match('/(?:[^\\\\])["\']/', $reg)){ $parameters[$key] = trim($regs[1][$key]); }else{ $parameters[$key] = trim($reg); } } } //load class try{ array_push($validators, Ficus_ClassLoader::load($className, $parameters)); }catch(Ficus_ClassNotFoundException $e){ throw new Ficus_IllegalArgumentException( "validator $className not found at $name line", $e); } } return $validators; } /** * multi line parser of parameter definition * this is a callback function. * * multi line format is below * whitespace must be ignored * first '\#' is comment * $definition = <<< DEF * \#first line will be used as wsdl message name * StoreResourceRequest * :id |anyURI |required,soyaURN * :target |anyURI |required * :creator |anyURI |required * :metadata|base64Binary|required,RDF * :data |base64Binary|required * DEF; * * nested * $definition = <<< DEF * StoreResourceResponse * :return|StoreResult| * \#nested definition of StoreResult * ::id |anyURI |soyaURN * ::target |anyURI | * ::creator |anyURI | * ::metadata|base64Binary| * ::data |base64Binary| * DEF; * * array indicator is '[]' * array simple type * $definition = <<< DEF * \#first line will be used as wsdl message name * StoreResourceResponse * :id |anyURI[] |required,SoyaID * DEF; * * complex type array * $definition = <<< DEF * StoreResourceResponse * :return|StoreResult[]| * \#nested definition of StoreResult * ::id |anyURI |soyaURN * ::target |anyURI | * ::creator |anyURI | * ::metadata|base64Binary| * ::data |base64Binary| * DEF; * and use like this. * $response = $builder->createWithDefString($definition); * * create parameter tree. * @param $root Ficus_ComplexParameter root parameter * @param $lines array array of lines * @param $baseLevel integer base depth level * @return Ficus_ValidatableComplexParameter result * @throw Ficus_IllegalArgumentException illegal next level. */ private function parseMultiLine($root, $lines, $baseLevel){ for($i = 0; $i < count($lines); $i++){ if(empty($lines[$i])){ continue; } $currentLine = trim($lines[$i]); $currentLevel = self::getLevel($currentLine); $nextLevel = 0; //ignore comment if($currentLevel === self::T_COMMENT){ continue; } //check for next line for($k = $i + 1; $k <= count($lines); $k++){ if(isset($lines[$k]) == false){ $nextLevel = self::getLevel(null); }else{ $nextLevel = self::getLevel($lines[$k]); } if($nextLevel === self::T_COMMENT){ continue; }else if($nextLevel === self::T_EOD){ $nextLevel = $currentLevel; break; }else if($nextLevel - $baseLevel >= 2){ throw new Ficus_IllegalArgumentException("nest level is wrong"); }else{ break; } } if($nextLevel > $baseLevel || $root == null){ if($currentLevel == 0 && $root == null){ $set = self::parseOneLine($currentLine); $root = self::buildRootParameter($set[self::NAME], $set[self::VALIDATOR]); $root = self::parseMultiLine( $root,array_slice($lines, $i + 1), $nextLevel); }else{ $array = self::buildArrayParameter($currentLine); if($array){ $branch = self::buildComplexParameter($currentLine); $branch = self::parseMultiLine( $branch, array_slice($lines, $i + 1), $nextLevel); $array->append($branch); $root->append($array); }else{ $branch = self::buildComplexParameter($currentLine); $root->append(self::parseMultiLine( $branch, array_slice($lines, $i + 1), $nextLevel)); } } //jump next target for($i = $i + 1; $i < count($lines); $i++){ $currentLevel = self::getLevel($lines[$i]); if($currentLevel == self::T_COMMENT){ continue; }else if($currentLevel == self::T_EOD || $currentLevel < $nextLevel){ break; } } }else if($nextLevel == $baseLevel){ $root->append(self::buildSimpleParameter($currentLine)); }else{ return $root; } } return $root; } /** * get Level of line * @param $string string parameter definition * @return integer level */ private function getLevel($string){ if(empty($string)){ return self::T_EOD; } if(ereg("^" . self::T_COMMENT, $string)){ return self::T_COMMENT; } $level = ereg("^" . self::T_LEVEL . "+", $string, $regs); return $level ? strlen($regs[0]) : 0; } /** * explode lines with new line spesific charactor. * @param $lines string strings * @return array array of string * @throw Ficus_IllegalTypeException no string. */ private function explodeNewline($lines){ if(is_string($lines) == false){ throw new Ficus_IllegalTypeException("input must be string"); } if(strpos($lines, "\r\n")){ $newline = "\r\n"; }else if(strpos($lines, "\r")){ $newline = "\r"; }else if(strpos($lines, "\n")){ $newline = "\n"; }else{ return; } return explode($newline, $lines); } } ?> ficus/analyzer/AnnotationAnalyzeData.php100644 1751 144 3454 10645132217 14163 SUMI Masafumi * @version $Id: AnnotationAnalyzeData.php 2 2007-07-11 10:37:48Z ishitoya $ * * Annotation Analyze data of PHP. */ require_once('ficus/lang/Arrays.php'); require_once('ficus/analyzer/AnalyzeData.php'); /** * @class Ficus_AnnotationAnalyzeData */ class Ficus_AnnotationAnalyzeData extends Ficus_AnalyzeData { /** * @var annotation data. */ protected $data; /** * Constructor. * * @param $name string name. */ public function __construct($name) { $this->name = $name; } /** * Set data. * * @param $data annotation data. */ public function setData($data) { $this->data = $data; } /** * Get data. * * @return string of annotation data. */ public function getData() { return $this->data; } /** * To string. * * @return string of this. */ public function __toString() { return $this->name . ' ' . $this->data . "\n"; } } ?> ficus/analyzer/AnnotationChecker.php100644 1751 144 12770 10645132217 13353 SUMI Masafumi * @version $Id: AnnotationChecker.php 2 2007-07-11 10:37:48Z ishitoya $ * * Annotation checker of PHP. */ require_once('ficus/analyzer/AnalyzeData.php'); require_once('ficus/analyzer/AnnotationAnalyzeData.php'); require_once('ficus/analyzer/ClassAnalyzeData.php'); require_once('ficus/analyzer/FunctionAnalyzeData.php'); require_once('ficus/analyzer/ParameterAnalyzeData.php'); require_once('ficus/analyzer/ThrowAnalyzeData.php'); require_once('ficus/analyzer/SourceAnalyzer.php'); /** * @class Ficus_AnnotationChecker */ class Ficus_AnnotationChecker extends Ficus_SourceAnalyzer { /** * call each source. * * @param $classes classes in this source. * @see Ficus_SourceAnalyzer. */ public function callSource($classes) { foreach ($classes as $class) { self::checkAnnotation($class); } } /** * check annotation. * * @param $class class. */ protected function checkAnnotation($class) { self::checkClassAnnotation($class); foreach ($class->getFunctions() as $function) { self::checkFunctionAnnotation($class, $function); } } /** * check class annotation. * * @param $class class. */ protected function checkClassAnnotation($class) { $ano = array(); $atClass = ''; foreach ($class->getAnnotations() as $annotation) { if ($annotation->getName() == '@class' || $annotation->getName() == '@interface') { $atClass = $annotation->getData(); } } // no class if ($class->getName() == '* NO_CLASS *') { return; } if ($atClass == '') { echo "No declare annotation @class in 'class " . $class->getName() . "' at '" . $class->getPath() . "'\n"; } else if ($class->getName() != $atClass) { echo "Bad annotation '@class " . $atClass . "' in 'class " . $class->getName() . "' at '" . $class->getPath() . "'\n"; } } /** * Get annotation array. * * @param $annotations array of Ficus_AnnotattionAnalyzeData. * @param $type Annotation type. * @return array array of annotation strings. */ protected function getAnnotationArray($annotations, $type) { $atParams = array(); if (is_array($annotations[$type])) { foreach ($annotations[$type] as $paramData) { $split = preg_split('/ /', $paramData); $atParams[] = $split[0]; } } return $atParams; } /** * Check function annotation. * * @param $class Ficus_ClassAnalyzeData. * @param $function Ficus_FunctionAnalyzeData function. */ protected function checkFunctionAnnotation(Ficus_ClassAnalyzeData $class, Ficus_FunctionAnalyzeData $function) { $ano = array(); foreach ($function->getAnnotations() as $annotation) { $ano[$annotation->getName()][] = $annotation->getData(); } $params = array(); foreach ($function->getParameters() as $parameter) { $params[] = $parameter[0]->getName(); } $throws = array(); foreach ($function->getThrows() as $throw) { $throws[] = $throw->getName(); } $atParams = self::getAnnotationArray($ano, '@param'); $atExceptions = self::getAnnotationArray($ano, '@exception'); $atThrows = self::getAnnotationArray($ano, '@throw'); $atThrows = array_merge($atExceptions, $atThrows); // no @params foreach (array_diff($params, $atParams) as $param) { echo "No declare annotation @param '" . $param . "' in '" . $class->getName() . "#" . $function->getName() . "()' at '" . $class->getPath() . "'\n"; } // no using @params foreach (array_diff($atParams, $params) as $param) { if (strcasecmp($param, 'mixed') == 0 && sizeof($params) == 0) { // probably variable-length argument. } else { echo "No exist parameter '" . $param . "' in '" . $class->getName() . "#" . $function->getName() . "()' at '" . $class->getPath() . "'\n"; } } // no @throw foreach (array_diff($throws, $atThrows) as $param) { echo "No declare annotation @throw '" . $param . "' in '" . $class->getName() . "#" . $function->getName() . "()' at '" . $class->getPath() . "'\n"; } // no using @throw // possibility throw in deep function. // no check. } } /* if ($argv[1] == null) { echo "need start path."; exit; } $analyze = new Ficus_AnnotationChecker(); $analyze->traverse($argv[1]); */ ?> ficus/analyzer/ThrowAnalyzeData.php100644 1751 144 2616 10645132217 13153 SUMI Masafumi * @version $Id: ThrowAnalyzeData.php 2 2007-07-11 10:37:48Z ishitoya $ * * Throw Analyze data of PHP. */ require_once('ficus/analyzer/AnalyzeData.php'); /** * @class Ficus_ThrowAnalyzeData */ class Ficus_ThrowAnalyzeData extends Ficus_AnalyzeData { /** * Constructor. * * @param $name string of name. */ public function __construct($name) { $this->name = $name; } /** * To string. * * @return string of this. */ public function __toString() { return 'throw ' . $this->name . "\n"; } } ?> ficus/analyzer/AnalyzeData.php100644 1751 144 5400 10645132217 12121 SUMI Masafumi * @version $Id: AnalyzeData.php 2 2007-07-11 10:37:48Z ishitoya $ * * Analyze data of PHP. */ require_once('ficus/lang/Arrays.php'); /** * @class Ficus_AnalyzeData */ class Ficus_AnalyzeData { /** * @var data name. */ protected $name; /** * @var comment. */ protected $comment; /** * @var annotations. */ protected $annotations = array(); /** * Set name. * * @param $name string name. */ public function setName($name) { $this->name = $name; } /** * Get name. * * @return string name. */ public function getName() { return $this->name; } /** * Set comment. * * @param $comment string comment. */ public function setComment($comment) { $this->comment = $comment; } /** * Get comment. * * @return string comment. */ public function getComment() { return $this->comment; } /** * Add annotation. * * @param $annotation Ficus_AnnotationAnalyzeData. */ public function addAnnotation($annotation) { $this->annotations[] = $annotation; } /** * Set annotations. * * @param $annotations array of Ficus_AnnotationAnalyzeData. */ public function setAnnotations($annotations) { $this->annotations = $annotations; } /** * Get annotations. * * @return array of annotation. */ public function getAnnotations() { return $this->annotations; } /** * Get Annotation. * * @param $index int index of annotation. * @return Ficus_AnnotationAnalyzeData annotation analyze data. */ public function getAnnotation($index) { return $this->annotations[$index]; } /** * To string. * * @return string of this. */ public function __toString() { $buf = $this->getName() . "\n"; $buf .= Ficus_Arrays::arrayToString($this->annotations); return $buf; } } ?> ficus/analyzer/SourceAnalyzer.php100644 1751 144 16422 10645132217 12720 SUMI Masafumi * @version $Id: SourceAnalyzer.php 2 2007-07-11 10:37:48Z ishitoya $ * * Source analyzer of PHP. */ require_once('ficus/io/Dir.php'); require_once('ficus/io/PathPattern.php'); require_once('ficus/analyzer/AnalyzeData.php'); require_once('ficus/analyzer/AnnotationAnalyzeData.php'); require_once('ficus/analyzer/ClassAnalyzeData.php'); require_once('ficus/analyzer/FunctionAnalyzeData.php'); require_once('ficus/analyzer/ParameterAnalyzeData.php'); require_once('ficus/analyzer/ThrowAnalyzeData.php'); /** * @class Ficus_SourceAnalyzer */ class Ficus_SourceAnalyzer { /** * @var sources. */ private $sources = array(); /** * traverse files in path. * * @param $path traverse path. * @return array sources. */ public function traverse($path) { $pattern = new Ficus_PathPattern(); $pattern->addInclude("**.php"); $dir = new Ficus_Dir($path, $pattern); $dir->each(array($this, 'analyze')); return $this->sources; } /** * analyze source. * * @param $fullpath fullpath. */ public function analyze($fullpath) { $this->analyzeClass($fullpath); $this->callSource($this->sources[sizeof($this->sources)-1]); } /** * get sources. * * @return array sources. */ public function getSources() { return $this->sources; } /** * to string. * * @return string preview. */ public function __toString() { $buf = ''; foreach ($this->sources as $source) { foreach ($source as $class) { $buf .= $class->__toString() . "\n"; } } return $buf; } /** * call each source. * * @param $classes array of Ficus_ClassAnalyzeData in source. */ public function callSource($classes) {} /** * analyze class. * * @param $path path. */ public function analyzeClass($path) { $classes = array(); $comment = ''; $annotations = array(); $tokens= token_get_all(file_get_contents($path)); foreach ($tokens as $index => $token) { if ($token[0] == T_CLASS || $token[0] == T_INTERFACE) { $nextToken = self::nextTypeOf(T_STRING, $index, $tokens); $class = new Ficus_ClassAnalyzeData($path, $nextToken); $class->setAnnotations($annotations); $class->setComment($comment); $classes[] = $class; $comment = ''; } else if ($token[0] == T_FUNCTION) { if ($class == null) { $class = new Ficus_ClassAnalyzeData($path, null); $classes[] = $class; } $nextToken = self::nextTypeOf(T_STRING, $index, $tokens); $function = new Ficus_FunctionAnalyzeData($nextToken); $function->setComment($comment); $function->setAnnotations($annotations); $function->setParameters(self::analyzeParameters($index, $tokens)); $class->addFunction($function); $comment = ''; } else if ($token[0] == T_DOC_COMMENT) { $comment = $token[1]; $annotations = self::analyzeComment($token[1]); } else if ($token[0] == T_THROW) { if ($tokens[$index+2][0] != T_NEW) { // T_THROW T_VARIABLE // search backward. $i = $index; do { $i--; } while ($tokens[$i][0] != T_STRING); $nextToken = $tokens[$i][1]; } else { // T_THROW T_NEW T_STRING // search forward. $nextToken = self::nextTypeOf(T_STRING, $index, $tokens); } $throw = new Ficus_ThrowAnalyzeData($nextToken); $function->addThrow($throw); } } $this->sources[] = $classes; } /** * analyze parameters. * * @param $index index of tokens. * @param $tokens PHP tokens. * @return array parameters. */ static function analyzeParameters($index, $tokens) { $args = array(); $arg = null; // T_FUNCTION T_WHITESPACE T_STRING ( $index += 4; while (($type = $tokens[$index][0]) != '{' && $type != ';') { switch ($type) { case T_WHITESPACE: $index++; continue 2; break; case ',': case ')': case ':': case ';': case '(': case '=': break; case T_VARIABLE: $args[] = array(); $arg = new Ficus_ParameterAnalyzeData($tokens[$index][1]); $args[sizeof($args)-1][] = $arg; break; default: if ($arg != null) { $arg->setDefaultValue($tokens[$index][1]); } break; } /* if (is_string($type)) { echo $type . "\n"; } else if ($type != T_WHITESPACE) { // T_VARIABLE // T_VARIABLE = T_STRING // T_VARIABLE = T_CONSTANT_ENCAPSED_STRING // T_VARIABLE = T_ARRAY() echo token_name($type) . "\n"; } */ $index++; } return $args; } /** * analyze comment. * * @param $comment * @return array annotations. */ static function analyzeComment($comment) { $annotations = array(); foreach (preg_split('/\r|\n/', $comment) as $line) { if (preg_match('/(@\S+)\s+(.*)$/', $line, $matches) > 0) { $annotation = new Ficus_AnnotationAnalyzeData($matches[1]); $annotation->setData($matches[2]); $annotations[] = $annotation; } } return $annotations; } /** * search type. * * @param $type find type. * @param $index index of tokens. * @param $tokens PHP tokens. * @return string value. */ static function nextTypeOf($type, $index, $tokens) { $i = $index; do { $i++; } while ($tokens[$i][0] != $type); return $tokens[$i][1]; } } ?> ficus/analyzer/FunctionAnalyzeData.php100644 1751 144 6411 10645132217 13632 SUMI Masafumi * @version $Id: FunctionAnalyzeData.php 2 2007-07-11 10:37:48Z ishitoya $ * * Function Analyze data of PHP. */ require_once('ficus/analyzer/AnalyzeData.php'); /** * @class Ficus_FunctionAnalyzeData */ class Ficus_FunctionAnalyzeData extends Ficus_AnalyzeData { /** * @var function parameters. */ protected $parameters = array(); /** * @var throwing exceptions in function. */ protected $throws = array(); /** * Constructor. * * @param $name string name. */ public function __construct($name) { $this->name = $name; } /** * Add throw analyze data. * * @param $throw Ficus_ThrowAnalyzeData. */ public function addThrow($throw) { $this->throws[] = $throw; } /** * Set throw analyze data. * * @param $throws array of Ficus_ThrowAnalyzeData. */ public function setThrows($throws) { $this->throws = $throws; } /** * Get throw analyze data by index. * * @param $index int index of throw analyze data. * @return Ficus_ThrowAnalyzeData. */ public function getThrow($index) { return $this->throws[$index]; } /** * Get throw analyze data. * * @return array of Ficus_ThrowAnalyzeData. */ public function getThrows() { return $this->throws; } /** * Add parameter analyze data. * * @param $parameter Ficus_ParameterAnalyzeData. */ public function addParameter($parameter) { $this->parameters[] = $parameter; } /** * Set parameter analyze data. * * @param $parameters array of Ficus_ParameterAnalyzeData. */ public function setParameters($parameters) { $this->parameters = $parameters; } /** * Get parameter analyze data by index. * * @param $index int index of parameter analyze data. */ public function getParameter($index) { return $this->parameters[$index]; } /** * Get parameter analyze data. * * @return array of Ficus_ParameterAnalyzeData. */ public function getParameters() { return $this->parameters; } /** * To string. * * @return string of this. */ public function __toString() { $buf = "\nfunction " . parent::__toString(); foreach ($this->parameters as $parameter) { $buf .= Ficus_Arrays::arrayToString($parameter); } $buf .= Ficus_Arrays::arrayToString($this->throws); return $buf; } } ?> ficus/analyzer/ClassAnalyzeData.php100644 1751 144 5210 10645132217 13106 SUMI Masafumi * @version $Id: ClassAnalyzeData.php 2 2007-07-11 10:37:48Z ishitoya $ * * Class Analyze data of PHP. */ require_once('ficus/lang/Arrays.php'); require_once('ficus/analyzer/AnalyzeData.php'); /** * @class Ficus_ClassAnalyzeData */ class Ficus_ClassAnalyzeData extends Ficus_AnalyzeData { /** * @var path. */ protected $path; /** * @var Ficus_FunctionAnalyzeData in this class. */ protected $functions = array(); /** * Constructor. * * @param $path string of path. * @param $name string of name. */ public function __construct($path, $name) { $this->path = $path; $this->name = $name; } /** * Get name. * * @return string of name. */ public function getName() { return ($this->name != null) ? $this->name : '* NO_CLASS *'; } /** * Get path. * * @return string of path. */ public function getPath() { return $this->path; } /** * Add function. * * @param $function Ficus_FunctionAnalyzeData. */ public function addFunction($function) { $this->functions[] = $function; } /** * Get function analyze data by index. * * @param $index int index of Ficus_FunctionAnalyzeData. * @return Ficus_FunctionAnalyzeData. */ public function getFunction($index) { return $this->functions[$index]; } /** * Get function analyze data. * * @return array of Ficus_FunctionAnalyzeData. */ public function getFunctions() { return $this->functions; } /** * To string. * * @return string of this. */ public function __toString() { $buf = "[" . $this->path . "]\n"; $buf .= 'class ' . parent::__toString(); $buf .= Ficus_Arrays::arrayToString($this->functions); return $buf; } } ?> ficus/analyzer/ParameterAnalyzeData.php100644 1751 144 3770 10645132217 13772 SUMI Masafumi * @version $Id: ParameterAnalyzeData.php 2 2007-07-11 10:37:48Z ishitoya $ * * Parameter Analyze data of PHP. */ require_once('ficus/analyzer/AnalyzeData.php'); /** * @class Ficus_ParameterAnalyzeData */ class Ficus_ParameterAnalyzeData extends Ficus_AnalyzeData { /** * @var default parameter value. */ protected $defaultValue; /** * Constructor. * * @param $name string parameter name. */ public function __construct($name) { $this->name = $name; } /** * Set default parameter value. * * @param $defaultValue default parameter value. */ public function setDefaultValue($defaultValue) { $this->defaultValue = $defaultValue; } /** * Get default parameter value. * * @return default parameter value. */ public function getDefaultValue() { return $this->defaultValue; } /** * To string. * * @return string of this. */ public function __toString() { if ($thid->defaultValue != null) { return $this->name . ' = ' . $this->defaultValue . "\n"; } else { return $this->name . "\n"; } } } ?>