public function getResponse() { if ($this->_response === null) { return $this->_connection->getResponse($this->_streamId); } return $this->_response; }
public function perform() { if (!$this->canPerform()) { return; } $news = $this->getNews(); if (empty($news)) { return; } $urls = array(); foreach ($news as $news) { if (!empty($news->url)) { $urls[$news->buildUrl(array(), false)][] = $news; } } $c = new Connection(array(CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_NOBODY => true, CURLOPT_MAXREDIRS => 1)); foreach ($urls as $url => $news) { $c->addRequest(new ConnectionRequest($url)); } $requests = $c->run(); foreach ($requests as $i => $request) { foreach ($urls[$request->url] as $news) { $result = $request->reply->result == 0 ? $request->reply->info['http_code'] : $request->reply->result; /** @var News $news */ if ($news->url_status != $result) { $news->updateByPk($news->id, array('url_status' => $result)); if ($result !== 200) { SMail::sendMail(Yii::app()->params->notifyEmail, 'Новость "' . $news->name . '" не доступна.', 'NewsUrlCheckError', array('news' => $news, 'request' => $request)); } } } } }
/** * @param Connection $dbh */ public function __construct(Connection $conn) { $this->conn = $conn; $this->dblink = $conn->getResource(); $dsn = $conn->getDSN(); $this->dbname = $dsn['database']; }
function insert($nroAula) { $claseConexion = new Connection(); $csql = "CALL SP_InsertAula(:nroAula)"; $claseConexion->queryWithParams($csql, array(':nroAula' => $nroAula)); return $claseConexion->getLastInsertedId(); }
/** * Function executed when the service is called * * @param Request * @return Response * */ public function _main(Request $request) { // display help for an specific service if (!empty($request->query)) { // check if the query passed is a service $connection = new Connection(); $res = $connection->deepQuery("SELECT * FROM service WHERE name = '{$request->query}'"); if (count($res) > 0) { $service = $res[0]; // update the valid email on the usage text $utils = new Utils(); $validEmailAddress = $utils->getValidEmailAddress(); $usage = str_replace('{APRETASTE_EMAIL}', $validEmailAddress, $service->usage_text); // send variables to the template $responseContent = array("name" => $service->name, "description" => $service->description, "category" => $service->category, "usage" => nl2br($usage)); // create response for an specific service $response = new Response(); $response->subject = "Ayuda para el servicio " . ucfirst($service->name); $response->createFromTemplate("service.tpl", $responseContent); return $response; } } // create response $responseContent = array("userEmail" => $request->email); $response = new Response(); $response->subject = "Ayuda de Apretaste"; $response->createFromTemplate("basic.tpl", $responseContent); return $response; }
public function setCliente(array $laCliente) { $loConnection = new Connection(); $stmt = $loConnection->prepare('INSERT INTO clientes(nome,cpf,tipoCliente,ativo,status) VALUES ("' . $laCliente['nome'] . '","' . $laCliente['cpf'] . '","' . $laCliente['tipoCliente'] . '",1,1)'); $stmt->execute(); header('location:index.php'); }
function login() { $authorized = false; $error = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (strlen($_POST['userid']) > 0) { $validation = new Validation(); if ($message = $validation->userid($_POST['userid'], 'ユーザー名')) { $error[] = $message; } else { $userid = $_POST['userid']; } $_POST['password'] = trim($_POST['password']); if ($message = $validation->alphaNumeric($_POST['password'], 'パスワード')) { $error[] = $message; } else { $password = md5($_POST['password']); } if (count($error) <= 0) { $connection = new Connection(); $query = sprintf("SELECT id,userid,password,realname,user_group,authority FROM %suser WHERE userid = '%s'", DB_PREFIX, $connection->quote($userid)); $data = $connection->fetchOne($query); $connection->close(); if (count($data) > 0 && $data['userid'] === $userid && $data['password'] === $password) { $authorized = true; } else { $error[] = 'ユーザー名もしくはパスワードが<br />異なります。'; } } } else { $error[] = 'ユーザー名を入力してください。'; } } elseif (isset($_SESSION['status'])) { if ($_SESSION['status'] == 'idle') { $error[] = '自動的にログアウトしました。<br />ログインしなおしてください。'; } elseif ($_SESSION['status'] == 'expire') { $error[] = 'ログインの有効期限が切れました。<br />ログインしなおしてください。'; } session_unregister('status'); } if ($authorized === true && count($error) <= 0) { session_regenerate_id(); $_SESSION['logintime'] = time(); $_SESSION['accesstime'] = $_SESSION['logintime']; $_SESSION['authorized'] = md5(__FILE__ . $_SESSION['logintime']); $_SESSION['userid'] = $data['userid']; $_SESSION['realname'] = $data['realname']; $_SESSION['group'] = $data['user_group']; $_SESSION['authority'] = $data['authority']; if (isset($_SESSION['referer'])) { header('Location: ' . $_SESSION['referer']); session_unregister('referer'); } else { header('Location: index.php'); } exit; } else { return $error; } }
/** * {@inheritdoc} */ protected function createStatistics($type, $dateFrom, $dateTo = null, $id) { if (empty($dateFrom)) { throw new \InvalidArgumentException("{$dateFrom} is invalid, a valid dateFrom must be passed"); } //Check type, create objects accordingly switch ($type) { case parent::PUBLISHER: $obj = new Publisher(); break; case parent::WEBSITE: $obj = new Website(); break; case parent::ZONE: $obj = new Zone(); break; default: throw new \InvalidArgumentException("{$type} is not a valid statistics set"); } $host = $obj->getAddress($id) . "&from=" . $dateFrom; if (!empty($dateTo)) { $host = $host . "&to=" . $dateTo; } //connect to the API service $connection = new Connection(new ArrayConfig(array("host" => $host, "key" => self::KEY, "sharedSecret" => self::SHARED_SECRET))); //get the response from API connection $arr = $connection->getResponse(); //API returns everything under one element, load it $arr = $arr[0]; //set stats from result $obj->setImpressions($arr["impressions"]); $obj->setClicks($arr["clicks"]); $obj->setRevenues($arr["revenue"]); return $obj; }
/** * @param string $columnName * @param string $typeName * @param array $options * * @return Column */ public function addColumn($columnName, $typeName, array $options = array()) { if ($this->connection->getDatabasePlatform()->getName() === 'sqlite' && in_array($typeName, ['string', 'text'])) { $options['customSchemaOptions']['collation'] = 'NOCASE'; } return $this->table->addColumn($columnName, $typeName, $options); }
/** * @covers PhiKettle\Kettle::__construct * @covers PhiKettle\Kettle::getStream * @covers PhiKettle\Kettle::getState */ public function testConstructor() { $connection = new Connection($this->host, $this->port, new DummyLoop()); $kettle = new Kettle($connection); $this->assertEquals(new KettleState(), $kettle->getState()); $this->assertEquals($connection->getStream(), $kettle->getStream()); }
protected static function connect($config) { $instance = new Connection(); $backupServer = array(); if (is_array(current($config))) { foreach ($config as $host) { if (isset($host['type']) && $host['type'] == 'backup') { //作为集群二级缓存使用 unset($host['type']); $backupServer[] = $host; continue; } $persistent = isset($host['persistent']) ? $host['persistent'] : false; $instance->addServer($host['host'], $host['port'], $persistent); } } else { if (isset($config['host'])) { if (!isset($config['port'])) { $config['port'] = 11211; } $persistent = isset($host['persistent']) ? $host['persistent'] : false; $instance->addServer($config['host'], $config['port'], $persistent); } } if (!empty($backupServer)) { $instance->setBackupInstance(self::connect($backupServer)); } return $instance; }
function delete($details) { $conn = new Connection("auto"); $query = new Build(); $result = $query->delete($conn->grab_conn(), $details, "close"); return $result; }
public function droppedAction() { // do not allow empty calls if (empty($_POST)) { die("EMPTY CALL"); } // get the params from post $email = $_POST['recipient']; $domain = $_POST['domain']; $reason = $_POST['reason']; $code = isset($_POST['code']) ? $_POST['code'] : ""; $desc = isset($_POST['description']) ? str_replace("'", "", $_POST['description']) : ""; // do not save Spam as hardfail if (stripos($desc, 'spam') !== false) { $reason = "spam"; } // mark as bounced if the email is part of the latest campaign $connection = new Connection(); $campaign = $connection->deepQuery("\n\t\t\tSELECT campaign, email FROM (\n\t\t\t\tSELECT * FROM `campaign_sent`\n\t\t\t\tWHERE campaign = (SELECT id FROM campaign WHERE status='SENT' ORDER BY sending_date DESC LIMIT 1)\n\t\t\t) A WHERE email = '{$email}'"); if (count($campaign) > 0) { // increase the bounce number for the campaign $campaign = $campaign[0]; $connection->deepQuery("\n\t\t\t\tUPDATE campaign SET\tbounced=bounced+1 WHERE id={$campaign->campaign};\n\t\t\t\tUPDATE campaign_sent SET status='BOUNCED', date_opened=CURRENT_TIMESTAMP WHERE id={$campaign->campaign} AND email='{$email}'"); // unsubscribe from the list $utils = new Utils(); $utils->unsubscribeFromEmailList($email); } // save into the database $sql = "INSERT INTO delivery_dropped(email,sender,reason,code,description) VALUES ('{$email}','{$domain}','{$reason}','{$code}','{$desc}')"; $connection->deepQuery($sql); // echo completion message echo "FINISHED"; }
public function __construct(Connection $conn) { $this->conn = $conn; $this->db = $conn->getDatabase(); $this->queue = $this->db->deferred_queue; $this->refs = $this->db->references_queue; }
public function getTiposClientes() { $loConnection = new Connection(); $stmt = $loConnection->prepare('SELECT * FROM tiposClientes WHERE status <> 0'); $stmt->execute(); return $stmt->fetchAll(); }
/** * Function executed when a payment is finalized * Add new tickets to the database when the user pays * * @author salvipascual * */ public function payment(Payment $payment) { // get the number of times the loop has to iterate $numberTickets = null; if ($payment->code == "1TICKET") { $numberTickets = 1; } if ($payment->code == "5TICKETS") { $numberTickets = 5; } if ($payment->code == "10TICKETS") { $numberTickets = 10; } // do not give tickets for wrong codes if (empty($numberTickets)) { return false; } // create as many tickets as necesary $query = "INSERT INTO ticket(email,origin) VALUES "; for ($i = 0; $i < $numberTickets; $i++) { $query .= "('{$payment->buyer}','PURCHASE')"; $query .= $i < $numberTickets - 1 ? "," : ";"; } // save the tickets in the database $connection = new Connection(); $transfer = $connection->deepQuery($query); }
public function mainAction() { // inicialize supporting classes $connection = new Connection(); $email = new Email(); $service = new Service(); $service->showAds = false; $render = new Render(); $response = new Response(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; // get valid people $people = $connection->deepQuery("\n\t\t\tSELECT email, username, first_name, last_access\n\t\t\tFROM person\n\t\t\tWHERE active=1\n\t\t\tAND email not in (SELECT DISTINCT email FROM delivery_dropped)\n\t\t\tAND DATE(last_access) > DATE('2016-05-01')\n\t\t\tAND email like '%.cu'\n\t\t\tAND email not like '*****@*****.**'"); // send the remarketing $log = ""; foreach ($people as $person) { // get the email address $newEmail = "apretaste+{$person->username}@gmail.com"; // create the variabels to pass to the template $content = array("newemail" => $newEmail, "name" => $person->first_name); // create html response $response->setEmailLayout("email_simple.tpl"); $response->createFromTemplate('newEmail.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send the email $email->sendEmail($person->email, "Sorteando las dificultades, un email lleno de alegria", $html); $log .= $person->email . "\n"; } // saving the log $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/newemail.log"); $logger->log($log); $logger->close(); }
public static function setNewConnection($cookie) { // The old connections details are removed from the database in order to spare some memory Connection::cleanConnectionsPages(); // A new connection is created if the guest made no actions during 30 minutes $result = Db::getInstance()->getRow(' SELECT c.`id_guest` FROM `' . _DB_PREFIX_ . 'connections` c LEFT JOIN `' . _DB_PREFIX_ . 'connections_page` cp ON c.`id_connections` = cp.`id_connections` WHERE c.`id_guest` = ' . intval($cookie->id_guest) . ' AND DATE_ADD(cp.`time_start`, INTERVAL 30 MINUTE) > \'' . pSQL(date('Y-m-d H:i:s')) . '\' ORDER BY cp.`time_start` DESC'); if (!$result['id_guest'] and intval($cookie->id_guest)) { $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; if (preg_replace('/^www./', '', parse_url($referer, PHP_URL_HOST)) == preg_replace('/^www./', '', $_SERVER['HTTP_HOST'])) { $referer = ''; } $connection = new Connection(); $connection->id_guest = intval($cookie->id_guest); $connection->id_page = Page::getCurrentId(); $connection->ip_address = isset($_SERVER['REMOTE_ADDR']) ? ip2long($_SERVER['REMOTE_ADDR']) : ''; if (Validate::isAbsoluteUrl($referer)) { $connection->http_referer = $referer; } $connection->add(); $cookie->id_connections = $connection->id; return $connection->id_page; } }
public function generateKey() { $key = "00000"; $db = new Connection(); $conn = $db->open(); $sql = "SELECT id, `key` FROM urlmapping ORDER BY id DESC LIMIT 1"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $key = $row["key"]; } } for ($i = 4; $i >= 0; $i--) { $ascii = ord($key[$i]); if ($ascii < 122) { if ($ascii == 57) { $ascii = 65; } else { if ($ascii == 90) { $ascii = 97; } else { $ascii++; } } $key[$i] = chr($ascii); break; } $key[$i] = '0'; } $conn->close(); return $key; }
/** * Function executed when the service is called * * @param Request * @return Response * */ public function _main($request) { // get list of services $connection = new Connection(); $result = $connection->deepQuery("SELECT name, description, category FROM service WHERE listed=1"); $services = array(); $others = array(); // to keep the categoty "others" at the end // create array of arrays foreach ($result as $res) { // to keep the categoty "others" at the end if ($res->category == "otros") { $others[] = $res; continue; } // group all other categories in a big array if (!isset($services[$res->category])) { $services[$res->category] = array(); } array_push($services[$res->category], $res); } // sort by category alphabetically and merge to "other" ksort($services); $services = array_merge($services, array("otros" => $others)); // get variables to send to the template $responseContent = array("services" => $services, "serviceNum" => count($result)); // create response $response = new Response(); $response->setResponseSubject("Lista de servicios de Apretaste"); $response->createFromTemplate("basic.tpl", $responseContent); // return return $response; }
public function addConnection(Connection $connection) { if (!isset($this->connections[$connection->getId()])) { $this->connections[$connection->getId()] = $connection; } return $this; }
static function getInstance(Connection $conn, $table_name) { if (self::$instance === NULL || !isset(self::$instance[$table_name])) { self::$instance[$table_name] = $conn->getDatabaseInfo()->getTable($table_name); } return self::$instance[$table_name]; }
public function load(Connection $connection) { if (!$connection->isConnected) { $connection->Connect(); } if (!$connection->query($this->medicationQuery)) { return false; } else { $result = null; $medication = null; while ($result = $connection->getObject()) { $medication = new Medication(); $medication->setCommonDose($result->commonDose); $medication->setGenericName($result->genericName); $medication->setRoute($result->route); $medication->setUnit($result->unit); $medication->setMedicationID($result->medicationId); $medication->setActive($result->active); $medication->setConfirmed($result->confirmed); $medication->setConfirmedBy($result->confirmedBy); array_push($this->medicationList, $medication); } } return true; }
function insert($codigo, $nombre, $semestre, $costo) { $claseConexion = new Connection(); $csql = "CALL SP_InsertMateria(:codigo,:nombre,:semestre,:costo)"; $claseConexion->queryWithParams($csql, array(':codigo' => $codigo, ':nombre' => $nombre, ':semestre' => $semestre, ':costo' => $costo)); return $claseConexion->getLastInsertedId(); }
function insert($txtDias, $horaEntrada, $horaSalida, $idAula, $idMateria) { $claseConexion = new Connection(); $csql = "CALL SP_InsertHorario(:dias, :horaEntrada, :horaSalida, :idAula, :idMateria)"; $claseConexion->queryWithParams($csql, array(':dias' => $txtDias, ':horaEntrada' => $horaEntrada, ':horaSalida' => $horaSalida, ':idAula' => $idAula, ':idMateria' => $idMateria)); return $claseConexion->getLastInsertedId(); }
public static function getAll() { static::getConnection(); $prep = static::$con->prepare('SELECT * FROM ' . static::getTableName()); $prep->execute(); return $prep->fetchAll(); }
public function ejectInvoice() { $con = new Connection(); $link = $con->getConnection(); $stmt = $link->prepare($this->query); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_BOTH); //execute the second query $stmt1 = $link->prepare($this->query_row); $stmt1->execute(); $row1 = $stmt1->fetch(PDO::FETCH_BOTH); //convert the material to an array and iterate $codes = explode("*", $row1["stock_code"]); $desc = explode("*", $row1["item_description"]); $qty = explode("*", $row1["qty"]); $rate = explode("*", $row1["unit_price"]); $value = explode("*", $row1["value"]); //print_r($materials); for ($i = 0; $i < sizeof($codes) - 1; $i++) { $this->invoiceRows .= ' <tr class="item-row" id="itemID"><td>' . ($i + 1) . '</td> <td class="item-name"><div class="delete-wpr"><textarea data-role="none" class="item_name">' . $codes[$i] . '</textarea></div></td> <td class="description"><textarea disabled data-role="none" class="item_description">' . html_entity_decode($desc[$i]) . '</textarea></td> <td><span disabled class="cost" data-role="none" id="re-unitCost"><del>N</del>' . $rate[$i] . '</span></td> <td><textarea disabled class="qty" data-role="none" id="re-quantity">' . $qty[$i] . '</textarea></td> <td><span class="price" ><del>N</del>' . $value[$i] . '</span></td> </tr>'; } return array("invoiceDate" => $row["invoiceDate"], "jobid" => $row["jobNumber"], "invoiceNumber" => $row["invoiceNumber"], "subtotal" => $row["subTotal"], "total" => $row["total"], "invoiceRows" => $this->invoiceRows, "amountPaid" => $row["amountPaid"], "balanceDue" => $row["balanceDue"], "vat" => $row["vat"], "labourCost" => $row["labourcost"], "customer" => $row["customerTitle"]); }
/** * Execute and get the traversal result * * @return array $responseArray */ public function getResult() { $bodyParams = $this->attributes; $response = $this->_connection->post(Urls::URL_TRAVERSAL, $this->getConnection()->json_encode_wrapper($bodyParams)); $responseArray = $response->getJson(); return $responseArray; }
function login($email, $password) { $mysqli = new Connection(); $db = $mysqli->connect(); //hash the password $password = hashPassword($password); //prepare the query $query = $db->prepare("SELECT id FROM users WHERE email = ? AND password = ? LIMIT 1") or die("error"); $query->bind_param('ss', $email, $password); //excuting $query->execute(); //store results $query->store_result(); //bind results $query->bind_result($id); $query->fetch(); //get the num rows if ($query->num_rows == 1) { $user_browser = $_SERVER['HTTP_USER_AGENT']; session_start(); $_SESSION['login_string'] = array(); $_SESSION['login_string']['browserInfo'] = hash('sha512', $user_browser); $_SESSION['login_string']['id'] = hash('sha512', $id); return TRUE; } else { return FALSE; } //close the query $db->close(); }
public function __construct($sql, $params, Connection $connection, Database $db) { try { $stmt = $connection->prepare($sql); $stmt->execute($params); $this->statement = $stmt; $this->connection = $connection; } catch (\PDOException $e) { // 服务端断开时重连一次 if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) { $master_or_slave = $connection->getMasterOrSlave(); $db->closeConnection($master_or_slave, $connection->getConnectionIndex()); $connection = $db->getConnection($master_or_slave == Connection::MASTER_CONNECTION); try { $stmt = $connection->prepare($sql); $stmt->execute($params); $this->statement = $stmt; $this->connection = $connection; } catch (\PDOException $ex) { $db->rollback(); throw $ex; } } else { $db->rollback(); throw $e; } } }