Ejemplo n.º 1
0
 /**
  * undocumented function
  *
  * @param string $file 
  * @return void
  * @access public
  */
 function import($file)
 {
     $source = file_get_contents($file);
     $xml = new Xml($source);
     $result = $xml->toArray();
     $result = $result['Xmlarchive']['Fileset']['File'];
     if (empty($result)) {
         return false;
     }
     $count = 0;
     foreach ($result as $smiley) {
         $name = $smiley['filename'];
         $content = $smiley['content'];
         $content = preg_replace('/\\s/', '', $content);
         $content = base64_decode($content);
         $filePath = SMILEY_PATH . $name;
         if (file_exists($filePath)) {
             continue;
         }
         $this->create(array('code' => ':' . r('.gif', '', $name) . ':', 'filename' => $name));
         $this->save();
         $f = fopen($filePath, 'w+');
         fwrite($f, $content);
         fclose($f);
         $count++;
     }
     return $count;
 }
Ejemplo n.º 2
0
    /**
     * Parses XML files into config files
     * @access public 
     * @static
     * @param string $path 
     *
     */
    public static function xml2Config($path){
        
        foreach(scandir($path) as $file){
            $ext = pathinfo($file, PATHINFO_EXTENSION);

            //Skip file if it's not XML
            if(strtolower($ext) !== 'xml') {
                continue;
            }
            
            if(is_file($path . DS . $file)){
                
                $xmlData = Xml::toArray(Xml::build($path . DS . $file));
                
                $outFile = 
                    ROOT . DS . APP_DIR . DS . 'Config' . DS . 'Includes' . DS . str_replace('.xml', '.php', $file);
                
                $configureString = "<?php\n";

                foreach($xmlData['root'] as $key => $value){
                    $val = empty($value['value'])?$value['default']:$value['value'];
                    $decoded = htmlspecialchars_decode($val, ENT_QUOTES);
                    $configureString .= "Configure::write('{$value['name']}', {$decoded});\n";
                }
                
                file_put_contents ($outFile , $configureString);
            }
            
        }
        
    }
 public function styleList()
 {
     $style = array();
     $dirs = Dir::tree('template');
     foreach ($dirs as $tpl) {
         $xml = $tpl['path'] . '/config.xml';
         if (!is_file($xml)) {
             continue;
         }
         if (!($config = Xml::toArray(file_get_contents($xml)))) {
             continue;
         }
         $tpl['name'] = isset($config['name']) ? $config['name'][0] : '';
         //模型名
         $tpl['author'] = isset($config['author']) ? $config['author'][0] : '';
         //作者
         $tpl['image'] = isset($config['image']) ? __ROOT__ . '/template/' . $tpl['filename'] . '/' . $config['image'][0] : __CONTROLLER_TPL__ . '/img/preview.jpg';
         //预览图
         $tpl['email'] = isset($config['email']) ? $config['email'][0] : '';
         //邮箱
         $tpl['current'] = C("WEB_STYLE") == $tpl['filename'] ? 1 : 0;
         //正在使用的模板
         $style[] = $tpl;
     }
     $this->assign('style', $style);
     $this->display();
 }
 public function parseRss()
 {
     $channel = Xml::toArray(Xml::build($this->args[0])->channel);
     $items = $channel['channel']['item'];
     $list = $this->PinterestPin->find('list', array('fields' => array('id', 'guid')));
     $data = array();
     foreach ($items as $item) {
         if (!in_array($item['guid'], $list)) {
             $html = file_get_html($item['guid']);
             $image = $html->find('img.pinImage', 0);
             if (is_object($image)) {
                 $data[] = array('guid' => $item['guid'], 'title' => $item['title'], 'image' => $image->attr['src'], 'description' => strip_tags($item['description']), 'created' => date('Y-m-d H:i:s', strtotime($item['pubDate'])));
             }
         }
     }
     if (!empty($data)) {
         if ($this->PinterestPin->saveAll($data)) {
             $this->out(__d('pinterest', '<success>All records saved sucesfully.</success>'));
             return true;
         } else {
             $this->err(__d('pinterest', 'Cannot save records.'));
             return false;
         }
     }
     $this->out(__d('pinterest', '<warning>No records saved.</warning>'));
 }
Ejemplo n.º 5
0
 public function get(&$accessToken, &$oauthConsumer)
 {
     // we need the GUID of the user for Yahoo
     $guid = $oauthConsumer->get($accessToken->key, $accessToken->secret, 'http://social.yahooapis.com/v1/me/guid');
     // Yahoo returns XML, so break it apart and make it an array
     $xml = new Xml($guid);
     // Or you can convert simply by calling toArray();
     $guid = $xml->toArray();
     // get them contacts
     $contacts = $oauthConsumer->get($accessToken->key, $accessToken->secret, 'http://social.yahooapis.com/v1/user/' . $guid['Guid']['value'] . '/contacts', array('count' => 'max', 'format' => 'xml'));
     // return array
     $c = array();
     // counter
     $i = 0;
     // new xml object
     $xml = new Xml($contacts);
     $contacts = $xml->toArray();
     // let's break apart Yahoo's contact format and make it our own, extracting what we want
     foreach ($contacts['Contacts']['Contact'] as $contact) {
         foreach ($contact['Fields'] as $field) {
             if ($field['type'] == 'email') {
                 $c[$i]['Contact']['email'][] = $field['value'];
             }
             if ($field['type'] == 'name' && isset($c[$i]['Contact']['email'])) {
                 $firstName = isset($field['Value']['givenName']) ? $field['Value']['givenName'] : '';
                 $lastName = isset($field['Value']['familyName']) ? $field['Value']['familyName'] : '';
                 $c[$i]['Contact']['fullName'] = $firstName . ' ' . $lastName;
             }
         }
         $i++;
     }
     return $c;
 }
Ejemplo n.º 6
0
 /**
  * Serialize to array data from xml
  *
  * @param array $url url
  * @return array Xml serialize array data
  */
 public function serializeXmlToArray($url)
 {
     $xmlData = Xml::toArray(Xml::build($url));
     // rssの種類によってタグ名が異なる
     if (isset($xmlData['feed'])) {
         $items = Hash::get($xmlData, 'feed.entry');
         $dateKey = 'published';
         $linkKey = 'link.@href';
         $summaryKey = 'summary';
     } elseif (Hash::get($xmlData, 'rss.@version') === '2.0') {
         $items = Hash::get($xmlData, 'rss.channel.item');
         $dateKey = 'pubDate';
         $linkKey = 'link';
         $summaryKey = 'description';
     } else {
         $items = Hash::get($xmlData, 'RDF.item');
         $dateKey = 'dc:date';
         $linkKey = 'link';
         $summaryKey = 'description';
     }
     if (!isset($items[0]) && is_array($items)) {
         $items = array($items);
     }
     $data = array();
     foreach ($items as $item) {
         $date = new DateTime($item[$dateKey]);
         $summary = Hash::get($item, $summaryKey);
         $data[] = array('title' => $item['title'], 'link' => Hash::get($item, $linkKey), 'summary' => $summary ? strip_tags($summary) : '', 'last_updated' => $date->format('Y-m-d H:i:s'), 'serialize_value' => serialize($item));
     }
     return $data;
 }
 /**
  * Verifica se os menus do banco estão atualizados com os do arquivo
  * @param $aDados- array de menus do banco
  * @return boolean
  */
 public function isUpToDate($aDados)
 {
     $aDados = Set::combine($aDados, "/Menu/id", "/Menu");
     App::import("Xml");
     App::import("Folder");
     App::import("File");
     $sCaminhosArquivos = Configure::read("Cms.CheckPoint.menus");
     $oFolder = new Folder($sCaminhosArquivos);
     $aConteudo = $oFolder->read();
     $aArquivos = Set::sort($aConteudo[1], "{n}", "desc");
     if (empty($aArquivos)) {
         return false;
     }
     $oFile = new File($sCaminhosArquivos . $aArquivos[0]);
     $oXml = new Xml($oFile->read());
     $aAntigo = $oXml->toArray();
     foreach ($aDados as &$aMenu) {
         $aMenu['Menu']['content'] = str_replace("\r\n", " ", $aMenu['Menu']['content']);
     }
     if (isset($aAntigo["menus"])) {
         $aAntigo["Menus"] = $aAntigo["menus"];
         unset($aAntigo["menus"]);
     }
     if (isset($aAntigo["Menus"])) {
         $aAntigo = Set::combine($aAntigo["Menus"], "/Menu/id", "/Menu");
         $aRetorno = Set::diff($aDados, $aAntigo);
     }
     return empty($aRetorno);
 }
 public function wordpress()
 {
     if ($this->request->is('post')) {
         /*
          * validate file upload
          */
         $this->CloggyValidation->set($this->request->data['CloggyBlogImport']);
         $this->CloggyValidation->validate = array('wordpress_xml' => array('ext' => array('rule' => array('extension', array('xml')), 'message' => __d('cloggy', 'You must upload xml file'))));
         if ($this->CloggyValidation->validates()) {
             /*
              * setup import files
              */
             $this->__CloggyFileUpload->settings(array('allowed_types' => array('xml'), 'field' => 'wordpress_xml', 'data_model' => 'CloggyBlogImport', 'folder_dest_path' => APP . 'Plugin' . DS . 'Cloggy' . DS . 'webroot' . DS . 'uploads' . DS . 'CloggyBlog' . DS . 'import' . DS));
             //upload xml
             $this->__CloggyFileUpload->proceedUpload();
             //check error upload
             $checkUploadError = $this->__CloggyFileUpload->isError();
             /*
              * if error then back to original view
              * if not then render new view, continue with download and import
              * data and files
              */
             if ($checkUploadError) {
                 $this->set('error', $this->__CloggyFileUpload->getErrorMsg());
             } else {
                 $xmlUploadedData = $this->__CloggyFileUpload->getUploadedData();
                 $xmlFile = $xmlUploadedData['dirname'] . DS . $xmlUploadedData['basename'];
                 //read wordpress xml data
                 $xml = Xml::toArray(Xml::build($xmlFile));
                 /*
                  * if option enabled
                  */
                 if (isset($this->request->data['CloggyBlogImport']['wordpress_import_options'])) {
                     $this->__CloggyBlogImport->setupOptions($this->request->data['CloggyBlogImport']['wordpress_import_options']);
                 }
                 //setup imported data
                 $this->__CloggyBlogImport->setupData($xml);
                 //genereate adapter
                 $this->__CloggyBlogImport->generate();
                 /*
                  * check if given data is valid based on adapter
                  */
                 $checkValidData = $this->__CloggyBlogImport->isValidImportedData();
                 if ($checkValidData) {
                     $checkImport = $this->__CloggyBlogImport->import();
                     if ($checkImport) {
                         $this->Session->setFlash(__d('cloggy', 'Data imported'), 'default', array(), 'success');
                     }
                 } else {
                     $this->set('error', __d('cloggy', 'Given data is not valid.'));
                 }
             }
         } else {
             $this->set('errors', $this->CloggyValidation->validationErrors);
         }
     }
     $this->set('title_for_layout', __d('cloggy', 'Import Post From Wordpress'));
 }
 /**
  * Constructor
  * 
  * @param array $config
  * @param HttpSourceConnection $Connection
  * @throws RuntimeException
  */
 public function __construct($config = array(), HttpSourceConnection $Connection = null)
 {
     parent::__construct($config, $Connection);
     $this->setDecoder('text/html', function (HttpSocketResponse $HttpSocketResponse) {
         $Xml = Xml::build((string) $HttpSocketResponse);
         $response = Xml::toArray($Xml);
         return $response;
     }, true);
 }
Ejemplo n.º 10
0
 /**
  * Parse xml
  *
  * @return array
  */
 protected static function _parseXml($file)
 {
     $xml = Xml::build($file);
     $res = Xml::toArray($xml);
     if (!empty($res['xss']['attack'])) {
         return (array) $res['xss']['attack'];
     }
     return [];
 }
 public function getPrototypes()
 {
     $searchdirs['App'] = APP . 'View';
     $searchdirs['Basic'] = CakePlugin::path('Muffin');
     foreach (CakePlugin::loaded() as $plugin) {
         if ($plugin != 'Muffin') {
             $searchdirs[$plugin] = CakePlugin::path($plugin) . 'View';
         }
     }
     $configs = array();
     foreach ($searchdirs as $plugin => $searchdir) {
         $dir = new Folder($searchdir, false);
         if ($files = $dir->findRecursive('config.xml')) {
             $configs = Hash::merge($configs, array($plugin => $files));
         }
     }
     $prototypes = array();
     foreach ($configs as $plugin => $configFiles) {
         $i = 0;
         foreach ($configFiles as $configFile) {
             $xml = Xml::build($configFile);
             $items = $xml->xpath('menu/item');
             if (!is_array($items) || empty($items)) {
                 continue;
             }
             foreach ($items as $item) {
                 $item = Xml::toArray($item);
                 if (empty($item['item']['@label'])) {
                     continue;
                 }
                 if (!isset($item['item']['@id']) || empty($item['item']['@id'])) {
                     $id = ucfirst(Inflector::variable($item['item']['@label']));
                 } else {
                     $id = $item['item']['@id'];
                 }
                 $fields = array();
                 foreach ($item['item']['field'] as $key => $field) {
                     foreach ($field as $name => $value) {
                         $name = str_replace('@', '', $name);
                         $fields[$key][$name] = $value;
                     }
                 }
                 $prototypes[$plugin][$i]['Link']['id'] = $id;
                 $prototypes[$plugin][$i]['Link']['priority'] = !empty($item['item']['@priority']) ? $item['item']['@priority'] : '10';
                 $prototypes[$plugin][$i]['Link']['model'] = !empty($item['item']['@model']) ? $item['item']['@model'] : '';
                 $prototypes[$plugin][$i]['Link']['label'] = $item['item']['@label'];
                 $prototypes[$plugin][$i]['Field'] = $fields;
                 $i++;
             }
         }
     }
     foreach ($prototypes as $plugin => $section) {
         $prototypes[$plugin] = Hash::sort($section, '{n}.Link.priority', 'asc');
     }
     return $prototypes;
 }
Ejemplo n.º 12
0
 /**
  * parse xml
  * 2010-02-07 ms
  */
 function parse($file)
 {
     App::import('Core', 'Xml');
     $xml = new Xml($file);
     $res = $xml->toArray();
     if (!empty($res['Xss']['Attack'])) {
         return (array) $res['Xss']['Attack'];
     }
     return array();
 }
Ejemplo n.º 13
0
 /**
  * 删除模块
  *
  * @param string $module 模块名称
  * @param int $removeData 删除模块数据
  *
  * @return bool
  */
 public function remove($module, $removeData = 0)
 {
     //删除封面关键词数据
     if ($removeData) {
         //本地安装的模块删除处理
         $xmlFile = 'addons/' . $module . '/manifest.xml';
         if (is_file($xmlFile)) {
             $manifest = Xml::toArray(file_get_contents($xmlFile));
             //卸载数据
             $installSql = trim($manifest['manifest']['uninstall']['@cdata']);
             if (!empty($installSql)) {
                 if (preg_match('/.php$/', $installSql)) {
                     $file = 'addons/' . $module . '/' . $installSql;
                     if (!is_file($file)) {
                         $this->error = '卸载文件:' . $file . '不存在';
                         return;
                     }
                     require $file;
                 } else {
                     \Schema::sql($installSql);
                 }
             }
         }
         //删除模块回复规则列表
         $rids = Db::table('rule')->where('module', $module)->lists('rid') ?: [];
         foreach ($rids as $rid) {
             service('WeChat')->removeRule($rid);
         }
         //删除站点模块
         Db::table('site_modules')->where('module', $module)->delete();
         //模块设置
         Db::table('module_setting')->where('module', $module)->delete();
         //代金券使用的模块
         Db::table('ticket_module')->where('module', $module)->delete();
     }
     //删除模块数据
     $this->where('name', $module)->delete();
     //删除模块动作数据
     Db::table('modules_bindings')->where('module', $module)->delete();
     //更新套餐数据
     $package = Db::table('package')->get();
     if ($package) {
         foreach ($package as $p) {
             $p['modules'] = unserialize($p['modules']) ?: [];
             if ($k = array_search($_GET['module'], $p['modules'])) {
                 unset($p['modules'][$k]);
             }
             $p['modules'] = serialize($p['modules']);
             Db::table('package')->where('id', $p['id'])->update($p);
         }
     }
     //更新所有站点缓存
     service('site')->updateAllCache();
     return TRUE;
 }
Ejemplo n.º 14
0
 /**
  * paginate
  *
  * @param  mixed $conditions
  * @param  mixed $fields
  * @param  mixed $order
  * @param  integer $limit
  * @param  integer $page
  * @param  integer $recursive
  * @param  array $extract
  * @return array
  */
 public function paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra)
 {
     $HttpSocket = new HttpSocket();
     $query = array('q' => Set::extract('q', $conditions), 'page' => $page, 'rpp' => $limit, 'lang' => Set::extract('lang', $conditions));
     $ret = $HttpSocket->get(self::API_SEARCH, $query);
     if ($ret) {
         $Xml = new Xml($ret);
         return $Xml->toArray();
     }
     return array();
 }
 /**
  * Expect RssReaderItem->serializeXmlToArray() by atom format
  *
  * @return void
  */
 public function testByAtom()
 {
     $url = APP . 'Plugin' . DS . 'RssReaders' . DS . 'Test' . DS . 'Fixture' . DS . 'rss_atom.xml';
     //テスト実施
     $result = $this->RssReaderItem->serializeXmlToArray($url);
     //期待値
     $xmlData = Xml::toArray(Xml::build($url));
     $items = Hash::get($xmlData, 'feed.entry');
     $serializeValue = isset($items[0]) && is_array($items[0]) ? $items[0] : $items;
     $expected = array(array('title' => 'content title', 'link' => 'http://example.com/1.html', 'summary' => 'content description', 'last_updated' => '2015-03-13 17:07:41', 'serialize_value' => serialize($serializeValue)));
     $this->assertEquals($result, $expected);
 }
Ejemplo n.º 16
0
 public function genericDataExtractor($data)
 {
     $output = array();
     $method = $data['method'];
     $result = $this->http->{$method}($data['url'], $data['data'], $data['request']);
     if ($result->body != "") {
         $xmlArray = Xml::toArray(Xml::build($result->body));
         $output['result'] = Hash::extract($xmlArray, $data['path']);
         $output['array'] = $xmlArray;
     }
     return $output;
 }
Ejemplo n.º 17
0
 /**
  * undocumented function
  *
  * @return void
  */
 function __tickets()
 {
     $this->out('This may take a while...');
     $project = @$this->args[1];
     $fork = null;
     if ($this->Project->initialize(compact('project', 'fork')) === false || $this->Project->current['url'] !== $project) {
         $this->err('Invalid project');
         return 1;
     }
     $path = $this->args[2];
     $ext = array_pop(explode('.', $path));
     if ($ext == 'xml') {
         App::import('Xml');
         $Xml = new Xml($path);
         $rows = array();
         $this->out('Importing Data...');
         foreach ($Xml->toArray() as $key => $data) {
             foreach ($data['Records']['Row'] as $columns) {
                 $new = array();
                 foreach ($columns['Column'] as $column) {
                     if ($column['name'] == 'created' || $column['name'] == 'modified') {
                         $column['value'] = date('Y-m-d H:i:s', $column['value']);
                     }
                     $new[$column['name']] = $column['value'];
                 }
                 $new['project_id'] = $this->Project->id;
                 $this->Ticket->create($new);
                 if ($this->Ticket->save()) {
                     $this->out('Ticket ' . $new['number'] . ' : ' . $new['title'] . ' migrated');
                     sleep(1);
                 }
             }
         }
         return 0;
     }
     $File = new File($path);
     $data = explode("\n", $File->read());
     $fields = explode(',', array_shift($data));
     foreach ($fields as $key => $field) {
         $fields[$key] = str_replace('"', '', $field);
     }
     pr($fields);
     $result = array();
     foreach ($data as $line) {
         $values = explode(',', $line);
         foreach ($values as $key => $value) {
             $field = str_replace('"', '', $fields[$key]);
             $result[$field] = str_replace('"', '', $value);
         }
     }
     pr($result);
 }
Ejemplo n.º 18
0
 public function getTweets($q)
 {
     App::uses('Xml', 'Utility');
     $output = array();
     $this->searchURL = 'http://search.twitter.com/search.atom?page=' . $this->settings['page'] . '&lang=' . $this->settings['lang'] . '&rpp=' . $this->settings['rpp'] . '&q=';
     $ch = curl_init($this->searchURL . urlencode($q));
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
     $response = curl_exec($ch);
     $xmlResult = Xml::toArray(Xml::build($response));
     curl_close($ch);
     return $xmlResult;
 }
 public function __construct($id = false, $table = null, $ds = null)
 {
     parent::__construct($id, $table, $ds);
     $datasource = ConnectionManager::getDataSource($this->useDbConfig);
     //$datasource = ConnectionManager::loadDataSource('SalesforceSource');
     if ($datasource->_baseConfig['dynamic_mode']) {
         $this->_schema = $datasource->getSchema($this->name);
     } else {
         if (!empty($datasource->_baseConfig['my_wsdl'])) {
             $wsdl = APP . "Config" . DS . $datasource->_baseConfig['my_wsdl'];
         } else {
             $wsdl = App::Path('Vendor')[0] . 'salesforce/soapclient/' . $datasource->_baseConfig['standard_wsdl'];
         }
         $database_fields = Xml::toArray(Xml::build($wsdl));
         $schemas = $database_fields['definitions']['types']['schema'][0]['complexType'];
         $this_wsdl_schema = array();
         foreach ($schemas as $schema) {
             if ($schema['@name'] == $this->name) {
                 $this_wsdl_schema = $schema['complexContent']['extension']['sequence']['element'];
                 break;
             }
         }
         $names = Hash::extract($this_wsdl_schema, '{n}.@name');
         $types = Hash::extract($this_wsdl_schema, '{n}.@type');
         $new_array = array('Id' => array('type' => 'string', 'length' => 16));
         $n = 0;
         $type_name = "";
         foreach ($names as $name) {
             if (substr($types[$n], 0, 3) != "ens") {
                 //we dont want type of ens
                 if (substr($types[$n], 4) != "QueryResult") {
                     //Or this
                     if (substr($types[$n], 4) == "int") {
                         $type_name = "integer";
                     } elseif (substr($types[$n], 4) == "boolean") {
                         $type_name = "boolean";
                     } elseif (substr($types[$n], 4) == "dateTime" || substr($types[$n], 4) == "date") {
                         $type_name = "datetime";
                     } else {
                         $type_name = "string";
                     }
                     $new_array[$name] = array('type' => $type_name, 'length' => 255);
                 }
             }
             $n++;
         }
         $this->_schema = $new_array;
     }
     return true;
 }
Ejemplo n.º 20
0
 /**
  * Sobrescreve exceção do Cake para incluir informação
  * do erro que poderá ser logada.
  *
  * @param string  $message Mensagem da Exceção
  * @param integer $code    Código do erro
  * @param string  $error   O erro retornado pelo PagSeguro (possivelmente um XML)
  */
 public function __construct($message, $code = 1, $error = null)
 {
     if (!empty($error)) {
         try {
             $decoded = Xml::toArray(Xml::build($error));
             $error = $this->_parseXmlError($decoded);
         } catch (XmlException $e) {
             // apenas uma string... não faz conversão
         }
         $error .= $this->getTraceAsString();
         $msg = $message . " (Problema relacionado ao PagSeguro)\n" . $error;
         CakeLog::write('error', $msg);
     }
     parent::__construct($message, $code);
 }
Ejemplo n.º 21
0
function execSvn($params, $xml = true)
{
    $execParams = array();
    if ($xml) {
        $execParams[] = '--xml';
    }
    $execParams = array_merge($execParams, $params);
    $exec = 'svn ' . implode(' ', array_map('escapeshellarg', $execParams));
    echo date('[d/m/y H:i] ') . "* Executing: {$exec}\n";
    $return = shell_exec($exec);
    if ($xml) {
        return Xml::toArray(new SimpleXMLElement($return));
    }
    return $return;
}
Ejemplo n.º 22
0
 /**
  * Get plugin information
  *
  * @return array
  */
 public static function getPluginData()
 {
     $dir = new Folder(APP . 'Plugin');
     $files = $dir->read(true, ['empty']);
     $plugins = [];
     foreach ($files[0] as $folder) {
         $file = new File(APP . 'Plugin' . DS . $folder . DS . 'Config' . DS . 'info.xml');
         if ($file->exists()) {
             $fileContent = $file->read();
             $plugin = Xml::toArray(Xml::build($fileContent));
             $plugins[$folder] = $plugin['plugin'];
         }
     }
     return $plugins;
 }
Ejemplo n.º 23
0
 function valorFrete(&$model, $servico, $cepOrigem, $cepDestino, $peso, $maoPropria = false, $valorDeclarado = 0.0, $avisoRecebimento = false)
 {
     // Validação dos parâmetros
     $tipos = array(CORREIOS_SEDEX, CORREIOS_SEDEX_A_COBRAR, CORREIOS_SEDEX_10, CORREIOS_SEDEX_HOJE, CORREIOS_ENCOMENDA_NORMAL);
     if (!in_array($servico, $tipos)) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     $Validacao = new ValidacaoBehavior();
     if (!$Validacao->_cep($cepOrigem, '-') || !$Validacao->_cep($cepDestino, '-')) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     if (!is_numeric($peso) || !is_numeric($valorDeclarado)) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     if ($peso > 30.0) {
         return ERRO_CORREIOS_EXCESSO_PESO;
     } elseif ($peso < 0.0) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     if ($valorDeclarado < 0.0) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     // Ajustes nos parâmetros
     if ($maoPropria) {
         $maoPropria = 'S';
     } else {
         $maoPropria = 'N';
     }
     if ($avisoRecebimento) {
         $avisoRecebimento = 'S';
     } else {
         $avisoRecebimento = 'N';
     }
     // Requisição
     $HttpSocket = new HttpSocket();
     $uri = array('scheme' => 'http', 'host' => 'www.correios.com.br', 'port' => 80, 'path' => '/encomendas/precos/calculo.cfm', 'query' => array('resposta' => 'xml', 'servico' => $servico, 'cepOrigem' => $cepOrigem, 'cepDestino' => $cepDestino, 'peso' => $peso, 'MaoPropria' => $maoPropria, 'valorDeclarado' => $valorDeclarado, 'avisoRecebimento' => $avisoRecebimento));
     $retornoCorreios = trim($HttpSocket->get($uri));
     if ($HttpSocket->response['status']['code'] != 200) {
         return ERRO_CORREIOS_FALHA_COMUNICACAO;
     }
     $Xml = new Xml($retornoCorreios);
     $infoCorreios = $Xml->toArray();
     if (!isset($infoCorreios['CalculoPrecos']['DadosPostais'])) {
         return ERRO_CORREIOS_CONTEUDO_INVALIDO;
     }
     extract($infoCorreios['CalculoPrecos']['DadosPostais']);
     return array('ufOrigem' => $uf_origem, 'ufDestino' => $uf_destino, 'capitalOrigem' => $local_origem == 'Capital', 'capitalDestino' => $local_destino == 'Capital', 'valorMaoPropria' => $mao_propria, 'valorTarifaValorDeclarado' => $tarifa_valor_declarado, 'valorFrete' => $preco_postal - $tarifa_valor_declarado - $mao_propria, 'valorTotal' => $preco_postal);
 }
 /**
  * Função para restauração
  */
 public function restore()
 {
     $sDiretorio = Configure::read('Cms.CheckPoint.menus');
     if (!is_dir($sDiretorio)) {
         $this->Session->setFlash("Diretório das restaurações não configurado.", 'default', array('class' => "alert alert-error"));
         $this->redirect(array('controller' => 'dashboard', 'action' => 'index'));
     }
     /**
      * Faz a restauração
      */
     if (!empty($this->data)) {
         $this->loadModel('Cms.Menu');
         App::import('Xml');
         $oSnapXml = new Xml($sDiretorio . $this->data['CheckPoint']['snapshot']);
         $aSnap = $oSnapXml->toArray();
         $aRestore = !empty($aSnap['Menus']) ? $aSnap['Menus']['Menu'] : array();
         /**
          * Verifica se possui apenas um item de menu no xml e trata de uma forma diferente.
          * -- Função de XML do Cake salva de formas diferentes o XML quando possui apenas um item.
          */
         if (!empty($aRestore) && !isset($aRestore[0])) {
             $aRestore = array($aRestore);
         }
         $this->CheckPoint->generate();
         if ($this->Menu->restauraBackup($aRestore)) {
             $this->Session->setFlash("Restaurado com sucesso.", 'default', array('class' => "alert alert-success"));
         } else {
             $this->Session->setFlash("Erro ao restaurar.", 'default', array('class' => "alert alert-error"));
         }
     }
     /**
      * Pega os snapshots salvos e invverte a ordem para exibir do mais novo para o mais antigo
      */
     $oFolder = new Folder(Configure::read('Cms.CheckPoint.menus'));
     $aFolder = $oFolder->read();
     $aFiles = array_reverse($aFolder[1]);
     $aSnapshot = array();
     foreach ($aFiles as $sFile) {
         if (!in_array($sFile, array('.', '..'))) {
             $aSnapshot[$sFile] = date('d/m/Y H:i:s', str_replace('.xml', '', $sFile));
         }
     }
     if (empty($aSnapshot)) {
         $this->Session->setFlash("Nenhum ponto de restauração encontrado.", 'default', array('class' => "alert alert-error"));
         $this->redirect(array('controller' => 'dashboard', 'action' => 'index'));
     }
     $this->set(compact('aSnapshot'));
 }
Ejemplo n.º 25
0
 function save($data = null, $validate = true, $fieldList = array())
 {
     if (is_null($this->data)) {
         return false;
     }
     $url = sprintf(self::API_URL, Configure::read('Tweet.username'), Configure::read('Tweet.password'));
     $url .= self::API_PATH_UPDATE;
     $this->connection = new HttpSocket();
     $result = $this->connection->post($url, $this->data['Tweet']);
     $Xml = new Xml($result);
     $result = $Xml->toArray();
     if (isset($result['Status']['id']) && is_numeric($result['Status']['id'])) {
         $this->setInsertId($result['Status']['id']);
         return true;
     }
     return false;
 }
Ejemplo n.º 26
0
 public static function getThemeData()
 {
     $defaults = array('name' => '', 'description' => '', 'theme_url' => '', 'author' => '', 'author_url' => '', 'version' => '', 'tags' => '');
     App::import('Utility', 'Xml');
     $viewPath = App::path('View');
     $dir = new Folder($viewPath[0] . 'Themed');
     $files = $dir->read(true, array('empty'));
     foreach ($files[0] as $i => $folder) {
         $file = new File($viewPath[0] . 'Themed' . DS . $folder . DS . 'Config' . DS . 'info.xml');
         if ($file->exists()) {
             $fileContent = $file->read();
             $theme = Xml::toArray(Xml::build($fileContent));
             $themes[Inflector::camelize($folder)] = Hash::merge($defaults, $theme['theme']);
         }
     }
     return $themes;
 }
Ejemplo n.º 27
0
 /**
  * Cálculo do valor do frete
  *
  * @param object $model
  * @param integer $servico Código do serviço, ver as defines CORREIOS_*
  * @param string $cepOrigem CEP de origem no formato XXXXX-XXX
  * @param string $cepDestino CEP de destino no formato XXXXX-XXX
  * @param float $peso Peso do pacote, em quilos
  * @param boolean $maoPropria Usar recurso de mão própria?
  * @param float $valorDeclarado Valor declarado do pacote
  * @param boolean $avisoRecebimento Aviso de recebimento?
  * @return mixed Array com os dados do frete ou integer com erro. Ver defines ERRO_CORREIOS_* para erros.
  * @access public
  */
 function valorFrete(&$model, $servico, $cepOrigem, $cepDestino, $peso, $maoPropria = false, $valorDeclarado = 0.0, $avisoRecebimento = false)
 {
     // Validação dos parâmetros
     $tipos = array(CORREIOS_SEDEX, CORREIOS_SEDEX_A_COBRAR, CORREIOS_SEDEX_10, CORREIOS_SEDEX_HOJE, CORREIOS_ENCOMENDA_NORMAL);
     if (!in_array($servico, $tipos)) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     if (!$this->_validaCep($cepOrigem) || !$this->_validaCep($cepDestino)) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     if (!is_numeric($peso) || !is_numeric($valorDeclarado)) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     if ($peso > 30.0) {
         return ERRO_CORREIOS_EXCESSO_PESO;
     } elseif ($peso < 0.0) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     if ($valorDeclarado < 0.0) {
         return ERRO_CORREIOS_PARAMETROS_INVALIDOS;
     }
     // Ajustes nos parâmetros
     if ($maoPropria) {
         $maoPropria = 'S';
     } else {
         $maoPropria = 'N';
     }
     if ($avisoRecebimento) {
         $avisoRecebimento = 'S';
     } else {
         $avisoRecebimento = 'N';
     }
     $query = array('resposta' => 'xml', 'servico' => $servico, 'cepOrigem' => $cepOrigem, 'cepDestino' => $cepDestino, 'peso' => $peso, 'MaoPropria' => $maoPropria, 'valorDeclarado' => $valorDeclarado, 'avisoRecebimento' => $avisoRecebimento);
     $retornoCorreios = $this->_requisitaUrl('/encomendas/precos/calculo.cfm', 'get', $query);
     if (is_integer($retornoCorreios)) {
         return $retornoCorreios;
     }
     $Xml = new Xml($retornoCorreios);
     $infoCorreios = $Xml->toArray();
     if (!isset($infoCorreios['CalculoPrecos']['DadosPostais'])) {
         return ERRO_CORREIOS_CONTEUDO_INVALIDO;
     }
     extract($infoCorreios['CalculoPrecos']['DadosPostais']);
     return array('ufOrigem' => $uf_origem, 'ufDestino' => $uf_destino, 'capitalOrigem' => $local_origem == 'Capital', 'capitalDestino' => $local_destino == 'Capital', 'valorMaoPropria' => $mao_propria, 'valorTarifaValorDeclarado' => $tarifa_valor_declarado, 'valorFrete' => $preco_postal - $tarifa_valor_declarado - $mao_propria, 'valorTotal' => $preco_postal);
 }
Ejemplo n.º 28
0
 public function beforeSave($options = array())
 {
     if (!empty($this->data['Post']['post_dt'])) {
         $this->data['Post']['post_dt'] = $this->dateFormatBeforeSave($this->data['Post']['post_dt']);
     }
     App::uses('Xml', 'Utility');
     App::uses('HttpSocket', 'Network/Http');
     $http = new HttpSocket();
     $response = $http->get('http://www.earthtools.org/timezone/' . $this->data['Post']['latitude'] . '/' . $this->data['Post']['longitude']);
     if ($response->code == '200') {
         $response = Xml::toArray(Xml::build($response->body()));
         $response = 'GMT' . $response['timezone']['offset'];
     } else {
         $response = '';
     }
     $this->data[$this->alias]['post_dt_offset'] = $response;
     return true;
 }
Ejemplo n.º 29
0
 protected function request($data = null)
 {
     App::uses('Xml', 'Utility');
     $xml = $this->buildRequest($data);
     //print_r($xml);
     $ch = curl_init($this->url);
     curl_setopt($ch, CURLOPT_HEADER, 1);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_TIMEOUT, 60);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
     $res = curl_exec($ch);
     $res = strstr($res, '<?');
     $response = Xml::toArray(Xml::build($res));
     //print_r($response);
     return $response;
 }
Ejemplo n.º 30
0
 public function getRate($data = null)
 {
     if ($data['Weight'] < 0.1) {
         $data['Weight'] = 0.1;
     }
     if ($data['Weight'] > 70) {
         $data['Weight'] = 70;
     }
     $xml = $this->buildRequest($data);
     App::uses('HttpSocket', 'Network/Http');
     $httpSocket = new HttpSocket();
     $res = $httpSocket->post($this->url, $xml);
     App::uses('Xml', 'Utility');
     $response = Xml::toArray(Xml::build($res['body']));
     $formattedResponse = $this->formatResponse($response);
     if (!empty($formattedResponse)) {
         return $formattedResponse;
     }
     return false;
 }