Beispiel #1
0
 /**
  * add shop to folder
  * 
  */
 function addShopToFolder()
 {
     $name = @$this->request->data['name'];
     $shop_id = @$this->request->data['shop_id'];
     if (!$shop_id || !$name) {
         return $this->responseng('faild to add shop.');
     }
     $dataFolder = array("user_id" => $this->user_id, "name" => $name, "type_folder" => intval(@$this->request->data['type_folder']));
     $ret = $this->FolderUser->save($dataFolder);
     $folder_id_old = @$this->request->data["older_folder_id"];
     $datashopFolder = array("folder_id" => $ret["FolderUser"]["id"], "shop_id" => $shop_id, "rank" => 1, "status" => NO_MY_FOLDER);
     $result = $this->FolderShop->save($datashopFolder);
     App::uses('Folder', 'Utility');
     $folder = new Folder();
     if (!empty($folder_id_old)) {
         $oldFolder = $this->FolderUser->findById($folder_id_old);
         $newFolder = $ret;
         $path = WWW_ROOT . 'shops' . DS . $oldFolder["FolderUser"]["user_id"] . DS . $oldFolder["FolderUser"]["id"] . DS . $shop_id;
         $newPath = WWW_ROOT . 'shops' . DS . $newFolder["FolderUser"]["user_id"] . DS . $newFolder["FolderUser"]["id"] . DS . $result["FolderShop"]["shop_id"];
         if (is_dir($path)) {
             if (!is_dir($newPath)) {
                 $folder->create($newPath);
             }
             $folder->copy(array('to' => $newPath, 'from' => $path, 'mode' => 0777));
         }
     }
     if ($result) {
         return $this->responseOk();
     }
     return $this->responseng('can not save data');
 }
Beispiel #2
0
/**
 * test bake all
 *
 * @return void
 */
	public function testAllWithModelName() {
		App::uses('User', 'Model');
		$userExists = class_exists('User');
		$this->skipIf($userExists, 'User class exists, cannot test `bake all [param]`.');

		$this->Shell->Model = $this->getMock('ModelTask', array(), array(&$this->Dispatcher));
		$this->Shell->Controller = $this->getMock('ControllerTask', array(), array(&$this->Dispatcher));
		$this->Shell->View = $this->getMock('ModelTask', array(), array(&$this->Dispatcher));
		$this->Shell->DbConfig = $this->getMock('DbConfigTask', array(), array(&$this->Dispatcher));

		$this->Shell->DbConfig->expects($this->once())->method('getConfig')->will($this->returnValue('test'));
	
		$this->Shell->Model->expects($this->never())->method('getName');
		$this->Shell->Model->expects($this->once())->method('bake')->will($this->returnValue(true));
	
		$this->Shell->Controller->expects($this->once())->method('bake')->will($this->returnValue(true));
		$this->Shell->View->expects($this->once())->method('execute');

		$this->Shell->expects($this->once())->method('_stop');
		$this->Shell->expects($this->at(0))->method('out')->with('Bake All');
		$this->Shell->expects($this->at(5))->method('out')->with('<success>Bake All complete</success>');

		$this->Shell->connection = '';
		$this->Shell->params = array();
		$this->Shell->args = array('User');
		$this->Shell->all();
	}
 public function createDatabaseFile($data)
 {
     App::uses('File', 'Utility');
     App::uses('ConnectionManager', 'Model');
     $config = $this->defaultConfig;
     foreach ($data['Install'] as $key => $value) {
         if (isset($data['Install'][$key])) {
             $config[$key] = $value;
         }
     }
     $result = copy(APP . 'Config' . DS . 'database.php.install', APP . 'Config' . DS . 'database.php');
     if (!$result) {
         return __d('croogo', 'Could not copy database.php file.');
     }
     $file = new File(APP . 'Config' . DS . 'database.php', true);
     $content = $file->read();
     foreach ($config as $configKey => $configValue) {
         $content = str_replace('{default_' . $configKey . '}', $configValue, $content);
     }
     if (!$file->write($content)) {
         return __d('croogo', 'Could not write database.php file.');
     }
     try {
         ConnectionManager::create('default', $config);
         $db = ConnectionManager::getDataSource('default');
     } catch (MissingConnectionException $e) {
         return __d('croogo', 'Could not connect to database: ') . $e->getMessage();
     }
     if (!$db->isConnected()) {
         return __d('croogo', 'Could not connect to database.');
     }
     return true;
 }
 /**
  * Loads/constructs a helper.  Will return the instance in the registry if it already exists.
  * By setting `$enable` to false you can disable callbacks for a helper.  Alternatively you
  * can set `$settings['enabled'] = false` to disable callbacks.  This alias is provided so that when
  * declaring $helpers arrays you can disable callbacks on helpers.
  *
  * You can alias your helper as an existing helper by setting the 'className' key, i.e.,
  * {{{
  * public $helpers = array(
  *   'Html' => array(
  *     'className' => 'AliasedHtml'
  *   );
  * );
  * }}}
  * All calls to the `Html` helper would use `AliasedHtml` instead.
  *
  * @param string $helper Helper name to load
  * @param array $settings Settings for the helper.
  * @return Helper A helper object, Either the existing loaded helper or a new one.
  * @throws MissingHelperException when the helper could not be found
  */
 public function load($helper, $settings = array())
 {
     if (is_array($settings) && isset($settings['className'])) {
         $alias = $helper;
         $helper = $settings['className'];
     }
     list($plugin, $name) = pluginSplit($helper, true);
     if (!isset($alias)) {
         $alias = $name;
     }
     if (isset($this->_loaded[$alias])) {
         return $this->_loaded[$alias];
     }
     $helperClass = $name . 'Helper';
     App::uses($helperClass, $plugin . 'View/Helper');
     if (!class_exists($helperClass)) {
         throw new MissingHelperException(array('class' => $helperClass, 'plugin' => substr($plugin, 0, -1)));
     }
     $this->_loaded[$alias] = new $helperClass($this->_View, $settings);
     $vars = array('request', 'theme', 'plugin');
     foreach ($vars as $var) {
         $this->_loaded[$alias]->{$var} = $this->_View->{$var};
     }
     $enable = isset($settings['enabled']) ? $settings['enabled'] : true;
     if ($enable) {
         $this->enable($alias);
     }
     return $this->_loaded[$alias];
 }
Beispiel #5
0
 /**
  * afterSave
  * 
  * Write out the routes.php file
  */
 public function afterSave($created, $options = array())
 {
     $aliases = $this->find('all');
     $routes = '';
     foreach ($aliases as $alias) {
         $alias['Alias']['name'] = $alias['Alias']['name'] == 'home' ? '' : $alias['Alias']['name'];
         // keyword home is the homepage
         $plugin = !empty($alias['Alias']['plugin']) ? '/' . $alias['Alias']['plugin'] : null;
         $controller = !empty($alias['Alias']['controller']) ? '/' . $alias['Alias']['controller'] : null;
         $action = !empty($alias['Alias']['action']) ? '/' . $alias['Alias']['action'] : null;
         $value = !empty($alias['Alias']['value']) ? '/' . $alias['Alias']['value'] : null;
         $url = $plugin . $controller . $action . $value;
         $routes .= 'Router::redirect(\'' . $url . '\', \'/' . $alias['Alias']['name'] . '\', array(\'status\' => 301));' . PHP_EOL;
         $routes .= 'Router::connect(\'/' . $alias['Alias']['name'] . '\', array(\'plugin\' => \'' . $alias['Alias']['plugin'] . '\', \'controller\' => \'' . $alias['Alias']['controller'] . '\', \'action\' => \'' . $alias['Alias']['action'] . '\', \'' . implode('\', \'', explode('/', $alias['Alias']['value'])) . '\'));' . PHP_EOL;
     }
     App::uses('File', 'Utility');
     $file = new File(ROOT . DS . SITE_DIR . DS . 'Config' . DS . 'routes.php');
     $currentRoutes = str_replace(array('<?php ', '<?php'), '', explode('// below this gets overwritten', $file->read()));
     $routes = '<?php ' . $currentRoutes[0] . '// below this gets overwritten' . PHP_EOL . PHP_EOL . $routes;
     if ($file->write($routes)) {
         $file->close();
     } else {
         $file->close();
         // Be sure to close the file when you're done
         throw new Exception(__('Error writing routes file'));
     }
     // <?php
     // Router::redirect('/webpages/webpages/view/113', '/lenovo', array('status' => 301));
     // Router::connect('/lenovo', array('plugin' => 'webpages', 'controller' => 'webpages', 'action' => 'view', 113));
 }
Beispiel #6
0
 public function beforeSave($options = array())
 {
     Configure::write('debug', 2);
     App::uses("HtmlHelper", "View/Helper");
     $html = new HtmlHelper(new View());
     if ($this->data[$this->alias]['image']['name'] != "") {
         $ext = pathinfo($this->data[$this->alias]['image']['name'], PATHINFO_EXTENSION);
         $image_name = date('YmdHis') . rand(1, 999) . "." . $ext;
         $destination = "files/recipe_images/" . $image_name;
         if (move_uploaded_file($this->data[$this->alias]['image']['tmp_name'], $destination)) {
             $bowl = $this->createBowl($destination);
             $tmp = explode("/", $bowl);
             $destination2 = "files/recipe_images/" . $tmp[1];
             //unlink($destination);
             rename($destination, $dt = "files/recipe_images/ori/" . $tmp[1]);
             rename($bowl, $destination2);
         }
         $this->data[$this->alias]['image'] = $html->url("/" . $dt, true);
         $this->data[$this->alias]['image_bowl'] = $html->url("/" . $destination2, true);
     } else {
         unset($this->data[$this->alias]['image']);
     }
     parent::beforeSave($options);
     return true;
 }
 /**
  * Initializes the fixture
  *
  */
 public function init($db)
 {
     $plugin = $this->plugin ? $this->plugin . '.' : null;
     App::uses($this->document, $plugin . 'Model');
     $documentClass = $this->document;
     $documentClass::$useDbConfig = Connectionmanager::getSourceName($db);
 }
 public function maestro($key = null)
 {
     if ($key != 'secret') {
         die('sorry');
     }
     App::uses('HttpSocket', 'Network/Http');
     $httpSocket = new HttpSocket();
     $yesterday = date("Y-m-d H:i:s", strtotime("-1 day"));
     // print_r($yesterday);
     // die;
     $products = $this->Product->find('all', array('recursive' => -1, 'conditions' => array('Product.user_id' => 11, 'Product.active' => 1, 'Product.stock_updated <' => $yesterday), 'order' => 'RAND()', 'limit' => 20));
     foreach ($products as $product) {
         //sleep(1);
         $response = $httpSocket->get('https://www.maestrolico.com/api/checkstockstatus.asp?distributorid=117&productid=' . $product['Product']['vendor_sku']);
         echo '<br /><hr><br />';
         echo $product['Product']['name'] . ' - ' . $product['Product']['vendor_sku'];
         echo '<br /><br />';
         debug($response['body']);
         $update = explode('|', $response['body']);
         debug($update);
         debug(date('H:i:s'));
         $data['Product']['id'] = $product['Product']['id'];
         $data['Product']['stock'] = $update[1];
         $data['Product']['stock_updated'] = date('Y-m-d H:i:s');
         $this->Product->save($data, false);
     }
     die('end');
 }
 public function countUsedRequests(Model $model, $userId)
 {
     //find subscription expire date
     //TODO: potentially we have risk to reset counter after each proposals increment
     App::uses('BillingSubscription', 'Billing.Model');
     $billingSubscription = new BillingSubscription();
     $billingSubscription->Behaviors->load('Containable');
     $subscription = $billingSubscription->find('first', array('contain' => array('BillingGroup'), 'conditions' => array('BillingSubscription.user_id' => $userId, 'BillingGroup.limit_units LIKE' => 'proposals'), 'callbacks' => false));
     $periodEndDate = date('Y-m-d H:i:s');
     $periodStartDate = date('Y-m-d H:i:s', strtotime("-1 month"));
     if (!empty($subscription)) {
         $periodEndDate = $subscription['BillingSubscription']['expires'];
         $periodStartDate = date('Y-m-d H:i:s', strtotime($periodEndDate) - (time() - strtotime("-3 month")));
     }
     App::uses('UserEventRequest', 'Model');
     $userEventRequestModel = new UserEventRequest();
     $requestsCount = $userEventRequestModel->find('count', array('conditions' => array('UserEventRequest.user_id' => $userId, array('UserEventRequest.created >=' => $periodStartDate), array('UserEventRequest.created <=' => $periodEndDate)), 'recursive' => -1));
     $requestsCount = $requestsCount - 5;
     App::uses('UserEventRequestLimit', 'Model');
     $userEventRequestLimitModel = new UserEventRequestLimit();
     $limit = $userEventRequestLimitModel->findByUserId($userId);
     if (!empty($limit)) {
         $userEventRequestLimitModel->id = $limit['UserEventRequestLimit']['id'];
         $userEventRequestLimitModel->saveField('requests_used', $requestsCount, array('validate' => false, 'callbacks' => false, 'counterCache' => false));
     }
     return $requestsCount;
 }
 public function save()
 {
     $id = isset($this->request->data['Admin']['id']) ? $this->request->data['Admin']['id'] : null;
     $this->loadModel('Admin');
     if ($id !== null and is_numeric($id)) {
         $admin = $this->Admin->find('first', array('conditions' => array('id' => $id)));
         if ($admin == null) {
             //!!!!
             $this->Error->setError('ERROR_201');
         } else {
             $this->Admin->save($this->request->data);
         }
     } else {
         //добавление нового администратора
         $pass = md5(time() . Configure::read('ADMIN_AUTH_SALT'));
         $pass = substr($pass, 0, 8);
         $pass_hash = get_hash(Configure::read('ADMIN_AUTH_SALT'), $pass);
         //$mail_key
         $mail_key = md5(Configure::read('ADMIN_AUTH_SALT') . time());
         $save_array = $this->request->data;
         $save_array['Admin']['password'] = $pass_hash;
         $save_array['Admin']['mail_key'] = $mail_key;
         $this->Admin->save($save_array);
         $id = $this->Admin->getLastInsertId();
         //pr($this->request->data);
         if (is_numeric($id)) {
             App::uses('CakeEmail', 'Network/Email');
             //$this->Email->smtpOptions = Configure::read('SMTP_CONFIG');
             //				$this->Email->from = Configure::read('SITE_MAIL');
             //				$this->Email->to = 'homoastricus2011@gmail.com';//Configure::read('ADMIN_MAIL');
             //
             //				$this->Email->sendAs = 'html';
             //
             //				$this->Email->delivery = 'smtp';
             //
             //				$this->Email->subject = "Добавлен новый администратор";
             $sended_data = "Добавлен новый администратор" . "<br>";
             $sended_data .= "Почтовый ящик: " . $this->request->data['Admin']['mail'];
             $sended_data .= ", ";
             $sended_data .= "пароль: " . $pass . "<br>";
             $sended_data .= "<a href='" . site_url() . "/activate_account/admin/" . $mail_key . "'>Ссылка для активации аккаунта</a> администратора: <br>";
             //				$this->Email->layout = 'mail';
             //				$this->Email->template = "mail_main_admin";
             //				$this->Email->viewVars = $sended_data;
             //				//pr($this->Email);
             //				$this->Email->send();
             $email = new CakeEmail();
             //$email->
             $email->emailFormat('html');
             $email->template('mail_main_admin', 'mail');
             $email->from(Configure::read('SITE_MAIL'));
             $email->to('homoastricus2011@gmail.com');
             //Configure::read('ADMIN_MAIL');
             $email->subject("Добавлен новый администратор");
             $email->viewVars(array('sended_data' => $sended_data));
             $email->send();
         }
     }
     $this->redirect(array('controller' => 'admincontrol', 'action' => 'view', 'id' => $id));
 }
Beispiel #11
0
 public function registration($state = null)
 {
     if ($state == 'success') {
         $this->render('registration_success');
     }
     if ($this->request->is('post')) {
         $User = $this->data['User'];
         $autoFields = array('visability_fields' => serialize($this->User->defaultVisibility), 'self_registered' => 1, 'activation_code' => $this->User->generate_code(), 'activation_code_date' => mysqldate(), 'activation_function' => 'registration');
         $User = array_merge($User, $autoFields);
         App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
         $passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha1'));
         $User['password'] = $passwordHasher->hash($User['password']);
         $User['repeat_password'] = $passwordHasher->hash($User['repeat_password']);
         $AvatarFile = array_merge($this->data['AvatarFile'], array('type' => 'photo'));
         //			$AvatarFile = array_merge($this->data['AvatarFile'], array('type' => 'photo'));
         /*$this->User->set( $User );
         		debug($this->User->validates());
         		debug($this->User->invalidFields());*/
         if ($this->User->saveAll(compact('User', 'AvatarFile'))) {
             $title = 'Регистрация на mcl.resp.su';
             $this->User->sendEmailToUser($this->User->id, 'registration', $title, array('code' => $User['activation_code']));
             $this->redirect(array('success'));
         }
         //			$this->Session->write('user.registration.allowedStates', array('step1', 'success'));
         //			$this->redirect(array('success'));
     }
     $this->set('geoCountries', $this->User->GeoCountry->find('list'));
 }
 public function contact()
 {
     $this->loadModel('Contact');
     if ($this->request->is('post')) {
         $this->Contact->set($this->request->data);
         if ($this->Contact->validates()) {
             App::uses('CakeEmail', 'Network/Email');
             if ($this->request->data['Contact']['subject'] == '') {
                 $this->request->data['Contact']['subject'] = 'Contact';
             }
             $Email = new CakeEmail('smtp');
             $Email->viewVars(array('mailData' => $this->request->data));
             $Email->template('contact', 'default');
             $Email->emailFormat('html');
             $Email->from(array($this->request->data['Contact']['mail'] => $this->request->data['Contact']['name']));
             $Email->to('contact@youthbook.be');
             $Email->subject($this->request->data['Contact']['subject']);
             $Email->attachments(array('logo.png' => array('file' => WWW_ROOT . '/img/icons/logo.png', 'mimetype' => 'image/png', 'contentId' => 'logo')));
             $Email->send();
             $this->Flash->success(__('Votre mail a bien été envoyé.'));
             return $this->redirect($this->referer());
         } else {
             $this->Session->write('errors.Contact', $this->Contact->validationErrors);
             $this->Session->write('data', $this->request->data);
             $this->Session->write('flash', 'Le mail n’a pas pu être envoyé. Veuillez réessayer SVP.');
             return $this->redirect($this->referer());
         }
     }
 }
Beispiel #13
0
 private function getUserSession()
 {
     App::uses('CakeSession', 'Model/Datasource');
     $Session = new CakeSession();
     $user = $Session->read('UserAuth');
     return $user;
 }
Beispiel #14
0
 /**
  * Получение списка worker-ов
  *
  * @param string $worker имя воркеров, параметры которого нам нужно получить
  * @return array массив доступных worker-ов с их загрузкой и тд
  */
 public function getWorkers($worker = null)
 {
     // получаем статистику по worker-ам
     \App::uses('CakeSocket', 'Network');
     $Socket = new \CakeSocket($this->_config['server']);
     $Socket->connect();
     $workers = array();
     // делаем 2 замера с интервалом в 1 секунду для получение точного результата
     for ($i = 0; $i <= 2; $i++) {
         $Socket->write("status\n");
         $content = $Socket->read(50000);
         $answers = explode("\n", trim($content));
         foreach ($answers as $string) {
             $temp = explode("\t", $string);
             $title = trim($temp[0]);
             if (strpos($title, 'restart') !== false || strpos($title, '.') !== false) {
                 continue;
             }
             if (!empty($workers[$title])) {
                 // тут нас интересует только макс. значение доступных worker-ов
                 $workers[$title][3] = intval($workers[$title][3]) < intval($temp[3]) ? $temp[3] : $workers[$title][3];
             } else {
                 $workers[$title] = $temp;
             }
         }
         sleep(1);
     }
     $Socket->disconnect();
     return $worker ? $workers[$worker] : $workers;
 }
 public function before($event = array())
 {
     App::uses('UpdateSchema', 'Model');
     $this->UpdateSchema = new UpdateSchema();
     $before = $this->UpdateSchema->before($event);
     return $before;
 }
Beispiel #16
0
 /**
  * The time element represents either a time on a 24 hour clock,
  * or a precise date in the proleptic Gregorian calendar,
  * optionally with a time and a time-zone offset.
  *
  * @param $content string
  * @param $options array
  *      'format' STRING: Use the specified TimeHelper method (or format()). FALSE: Generate the datetime. NULL: Do nothing.
  *      'datetime' STRING: If 'format' is STRING use as the formatting string. FALSE: Don't generate attribute
  *		'pubdate' BOOLEAN: If the pubdate attribute should be set
  */
 public function time($content, $options = array())
 {
     $options = array_merge(array('datetime' => DATE_W3C, 'pubdate' => false, 'format' => false), $options);
     if ($options['format'] !== null) {
         App::uses('TimeHelper', 'View/Helper');
         $t =& new TimeHelper($this->_View);
     }
     if ($options['format']) {
         $time = $content;
         if (method_exists($t, $options['format'])) {
             $content = $t->{$options}['format']($content);
         } else {
             $content = $t->format($options['format'], $content);
         }
         $options['datetime'] = $t->format($options['datetime'], strtotime($time));
     } elseif ($options['format'] === false && $options['datetime']) {
         $options['datetime'] = $t->format($options['datetime'], strtotime($content));
     }
     if ($options['pubdate']) {
         $pubdate = true;
     }
     unset($options['format']);
     unset($options['pubdate']);
     $attributes = $this->_parseAttributes($options, array(0), ' ', '');
     if (isset($pubdate)) {
         $attributes .= ' pubdate';
     }
     return sprintf($this->_tags['time'], $attributes, $content);
 }
Beispiel #17
0
 /**
  * test_Censorship
  *
  */
 public function test_Censorship()
 {
     $hash = $this->hash;
     $to = 'to+' . $hash . '@mailback.me';
     Configure::write('Postman.censorship.mode', true);
     Configure::write('Postman.censorship.config', array('transport' => 'Smtp', 'from' => array('form@mailback.me' => 'from'), 'to' => $to, 'host' => 'mail.mailback.me', 'port' => 25, 'timeout' => 30, 'log' => false, 'charset' => 'utf-8', 'headerCharset' => 'utf-8'));
     $message = 'Censored';
     $expect = $message;
     $this->email->subject('メールタイトル');
     $this->email->send($expect);
     sleep(15);
     $url = 'http://mailback.me/to/' . $hash . '.body';
     App::uses('HttpSocket', 'Network/Http');
     $HttpSocket = new HttpSocket();
     $results = $HttpSocket->get($url, array());
     $body = trim(str_replace(array("\r\n", "\n", ' '), '', $results->body));
     $message = trim(str_replace(array("\r\n", "\n", ' '), '', $message));
     $this->assertIdentical($results->code, '200');
     $this->assertIdentical($body, $message);
     // CC
     $ccUrl = 'http://mailback.me/to/unknown-cc-' . $hash . '.body';
     $results = $HttpSocket->get($ccUrl, array());
     $this->assertContains('404', $results->body);
     // BCC
     $bccUrl = 'http://mailback.me/to/unknown-bcc-' . $hash . '.body';
     $results = $HttpSocket->get($bccUrl, array());
     $this->assertContains('404', $results->body);
 }
 public static function get($class)
 {
     list($plugin, $class) = pluginSplit($class, true);
     $class .= 'AccessProvider';
     App::uses($class, $plugin . 'CustomerAccessProvider');
     return new $class();
 }
 public function setup($environment = null)
 {
     if (Configure::read('Environment.setup')) {
         return;
     }
     $current = $environment === null ? 'development' : $environment;
     if (empty($environment)) {
         foreach ($this->environments as $name => $config) {
             if ($this->_cliMatch($name) || $this->_match($config['params'])) {
                 $current = $name;
                 break;
             }
         }
     }
     $config = array_merge($this->environments[$current]['config'], array('Environment.name' => $current));
     foreach ($config as $param => $value) {
         if (isset($this->_configMap[$param])) {
             $param = $this->_configMap[$param];
         }
         Configure::write($param, $value);
     }
     if (is_callable($this->environments[$current]['callable'])) {
         $this->environments[$current]['callable']();
     }
     if (Configure::read('debug') > 0) {
         App::uses('CakeLog', 'Log');
         if (class_exists('CakeLog')) {
             CakeLog::write(LOG_INFO, $current);
             Configure::write('Environment.setup', true);
         }
     }
 }
Beispiel #20
0
 /**
  * Constructor
  *
  */
 public function __construct()
 {
     parent::__construct();
     App::uses('AclNode', 'Model');
     $this->Aro = ClassRegistry::init(array('class' => 'Aro', 'alias' => 'Aro'));
     $this->Aco = ClassRegistry::init(array('class' => 'Aco', 'alias' => 'Aco'));
 }
Beispiel #21
0
 /**
  * PwdShell::hash()
  *
  * @return void
  */
 public function hash()
 {
     $components = array('Tools.AuthExt', 'Auth');
     $class = null;
     foreach ($components as $component) {
         if (App::import('Component', $component)) {
             $component .= 'Component';
             list($plugin, $class) = pluginSplit($component);
             break;
         }
     }
     if (!$class || !method_exists($class, 'password')) {
         return $this->error(__('No Auth Component found'));
     }
     $this->out('Using: ' . $class);
     while (empty($pwToHash) || mb_strlen($pwToHash) < 2) {
         $pwToHash = $this->in(__('Password to Hash (2 characters at least)'));
     }
     if ($authType = Configure::read('Passwordable.authType')) {
         list($plugin, $authType) = pluginSplit($authType, true);
         $className = $authType . 'PasswordHasher';
         App::uses($className, $plugin . 'Controller/Component/Auth');
         $passwordHasher = new $className();
         $pw = $passwordHasher->hash($pwToHash);
     } else {
         $class = new $class(new ComponentCollection());
         $pw = $class->password($pwToHash);
     }
     $this->hr();
     $this->out($pw);
 }
Beispiel #22
0
 /**
  * リサイズ
  */
 public function resize($fileName, $mimeType, $sizeType = 'normal')
 {
     // 画像のサイズを取得する。
     $imageSize = $this->sizes($fileName);
     // 画像の拡張性を設定スル。
     $mimeType = explode('/', $mimeType);
     App::uses('ImageResize', 'Vendor');
     // 切り抜きサイズを取得
     $resize = Configure::read('resize_info');
     $resize = $resize[$sizeType];
     //画像を幅100pxでリサイズして保存
     $newImgname = time() . rand(100000, 999999) . '.png';
     $thumb = new ImageResize($fileName, $mimeType[1]);
     $thumb->name($newImgname);
     if ($resize['height'] > $resize['width']) {
         $thumb->height($resize['height']);
     } else {
         $thumb->width($resize['width']);
     }
     $thumb->save();
     // サイズの中心から抜き取り。
     $tmp_dir = ini_get('upload_tmp_dir');
     if (empty($tmp_dir)) {
         $tmp_dir = '/tmp';
     }
     if ($resize['height'] != null) {
         $thumb = new ImageResize($tmp_dir . '/' . $newImgname, $mimeType[1]);
         $thumb->name($newImgname);
         $thumb->width($resize['width']);
         $thumb->height($resize['height']);
         $thumb->crop(0, 0);
         $thumb->save();
     }
     return $tmp_dir . '/' . $newImgname;
 }
Beispiel #23
0
 public function currentUser()
 {
     App::uses('CakeSession', 'Model/Datasource');
     $Session = new CakeSession();
     $user = $Session->read('Auth.User');
     return array('id' => $user['User']['username']);
 }
 function sendSMS($phone, $message)
 {
     App::uses('HttpSocket', 'Network/Http');
     $HttpSocket = new HttpSocket();
     $results = $HttpSocket->post('http://mobileautomatedsystems.com/index.php?option=com_spc&comm=spc_api', array('username' => 'noibilism', 'password' => 'noheeb', 'sender' => 'NASFAT', 'recipient' => $phone, 'message' => $message));
     return $results;
 }
Beispiel #25
0
 function sendMail()
 {
     //        $this->request->data['api_token'] = "017d6a18596ec81a472d234457534a8c9e693532";
     //        $this->request->data['user_id'] = 3;
     //        $this->request->data['folder_id'] = 216;
     //        $this->request->data['title'] = "title";
     //        $this->request->data['content'] = "content";
     App::uses('CakeEmail', 'Network/Email');
     $data = $this->request->data;
     $user_id = @$data['user_id'];
     $this->user_id = $this->User->getUserIdByAPIToken(@$data['api_token']);
     $folder_id = @$data['folder_id'];
     if (empty($user_id) || empty($folder_id) || empty($this->user_id)) {
         return $this->response->body(json_encode(array("error" => 0)));
     }
     $my_user = $this->User->findById($this->user_id);
     $folder = $this->FolderUser->findById($folder_id);
     $title = $my_user["User"]['name'] . "さんからシークレットフォルダを共有しました ";
     $user = $this->User->findById($user_id);
     $Email = new CakeEmail('kaopass');
     $Email->viewVars(array('data' => $data));
     $result = 1;
     try {
         $Email->template('sendMail')->emailFormat('html')->to($user["User"]["email"])->from(array($my_user["User"]['email'] => $my_user["User"]['name']))->subject($title)->send();
         $result = 0;
     } catch (Exception $e) {
         $result = 1;
     }
     $this->autoRender = false;
     $this->response->type("json");
     $this->response->body(json_encode(array("error" => $result)));
 }
Beispiel #26
0
 /**
  * Make sure if the $appPath exists and copy the skel to there
  * @param string $appPath
  */
 public function initialAppPath($appPath)
 {
     App::uses('Folder', 'Utility');
     $fh = new Folder();
     if (file_exists($appPath)) {
         if (false === $fh->delete($appPath)) {
             $this->errorMessage = __('Target path exists. But the program could not delete the folder automatically');
             return false;
         } else {
             $this->tasks[] = array('title' => __('Target path exists. Delete the old folders.'), 'operactions' => $fh->messages());
         }
     }
     /*
      * Copy the skelecton of the application
      */
     $fh->copy(array('to' => $appPath, 'from' => VENDORS . 'olc_baker' . DS . 'skels' . DS . 'default', 'mode' => 0777));
     $errors1 = $fh->errors();
     $fh->copy(array('to' => $appPath . DS . 'cake2' . DS . 'lib', 'from' => CAKE_CORE_INCLUDE_PATH, 'mode' => 0777));
     $errors2 = $fh->errors();
     if (!empty($errors1) || !empty($errors2)) {
         $this->errorMessage = __('The program could not copy files to the folder automatically');
         return false;
     } else {
         $this->tasks[] = array('title' => __('Copy the skelecton of application to the target path'), 'operactions' => $fh->messages());
     }
     return true;
 }
Beispiel #27
0
 /**
  * Override startup of the Shell
  *
  * @return void
  */
 public function startup()
 {
     parent::startup();
     if (isset($this->params['connection'])) {
         $this->connection = $this->params['connection'];
     }
     $class = Configure::read('Acl.classname');
     list($plugin, $class) = pluginSplit($class, true);
     App::uses($class, $plugin . 'Controller/Component/Acl');
     if (!in_array($class, array('DbAcl', 'DB_ACL')) && !is_subclass_of($class, 'DbAcl')) {
         $out = "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n";
         $out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n";
         $out .= "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Current ACL Classname: %s', $class) . "\n";
         $out .= "--------------------------------------------------\n";
         $this->err($out);
         $this->_stop();
     }
     if ($this->command) {
         if (!config('database')) {
             $this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
             $this->args = null;
             return $this->DbConfig->execute();
         }
         require_once APP . 'Config' . DS . 'database.php';
         if (!in_array($this->command, array('initdb'))) {
             $collection = new ComponentCollection();
             $this->Acl = new AclComponent($collection);
             $controller = new Controller();
             $this->Acl->startup($controller);
         }
     }
 }
Beispiel #28
0
 public function links()
 {
     if (!CakePlugin::loaded('Menus')) {
         CakePlugin::load('Menus');
     }
     App::uses('View', 'View');
     App::uses('AppHelper', 'View/Helper');
     App::uses('MenusHelper', 'Menus.View/Helper');
     $Menus = new MenusHelper(new View());
     $Link = ClassRegistry::init('Menus.Link');
     $links = $Link->find('all', array('fields' => array('id', 'title', 'link')));
     $count = 0;
     foreach ($links as $link) {
         if (!strstr($link['Link']['link'], 'controller:')) {
             continue;
         }
         if (strstr($link['Link']['link'], 'plugin:')) {
             continue;
         }
         $url = $Menus->linkStringToArray($link['Link']['link']);
         if (isset($this->_controllerMap[$url['controller']])) {
             $url['plugin'] = $this->_controllerMap[$url['controller']];
             $linkString = $Menus->urlToLinkString($url);
             $Link->id = $link['Link']['id'];
             $this->out(__('Updating Link %s', $Link->id));
             $this->warn(__('- %s', $link['Link']['link']));
             $this->success(__('+ %s', $linkString), 2);
             $Link->saveField('link', $linkString, false);
             $count++;
         }
     }
     $this->out(__('Links updated: %d rows', $count));
 }
 function _write()
 {
     // Load library
     App::uses('File', 'Utility');
     $translations = $this->Translation->find('all');
     $trunced = array();
     foreach ($translations as $t) {
         $t = $t['Translation'];
         if (empty($t['value'])) {
             continue;
         }
         $lang = $t['language'];
         $domain = $t['domain'];
         $filePath = APP . 'Locale' . DS . $lang . DS . 'LC_MESSAGES' . DS . $domain . '.po';
         $file = new File($filePath);
         if (!isset($trunced[$filePath])) {
             $file->open('w');
             $trunced[$filePath] = true;
             $file->close();
         }
         $append = 'msgid "' . str_replace('"', '\\"', $t['name']) . "\"\n";
         $append .= 'msgstr "' . str_replace('"', '\\"', $t['value']) . "\"\n\n";
         $file->write($append, 'a');
     }
 }
Beispiel #30
0
 public function sendEmail()
 {
     App::import('Model', 'Setting');
     $setting_model = new Setting();
     $setting = $setting_model->find('first', array('fields' => 'email_contact'));
     $email_contact = empty($setting['Setting']['email_contact']) ? '' : $setting['Setting']['email_contact'];
     if (!empty($this->data['Contato'])) {
         $contato = $this->data['Contato'];
         App::uses('CakeEmail', 'Network/Email');
         $Email = new CakeEmail();
         $Email->config('smtp');
         $Email->template('contato', null);
         $Email->viewVars(array('contato' => $contato));
         $Email->to($email_contact);
         $Email->emailFormat('html');
         $Email->subject("Cartório NET - Contato: " . $contato['subject']);
         $success = false;
         try {
             if ($Email->send()) {
                 $success = true;
             } else {
                 $success = false;
             }
         } catch (Exception $e) {
             //                pr($e);die;
             $success = false;
         }
         return $success;
     }
     return false;
 }