public static function createSettingsFile($dbHostname, $dbName, $dbUsername, $dbPassword, $tablePrefix) { $encryptionSalt = Utils::generateRandomAlphanumericStr("DDD"); $dbUsername = Utils::sanitize($dbUsername); $dbPassword = Utils::sanitize($dbPassword); $tablePrefix = Utils::sanitize($tablePrefix); $content = <<<END <?php \$dbHostname = '{$dbHostname}'; \$dbName = '{$dbName}'; \$dbUsername = '******'; \$dbPassword = '******'; \$dbTablePrefix = '{$tablePrefix}'; \$encryptionSalt = '{$encryptionSalt}'; END; $file = __DIR__ . "/../../settings.php"; $handle = @fopen($file, "w"); if ($handle) { fwrite($handle, $content); fclose($handle); return array(true, ""); } // no such luck! we couldn't create the file on the server. The user will need to do it manually return array(false, $content); }
public function signin() { if ($this->get_request_method() != "POST") { $this->response('', 406); } $email = $this->_request['email']; $password = $this->_request['pwd']; $db = new DB(); $ultis = new Utils(); // Input validations if (!empty($email) and !empty($password)) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $sql = "SELECT _uid, _email FROM users WHERE _email = '{$email}' AND _password = '******' LIMIT 1"; $rs = $db->query($sql); if ($rs->num_rows > 0) { // If success return authenticated key (sample) $result = array('access_token' => "633uq4t0qdtd1mdllnv2h1vs32"); $this->response($ultis->json($result), 200); } } } // If invalid inputs "Bad Request" status message and reason $error = array('status' => "Failed", "msg" => "Invalid Email address or Password"); $this->response($ultis->json($error), 400); }
/** * Smarty plugin * * @package Smarty * @subpackage PluginsFunction */ function smarty_function_apretaste_email($params, $template) { // get a valid apretaste email address $utils = new Utils(); $validEmailAddress = $utils->getValidEmailAddress(); return $validEmailAddress; }
public static function login($usu_usuario, $usu_contrasena) { $conn = new Connect(); $u = new Utils(); $query = 'SELECT * FROM ' . self::DB_TBL_USUARIO . ' WHERE usu_usuario = :usu_usuario'; $consult = $conn->prepare($query); $consult->bindParam(':usu_usuario', $usu_usuario); $consult->execute(); $row = $consult->fetch(); if ($consult->rowCount() > 0) { $passValidate = $u->passValidate($usu_contrasena, $row['usu_contrasena']); if ($passValidate == true) { if ($row['usu_id_rol'] == 1) { session_start(); $_SESSION['session'] = $row['usu_usuario']; echo "<script>location.href='../../mod_admin/vista/administrador.php'</script>"; } else { session_start(); $_SESSION['session'] = $row['usu_usuario']; echo "<script>location.href='../../mod_admin/vista/tecnico.php'</script>"; } } else { echo "<script>alert('Error de autenticación. Por favor verifique sus credenciales de acceso.')</script>"; echo "<script>location.href = '../vista/form_login.php' </script>"; return false; } } else { echo "<script>alert('Error de autenticación.')</script>"; echo "<script>location.href = '../vista/form_login.php' </script>"; return false; } }
public function execute() { $utils = new Utils(); $c = new Convertor(); $c->connect($this->config->getServer(), $this->config->getUser(), $this->config->getPassword(), $this->config->getDBName()); //Requesting all the borough $requestRue = "\n\t\t\t\tSELECT idRue ,nom , prefixe\n\t\t\t\tFROM rue\n\t\t\t\tWHERE nom != ''\n\t\t\t\tGROUP BY idRue\n\t\t\t\tORDER BY idRue\n\t\t\t\t"; $res = $c->execute($requestRue); $listeQuartier = array(); $ruesByQuartier = array(); $i = 0; while ($fetch = mysql_fetch_assoc($res)) { $rue = array(); $rue['prefixe'] = $fetch['prefixe']; $rue['nom'] = $fetch['nom']; $request = "\n\t\t\t\t\tSELECT hi.idHistoriqueImage, hi.dateUpload\n\t\t\t\t\tFROM _evenementImage ei\n\t\t\t\t\tLEFT JOIN _evenementEvenement ee on ee.idEvenementAssocie = ei.idEvenement\n\t\t\t\t\tLEFT JOIN _adresseEvenement ae on ae.idEvenement = ee.idEvenement\n\t\t\t\t\tLEFT JOIN historiqueAdresse ha on ha.idAdresse = ae.idAdresse\n\t\t\t\t\tLEFT JOIN historiqueImage hi on hi.idImage = ei.idImage\n\t\t\t\t\tWHERE ha.idRue = " . $fetch['idRue'] . "\n\t\t\t\t\t\t\t"; $resProcess = $c->processRequest($request, 'url'); $j = 0; $urlImage = array(); foreach ($resProcess as $infoImage) { $indice = 'url' . $j++; $urlImage[$indice] = $utils->createArchiWikiPhotoUrl($infoImage['idHistoriqueImage'], $infoImage['dateUpload'], 'http://archi-strasbourg.org', 'grand'); } $rue['url'] = $urlImage; $label = 'rue' . $i++; $ruesByQuartier[$label] = $rue; } $c->complexArrayToXML($ruesByQuartier, "xml/urlPhotosRue.xml", 'urlPhotosRue', 'urlPhoto'); $c->complexArrayToCSV($ruesByQuartier, "csv/urlPhotosRue.csv", 'urlPhotosRue', 'urlPhoto'); }
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"; }
/** * 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; }
/** * Extracts and deploys a new service to the service directory * * @param String $path, path to the zip file of the service * @param String $deployKey, hash to avoid unauthorize updating of the service * @return array, results of the deploy [serviceName, creatorEmail, deployKey] */ public function deployServiceFromZip($pathToZip, $deployKey, $zipName) { // extract file to the temp folder $pathToService = $this->extractServiceZip($pathToZip); $pathToXML = "{$pathToService}/config.xml"; // get the service data from the XML $service = $this->loadFromXML($pathToXML); // remove the current project if it exist $utils = new Utils(); if ($utils->serviceExist($service['serviceName'])) { // check if the deploy key is valid if (!$this->checkDeployValidity($service['serviceName'], $deployKey)) { throw new Exception("Deploy key is invalid"); } // clean database and files if the service existed before $this->removeService($service); } // create a new deploy key $utils = new Utils(); $deployKey = $utils->generateRandomHash(); // add the new service $this->addService($service, $deployKey, $pathToZip, $pathToService); // remove temp service folder @system("rmdir " . escapeshellarg($dir) . " /s /q"); // windows version @system("rm -rfv " . escapeshellarg($pathToService)); // linux version // return deploy results return array("serviceName" => $service["serviceName"], "creatorEmail" => $service["creatorEmail"], "deployKey" => $deployKey); }
public function mainAction() { // inicialize supporting classes $timeStart = time(); $connection = new Connection(); $email = new Email(); $service = new Service(); $service->showAds = true; $render = new Render(); $response = new Response(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; $log = ""; // people who were invited but never used Apretaste $invitedPeople = $connection->deepQuery("\n\t\t\tSELECT invitation_time, email_inviter, email_invited\n\t\t\tFROM invitations \n\t\t\tWHERE used=0 \n\t\t\tAND DATEDIFF(CURRENT_DATE, invitation_time) > 15 \n\t\t\tAND email_invited NOT IN (SELECT DISTINCT email from delivery_dropped)\n\t\t\tAND email_invited NOT IN (SELECT DISTINCT email from remarketing)\n\t\t\tORDER BY invitation_time DESC\n\t\t\tLIMIT 450"); // send the first remarketing $log .= "\nINVITATIONS (" . count($invitedPeople) . ")\n"; foreach ($invitedPeople as $person) { // check number of days since the invitation was sent $datediff = time() - strtotime($person->invitation_time); $daysSinceInvitation = floor($datediff / (60 * 60 * 24)); // validate old invitations to avoid bounces if ($daysSinceInvitation > 60) { // re-validate the email $res = $utils->deepValidateEmail($person->email_invited); // if response not ok or temporal, delete from invitations list if ($res[0] != "ok" && $res[0] != "temporal") { $connection->deepQuery("DELETE FROM invitations WHERE email_invited = '{$person->email_invited}'"); $log .= "\t --skiping {$person->email_invited}\n"; continue; } } // send data to the template $content = array("date" => $person->invitation_time, "inviter" => $person->email_inviter, "invited" => $person->email_invited, "expires" => strtotime('next month')); // create html response $response->createFromTemplate('pendinginvitation.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send the invitation email $subject = "Su amigo {$person->email_inviter} esta esperando por usted!"; $email->sendEmail($person->email_invited, $subject, $html); // insert into remarketing table $connection->deepQuery("INSERT INTO remarketing(email, type) VALUES ('{$person->email_invited}', 'INVITE')"); // display notifications $log .= "\t{$person->email_invited}\n"; } // get final delay $timeEnd = time(); $timeDiff = $timeEnd - $timeStart; // printing log $log .= "EXECUTION TIME: {$timeDiff} seconds\n\n"; echo $log; // saving the log $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/remarketing_invitation.log"); $logger->log($log); $logger->close(); // save the status in the database $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='invitation'"); }
public function mainAction() { // inicialize supporting classes $timeStart = time(); $utils = new Utils(); $connection = new Connection(); $sender = new Email(); // get the first campaign created that is waiting to be sent $campaign = $connection->deepQuery("\n\t\t\tSELECT id, subject, content\n\t\t\tFROM campaign\n\t\t\tWHERE sending_date < CURRENT_TIMESTAMP\n\t\t\tAND status = 'WAITING'\n\t\t\tGROUP BY sending_date ASC\n\t\t\tLIMIT 1"); // check if there are not campaigns if (empty($campaign)) { return; } else { $campaign = $campaign[0]; } // check campaign as SENDING $connection->deepQuery("UPDATE campaign SET status='SENDING' WHERE id = {$campaign->id}"); // get the list of people in the list who hsa not receive this campaign yet // so in case the campaign fails when it tries again starts from the same place $people = $connection->deepQuery("\n\t\t\tSELECT email FROM person\n\t\t\tWHERE mail_list=1 AND active=1\n\t\t\tAND email NOT IN (SELECT email FROM campaign_sent WHERE campaign={$campaign->id})"); // show initial message $total = count($people); echo "\nSTARTING COUNT: {$total}\n"; // email people one by one $counter = 1; foreach ($people as $person) { // show message echo "{$counter}/{$total} - {$person->email}\n"; $counter++; // replace the template variables $content = $utils->campaignReplaceTemplateVariables($person->email, $campaign->content, $campaign->id); // send test email $sender->trackCampaign = $campaign->id; $result = $sender->sendEmail($person->email, $campaign->subject, $content); // add to bounced and unsubscribe if there are issues sending $bounced = ""; $status = "SENT"; if (!$result) { $utils->unsubscribeFromEmailList($person->email); $bounced = "bounced=bounced+1,"; $status = "BOUNCED"; } // save status before moving to the next email $connection->deepQuery("\n\t\t\t\tINSERT INTO campaign_sent (email, campaign, status) VALUES ('{$person->email}', '{$campaign->id}', '{$status}');\n\t\t\t\tUPDATE campaign SET {$bounced} sent=sent+1 WHERE id='{$campaign->id}'"); } // set the campaign as SENT $connection->deepQuery("UPDATE campaign SET status='SENT' WHERE id='{$campaign->id}'"); // get final delay $timeEnd = time(); $timeDiff = $timeEnd - $timeStart; // saving the log $wwwroot = $this->di->get('path')['root']; $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/campaigns.log"); $logger->log("ID: {$campaign->id}, RUNTIME: {$timeDiff}, SUBJECT: {$campaign->subject}"); $logger->close(); // save the status in the database $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='campaign'"); }
public function up() { $this->dbforge->add_field(array('id_program_area' => array('type' => 'INT', 'auto_increment' => true), 'area_name' => array('type' => 'varchar(100)'))); $this->dbforge->add_key('id_program_area', TRUE); $this->dbforge->create_table('program_area', TRUE); $addColumn = "ALTER TABLE program ADD id_area INT NULL DEFAULT NULL , ADD INDEX (id_area)"; $this->db->query($addColumn); $addConstraint = "ALTER TABLE program ADD CONSTRAINT PROGRAM_AREAID_FK FOREIGN KEY (id_area) REFERENCES program_area(id_program_area) ON DELETE RESTRICT ON UPDATE RESTRICT"; $this->db->query($addConstraint); $populate = new Utils(); $populate->loadAvaliationAreas(); }
public function mainAction() { // inicialize supporting classes $timeStart = time(); $connection = new Connection(); $email = new Email(); $service = new Service(); $service->showAds = true; $render = new Render(); $response = new Response(); $utils = new Utils(); $wwwroot = $this->di->get('path')['root']; $log = ""; // people in the list to be automatically invited $people = $connection->deepQuery("\n\t\t\tSELECT * FROM autoinvitations\n\t\t\tWHERE email NOT IN (SELECT email FROM person)\n\t\t\tAND email NOT IN (SELECT DISTINCT email FROM delivery_dropped)\n\t\t\tAND email NOT IN (SELECT DISTINCT email from remarketing)\n\t\t\tAND error=0\n\t\t\tLIMIT 450"); // send the first remarketing $log .= "\nAUTOMATIC INVITATIONS (" . count($people) . ")\n"; foreach ($people as $person) { // if response not ok, check the email as error $res = $utils->deepValidateEmail($person->email); if ($res[0] != "ok") { $connection->deepQuery("UPDATE autoinvitations SET error=1, processed=CURRENT_TIMESTAMP WHERE email='{$person->email}'"); $log .= "\t --skiping {$person->email}\n"; continue; } // create html response $content = array("email" => $person->email); $response->createFromTemplate('autoinvitation.tpl', $content); $response->internal = true; $html = $render->renderHTML($service, $response); // send invitation email $subject = "Dos problemas, y una solucion"; $email->sendEmail($person->email, $subject, $html); // mark as sent $connection->deepQuery("\n\t\t\t\tSTART TRANSACTION;\n\t\t\t\tDELETE FROM autoinvitations WHERE email='{$person->email}';\n\t\t\t\tINSERT INTO remarketing(email, type) VALUES ('{$person->email}', 'AUTOINVITE');\n\t\t\t\tCOMMIT;"); // display notifications $log .= "\t{$person->email}\n"; } // get final delay $timeEnd = time(); $timeDiff = $timeEnd - $timeStart; // printing log $log .= "EXECUTION TIME: {$timeDiff} seconds\n\n"; echo $log; // saving the log $logger = new \Phalcon\Logger\Adapter\File("{$wwwroot}/logs/remarketing_autoinvitation.log"); $logger->log($log); $logger->close(); // save the status in the database $connection->deepQuery("UPDATE task_status SET executed=CURRENT_TIMESTAMP, delay='{$timeDiff}' WHERE task='autoinvitation'"); }
/** * Process the page when its submitted * * @author kuma, salvipascual * @version 1.0 * */ public function processAction() { // get the values from the post $captcha = trim($this->request->getPost('captcha')); $name = trim($this->request->getPost('name')); $inviter = trim($this->request->getPost('email')); $guest = trim($this->request->getPost('guest')); if (!isset($_SESSION['phrase'])) { $_SESSION['phrase'] = uniqid(); } // throw a die() // check all values passed are valid if (strtoupper($captcha) != strtoupper($_SESSION['phrase']) || $name == "" || !filter_var($inviter, FILTER_VALIDATE_EMAIL) || !filter_var($guest, FILTER_VALIDATE_EMAIL)) { die("Error procesando, por favor valla atras y comience nuevamente."); } // params for the response $this->view->name = $name; $this->view->email = $inviter; // create classes needed $connection = new Connection(); $email = new Email(); $utils = new Utils(); $render = new Render(); // do not invite people who are already using Apretaste if ($utils->personExist($guest)) { $this->view->already = true; return $this->dispatcher->forward(array("controller" => "invitar", "action" => "index")); } // send notification to the inviter $response = new Response(); $response->setResponseSubject("Gracias por darle internet a un Cubano"); $response->setEmailLayout("email_simple.tpl"); $response->createFromTemplate("invitationThankYou.tpl", array('num_notifications' => 0)); $response->internal = true; $html = $render->renderHTML(new Service(), $response); $email->sendEmail($inviter, $response->subject, $html); // send invitations to the guest $response = new Response(); $response->setResponseSubject("{$name} le ha invitado a revisar internet desde su email"); $responseContent = array("host" => $name, "guest" => $guest, 'num_notifications' => 0); $response->createFromTemplate("invitation.tpl", $responseContent); $response->internal = true; $html = $render->renderHTML(new Service(), $response); $email->sendEmail($guest, $response->subject, $html); // save all the invitations into the database at the same time $connection->deepQuery("INSERT INTO invitations (email_inviter,email_invited,source) VALUES ('{$inviter}','{$guest}','abroad')"); // redirect to the invite page $this->view->message = true; return $this->dispatcher->forward(array("controller" => "invitar", "action" => "index")); }
public static function fieldControl($field, array $fields, $default = '') { if (Utils::in_arrayi($field, $fields)) { return $field; } return $default; }
public function action() { if (!isset($this->parameters->teamInfo)) { Utils::forDebug($this->parameters, true); } return $actionResult = $this->install(isset($this->parameters->teamInfo) ? $this->parameters->teamInfo : NULL); }
public function testMarshalling() { $attributeQuery = new AttributeQuery(); $attributeQuery->setNameID(array('Value' => 'NameIDValue')); $attributeQuery->setAttributes(array('test1' => array('test1_attrv1', 'test1_attrv2'), 'test2' => array('test2_attrv1', 'test2_attrv2', 'test2_attrv3'), 'test3' => array())); $attributeQueryElement = $attributeQuery->toUnsignedXML(); // Test Attribute Names $attributes = Utils::xpQuery($attributeQueryElement, './saml_assertion:Attribute'); $this->assertCount(3, $attributes); $this->assertEquals('test1', $attributes[0]->getAttribute('Name')); $this->assertEquals('test2', $attributes[1]->getAttribute('Name')); $this->assertEquals('test3', $attributes[2]->getAttribute('Name')); // Test Attribute Values for Attribute 1 $av1 = Utils::xpQuery($attributes[0], './saml_assertion:AttributeValue'); $this->assertCount(2, $av1); $this->assertEquals('test1_attrv1', $av1[0]->textContent); $this->assertEquals('test1_attrv2', $av1[1]->textContent); // Test Attribute Values for Attribute 2 $av2 = Utils::xpQuery($attributes[1], './saml_assertion:AttributeValue'); $this->assertCount(3, $av2); $this->assertEquals('test2_attrv1', $av2[0]->textContent); $this->assertEquals('test2_attrv2', $av2[1]->textContent); $this->assertEquals('test2_attrv3', $av2[2]->textContent); // Test Attribute Values for Attribute 3 $av3 = Utils::xpQuery($attributes[2], './saml_assertion:AttributeValue'); $this->assertCount(0, $av3); }
public function control() { $this->redirectToSternIndiaEndpoint('forgot.php'); $config = Config::getInstance(); //$this->addToView('is_registration_open', $config->getValue('is_registration_open')); // if (isset($_POST['email']) && $_POST['Submit'] == 'Send Reset') { // /$_POST['email'] = '*****@*****.**'; if (isset($_POST['email'])) { $this->disableCaching(); $dao = DAOFactory::getDAO('UserDAO'); $user = $dao->getByEmail($_POST['email']); if (isset($user)) { $token = $user->setPasswordRecoveryToken(); $es = new ViewManager(); $es->caching = false; //$es->assign('apptitle', $config->getValue('app_title_prefix')."ThinkUp" ); $es->assign('first_name', $user->first_name); $es->assign('recovery_url', "session/reset.php?token={$token}"); $es->assign('application_url', Utils::getApplicationURL(false)); $es->assign('site_root_path', $config->getValue('site_root_path')); $message = $es->fetch('_email.forgotpassword.tpl'); $subject = $config->getValue('app_title_prefix') . "Stern India Password Recovery"; //Will put the things in queue to mail the things. Resque::enqueue('user_mail', 'Mailer', array($_POST['email'], $subject, $message)); $this->addToView('link_sent', true); } else { $this->addErrorMessage('Error: account does not exist.'); } } $this->setViewTemplate('Session/forgot.tpl'); return $this->generateView(); }
function manipulateValues($column) { $field = Utils::findField($column); if ($column == "date_date") { $_POST[$column] = Utils::dateEn($_POST[$column]); } }
public static function display($strLink, $business, $totalItems, $curPage, $maxPages, $maxItems) { $strResult = "<br>"; $strResult .= "<table id='tblist' width='100%' border='0' style='border:solid 1px #D3D3D3;' cellpadding='0' cellspacing='0'>"; //$strResult.= "<tr style='height:20px; font-weight:bold; font-size:10px; background:#8BC5F4;'>Name</tr>"; //$strResult.= "<tr style='height:36px; font-weight:bold; font-size:13px; background:#8BC5F4;'>NoiDung</tr>"; //$strResult.= "<td style='border-right:solid 1px #D3D3D3; padding:4px;'>idconnect</td>"; //$strResult.= "<td style='border-right:solid 1px #D3D3D3; padding:4px;'>NoiDung</td></tr>"; //$strResult.= "<td style='border-right:solid 1px #D3D3D3; padding:4px;'>Name</td>"; for ($i = 0; $i < count($business); $i++) { $images = "select* from phongthuy"; //div style="margin-left: 10px; margin-top: 10px; font-family: tahoma; font-size: 18px; // font-weight: bold; color:#890C29; text-transform:uppercase;"> $strResult .= "<table>"; $strResult .= "<tr><div><a href='chitietphongthuy.php?idphongthuy=" . $business[$i]['id'] . "'><b style='font-size:14px;font-weight:bold;color: #006DB9;'>" . $business[$i]['Name'] . " </b></a></div></tr>"; $strResult .= "<tr>"; $strResult .= "</br>"; //$strResult.="<tr>"; //$strResult.="<img src='../images/phongthuy/".$business[$i]['HinhAnh']."'>"; $strResult .= "<td style='border-right:solid 1px #D3D3D3; padding:4px;'> <img width='70px' heigh='70px' src='../images/phongthuy/" . $business[$i]['HinhAnh1'] . "' style='vertical-align: middle;'/></td>"; //$strResult.= echo $business[$i]['HinhAnh'] ; //$strResult.="<a href='chitietphongthuy.php?id=".$business[$i]['id']."'><img src='../".$images[0]['path']."' width='150px' /></a></td>"; $strResult .= "<td style='padding:4px;' width='450px'>" . $business[$i]['NoiDung'] . " </td>"; $strResult .= "</tr>"; $strResult .= "</table>"; $strResult .= "</br>"; $strResult .= "</br>"; } $strPaging = Utils::paging($strLink, $totalItems, $curPage, $maxPages, $maxItems); $strResult .= $strPaging; $strResult .= "</table>"; return $strResult; //echo $strPaging; }
/** * Check the $_POST'ed CAPTCHA inputs match the contents of the CAPTCHA. * @return bool */ public function doesTextMatchImage() { //if in test mode, assume check is good if user_code is set to 123456 if (Utils::isTest()) { if (isset($_POST['user_code']) && $_POST['user_code'] == '123456') { return true; } else { return false; } } switch ($this->type) { case self::RECAPTCHA_CAPTCHA: $config = Config::getInstance(); $priv_key = $config->getValue('recaptcha_private_key'); $resp = recaptcha_check_answer($priv_key, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { return false; } else { return true; } break; default: if (strcmp(md5($_POST['user_code']), SessionCache::get('ckey'))) { return false; } else { return true; } break; } }
public function __construct($dir) { $this->directory = $dir; $metadata_json = file_get_contents($this->directory . '/zing/plugin.json'); if ($metadata_json === false) { throw new InvalidPluginException("Error loading plugin metadata"); } $this->metadata = json_decode($metadata_json, true); if (!$this->metadata) { throw new InvalidPluginException("Error decoding JSON metadata"); } if (!$this->metadata('id')) { throw new InvalidPluginException("Plugin ID not found"); } if (!Utils::is_valid_plugin_id($this->metadata('id'))) { throw new InvalidPluginException("Plugin ID is invalid"); } if (!isset($this->metadata['version'])) { throw new InvalidPluginException("Plugin version is missing"); } $this->class_name = \zing\lang\Introspector::first_class_in_file($this->directory . '/zing/plugin.php'); if (!$this->class_name) { throw new InvalidPluginException("plugin primary class is missing"); } }
public function getGraph() { $collection = ['in' => [], 'out' => []]; $keys = redis()->keys("g:*:i:{$this->ns}"); foreach ($keys as $key) { if (fnmatch('*:d:*', $key) || fnmatch('*:data:*', $key)) { continue; } $to = Utils::cut('g:', ':i:', $key); $froms = redis()->smembers($key); $graph = [$to => $froms]; $collection['in'][] = $graph; } $keys = redis()->keys("g:*:o:{$this->ns}"); foreach ($keys as $key) { if (fnmatch('*:d:*', $key) || fnmatch('*:data:*', $key)) { continue; } $from = Utils::cut('g:', ':o:', $key); $tos = redis()->smembers($key); $graph = [$from => $tos]; $collection['out'][] = $graph; } return $collection; }
/** * Get list of available controllers */ public function controllersAction() { $appPath = $this->_configMain['application_path']; $folders = File::scanFiles($this->_configMain->get('frontend_controllers'), false, true, File::Dirs_Only); $data = array(); if (!empty($folders)) { foreach ($folders as $item) { $name = basename($item); if (file_exists($item . '/Controller.php')) { $name = str_replace($appPath, '', $item . '/Controller.php'); $name = Utils::classFromPath($name); $data[] = array('id' => $name, 'title' => $name); } } } if ($this->_configMain->get('allow_externals')) { $config = Config::factory(Config::File_Array, $this->_configMain->get('configs') . 'externals.php'); $eExpert = new Externals_Expert($this->_configMain, $config); $classes = $eExpert->getClasses(); $extControllers = $eExpert->getFrontendControllers(); if (!empty($extControllers)) { $data = array_merge($data, array_values($extControllers)); } } Response::jsonSuccess($data); }
public function oAuthRequest($url, $method = NULL, $args = array()) { $url = Utils::getURLWithParams($url, $args); $FAUX_DATA_PATH = THINKUP_ROOT_PATH . $this->data_path; $url = str_replace('https://twitter.com/', '', $url); $url = str_replace('https://api.twitter.com/1/', '', $url); $url = str_replace('http://search.twitter.com/', '', $url); $url = str_replace('/', '_', $url); $url = str_replace('&', '-', $url); $url = str_replace('?', '-', $url); $debug = getenv('TEST_DEBUG') !== false ? true : false; if ($debug) { echo "READING LOCAL DATA FILE: " . $FAUX_DATA_PATH . $url . "\n"; } if (!file_exists($FAUX_DATA_PATH . $url)) { if (is_numeric($url) && strlen($url) == 3) { // if the URL is a 3 character, numeric string, set the last error code to it. For testing errors. $this->last_status_code = (int) $url; } else { $this->last_status_code = 404; } return ""; } else { $data = file_get_contents($FAUX_DATA_PATH . $url); $this->last_status_code = 200; return $data; } }
function pagination($messageParPage, $table, $sscategorie) { /* paginatio_array 0->Nbre d'enregistrements paginatio_array 1->Nbre de pages paginatio_array 2->Pages actuelle paginatio_array 3->Première entrée */ $sscategorie = Utils::anti_injection($sscategorie); $pagination_array = array(); $sqlQuery = "SELECT COUNT(*) AS total FROM " . TABLE_PREFIX . $table . " WHERE sscat_radio=" . $sscategorie; $getTotal = Db::query($sqlQuery); $donnees_total = Db::fetch_assoc($getTotal); $pagination_array[0] = $donnees_total['total']; $pagination_array[1] = ceil($pagination_array[0] / $messageParPage); if (isset($_GET['page'])) { $pagination_array[2] = intval($_GET['page']); if ($pagination_array[2] > $pagination_array[1] && $pagination_array[1] > 0) { $pagination_array[2] = $pagination_array[1]; } } else { $pagination_array[2] = 1; } $pagination_array[3] = ($pagination_array[2] - 1) * $messageParPage; return $pagination_array; }
public function generateInsight(Instance $instance, User $user, $last_week_of_posts, $number_days) { parent::generateInsight($instance, $user, $last_week_of_posts, $number_days); $this->logger->logInfo("Begin generating insight", __METHOD__ . ',' . __LINE__); $baseline_dao = DAOFactory::getDAO('InsightBaselineDAO'); foreach ($this->getSchedule() as $baseline_slug => $data) { $now = TimeHelper::getTime(); if ($now >= strtotime($data['start']) && $now <= strtotime($data['end'])) { $this->logger->logInfo("{$now} is in-schedule", __METHOD__ . ',' . __LINE__); $baseline = $baseline_dao->getMostRecentInsightBaseline($baseline_slug, $instance->id); if (!$baseline) { if ($instance->network == 'facebook' && date('w') == 4 || $instance->network == 'twitter' && date('w') == 1 || Utils::isTest()) { $found = $this->runInsightForConfig($data, $instance); $baseline_dao->insertInsightBaseline($baseline_slug, $instance->id, $found); } else { $this->logger->logInfo("Not today", __METHOD__ . ',' . __LINE__); } } else { $this->logger->logInfo("Already exists", __METHOD__ . ',' . __LINE__); } } else { $this->logger->logInfo("Not in-schedule", __METHOD__ . ',' . __LINE__); } } $this->logger->logInfo("Done generating insight", __METHOD__ . ',' . __LINE__); }
/** * Returns a Request object with complete context to create a contest * * @param string $title * @param string $public * @param Users $contestDirector * @return Request */ public static function getRequest($title = null, $public = 0, Users $contestDirector = null, $languages = null, $finish_time = null) { if (is_null($contestDirector)) { $contestDirector = UserFactory::createUser(); } if (is_null($title)) { $title = Utils::CreateRandomString(); } // Set context $r = new Request(); $r['title'] = $title; $r['description'] = 'description'; $r['start_time'] = Utils::GetPhpUnixTimestamp() - 60 * 60; $r['finish_time'] = $finish_time == null ? Utils::GetPhpUnixTimestamp() + 60 * 60 : $finish_time; $r['window_length'] = null; $r['public'] = $public; $r['alias'] = substr($title, 0, 20); $r['points_decay_factor'] = '.02'; $r['partial_score'] = '0'; $r['submissions_gap'] = '0'; $r['feedback'] = 'yes'; $r['penalty'] = 100; $r['scoreboard'] = 100; $r['penalty_type'] = 'contest_start'; $r['penalty_calc_policy'] = 'sum'; $r['languages'] = $languages; $r['recommended'] = 0; // This is just a default value, it is not honored by apiCreate. return array('request' => $r, 'director' => $contestDirector); }
function _dig($params) { $user = $params['user']; $channel = $params['channel']; $domain = $params['domain']; $record = $params['record']; if (strpos($domain, '.') === false) { $domain .= '.rockriverstar.com'; } $output = Utils::cmdout($params); $records = array('a' => DNS_A, 'cname' => DNS_CNAME, 'hinfo' => DNS_HINFO, 'mx' => DNS_MX, 'ns' => DNS_NS, 'ptr' => DNS_PTR, 'soa' => DNS_SOA, 'txt' => DNS_TXT, 'aaaa' => DNS_AAAA, 'srv' => DNS_SRV, 'naptr' => DNS_NAPTR, 'a6' => DNS_A6, 'all' => DNS_ALL, 'and' => DNS_ANY); $record = $records[strtolower($record)]; $result = dns_get_record($domain, $record); if (count($result) > 0) { $cols = array_keys(reset($result)); $output .= '<table class="net"><tr>'; foreach ($cols as $col) { $output .= '<th>' . $col . '</th>'; } $output .= '</tr>'; foreach ($result as $res) { $output .= '<tr>'; foreach ($cols as $col) { $output .= '<td>' . $res[$col] . '</td>'; } $output .= '</tr>'; } $output .= '</table>'; } else { $output .= 'No results found.'; } //$output .= '<pre>' . print_r(,1) . '</pre>'; Status::create()->data($output)->user_id($user->id)->channel($channel)->type('message')->cssclass('net ip')->insert(); return true; }
public function getPostDetailMenuItems($post) { $menus = array(); $map_template_path = Utils::getPluginViewDirectory('geoencoder').'geoencoder.map.tpl'; //Define a menu item $map_menu_item = new MenuItem("Response Map", "", $map_template_path, 'Geoencoder'); //Define a dataset to be displayed when that menu item is selected $map_menu_item_dataset_1 = new Dataset("geoencoder_map", 'PostDAO', "getRelatedPosts", array($post->post_id, $post->network, 'location') ); //Associate dataset with menu item $map_menu_item->addDataset($map_menu_item_dataset_1); //Add menu item to menu $menus["geoencoder_map"] = $map_menu_item; $nearest_template_path = Utils::getPluginViewDirectory('geoencoder').'geoencoder.nearest.tpl'; //Define a menu item $nearest_menu_item = new MenuItem("Nearest Responses", "", $nearest_template_path); //Define a dataset to be displayed when that menu item is selected $nearest_dataset = new Dataset("geoencoder_nearest", 'PostDAO', "getRelatedPosts", array($post->post_id, $post->network, !Session::isLoggedIn())); //Associate dataset with menu item $nearest_menu_item->addDataset($nearest_dataset); $nearest_dataset_2 = new Dataset("geoencoder_options", 'PluginOptionDAO', 'getOptionsHash', array('geoencoder', true)); $nearest_menu_item->addDataset($nearest_dataset_2); //Add menu item to menu $menus["geoencoder_nearest"] = $nearest_menu_item; return $menus; }
function _queues($params) { $user = $params['user']; $drawers = DB::get()->results("SELECT user_id, username, indexed, added FROM drawers inner join users on users.id = drawers.user_id WHERE indexed LIKE 'queue_%' order by user_id asc, added asc;"); $out = ''; foreach ($drawers as $drawer) { if (preg_match('#_([^_]+)_(\\d+)$#', $drawer->indexed, $matches)) { if ($matches[2] == $user->id) { $out .= "<li>" . '<a href="#" onclick="send(\'/c' . $matches[1] . ' ' . $drawer->username . '\');return false;" style="margin-right:5px;"><img src="'; switch ($matches[1]) { case 'chat': $out .= '/plugins/queue/user_comment_delete.png'; break; default: $out .= '/plugins/queue/phone_delete.png'; break; } $out .= '"></a>' . "{$matches[1]} queued with {$drawer->username} <small>" . date('M j, Y h:ia', strtotime($drawer->added)) . "</small></li>"; } } } if ($out == '') { $out = 'You have no active queues.'; } else { $out = '<ul>' . $out . '</ul>'; } $out = Utils::cmdout($params) . $out; Status::create()->data($out)->type('system')->user_to($user->id)->cssclass('ok')->insert(); return true; }