/**
  * This action list all admin controller in all active modules.
  * It can help to build navigation.
  */
 public function listAdminAction()
 {
     $front = $this->getFrontController();
     $modules = $front->getControllerDirectory();
     $moduleEnabled = Centurion_Config_Manager::get('resources.modules');
     $this->view->modules = array();
     foreach ($modules as $moduleName => $module) {
         $this->view->modules[$moduleName] = array();
         if (!in_array($moduleName, $moduleEnabled)) {
             continue;
         }
         $dbTableDir = realpath($module);
         if (!file_exists($dbTableDir)) {
             continue;
         }
         $dir = new Centurion_Iterator_DbTableFilter($dbTableDir);
         foreach ($dir as $fileInfo) {
             if (substr($fileInfo, 0, 5) == 'Admin') {
                 if (substr($fileInfo, -14) == 'Controller.php') {
                     $controllerName = Centurion_Inflector::tableize(substr($fileInfo, 0, -14), '-');
                     $this->view->modules[$moduleName][] = $controllerName;
                 }
             }
         }
     }
     ksort($this->view->modules);
 }
Exemplo n.º 2
0
 public function getAction()
 {
     $this->getHelper('layout')->disableLayout();
     $this->getHelper('viewRenderer')->setNoRender(true);
     $media = $this->getInvokeArg('bootstrap')->getOption('media');
     if (!(null != ($fileRow = $this->_getParam('file')) && $fileRow instanceof Media_Model_DbTable_Row_File)) {
         $mediaAdapter = Media_Model_Adapter::factory($media['adapter'], $media['params']);
         $id = bin2hex(Centurion_Inflector::urlDecode($this->_request->getParam('id')));
         $key = bin2hex(Centurion_Inflector::urlDecode($this->_request->getParam('key')));
         $fileRow = $this->_helper->getObjectOr404('media/file', array('id' => $id));
         $this->forward404If(!$mediaAdapter->isValidKey($fileRow, $key, '', $media['key_lifetime']));
     }
     $source = $media['uploads_dir'] . DIRECTORY_SEPARATOR . $fileRow->local_filename;
     if (null == $this->_getParam('noAdapter', null)) {
         $isSaved = $mediaAdapter->save($source, $fileRow->getRelativePath(null, false, true), true);
         if ($isSaved) {
             Centurion_Db::getSingleton('media/duplicate')->insert(array('file_id' => $fileRow->id, 'adapter' => $media['adapter'], 'params' => serialize($media['params']), 'dest' => $fileRow->getRelativePath(null, false, true)));
             return $this->getHelper('redirector')->gotoUrlAndExit($fileRow->getStaticUrl());
         }
     }
     $offset = 24 * 60 * 60 * 365;
     $this->getResponse()->setHeader('Content-type', $fileRow->mime)->setHeader('Content-Length', filesize($source))->setHeader('Content-Disposition', sprintf('inline; filename="%s";', $fileRow->filename))->setHeader('Cache-Control', sprintf('max-age=%d, public', $offset))->setHeader('Expires', sprintf('%s GMT', gmdate('D, d M Y H:i:s', time() + $offset)))->sendHeaders();
     while (@ob_end_flush()) {
     }
     $fp = fopen($source, 'rb');
     fpassthru($fp);
     fclose($fp);
     $this->getResponse()->clearHeaders();
 }
Exemplo n.º 3
0
 protected function _makeDisplayGroup(Centurion_Form $form, $data, $class)
 {
     if (isset($data['noFieldset']) && $data['noFieldset'] === true) {
         $form->addInDisplayGroup($data['elements'], $class, array('class' => 'form-' . substr($class, 1)));
         foreach ($data['elements'] as $key => $element) {
             if (null !== ($element = $form->getElement($element))) {
                 $element->setLabel(null);
                 $element->removeDecorator('label');
             }
         }
         return true;
     }
     if (!isset($data['label'])) {
         $name = uniqid();
     } else {
         $name = Centurion_Inflector::slugify($data['label']);
     }
     $name = $name . '_group';
     $form->addDisplayGroup($data['elements'], $name, array('class' => 'form-group'));
     $displayGroup = $form->getDisplayGroup($name);
     if (isset($data['label']) && is_string($data['label'])) {
         $displayGroup->setLegend($data['label']);
         if (isset($data['description'])) {
             $displayGroup->setDescription($data['description']);
         }
     } else {
         $displayGroup->setDescription(' ');
     }
     $form->addInDisplayGroup(array($name), $class, array('class' => 'form-' . substr($class, 1)));
 }
Exemplo n.º 4
0
 /**
  * Inspect db for Zend_Db adapter.
  * Connect to a database and generate models.
  *
  * @param string $tablePrefix 
  * @param string $environment 
  * @return void
  */
 public function inspect($tablePrefix = self::DEFAULT_TABLE_PREFIX, $environment = self::DEFAULT_ENVIRONMENT)
 {
     $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION);
     $buildDirectory = $this->_loadedProfile->search('buildDirectory');
     $tables = $this->_getDbImport()->getAdapter()->listTables();
     $dependentTables = array();
     $classes = array();
     foreach ($tables as $key => $table) {
         $metadata = $this->_getDbImport()->getAdapter()->describeTable($table);
         $primary = array();
         $className = Centurion_Inflector::modelize($table);
         $classNamePrefix = sprintf('%s%s', $this->_formatPrefix($tablePrefix), $className);
         $relations[$table] = array();
         foreach ($metadata as $columnName => $columnValue) {
             if ($columnValue[self::PRIMARY] === true) {
                 array_push($primary, $columnName);
             }
         }
         $localRelations = $this->_getDbImport()->listTableRelations($table);
         foreach ($localRelations as $localRelationKey => $localRelation) {
             $referenceClassName = Centurion_Inflector::modelize($localRelation['table']);
             if (!array_key_exists($referenceClassName, $dependentTables)) {
                 $dependentTables[$referenceClassName] = array();
             }
             $relations[$table][strtolower($referenceClassName)] = array('columns' => $localRelation['local'], 'refColumns' => $localRelation['foreign'], 'refTableClass' => sprintf('%s%s', $this->_formatPrefix($tablePrefix), $referenceClassName));
             $key = strtolower(Centurion_Inflector::pluralize($className));
             $dependentTables[$referenceClassName][$key] = $classNamePrefix;
         }
         $existingModelFile = $this->_loadedProfile->search(array('dataDirectory', 'buildDirectory', 'buildFile' => array('fileName' => $className)));
         if (false !== $existingModelFile) {
             $existingModelFile->delete();
         }
         $buildFile = $buildDirectory->createResource('BuildFile', array('name' => $table, 'primary' => $primary, 'cols' => array_keys($metadata), 'metadata' => $metadata, 'className' => $classNamePrefix, 'fileName' => $className, 'referenceMap' => $relations[$table]));
         $classes[$className] = $buildFile;
     }
     foreach ($dependentTables as $key => $dependentTable) {
         if (!array_key_exists($key, $classes)) {
             continue;
         }
         $classes[$key]->getModelClass()->getProperty('_dependentTables')->setDefaultValue($dependentTable);
     }
     if ($this->_registry->getRequest()->isPretend()) {
         foreach ($classes as $key => $class) {
             $this->_registry->getResponse()->appendContent(sprintf('Would create model at %s: %s', $buildDirectory->getPath(), $key));
             $this->_registry->getResponse()->appendContent($class->getContents());
         }
     } else {
         if (!file_exists($buildDirectory->getPath())) {
             throw new Centurion_Exception('Build directory does not exist.');
         }
         if (!is_writable($buildDirectory->getPath())) {
             throw new Centurion_Exception('Build directory is not writable.');
         }
         foreach ($classes as $key => $class) {
             $this->_registry->getResponse()->appendContent(sprintf('Creating model at %s: %s', $buildDirectory->getPath(), $key));
             $class->create();
         }
         $this->_storeProfile();
     }
 }
Exemplo n.º 5
0
 public function insert(array $data)
 {
     $primary = $this->_primary;
     if (is_array($primary)) {
         $primary = $primary[1];
     }
     if (!isset($data[$primary])) {
         $data[$primary] = md5(Centurion_Inflector::uniq(uniqid()));
     }
     if (!isset($data['sha1'])) {
         $data['sha1'] = sha1_file(Centurion_Config_Manager::get('media.uploads_dir') . DIRECTORY_SEPARATOR . $data['local_filename']);
     }
     $row = $this->fetchRow(array('sha1=?' => $data['sha1'], 'filesize=?' => $data['filesize']));
     //We want to be sure
     if ($row !== null && sha1_file(Centurion_Config_Manager::get('media.uploads_dir') . DIRECTORY_SEPARATOR . $data['local_filename']) == $row->sha1 && filesize(Centurion_Config_Manager::get('media.uploads_dir') . DIRECTORY_SEPARATOR . $data['local_filename']) == $row->filesize) {
         //We reuse the same local filename
         unlink(Centurion_Config_Manager::get('media.uploads_dir') . DIRECTORY_SEPARATOR . $data['local_filename']);
         $data['file_id'] = $row->file_id;
         $data['local_filename'] = $row->local_filename;
         $data['filesize'] = $row->filesize;
         $data['proxy_model'] = $row->proxy_model;
         $data['proxy_pk'] = $row->proxy_pk;
         $data['belong_model'] = $row->belong_model;
         $data['belong_pk'] = $row->belong_pk;
     }
     if (!isset($data['file_id'])) {
         $data['file_id'] = $data[$primary];
     }
     if (!isset($data['proxy_pk'])) {
         foreach ($this->_dependentProxies as $key => $dependentProxy) {
             $proxyTable = Centurion_Db::getSingletonByClassName($dependentProxy);
             if (!in_array($data['mime'], array_keys($proxyTable->getMimeTypes()))) {
                 continue;
             }
             $cols = $proxyTable->info('cols');
             $proxyData = array();
             foreach ($data as $key => $value) {
                 if ($key == $primary || !in_array($key, $cols)) {
                     continue;
                 }
                 $proxyData[$key] = $value;
                 unset($data[$key]);
             }
             $proxyData = $data;
             unset($proxyData[$primary]);
             $pk = $proxyTable->insert($proxyData);
             $data = array_merge($data, array('proxy_model' => $dependentProxy, 'proxy_pk' => $pk));
         }
     }
     if (array_key_exists(self::BELONG_TO, $data)) {
         list($model, $pk) = $this->_setupProxyBelong($data[self::BELONG_TO]);
         $data = array_merge($data, array('belong_model' => $model, 'belong_pk' => $pk));
         unset($data[self::BELONG_TO]);
     }
     return parent::insert($data);
 }
Exemplo n.º 6
0
 public function __construct($name = NULL, array $data = array(), $dataName = '')
 {
     if ($this->_moduleName == null && $this->_objectName == null) {
         $class = get_class($this);
         preg_match('`([a-z]*)_.*_Admin([a-z]*)ControllerTest`i', $class, $matches);
         $this->_moduleName = strtolower($matches[1]);
         $this->_objectName = Centurion_Inflector::tableize($matches[2], '-');
     }
     parent::__construct($name, $data, $dataName);
 }
Exemplo n.º 7
0
 /**
  *
  * @param string $key
  * @return Centurion_Signal_Abstract
  */
 public static function factory($key)
 {
     $registered = self::registry($key);
     if (is_null($registered)) {
         $className = Centurion_Inflector::classify($key);
         $className = self::getPluginLoader()->load($className);
         $registered = new $className();
         self::register($key, $registered);
     }
     return $registered;
 }
Exemplo n.º 8
0
 /**
  * Initialize modules
  *
  * @return array[string]Centurion_Application_Module_Bootstrap
  * @throws Centurion_Application_Resource_Exception When bootstrap class was not found
  */
 public function init()
 {
     $bootstrap = $this->getBootstrap();
     $bootstrap->bootstrap('FrontController');
     $front = $bootstrap->getResource('FrontController');
     $modules = $front->getControllerDirectory();
     $default = $front->getDefaultModule();
     $curBootstrapClass = get_class($bootstrap);
     $options = $this->getOptions();
     if (is_array($options) && !empty($options[0])) {
         $diffs = array_diff($options, array_keys($modules));
         if (count($diffs)) {
             throw new Centurion_Application_Resource_Exception(sprintf('The modules %s is not found in your registry (%s)', implode(', ', $diffs), implode(PATH_SEPARATOR, $modules)));
         }
         foreach ($modules as $key => $module) {
             if (!in_array($key, $options) && $key !== $default) {
                 unset($modules[$key]);
                 $front->removeControllerDirectory($key);
             }
         }
         $modules = Centurion_Inflector::sortArrayByArray($modules, array_values($options));
     }
     foreach ($modules as $module => $moduleDirectory) {
         $bootstrapClass = $this->_formatModuleName($module) . '_Bootstrap';
         if (!class_exists($bootstrapClass, false)) {
             $bootstrapPath = dirname($moduleDirectory) . '/Bootstrap.php';
             if (!file_exists($bootstrapPath)) {
                 throw new Centurion_Application_Exception('Module ' . $module . ' has no Bootstrap class', 500);
             }
             include_once $bootstrapPath;
             if ($default != $module && !class_exists($bootstrapClass, false)) {
                 $eMsgTpl = 'Bootstrap file found for module "%s" but bootstrap class "%s" not found';
                 throw new Centurion_Application_Resource_Exception(sprintf($eMsgTpl, $module, $bootstrapClass));
             } elseif ($default == $module) {
                 if (!class_exists($bootstrapClass, false)) {
                     $bootstrapClass = 'Bootstrap';
                     if (!class_exists($bootstrapClass, false)) {
                         throw new Zend_Application_Resource_Exception(sprintf($eMsgTpl, $module, $bootstrapClass));
                     }
                 }
             }
         }
         if ($bootstrapClass == $curBootstrapClass) {
             // If the found bootstrap class matches the one calling this
             // resource, don't re-execute.
             continue;
         }
         $moduleBootstrap = new $bootstrapClass($bootstrap);
         $moduleBootstrap->bootstrap();
         $this->_bootstraps[$module] = $moduleBootstrap;
     }
     return $this->_bootstraps;
 }
Exemplo n.º 9
0
 public function publish($message)
 {
     foreach ($message as $key => $params) {
         if (null !== $this->_mapReference[$key] && strlen($params) > $this->_mapReference[$key]) {
             $message[$key] = Centurion_Inflector::cuttext($params, $this->_mapReference[$key]);
         }
     }
     if (!$this->getTokenHandler()->getToken()) {
         throw new Centurion_Social_NoTokenException('No access token');
     }
     $target = $this->getTargetObject();
     if (null === $target || '' == trim($target)) {
         throw new Centurion_Social_Exception('No target for publishing has been defined');
     }
     // if targetobject is a person id (other than "me"), it will not work
     if ($this->getTargetObject() != self::DEFAULT_TARGET) {
         $client = new Zend_Http_Client();
         $client->setParameterGet(array('access_token' => $this->getTokenHandler()->getToken()))->setUri(self::ACCOUNTS_URI);
         $response = $client->request(Zend_Http_Client::GET);
         $data = Zend_Json::decode($response->getBody());
         $pageAccessToken = null;
         echo '<pre>';
         foreach ($data['data'] as $page) {
             if (in_array($this->getTargetObject(), $page)) {
                 $pageAccessToken = $page['access_token'];
                 break;
             }
         }
     }
     $message = array_merge(array('access_token' => $pageAccessToken ? $pageAccessToken : $this->getTokenHandler()->getToken()), $message);
     $client = new Zend_Http_Client();
     $client->setParameterPost($message)->setUri(sprintf(self::PUBLISH_URI_PATTERN, $this->getTargetObject()));
     $response = $client->request(Zend_Http_Client::POST);
     $data = Zend_Json::decode($response->getBody());
     if (isset($data['error'])) {
         if ($data['error']['type'] == 'Exception') {
             if (strpos($data['error']['message'], '#200')) {
                 throw new Centurion_Social_NoTokenException($data['error']['message']);
             }
             if (strpos($data['error']['message'], '#210')) {
                 throw new Centurion_Social_NoTokenException($data['error']['message']);
             }
             throw new Centurion_Social_Exception($data['error']['message']);
             //                elseif (strpos($data['error']['message'],'#506')) {
             //                    throw new Centurion_Social_Exception($data['error']['message']);
             //                }
         } elseif ($data['error']['type'] == 'OAuthException') {
             throw new Centurion_Social_NoTokenException($data['error']['message']);
         }
     }
     return $data->id;
 }
Exemplo n.º 10
0
 /**
  * This function list all action available for current controller (so all available static html integration)
  *
  */
 public function indexAction()
 {
     $reflection = new ReflectionClass('HtmlController');
     $methods = $reflection->getMethods();
     $htmlMethod = array();
     foreach ($methods as $methodClass) {
         $method = $methodClass->name;
         if ('_' !== $method[0] && 'indexAction' !== $method && 'Action' === substr($method, -6)) {
             $htmlMethod[] = Centurion_Inflector::tableize(substr($method, 0, -6), '-');
         }
     }
     $this->view->methods = $htmlMethod;
 }
Exemplo n.º 11
0
 public function preSave()
 {
     $slugParts = $this->_row->getSlugifyName();
     $slugifiedParts = array();
     if (count(array_intersect($this->_row->getModifiedFields(), (array) $slugParts)) || $this->isNew()) {
         foreach ((array) $slugParts as $part) {
             $slugifiedParts[] = Centurion_Inflector::slugify($this->_row->{$part});
         }
         $slug = implode('-', $slugifiedParts);
         $currentSlug = $this->_row->slug;
         if ($separatorPos = strpos($this->_row->slug, '_')) {
             $currentSlug = substr($currentSlug, 0, $separatorPos);
         }
         $name = $this->_row->getTable()->info('name');
         $select = $this->getTable()->select();
         $filters = array();
         if (method_exists($this->_row, 'getFilterFieldsForSlug')) {
             $filterField = $this->_row->getFilterFieldsForSlug();
             if (is_array($filterField)) {
                 foreach ($filterField as $field) {
                     $filters[$field] = $this->_row->{$field};
                 }
             }
         }
         if (!$this->_row->isNew()) {
             foreach ($this->_getPrimaryKey() as $key => $value) {
                 $filters[Centurion_Db_Table_Select::OPERATOR_NEGATION . $key] = $value;
             }
         }
         $filters['slug__' . Centurion_Db_Table_Select::OPERATOR_CONTAINS] = $slug . '%';
         $rows = $select->filter($filters)->fetchAll();
         if ($rows->count() > 0) {
             $identicalSlugIds = array();
             foreach ($rows as $row) {
                 if ($separatorPos = strpos($row->slug, '_')) {
                     $identicalSlugIds[] = substr($row->slug, ++$separatorPos);
                 }
             }
             if (count($identicalSlugIds) > 0) {
                 $i = 1;
                 while (in_array($i, $identicalSlugIds)) {
                     $i++;
                 }
                 $slug .= '_' . $i;
             }
         }
         $this->_row->slug = $slug;
     }
 }
Exemplo n.º 12
0
 /**
  * Receive the uploaded file
  *
  * @return boolean
  */
 public function receive()
 {
     $fileinfo = $this->getFileInfo();
     if (null === $this->_initialFilename) {
         $this->_initialFilename = $fileinfo[$this->getName()]['name'];
     }
     $dirName = md5(Centurion_Inflector::uniq($fileinfo[$this->getName()]['tmp_name']));
     $filename = substr($dirName, 0, 2) . DIRECTORY_SEPARATOR . substr($dirName, 2) . Centurion_Inflector::extension($fileinfo[$this->getName()]['name']);
     $this->_localFilename = $filename;
     if (!file_exists($this->getDestination() . DIRECTORY_SEPARATOR . substr($dirName, 0, 2))) {
         mkdir($this->getDestination() . DIRECTORY_SEPARATOR . substr($dirName, 0, 2), 0770, true);
     }
     $this->getTransferAdapter()->addFilter('Rename', array('target' => $this->getDestination() . DIRECTORY_SEPARATOR . $filename, 'overwrite' => true))->setOptions(array('useByteString' => false));
     // retrieve the real filesize
     return parent::receive();
 }
Exemplo n.º 13
0
 public function isValid($data)
 {
     if (!$data['url']) {
         if ($this->hasInstance()) {
             $data['url'] = '/' . $this->getInstance()->slug;
         } elseif ($data['title']) {
             $data['url'] = '/' . Centurion_Inflector::slugify($data['title']);
         }
     }
     $params = array();
     // @todo: should be done with a trait ?
     if (isset($data['language_id'])) {
         $params['language_id'] = $data['language_id'];
     }
     $this->getElement('url')->getValidator('Centurion_Form_Model_Validator_AlreadyTaken')->mergeParams($params);
     return parent::isValid($data);
 }
 /**
  * Generic test for findOneBy method.
  */
 public function testFindOneBy()
 {
     return;
     $modelId = $this->_model->insert($this->_getData());
     $this->assertFalse(null === $modelId);
     if (is_array($modelId)) {
         $this->_data = call_user_func_array(array($this->_model, 'find'), array_values($modelId))->current()->toArray();
     } else {
         $this->_data = $this->_model->find($modelId)->current()->toArray();
     }
     foreach ($this->_getData() as $key => $value) {
         if (null === $value) {
             continue;
         }
         $method = 'findOneBy' . Centurion_Inflector::classify($key);
         $modelRow = $this->_model->{$method}($value);
         $this->assertEquals($this->_getData(), $modelRow->toArray(), sprintf('Method %s of %s object doesn\'t return the expected values', $method, get_class($this->_model)));
     }
 }
Exemplo n.º 15
0
 public function preSave()
 {
     // Get the column used to generate the slug
     $slugParts = (array) $this->_row->getSlugifyName();
     $slugifiedParts = array();
     $modifiedFields = $this->_row->getModifiedFields();
     if (isset($modifiedFields['slug'])) {
         return;
     }
     // If one of the column used to generate the slug has been modified OR if the row is new : generate a slug
     if (count(array_intersect(array_keys($modifiedFields), $slugParts)) || $this->isNew()) {
         foreach ($slugParts as $part) {
             $partValue = $this->_row->{$part};
             if (null == $partValue) {
                 continue;
             }
             // Slugify each value of selected columns
             $slugifiedParts[] = Centurion_Inflector::slugify($partValue);
         }
         // Assemble the slugified values to get a slug
         $slug = implode($this->_slugColumnsSeparator, $slugifiedParts);
         if (null == $slug) {
             $slug = $this->_slugColumnsSeparator;
         }
         // Get the current slug of the row ($currentSlug = null if the row is new)
         $currentSlug = $this->_row->slug;
         /**
          * Get the original slug
          *
          * Explanation : If a slug is already taken by another row, the generated slug is {expected_slug}_#
          *               where # is an incremental value of the number of occurrences of this slug
          */
         if ($separatorPos = strpos($this->_row->slug, $this->_slugIteratorSeparator)) {
             $currentSlug = substr($currentSlug, 0, $separatorPos);
         }
         // Get the table name
         $name = $this->_row->getTable()->info('name');
         $select = $this->getTable()->select();
         $filters = array();
         /**
          * A function named getFilterFieldsForSlug could be defined in the row,
          * to filter the search of duplicate field by a given column.
          * Exemple if my table have a category_id, i could tell slug trait, to have uniq slug in a category.
          * In that case 2 row, of different category, could have the same slug.
          */
         if (method_exists($this->_row, 'getFilterFieldsForSlug')) {
             $filterField = $this->_row->getFilterFieldsForSlug();
             if (is_array($filterField)) {
                 foreach ($filterField as $field) {
                     $filters[$field] = $this->_row->{$field};
                 }
             }
         }
         /**
          * We ignore the current row for duplicate slug search
          */
         if (!$this->_row->isNew()) {
             foreach ($this->_getPrimaryKey() as $key => $value) {
                 $filters[Centurion_Db_Table_Select::OPERATOR_NEGATION . $key] = $value;
             }
         }
         // Generate the array used for filters method to find identical slug
         $filters['slug__' . Centurion_Db_Table_Select::OPERATOR_CONTAINS] = $slug . '%';
         // Get all the rows of the table with the same slug
         $rows = $select->filter($filters)->fetchAll();
         // If the slug we want to use is already taken generate a new one with the syntax : {slug}_#
         if ($rows->count() > 0) {
             $identicalSlugIds = array();
             foreach ($rows as $row) {
                 if ($separatorPos = strpos($row->slug, $this->_slugIteratorSeparator)) {
                     $identicalSlugIds[] = substr($row->slug, ++$separatorPos);
                 }
             }
             /**
              * Generate the suffix "_#" for the slug
              *
              * /!\ During the generation of suffix _#, if we have a a free slot between two suffix
              *     Ex : We have a table with three row, their respective slug are : slug, slug_1 & slug_3
              *          We fill this slot with the current generated slug and we get :
              *          slug, slug_1, slug_3, slug_2 (= current generated slug)
              */
             $i = 1;
             if (count($identicalSlugIds) > 0) {
                 while (in_array($i, $identicalSlugIds)) {
                     $i++;
                 }
             }
             // Add suffix "_#" at the end of the generated slug
             $slug .= $this->_slugIteratorSeparator . $i;
         }
         $this->_row->slug = $slug;
     }
 }
Exemplo n.º 16
0
 /**
  * @dataProvider dataForTestFunctionRoundTo
  */
 public function testFunctionRound4nTo($number, $increment, $expectedResult)
 {
     $this->assertEquals($expectedResult, Centurion_Inflector::roundTo($number, $increment));
 }
Exemplo n.º 17
0
 public function slugify($text)
 {
     return Centurion_Inflector::slugify($text);
 }
Exemplo n.º 18
0
 public function cuttext($value, $length, $separator = '...')
 {
     return Centurion_Inflector::cuttext($value, $length, $separator);
 }
Exemplo n.º 19
0
 /**
  * Process values attached to the form.
  *
  * @param array $values Values
  * @return array Values processed
  */
 protected function _processValues($values)
 {
     $valuesToProcess = $values;
     foreach ($valuesToProcess as $key => $value) {
         $method = sprintf('_update%sColumn', Centurion_Inflector::camelize($key));
         if (method_exists($this, $method)) {
             if (false === ($ret = $this->{$method}($value))) {
                 unset($values[$key]);
             } else {
                 $values[$key] = $ret;
             }
         }
         $element = $this->getElement($key);
         if (null !== $element) {
             $class = $element->getAttrib('class');
             if (false !== strpos($class, 'field-datetimepicker')) {
                 $posted_at = new Zend_Date($value, $this->getDateFormat(true));
                 $values[$key] = $posted_at->get(Centurion_Date::MYSQL_DATETIME);
             } else {
                 if (false !== strpos($class, 'field-datepicker')) {
                     $posted_at = new Zend_Date($value, $this->getDateFormat());
                     $values[$key] = $posted_at->get(Centurion_Date::MYSQL_DATETIME);
                 }
             }
         }
     }
     return $values;
 }
Exemplo n.º 20
0
 public function getAction()
 {
     $fileId = $this->_getParam('file_id');
     if (null === $fileId && $this->getRequest()->getServer('REDIRECT_QUERY_STRING')) {
         // Here, it's for an same apache server without urlrewriting
         list($id, $fileid, $key, $effect) = explode(':', $this->getRequest()->getServer('REDIRECT_QUERY_STRING'));
         $this->_request->setParam('id', $id);
         $this->_request->setParam('fileid', $fileId);
         $this->_request->setParam('key', $key);
         $this->_request->setParam('effect', $effect);
         // If the server don't have urlrewriting, he could (must?) use ErrorDocument 404 in .htaccess
         $this->getResponse()->setHttpResponseCode(200);
     }
     $fileId = bin2hex(Centurion_Inflector::urlDecode($this->_request->getParam('file_id')));
     $key = bin2hex(Centurion_Inflector::urlDecode($this->_request->getParam('key')));
     if (trim($this->_request->getParam('id')) == '') {
         $id = $fileId;
     } else {
         $id = bin2hex(Centurion_Inflector::urlDecode($this->_request->getParam('id')));
     }
     if (!($effectPath = $this->_request->getParam('effect'))) {
         return $this->_forward('get', 'file');
     }
     $media = Centurion_Config_Manager::get('media');
     $fileRow = $this->_helper->getObjectOr404('media/file', array('id' => $id));
     $mediaAdapter = Media_Model_Adapter::factory($media['adapter'], $media['params']);
     $this->forward404If(!$mediaAdapter->isValidKey($fileRow, $key, $effectPath), sprintf("key '%s' for file '%s' is not valid or expired", $key, $fileRow->pk));
     // TODO : modifier le file exist sur le bon chemin (cf getFullpath)
     if (!file_exists($media['uploads_dir'] . DIRECTORY_SEPARATOR . $fileRow->local_filename)) {
         $this->_redirect('/layouts/backoffice/images/px.png', array('code' => 307));
     }
     $effects = Media_Model_DbTable_Image::effectsString2Array($effectPath);
     $imageAdapter = Centurion_Image::factory();
     $imagePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid();
     $imageAdapter->open($media['uploads_dir'] . DIRECTORY_SEPARATOR . $fileRow->local_filename);
     foreach ($effects as $key => $effect) {
         switch ($key) {
             //                case 'adaptiveresize':
             //                    $effect = array_merge(array('width' => null, 'height' => null), $effect);
             //                    $imageAdapter->adaptiveResize($effect['width'], $effect['height']);
             //                    break;
             case 'adaptiveresize':
                 $effect = array_merge(array('width' => null, 'height' => null), $effect);
                 $imageAdapter->adaptiveResize($effect[1]['width'], $effect[1]['height']);
                 break;
             case 'cropcenter':
                 $effect = array_merge(array('width' => null, 'height' => null), $effect);
                 $imageAdapter->cropFromCenter($effect['width'], $effect['height']);
                 break;
             case 'resize':
                 $effect = array_merge(array('maxWidth' => null, 'maxHeight' => null, 'minWidth' => null, 'minHeight' => null), $effect);
                 $imageAdapter->resize($effect['maxWidth'], $effect['maxHeight'], $effect['minWidth'], $effect['minHeight']);
                 break;
             case 'crop':
                 $effect = array_merge(array('x' => null, 'y' => null, 'width' => null, 'height' => null), $effect);
                 $imageAdapter->crop($effect['x'], $effect['y'], $effect['width'], $effect['height']);
                 break;
             case 'cropcenterresize':
                 $effect = array_merge(array('width' => null, 'height' => null), $effect);
                 $imageAdapter->cropAndResizeFromCenter($effect['width'], $effect['height']);
                 break;
             case 'cropedgeresize':
                 $effect = array_merge(array('width' => null, 'height' => null, 'edge' => null), $effect);
                 $imageAdapter->cropAndResizeFromEdge($effect['width'], $effect['height'], $effect['edge']);
                 break;
             case 'IMG_FILTER_NEGATE':
                 $imageAdapter->effect('IMG_FILTER_NEGATE');
                 break;
             case 'IMG_FILTER_GRAYSCALE':
                 $imageAdapter->effect('IMG_FILTER_GRAYSCALE');
                 break;
             case 'IMG_FILTER_BRIGHTNESS':
                 $effect = array_merge(array('degree' => null), $effect);
                 $imageAdapter->effect('IMG_FILTER_BRIGHTNESS', $effect['degree']);
                 break;
             case 'IMG_FILTER_CONTRAST':
                 $effect = array_merge(array('degree' => null), $effect);
                 $imageAdapter->effect('IMG_FILTER_CONTRAST', $effect['degree']);
                 break;
             case 'IMG_FILTER_COLORIZE':
                 $effect = array_merge(array('red' => null, 'green' => null, 'blue' => null), $effect);
                 $imageAdapter->effect('IMG_FILTER_COLORIZE', $effect['red'], $effect['green'], $effect['blue']);
                 break;
             case 'IMG_FILTER_EDGEDETECT':
                 $imageAdapter->effect('IMG_FILTER_EDGEDETECT');
                 break;
             case 'IMG_FILTER_EMBOSS':
                 $imageAdapter->effect('IMG_FILTER_EMBOSS');
                 break;
             case 'IMG_FILTER_SELECTIVE_BLUR':
                 $imageAdapter->effect('IMG_FILTER_SELECTIVE_BLUR');
                 break;
             case 'IMG_FILTER_GAUSSIAN_BLUR':
                 $imageAdapter->effect('IMG_FILTER_GAUSSIAN_BLUR');
                 break;
             case 'IMG_FILTER_MEAN_REMOVAL':
                 $imageAdapter->effect('IMG_FILTER_MEAN_REMOVAL');
                 break;
             case 'IMG_FILTER_SMOOTH':
                 $imageAdapter->effect('IMG_FILTER_SMOOTH', $effect['degree']);
                 break;
             case 'IMG_FILTER_PIXELATE':
                 $imageAdapter->effect('IMG_FILTER_PIXELATE', $effect['size'], $effect['pixelate']);
         }
     }
     if (!is_dir(dirname($imagePath))) {
         mkdir(dirname($imagePath), 0777, true);
     }
     $imageAdapter->save($imagePath, $fileRow->mime);
     $isSaved = $mediaAdapter->save($imagePath, $fileRow->getRelativePath($effectPath, false, true));
     if ($isSaved) {
         Centurion_Db::getSingleton('media/duplicate')->insert(array('file_id' => $fileRow->id, 'adapter' => $media['adapter'], 'params' => serialize($media['params']), 'dest' => $fileRow->getRelativePath($effectPath, false, true)));
         return $this->getHelper('redirector')->gotoUrlAndExit($fileRow->getStaticUrl($effectPath) . '&');
     }
     $offset = 24 * 60 * 60 * 365;
     $this->getResponse()->setHeader('Content-type', $fileRow->mime)->setHeader('Content-Length', filesize($imagePath))->setHeader('Content-Disposition', sprintf('inline; filename="%s";', $fileRow->filename))->setHeader('Cache-Control', sprintf('max-age=%d, public', $offset))->setHeader('Expires', sprintf('%s GMT', gmdate('D, d M Y H:i:s', time() + $offset)))->sendHeaders();
     while (@ob_end_flush()) {
     }
     $fp = fopen($imagePath, 'rb');
     fpassthru($fp);
     fclose($fp);
     if (file_exists($imagePath)) {
         unlink($imagePath);
     }
     $this->getResponse()->clearHeaders();
 }
Exemplo n.º 21
0
 /**
  * Check if a field name belongs to the table.
  *
  * @param   string          $fieldName
  * @return  boolean|string  False if the field doesn't belong to the table, otherwise, tableized field
  */
 protected function _isFieldNameBelongToTable($fieldName)
 {
     $fieldName = Centurion_Inflector::tableize($fieldName);
     if (in_array($fieldName, $this->_getCols())) {
         return $fieldName;
     }
     return false;
 }
Exemplo n.º 22
0
 /**
  * Assembles user submitted parameters forming a URL path defined by this route
  *
  * @param  array $data An array of variable and value pairs used as parameters
  * @param  boolean $reset Whether or not to set route defaults with those provided in $data
  * @return string Route path with user submitted parameters
  */
 public function assemble($data = array(), $reset = false, $encode = false, $partial = false)
 {
     if ($this->_isTranslated) {
         $translator = $this->getTranslator();
         if (isset($data['@locale'])) {
             $locale = $data['@locale'];
             unset($data['@locale']);
         } else {
             $locale = $this->getLocale();
         }
     }
     $url = array();
     $flag = false;
     foreach ($this->_parts as $key => $part) {
         $name = isset($this->_variables[$key]) ? $this->_variables[$key] : null;
         $useDefault = false;
         if (isset($name) && array_key_exists($name, $data) && $data[$name] === null) {
             $useDefault = true;
         }
         if (isset($name)) {
             if (isset($data[$name]) && !$useDefault) {
                 $value = $data[$name];
                 unset($data[$name]);
             } elseif (!$reset && !$useDefault && isset($this->_values[$name])) {
                 $value = $this->_values[$name];
             } elseif (!$reset && !$useDefault && isset($this->_wildcardData[$name])) {
                 $value = $this->_wildcardData[$name];
             } elseif (isset($this->_defaults[$name])) {
                 $value = $this->_defaults[$name];
             } else {
                 require_once 'Zend/Controller/Router/Exception.php';
                 throw new Zend_Controller_Router_Exception($name . ' is not specified');
             }
             if ($this->_isTranslated && in_array($name, $this->_translatable)) {
                 $url[$key] = Centurion_Inflector::slugify($translator->translate($value, $locale));
             } else {
                 $url[$key] = $value;
             }
         } elseif ($part != '*') {
             if ($this->_isTranslated && substr($part, 0, 1) === '@') {
                 if (substr($part, 1, 1) !== '@') {
                     $url[$key] = Centurion_Inflector::slugify($translator->translate(substr($part, 1), $locale));
                 } else {
                     $url[$key] = substr($part, 1);
                 }
             } else {
                 if (substr($part, 0, 2) === '@@') {
                     $part = substr($part, 1);
                 }
                 $url[$key] = $part;
             }
         } else {
             $defaults = $this->getDefaults();
             foreach ($this->_wildcardData as $key => $val) {
                 if (substr($key, 0, 1) !== '@' && isset($defaults['@' . $key])) {
                     $this->_wildcardData['@' . $key] = $val;
                     unset($this->_wildcardData[$key]);
                 }
             }
             if (!$reset) {
                 $data += $data + $this->_wildcardData;
             }
             $dataTemp = array();
             foreach ($defaults as $key => $val) {
                 if (isset($data[$key])) {
                     $dataTemp[$key] = $data[$key];
                     unset($data[$key]);
                 }
             }
             $data = $dataTemp + $data;
             foreach ($data as $var => $value) {
                 if ($value !== null && (!isset($defaults[$var]) || $value != $defaults[$var])) {
                     if ($this->_isTranslated && substr($var, 0, 1) === '@') {
                         $url[$key++] = Centurion_Inflector::slugify($translator->translate(substr($var, 1), $locale));
                     } else {
                         if (isset($defaults['@' . $var])) {
                             $data['@' . $var] = $value;
                             unset($data[$var]);
                             continue;
                         }
                         $url[$key++] = $var;
                     }
                     $url[$key++] = $value;
                     $flag = true;
                 }
             }
         }
     }
     $return = '';
     foreach (array_reverse($url, true) as $key => $value) {
         $defaultValue = null;
         if (isset($this->_variables[$key])) {
             $defaultValue = $this->getDefault($this->_variables[$key]);
             if ($this->_isTranslated && $defaultValue !== null && isset($this->_translatable[$this->_variables[$key]])) {
                 $defaultValue = Centurion_Inflector::slugify($translator->translate($defaultValue, $locale));
             }
         }
         if ($flag || $value !== $defaultValue || $partial) {
             if ($encode) {
                 $value = rawurlencode($value);
             }
             $return = $this->_urlDelimiter . $value . $return;
             $flag = true;
         }
     }
     return trim($return, $this->_urlDelimiter);
 }
Exemplo n.º 23
0
 public function acl($env)
 {
     $this->bootstrap($env);
     $application = $this->_application;
     $bootstrap = $application->getBootstrap();
     $front = $bootstrap->getResource('FrontController');
     $modules = $front->getControllerDirectory();
     $default = $front->getDefaultModule();
     $curBootstrapClass = get_class($bootstrap);
     $options = $bootstrap->getOption('resources');
     $options = $options['modules'];
     if (is_array($options) && !empty($options[0])) {
         $diffs = array_diff($options, array_keys($modules));
         if (count($diffs)) {
             throw new Centurion_Application_Resource_Exception(sprintf("The modules %s is not found in your registry (%s)", implode(', ', $diffs), implode(PATH_SEPARATOR, $modules)));
         }
         foreach ($modules as $key => $module) {
             if (!in_array($key, $options) && $key !== $default) {
                 unset($modules[$key]);
                 $front->removeControllerDirectory($key);
             }
         }
         $modules = Centurion_Inflector::sortArrayByArray($modules, array_values($options));
     }
     require_once APPLICATION_PATH . '/../library/Centurion/Contrib/auth/models/DbTable/Permission.php';
     require_once APPLICATION_PATH . '/../library/Centurion/Contrib/auth/models/DbTable/Row/Permission.php';
     $permissionTable = Centurion_Db::getSingleton('auth/permission');
     foreach ($modules as $module => $moduleDirectory) {
         echo "\n\n" . 'Scan new module: ' . $module . "\n";
         $bootstrapClass = $this->_formatModuleName($module) . '_Bootstrap';
         $modulePath = dirname($moduleDirectory);
         $dataPath = $modulePath . '/controllers/';
         if (is_dir($dataPath)) {
             $db = Zend_Db_Table::getDefaultAdapter();
             foreach (new DirectoryIterator($dataPath) as $file) {
                 if ($file->isDot() || !$file->isFile()) {
                     continue;
                 }
                 if (substr($file, 0, 5) !== 'Admin') {
                     continue;
                 }
                 $controllerName = substr($file, 5, -14);
                 $object = Centurion_Inflector::tableize($controllerName, '-');
                 $tab = array('index' => 'View %s %s index', 'list' => 'View %s %s list', 'get' => 'View an %s %s', 'post' => 'Create an %s %s', 'new' => 'Access to creation of an %s %s', 'delete' => 'Delete an %s %s', 'put' => 'Update an %s %s', 'batch' => 'Batch an %s %s', 'switch' => 'Switch an %s %s');
                 foreach ($tab as $key => $description) {
                     list($row, $created) = $permissionTable->getOrCreate(array('name' => $module . '_' . $object . '_' . $key));
                     if ($created) {
                         echo 'Create permission: ' . $module . '_' . $object . '_' . $key . "\n";
                         $row->description = sprintf($description, $module, $object);
                         $row->save();
                     }
                 }
             }
         }
     }
     Centurion_Loader_PluginLoader::clean();
     Centurion_Signal::factory('clean_cache')->send($this);
 }
Exemplo n.º 24
0
 /**
  * 
  * @param mixed $sender
  * @return Centurion_Collection
  */
 protected function _setupObjectContainer($sender)
 {
     $id = Centurion_Inflector::id($sender);
     if (!isset($this->_objectCollection->{$id}) || !(is_array($this->_objectCollection->{$id}) || $this->_objectCollection->{$id} instanceof ArrayAccess)) {
         $this->_objectCollection->{$id} = new Centurion_Collection();
     }
     return $this->_objectCollection->{$id};
 }
Exemplo n.º 25
0
 public function getSeoUrl($effects = null, $extra = false, $realPath = false)
 {
     if (is_array($effects)) {
         $effects = Media_Model_DbTable_Image::effectsArray2String($effects);
     }
     $fileId = Centurion_Inflector::urlEncode(pack("H*", $this->file_id));
     /*if (!$realPath && $this->file_id === $this->pk)
           $pk = '';
       else */
     $pk = Centurion_Inflector::urlEncode(pack("H*", $this->pk));
     $key = Centurion_Inflector::urlEncode(pack("H*", $this->getTemporaryKey($effects)));
     return $this->getDateObjectByCreatedAt()->toString('y/MM/dd/') . ($realPath ? $pk . '_' . (null !== $effects ? $effects . '_' : '_') : '') . $this->filename . ($extra ? '?' . $pk . ':' . $fileId . ':' . $key . (null !== $effects ? ':' . $effects : '') : '');
 }
Exemplo n.º 26
0
 protected function _preSave()
 {
     parent::_preSave();
     if ($this->title) {
         $this->slug = Centurion_Inflector::slugify($this->title);
     } else {
         $this->slug = Centurion_Inflector::slugify($this->slug);
     }
 }
Exemplo n.º 27
0
 /**
  * Retrieve the next or previous row count.
  *
  * @param string $by                        Column name
  * @param boolean $isNext                   Next row if true, previous instead
  * @param array $kwargs                     Arguments passed to the table
  * @param Centurion_Db_Table_Select $select The select used to process the query
  * @return int
  */
 protected function _getNextOrPreviousCountByField($by, $isNext = true, $kwargs = null, $select = null)
 {
     if (is_string($by)) {
         $by = Centurion_Inflector::tableize($by);
     }
     if (null === $select) {
         $select = $this->getTable()->select(true);
     }
     return $this->_getNextOrPreviousSelectByField($by, $isNext, $kwargs, $select)->count();
 }
Exemplo n.º 28
0
 /**
  * Adds a JOIN table and columns to the query with the referenceMap.
  *
  * @param  string $key                 The referenceMap key
  * @param  array|string $cols          The columns to select from the joined table.
  * @param  string $schema              The database name to specify, if any.
  * @return Centurion_Db_Table_Select   This Centurion_Db_Table_Select object.
  */
 protected function _joinUsingVia($key, $type, $cols = '*', $schema = null)
 {
     if (empty($this->_parts[self::FROM])) {
         require_once 'Zend/Db/Select/Exception.php';
         throw new Zend_Db_Select_Exception("You can only perform a joinUsing after specifying a FROM table");
     }
     $referenceMap = $this->getTable()->getReferenceMap(Centurion_Inflector::tableize($key));
     $refTable = Centurion_Db::getSingletonByClassName($referenceMap['refTableClass']);
     $name = $refTable->info('name');
     $join = $this->_adapter->quoteIdentifier(key($this->_parts[self::FROM]), true);
     $from = $this->_adapter->quoteIdentifier($name);
     $primary = $refTable->info('primary');
     $cond1 = $join . '.' . $referenceMap['columns'];
     $cond2 = $from . '.' . $primary[1];
     $cond = $cond1 . ' = ' . $cond2;
     return $this->_join($type, $name, $cond, $cols, $schema);
 }
Exemplo n.º 29
0
 /**
  *  Test slug when this one is composed of several columns
  */
 public function testSlugResultWithEmptyColumn()
 {
     /**
      * @Given an empty table that implement slug 
      * @And that this table have 2 columns that implement is used to create the slug
      */
     $table = new Asset_Model_DbTable_WithMultiColumnsForSlug();
     $table->select()->fetchAll()->delete();
     /**
      * @If i a create a new row
      * @And i fill the 2 columns
      */
     $titleSubtitleRow = $table->createRow();
     $titleSubtitleRow->title = 'Title slug test';
     $titleSubtitleRow->subtitle = 'Subtitle slug test';
     $titleSubtitleRow->save();
     /**
      * @Except that the slug is composed by the 2 columns, slugify, concatened by 
      */
     $this->assertEquals(Centurion_Inflector::slugify('Title slug test') . '-' . Centurion_Inflector::slugify('Subtitle slug test'), $titleSubtitleRow->slug, 'The slug isn\'t equals to what we expect');
     /**
      * In this case the slug is composed of the title
      *
      * We except :
      *  - slug = Centurion_Inflector::slugify('Titre de test')
      */
     $titleRow = $table->createRow();
     $titleRow->title = 'Only title slug test';
     $titleRow->save();
     $this->assertEquals(Centurion_Inflector::slugify('Only title slug test'), $titleRow->slug, 'The slug isn\'t equals to what we expect');
     /**
      * In this case the slug is composed of the subtitle
      *
      * We except :
      *  - slug = Centurion_Inflector::slugify('SubTitre de test')
      */
     $subtitleRow = $table->createRow();
     $subtitleRow->subtitle = 'Only subtitle slug test';
     $subtitleRow->save();
     $this->assertEquals(Centurion_Inflector::slugify('Only subtitle slug test'), $subtitleRow->slug, 'The slug isn\'t equals to what we expect');
 }
Exemplo n.º 30
0
 /**
  * Retrieve the class name for a registry name.
  *
  * @param string $registryName
  */
 public static function getClassName($registryName)
 {
     $classArr = explode('/', trim($registryName));
     $className = sprintf('%s_Model_DbTable_%s', ucfirst($classArr[0]), Centurion_Inflector::classify($classArr[1]));
     return $className;
 }