public function setup() { parent::setup(); $user = self::getValidUser(); unset($this['updated_at']); $this->widgetSchema->setHelps(array('slug' => 'The field is not required', 'excerpt' => 'The field is not required')); $this->widgetSchema->moveField('slug', sfWidgetFormSchema::AFTER, 'title'); $this->widgetSchema['content'] = new sfWidgetFormCKEditor(array('jsoptions' => array('customConfig' => '/js/ckeditor/config.js', 'filebrowserBrowseUrl' => '/js/filemanager/index.html', 'filebrowserImageBrowseUrl' => '/js/filemanager/index.html?type=Images'))); $this->widgetSchema['status'] = new sfWidgetFormChoice(array('choices' => Doctrine::getTable('PeanutPosts')->getStatus(), 'expanded' => false)); if (!$this->isNew()) { $this->widgetSchema['created_at'] = new sfWidgetFormI18nDate(array('culture' => $user->getCulture())); } else { unset($this['created_at']); } /** * Add tags for peanutPostsForm * * @author http://n8v.enteuxis.org/2010/05/adding-wordpress-like-tags-to-a-symfony-1-4-admin-generator-form/ * */ $default = 'Add tags with commas'; $this->widgetSchema['new_tags'] = new sfWidgetFormInput(array('default' => $default), array('onclick' => "if(this.value=='{$default}') { this.value = ''; this.style.color='black'; }", 'size' => '32', 'id' => 'new_tags', 'autocomplete' => 'off', 'style' => 'color: #aaa;')); $this->setValidator('new_tags', new sfValidatorString(array('required' => false))); $this->widgetSchema['remove_tags'] = new sfWidgetFormInputHidden(); $this->setValidator('remove_tags', new sfValidatorString(array('required' => false))); }
public function save() { $names = array('update_activity'); foreach ($names as $name) { Doctrine::getTable('SnsConfig')->set('op_community_topic_plugin_' . $name, $this->getValue($name)); } }
/** * Маппинг входящих значений к свойствам объекта операции * * @param array $values - исходные значения * @return array - преобразованные значения */ public function processValues($values) { // User // TODO: переделать через один запрос вместе с валидацией $values['user_id'] = Doctrine::getTable('User')->findByUserServiceMail($values['email'])->getFirst()->getId(); unset($values['email']); // Счет для привязки операции # Svel: закомментировал в соответствии с требованиями мягкости в t1713 // $values['account_id'] = Doctrine::getTable('Account')->findLinkedWithSource($values['user_id'], $values['source']); // выбрать ID счета по последней активной операции $values['account_id'] = Doctrine::getTable('Operation')->findAccountIdByLastAcceptedOperationBySource($values['user_id'], $values['source']); // Тип операции и сумма $values['money'] = abs((double) $values['amount']); // Дата и время $values['date'] = date('Y-m-d'); $values['time'] = date('H:i:s'); // Черновик $values['accepted'] = Operation::STATUS_DRAFT; // Источник $values['source_id'] = $values['source']; $values['SourceOperation'] = array('source_uid' => $values['source'], 'source_operation_uid' => $values['id']); // Комментарий $values['comment'] = sprintf("%s %s %s\n", $values['source'], $values['description'], $values['account']); unset($values['description']); unset($values['account']); unset($values['id']); unset($values['source']); return $values; }
protected function execute($arguments = array(), $options = array()) { $app = $options['app']; $env = $options['env']; $this->bootstrapSymfony($app, $env, true); // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase('doctrine')->getConnection(); $this->logSection('import', 'initializing...'); $plugins = SymfonyPluginApi::getPlugins(); $count = 0; foreach ($plugins as $plugin) { $new = Doctrine::getTable('SymfonyPlugin')->findOneByTitle($plugin['id']); // if plugin exists update info. Otherwise, create it if ($new) { // Nothing Yet } elseif ($plugin['id']) { $new = new SymfonyPlugin(); $new['title'] = (string) $plugin['id']; $new['description'] = (string) $plugin->description; $new['repository'] = (string) $plugin->scm; $new['image'] = (string) $plugin->image; $new['homepage'] = (string) $plugin->homepage; $new['ticketing'] = (string) $plugin->ticketing; $new->saveNoIndex(); $this->logSection('import', "added '{$new->title}'"); $count++; } } $this->logSection('import', "Running Lucene Cleanup"); $this->runLuceneRebuild(); $this->logSection('import', "Completed. Added {$count} new plugins(s)"); }
public function authenticateUserRequest() { $authResult = $this->authenticateKey($this->request->getParameter('_key')); switch ($authResult) { case self::AUTH_FAIL_KEY: $this->response->setStatusCode(401); sfLoader::loadHelpers('Partial'); $partial = get_partial('global/401'); $this->response->setContent($partial); $this->response->setHttpHeader('WWW-Authenticate', 'Your request must include a query parameter named "_key" with a valid API key value. To obtain an API key, visit http://api.littlesis.org/register'); $this->response->sendHttpHeaders(); $this->response->sendContent(); throw new sfStopException(); break; case self::AUTH_FAIL_LIMIT: $this->response = sfContext::getInstance()->getResponse(); $this->response->setStatusCode(403); $user = Doctrine::getTable('ApiUser')->findOneByApiKey($this->request->getParameter('_key')); sfLoader::loadHelpers('Partial'); $partial = get_partial('global/403', array('request_limit' => $user->request_limit)); $this->response->setContent($partial); $this->response->sendHttpHeaders(); $this->response->sendContent(); throw new sfStopException(); break; case self::AUTH_SUCCESS: break; default: throw new Exception("Invalid return value from LsApi::autheticate()"); } }
public function executeActivityBox(sfWebRequest $request) { $id = $request->getParameter('id', $this->getUser()->getMemberId()); $this->activities = Doctrine::getTable('ActivityData')->getActivityList($id, null, $this->gadget->getConfig('row')); $this->member = Doctrine::getTable('Member')->find($id); $this->isMine = $id == $this->getUser()->getMemberId(); }
public function executeDelete(sfWebRequest $request) { $request->checkCSRFProtection(); $this->forward404Unless($product = Doctrine::getTable('Product')->find(array($request->getParameter('id'))), sprintf('Object product does not exist (%s).', array($request->getParameter('id')))); $product->delete(); $this->redirect('product/index'); }
public function executeChangeOrder(sfWebRequest $request) { $col1 = explode(',', $request->getParameter('col1')); $col2 = explode(',', $request->getParameter('col2')); Doctrine::getTable('MyWidgets')->setUserRef($this->getUser()->getAttribute('db_user_id'))->changeOrder($request->getParameter('category') . "_widget", $col1, $col2); return $this->renderText(var_export($col1, true) . var_export($col2, true)); }
protected function execute($arguments = array(), $options = array()) { $con = $this->crearConexion(); try { $record = Doctrine::getTable('EmailConfiguration')->findAll()->getFirst(); $config_mail = array('charset' => 'UTF-8', 'encryption' => $record->getSmtpSecurityType(), 'host' => $record->getSmtpHost(), 'port' => $record->getSmtpPort(), 'username' => $record->getSmtpUsername(), 'password' => $record->getSmtpPassword(), 'authentication' => $record->getSmtpAuthType()); $mail = new PHPMailer(); $mail->IsSMTP(); $mail->CharSet = $config_mail['charset']; if ($config_mail['authentication'] == "login") { $mail->SMTPAuth = true; } if ($config_mail['encryption'] == "tls") { $mail->SMTPSecure = "tls"; } if ($config_mail['encryption'] == "ssl") { $mail->SMTPSecure = "ssl"; } $mail->Host = $config_mail['host']; $mail->Port = $config_mail['port']; $mail->Username = $config_mail['username']; $mail->Password = $config_mail['password']; $mail->FromName = 'Mi company'; $mail->From = $config_mail['username']; //email de remitente desde donde se env?a el correo $mail->AddAddress($config_mail['username'], 'Destinatario'); //destinatario que va a recibir el correo $mail->Subject = "confeccion de gafete"; /*Recojemos los datos del oficial*/ $dao = new EmployeeDao(); $employeeList = $dao->getEmployeeList(); foreach ($employeeList as $employee) { if ($employee->getJoinedDate() != "") { $datetime1 = new DateTime($employee->getJoinedDate()); $datetime2 = new DateTime(date('y-m-d', time())); $formato = $datetime2->format('y-m-d'); $intervalo = $datetime1->diff($datetime2, true); if ($intervalo->m == 2 && $intervalo->d == 0) { $html = "Identificador: " . $employee->getEmployeeId() . "<br/>"; $html .= "ID: " . $employee->getOtherId() . "<br/>"; $html .= "Nombre : " . utf8_encode($employee->getFullName()) . "<br/>"; $html .= "Fecha Nac : " . $employee->getEmpBirthday() . "<br/>"; $sexo = $employee->getEmpGender() == 1 ? "Masculino" : "Femenino"; $html .= "Género : " . $sexo . "<br/>"; $html .= "Nacionalidad: " . $employee->getNationality() . "<br/>"; $html .= "Móvil: " . $employee->getEmpMobile() . "<br/>"; $mail->MsgHTML($html); if (!$mail->Send()) { $this->escribirYML('log_tareas', false, $mail->ErrorInfo . " Error al enviar el correo con los datos del empleado " . $employee->getFullName()); } else { $this->escribirYML('log_tareas', true, "correo enviado con los datos del empleado " . $employee->getFullName()); } } } } Doctrine_Manager::getInstance()->closeConnection($con); } catch (Exception $e) { $this->escribirYML('log_tareas', false, $e->getMessage()); } }
public function executeDelete(sfWebRequest $request) { $request->checkCSRFProtection(); $this->forward404Unless($jobeet_job = Doctrine::getTable('JobeetJob')->find(array($request->getParameter('id'))), sprintf('Object jobeet_job does not exist (%s).', $request->getParameter('id'))); $jobeet_job->delete(); $this->redirect('job/index'); }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { sfContext::createInstance($this->configuration); $blast = Doctrine::getTable('Blast')->find(1); $response = Doctrine::getTable('BlastResponse')->find(1); BlastManager::createTextResponse($response); }
public function executeDelete(sfWebRequest $request) { $this->forward404Unless($mensagem = Doctrine::getTable('Mensagem')->find(array($request->getParameter('id'))), sprintf('Object mensagem does not exist (%s).', $request->getParameter('id'))); $mensagem->delete(); $this->getUser()->setFlash('success', 'Mensagem excluída com sucesso!'); $this->redirect('@mensagens'); }
public function executeSave(sfWebRequest $request) { $request->checkCSRFProtection(); $invoices = (array) $request->getParameter('invoices', array()); $estimates = (array) $request->getParameter('estimates', array()); // check that there is only one template for each one if (count($invoices) > 1 || count($estimates) > 1) { $this->getUser()->error($this->getContext()->getI18N()->__('There must be only one template for model.')); $this->redirect('@templates'); } $templates = Doctrine::getTable('Template')->createQuery()->execute(); foreach ($templates as $t) { $models = array(); if (in_array($t->getId(), $invoices)) { $models[] = 'Invoice'; } if (in_array($t->getId(), $estimates)) { $models[] = 'Estimate'; } $t->setModels(implode(',', $models)); $t->save(); } $this->getUser()->info($this->getContext()->getI18N()->__('Successfully saved.')); $this->redirect('@templates'); }
public function eliminar($cuenta_id) { $cuenta = Doctrine::getTable('Cuenta')->find($cuenta_id); $cuenta->delete(); $this->session->set_flashdata('message', 'Cuenta eliminada con éxito.'); redirect('manager/cuentas'); }
protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection(); $table = Doctrine::getTable('sfGuardUser'); $users = $table->createQuery('u')->innerJoin('u.Profile p')->execute(); $first = true; foreach ($users as $user) { if (preg_match("/[^\\w]/", $user->username)) { $user->username = preg_replace("/[^\\w]/", "_", $user->username); while ($table->findOneByUsername($user->username)) { $user->username .= rand(0, 9); echo $user->username; } $user->save(); $profile->save(); if ($first) { echo "The following usernames required change, contact them if they are legitimate users and\nlet them know their new username.\n"; echo "The report below shows the NEW username only.\n\n"; $first = false; } echo "Username: "******"\n"; } $profile = $user->getProfile(); if (preg_match("/[\\<\\>\\&\\|]/", $profile->fullname)) { // No need for a big announcement because we don't log in by our full names $profile->fullname = preg_replace("/[\\<\\>\\&\\|]/", "_", $profile->fullname); $profile->save(); } } }
public function executeDelete(sfWebRequest $request) { $this->forward404Unless($area_interesse = Doctrine::getTable('AreaInteresse')->find(array($request->getParameter('id'))), sprintf('Object area_interesse does not exist (%s).', $request->getParameter('id'))); $area_interesse->delete(); $this->getUser()->setFlash('success', 'Área de Interesse excluída com sucesso!'); $this->redirect('areaInteresse/index'); }
public function process() { $configuracao = Doctrine::getTable('Configuracao')->find(1); $this->document->pages[] = $page = $this->document->newPage(\Zend_Pdf_Page::SIZE_A4); //monta o cabecalho $color = array(); $color["black"] = new Zend_Pdf_Color_Html("#000000"); $fontTitle = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES_BOLD); $size = 12; $styleTitle = new Zend_Pdf_Style(); $styleTitle->setFont($fontTitle, $size); $styleTitle->setFillColor($color["black"]); $page->setStyle($styleTitle); $page->drawText($configuracao->instituicao, Documento::DOCUMENT_LEFT, Documento::DOCUMENT_TOP, 'UTF-8'); $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES); $style = new Zend_Pdf_Style(); $style->setFont($font, $size); $style->setFillColor($color["black"]); $page->setStyle($style); $text = wordwrap($this->text, 95, "\n", false); $token = strtok($text, "\n"); $y = 665; while ($token != false) { if ($y < 100) { $this->document->pages[] = $page = $this->document->newPage(Zend_Pdf_Page::SIZE_A4); $page->setStyle($style); $y = 665; } else { $y -= 15; } $page->drawText($token, 60, $y, 'UTF-8'); $token = strtok("\n"); } }
/** * Авторизовать пользователя * * @param User $user * @param bool $remember * @return void */ public function signIn(User $user, $remember = false) { $this->user = $user; $this->setAttribute('id', $user->getId(), 'user'); $this->setAuthenticated(true); $this->clearCredentials(); if ($remember) { $now = new DateTime(); $expired = clone $now; $expired->modify("-" . $this->getExpiration() . " sec"); // убить все старые кючи Doctrine::getTable('myAuthRememberKey')->removeOldKeys($expired)->execute(); // убить все ключи этого пользователя Doctrine::getTable('myAuthRememberKey')->removeKeysByUserId($user->getId())->execute(); // создать новый ключ $key = $this->generateRandomKey(); // сохранить ключ $rk = new myAuthRememberKey(); $rk->setRememberKey($key); $rk->setUser($user); $rk->setIpAddress($_SERVER['REMOTE_ADDR']); $rk->save(); // отдать ключ в виде печенья sfContext::getInstance()->getResponse()->setCookie($this->getCookieName(), $key, time() + $this->getExpiration()); } }
protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); $this->logSection('rdvz', "Retrieving users...") ; $ldap = new uapvLdap() ; $users = Doctrine::getTable('user')->retrieveLdapUsers() ; $this->logSection('rdvz', "Updating information...") ; foreach($users as $user) { $us = $ldap->searchOne(sfConfig::get('app_profile_var_translation_uid')."=".$user->getLdapId()) ; $user->setName($us[sfConfig::get('app_profile_var_translation_name')]) ; $user->setSurname($us[sfConfig::get('app_profile_var_translation_surname')]) ; $user->setMail($us[sfConfig::get('app_profile_var_translation_mail')]) ; $user->save(); } $this->logSection('rdvz', "Done.") ; }
/** * ajax action for customer name autocompletion * * @return JSON * @author Enrique Martinez **/ public function executeAjaxCustomerAutocomplete(sfWebRequest $request) { $this->getResponse()->setContentType('application/json'); $q = $request->getParameter('q'); $items = Doctrine::getTable('Customer')->simpleRetrieveForSelect($request->getParameter('q'), $request->getParameter('limit')); return $this->renderText(json_encode($items)); }
public function save() { Doctrine::getTable('BlogRssCache')->deleteByMemberId($this->member->getId()); parent::save(); Doctrine::getTable('BlogRssCache')->updateByMemberId($this->member->getId()); return true; }
protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); // add your code here $n = $options['n']; $tags = $this->createTags($n); if (!empty($options['models'])) { $modelClasses = explode(',', $options['models']); foreach ($modelClasses as $class) { try { $models = Doctrine::getTable($class)->createQuery()->execute(); foreach ($models as $model) { $modelTags = array(); while (count($modelTags) < $options['tags-per-model']) { $tag = $tags[rand(0, $n - 1)]; $modelTags[$tag] = $tag; } $modelTags = array_values($modelTags); $model->addTag($modelTags); $model->save(); } } catch (Exception $e) { echo $e->getMessage() . "\n"; } } } }
public function executeIndex(sfWebRequest $request) { if ($request->isMethod('post')){ $from = $request->getParameter('From'); if (!Utils::isEmptyStr($from)){ if (Utils::startsWith($from, "+1")) $from = substr($from, 2); //look up the user by phone number $guardUser = Doctrine::getTable('SfGuardUser')->findOneByPhone($from); if ($guardUser){ //get the last response $response = Doctrine::getTable('BlastResponse')->createQuery()->where('user_id = ?', $guardUser->getId()) ->orderBy('updated_at desc')->fetchOne(); if ($response) { $this->redirect('phoneResponse/intro?responseId=' . $response->getId()); } } } } ?> <Response> <Say>Thanks for calling Make A Minyan dot com. Please visit us online at Make A Minyan dot com. Thank you! Goodbye.</Say> <Hangup /> </Response> <? return sfView::NONE; }
public function executeList($request) { $page = $request->getParameter('page', 1); $num = $request->getParameter('num', 20); $q = LsDoctrineQuery::create()->from('UserView v')->leftJoin('v.User u')->orderBy('v.created_at DESC'); $this->constraints = array(); if ($userId = $request->getParameter('user_id')) { $user = Doctrine::getTable('sfGuardUser')->find($userId); $this->constraints[] = 'Limiting to ' . $user->Profile->getFullName(); $q->addWhere('v.user_id = ?', $userId); } if (($model = $request->getParameter('object_model')) && ($id = $request->getParameter('object_id'))) { if ($object = Objectable::getObjectByModelAndId($model, $id, $includeDeleted = true)) { $this->constraints[] = 'Limiting to ' . $object->getName(); } else { $this->constraints[] = 'Limiting to ' . $model . ' ID ' . $id; } $q->addWhere('v.object_model = ? AND v.object_id = ?', array($model, $id)); } if ($start = $request->getParameter('start')) { $start = date('Y-m-d H:i:s', strtotime($start)); $q->addWhere('v.created_at > ?', $start); } if ($end = $request->getParameter('end')) { $end = date('Y-m-d H:i:s', strtotime($end)); $q->addWhere('v.created_at < ?', $end); } $this->view_pager = new LsDoctrinePager($q, $page, $num); }
protected function doSave($con = null) { parent::doSave(); $newOptions = $this->getValue('option'); $newOptions = preg_split('/[\\s ]+/u', $newOptions, -1, PREG_SPLIT_NO_EMPTY); $voteQuestion = $this->getObject(); // 過去の選択肢の抽出 $oldOptions = $voteQuestion->getVoteQuestionOptions(); $oldOptions = $oldOptions->toKeyValueArray('id', 'body'); // 削除された選択肢の抽出 $deletedOptions = array_diff($oldOptions, $newOptions); foreach ($deletedOptions as $id => $body) { // 削除 $object = Doctrine::getTable('VoteQuestionOption')->find($id); $object->delete(); } // 新規の選択肢 $insertOptions = array_diff($newOptions, $oldOptions); foreach ($insertOptions as $body) { // 追加 $object = new VoteQuestionOption(); $object->setVoteQuestion($voteQuestion); $object->setBody($body); $object->save(); } }
public static function set($name, $value, $app = null) { if (is_null($app)) { $app = sfConfig::get('sf_app'); } Doctrine::getTable('SnsConfig')->set($app . '_' . $name, $value); }
public function executeDelete(sfWebRequest $request) { $request->checkCSRFProtection(); $this->forward404Unless($encuestado_sanciones = Doctrine::getTable('EncuestadoSanciones')->find(array($request->getParameter('id'))), sprintf('Object encuestado_sanciones does not exist (%s).', $request->getParameter('id'))); $encuestado_sanciones->delete(); $this->redirect('EncuestadoSancionesVigentes/index'); }
public static function fetchByName($title, $fund, $period, $type, $author, $accountno, $preparedby1, $preparedby2, $certifiedby1, $certifiedby2) { if (!$title) { return; } //remove "page 1" from title $start = strpos($title, " page "); if ($start === false) { $journaltitle = $title; } else { $journaltitle = substr($title, 0, $start); } //search journal with title in database //if not found, create $journal = Doctrine::getTable('Journal')->findOneByName($journaltitle); if (!$journal) { //create one $journal = new Journal(); $journal->setName($journaltitle); $journal->setFundId($fund->getId()); $journal->setPeriodId($period->getId()); $journal->setType($type); $journal->setAuthor($author); $journal->setAccountno($accountno); $journal->setPreparedby1($preparedby1); $journal->setPreparedby2($preparedby2); $journal->setCertifiedby1($certifiedby1); $journal->setCertifiedby2($certifiedby2); $journal->save(); } return $journal; }
protected function getTable($modelName) { if (!isset($this->tables[$modelName])) { $this->tables[$modelName] = Doctrine::getTable($modelName); } return $this->tables[$modelName]; }
public function executeIndex(sfWebRequest $request) { if ($request->hasParameter('object_id') && $request->hasParameter('object_class')) { $this->object = Doctrine::getTable($request->getParameter('object_class'))->find($request->getParameter('object_id')); } $this->setLayout(false); }