typo3 remove session data of fe-user - typo3

Hi I have an typo3 extension that stores data in session.
After my actions are finished I want to remove the session data.
I tried this:
$GLOBALS['TSFE']->fe_user->removeSessionData();
But this does not work.
What is my fail? Thanks in advance
UPDATE
if ( is_null($GLOBALS["TSFE"]->fe_user->getKey("ses", "Step1")) ) {
$this->redirect('noProductFound');
}
$arguments = $this->request->getArguments();
$reloadPage = new \TYPO3\ShopExtension\Controller\ShopStep();
$product = $arguments['product'];
$orderProcessed = $GLOBALS['TSFE']->fe_user->getKey('ses', 'orderProcessed');
#Verhindern das Seite neu geladen wird und eine neue Bestellung getätigt wird.
if ($reloadPage->getReload() == true | $orderProcessed == true) {
$this->redirect('noProductFound', null, null, array('error' => 'orderProcessed'));
} else {
if ($product == ShopConstant::AG_TRIAL) {
$this->save_Product_Trial();
$reloadPage->setReload(true);
$GLOBALS['TSFE']->fe_user->setKey('ses', 'orderProcessed', true);
$GLOBALS['TSFE']->storeSessionData();
} elseif ($product == ShopConstant::AG_PROFESSIONELL || $product == ShopConstant::AG_PREMIUM || $product == ShopConstant::AG_ULTIMATE) {
$afterOrderOrderId = $this->save_Product_Auditgarant($product);
$reloadPage->setReload(true);
$GLOBALS['TSFE']->fe_user->setKey('ses', 'orderProcessed', true);
$GLOBALS['TSFE']->storeSessionData();
} elseif ($product == ShopConstant::BOOK_AL || $product == ShopConstant::BOOK_PH || $product == ShopConstant::BOOK_CPMS || $product == ShopConstant::BOOK_USABILITY) {
$this->save_Product_Book($product);
$reloadPage->setReload(true);
$GLOBALS['TSFE']->fe_user->setKey('ses', 'orderProcessed', true);
$GLOBALS['TSFE']->storeSessionData();
} elseif ($product == ShopConstant::INSTITUTSTAG || $product == ShopConstant::INSTITUTSTAG_PARTNER || $product == ShopConstant::INSTITUTSTAG_ALUMNI) {
$this->save_Product_Institutstag($product);
$reloadPage->setReload(true);
$GLOBALS['TSFE']->fe_user->setKey('ses', 'orderProcessed', true);
$GLOBALS['TSFE']->storeSessionData();
} else {
$this->redirect('noProductFound');
}
#Session löschen, da Daten ab hier nicht mehr benötigt werden.
$GLOBALS['TSFE']->fe_user->removeSessionData();
$GLOBALS['TSFE']->fe_user->setKey('ses', 'Step1', null);
$GLOBALS['TSFE']->storeSessionData();
// \TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($GLOBALS['TSFE']);
// exit();
#Führt einen redirect durch mit angehängtem Attribut des letzten Step.
$this->redirect('getContent', null, null, array(
'step' => $arguments['lastStep'],
'shopStep' => $arguments['product'],
'afterOrderOrderId' => $afterOrderOrderId
));

In case you did $GLOBALS['TSFE']->fe_user->setAndSaveSessionData('session_key', $somevalue); you can simply do $GLOBALS['TSFE']->fe_user->setAndSaveSessionData('session_key', null); to delete the session data.

Related

SugarCRM 6.5 How to print php template?

I am newly SugarCRM 6.5 developer, I have write view.detail.php file and controller file. How to print template controller action json data php template. please help me. I have create controller and view.details code below.
Controller
protected function action_printinvoice(){
global $current_user, $db, $region;
$db = DBManagerFactory::getInstance();
$id = $_POST['record'];
$sql = "select gn.client_name, gn.client_address, gn.client_address_city, gn.client_address_state, gn.client_address_country, gn.client_address_postalcode, gn.id, gn.recipient_name, gn.recipient_address_city, gn.recipient_address_state, gn.recipient_address_country, gn.recipient_address_postalcode, gn.recipient_address, gn.recipient_vat_id, gn.recipient_tax_no, gn.recipient_name, gn.invoice_number as ginvo_client_invoice_id, "
. " gcstm.* "
. "from ginvo_client_invoice as gn "
. " inner join ginvo_client_invoice_cstm as gcstm on gn.id=gcstm.id_c "
. "where "
. " gn.deleted=0 and gn.id='".$id."' limit 1 ";
$result = $db->query($sql);
$ginv_invoice_ary=array();
while($row = $db->fetchByAssoc($result) ) {
$ginv_invoice_ary[]=$row;
}
if ($ginv_invoice_ary[0]['region_c'] == 'non_eu_client_and_freelancer_provider') {
$region = 'Non EU client and freelancer provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'non_eu_client_and_employed_provider'){
$region = 'Non EU client and employed provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'german_client_and_freelancer_provider'){
$region = 'German client and freelancer provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'german_client_and_employed_provider'){
$region = 'German client and employed provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'eu_client_and_freelancer_provider'){
$region = 'EU client and freelancer provider';
}else if ($ginv_invoice_ary[0]['region_c'] == 'eu_client_and_employed_provider') {
$region = 'EU client and employed provider';
}else {
$region = '';
}
echo json_encode($ginv_invoice_ary);
$this->view = 'invoiceprint';
//$this->view = 'custom/modules/ginvo_client_invoice/metadata/ClientInvoice.php';
exit;
}
View.detail.php
<?php
require_once('include/MVC/View/views/view.detail.php');
// require_once('modules/ginvo_client_invoice/view/invoice.php');
class ginvo_client_invoiceViewDetail extends ViewDetail {
function ginvo_client_invoiceViewDetail(){
parent::ViewDetail();
}
function display(){
echo $ginv_invoice_ary;
//$this->populateQuoteTemplates();
$this->displayPopupHtml();
parent::display();
}
function populateQuoteTemplates(){
global $app_list_strings, $current_user;
$inv_id = $this->bean->id;
$sql = "SELECT * FROM ginvo_client_invoice WHERE deleted=0 AND id='$inv_id'";
$res = $this->bean->db->query($sql);
$app_list_strings[] = array();
while($row = $this->bean->db->fetchByAssoc($res)){
if($row){
$app_list_strings[$row] = $row;
}
}
}
function displayPopupHtml(){
global $app_list_strings,$app_strings, $mod_strings;
$templates = array_keys($app_list_strings);
if($templates){
echo '
<script>
function showPopup(task){
var record = \''.$this->bean->id.'\';
var fdata = {\'record\':record};
var params = jQuery.param(fdata);
$.ajax({
type:\'post\',
data: fdata,
// dataType: "json",
// url:\'custom/client_invoice.php?\'+params,
//url:\'custom/modules/ginvo_client_invoice/ClientInvoice.php?\'+params,
url:\'index.php?module=ginvo_client_invoice&action=printinvoice\',
error:function(resp){},
success:function(resp){
console.log(resp);
// location.reload(true);
}
});
// var w = window.open(\'custom/ClientInvoice.php\');
//
// $(w).ready(function(){
// w.print();
// });
}
</script>';
}
else{
echo '<script>
function showPopup(task){
alert(\''.$current_user.'\');
}
</script>';
}
}
}
?>

Webmaster Tool Api Crawl Optimize

By using webmaster tool API to parse data from google. The speed of downloading is very slow, Is there any way to optimize, Or use another method. It can take more than hour depending on the data.
Regards.
const HOST = "https://www.google.com";
const SERVICEURI = "/webmasters/tools/";
public function __construct()
{
$this->_auth = $this->_loggedIn = $this->_domain = false;
$this->_data = array();
}
public function getArray($domain)
{
if ($this->_validateDomain($domain)) {
if ($this->_prepareData()) {
return $this->_data;
} else {
throw new Exception('Error receiving crawl issues for ' . $domain);
}
} else {
throw new Exception('The given domain is not connected to your Webmastertools account!');
exit;
}
}
public function getCsv($domain, $localPath = false)
{
if ($this->_validateDomain($domain)) {
if ($this->_prepareData()) {
if (!$localPath) {
$this->_HttpHeaderCSV();
$this->_outputCSV();
} else {
$this->_outputCSV($localPath);
}
} else {
throw new Exception('Error receiving crawl issues for ' . $domain);
}
} else {
throw new Exception('The given domain is not connected to your Webmastertools account!');
exit;
}
}
public function getSites()
{
if ($this->_loggedIn) {
$feed = $this->_getData('feeds/sites/');
if ($feed) {
$doc = new DOMDocument();
$doc->loadXML($feed);
$sites = array();
foreach ($doc->getElementsByTagName('entry') as $node) {
array_push($sites, $node->getElementsByTagName('title')->item(0)->nodeValue);
}
return (0 < sizeof($sites)) ? $sites : false;
} else {
return false;
}
} else {
return false;
}
}
public function login($mail, $pass)
{
$postRequest = array(
'accountType' => 'HOSTED_OR_GOOGLE',
'Email' => $mail,
'Passwd' => $pass,
'service' => "sitemaps",
'source' => "Google-WMTdownloadscript-0.11-php"
);
// Before PHP version 5.2.0 and when the first char of $pass is an # symbol,
// send data in CURLOPT_POSTFIELDS as urlencoded string.
if ('#' === (string) $pass[0] || version_compare(PHP_VERSION, '5.2.0') < 0) {
$postRequest = http_build_query($postRequest);
}
$ch = curl_init(self::HOST . '/accounts/ClientLogin');
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postRequest,
));
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if (200 != $info['http_code']) {
throw new Exception('Login failed!');
exit;
} else {
#preg_match('/Auth=(.*)/', $output, $match);
if (isset($match[1])) {
$this->_auth = $match[1];
$this->_loggedIn = true;
return true;
} else {
throw new Exception('Login failed!');
exit;
}
}
}
private function _prepareData()
{
if ($this->_loggedIn) {
$currentIndex = 1;
$maxResults = 100;
$encUri = urlencode($this->_domain);
/*
* Get the total result count / result page count
*/
$feed = $this->_getData("feeds/{$encUri}/crawlissues?start-index=1&max-results=1");
if (!$feed) {
return false;
}
$doc = new DOMDocument();
$doc->loadXML($feed);
$totalResults = (int) $doc->getElementsByTagNameNS('http://a9.com/-/spec/opensearch/1.1/', 'totalResults')->item(0)->nodeValue;
$resultPages = (0 != $totalResults) ? ceil($totalResults / $maxResults) : false;
unset($feed, $doc);
if (!$resultPages) {
return false;
}
/*
* Paginate over issue feeds
*/
else {
// Csv data headline
$this->_data = Array(
Array(
'Issue Id',
'Crawl type',
'Issue type',
'Detail',
'URL',
'Date detected',
'Last detected'
)
);
while ($currentIndex <= $resultPages) {
$startIndex = ($maxResults * ($currentIndex - 1)) + 1;
$feed = $this->_getData("feeds/{$encUri}/crawlissues?start-index={$startIndex}&max-results={$maxResults}");
$doc = new DOMDocument();
$doc->loadXML($feed);
foreach ($doc->getElementsByTagName('entry') as $node) {
$issueId = str_replace(self::HOST . self::SERVICEURI . "feeds/{$encUri}/crawlissues/", '', $node->getElementsByTagName('id')->item(0)->nodeValue);
$crawlType = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'crawl-type')->item(0)->nodeValue;
$issueType = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'issue-type')->item(0)->nodeValue;
$detail = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'detail')->item(0)->nodeValue;
$url = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'url')->item(0)->nodeValue;
$dateDetected = date('d/m/Y', strtotime($node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'date-detected')->item(0)->nodeValue));
$updated = date('d/m/Y', strtotime($node->getElementsByTagName('updated')->item(0)->nodeValue));
// add issue data to results array
array_push($this->_data, Array(
$issueId,
$crawlType,
$issueType,
$detail,
$url,
$dateDetected,
$updated
));
}
unset($feed, $doc);
$currentIndex++;
}
return true;
}
} else {
return false;
}
}
private function _getData($url)
{
if ($this->_loggedIn) {
$header = array(
'Authorization: GoogleLogin auth=' . $this->_auth,
'GData-Version: 2'
);
$ch = curl_init(self::HOST . self::SERVICEURI . $url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_ENCODING => 1,
CURLOPT_HTTPHEADER => $header
));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return (200 != $info['http_code']) ? false : $result;
} else {
return false;
}
}
private function _HttpHeaderCSV()
{
header('Content-type: text/csv; charset=utf-8');
header('Content-disposition: attachment; filename=gwt-crawlerrors-' . $this->_getFilename());
header('Pragma: no-cache');
header('Expires: 0');
}
private function _outputCSV($localPath = false)
{
$outstream = !$localPath ? 'php://output' : $localPath . DIRECTORY_SEPARATOR . $this->_getFilename();
$outstream = fopen($outstream, "w");
if (!function_exists('__outputCSV')) {
function __outputCSV(&$vals, $key, $filehandler)
{
fputcsv($filehandler, $vals); // add parameters if you want
}
}
array_walk($this->_data, "__outputCSV", $outstream);
fclose($outstream);
}
private function _getFilename()
{
return 'gwt-crawlerrors-' . parse_url($this->_domain, PHP_URL_HOST) . '-' . date('Ymd-His') . '.csv';
}
private function _validateDomain($domain)
{
if (!filter_var($domain, FILTER_VALIDATE_URL)) {
return false;
}
$sites = $this->getSites();
if (!$sites) {
return false;
}
foreach ($sites as $url) {
if (parse_url($domain, PHP_URL_HOST) == parse_url($url, PHP_URL_HOST)) {
$this->_domain = $domain;
return true;
}
}
return false;
}
The url from Google is in error Google has added a false extension look carefully and you will see it.
Google Crap!
Your site is probably fine.

Magento - Upload file in contact form

I have to create a new field in contact form to upload file.
I followed tuts and this is what i did :
in form.phtml :
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post" enctype="multipart/form-data">
Then i added the field in the contact form :
<li>
<label for="attachment"><?php echo Mage::helper('contacts')->__('Attachment') ?></label>
<div class="input-box">
<input name="MAX_FILE_SIZE" type="hidden" value="2000000" />
<input name="attachment" id="attachment" class="input-text" type="file" />
</div>
I modified the IndexController.php in : /www/app/code/core/Mage/Contacts/controllers as :
<?php
/**
* Contacts index controller
*
* #category Mage
* #package Mage_Contacts
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('contactForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
/**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************//**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg', 'jpeg', 'png', 'bmp', 'gif'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************/
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
/**************************************************************/
//sending file as attachment
$attachmentFilePath = Mage::getBaseDir('media'). DS . 'contacts' . DS . $fileName;
if(file_exists($attachmentFilePath)){
$fileContents = file_get_contents($attachmentFilePath);
$attachment = $mailTemplate->getMail()->createAttachment($fileContents);
$attachment->filename = $fileName;
}
/**************************************************************/
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
I created a contacts directory in medias with 777 rights
The contact form is correctly shown in my page, i can choose a file, but it isnt uploaded. In medias/contacts/ no file, and in my email i have a attached file called noname
Impossible to use it. Im sure i did something wrong but i cant find what exactly is wrong.
Im not a pro Magento admin, so if you can explain me in details that will be cool :)
Thanks all
i have tried recreating your scenario in my local installation and changed your contoller file uploader code with one of my working modules.
/**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts' . DS ;
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path, $_FILES['attachment']['contacts'] );
$newFilename = $uploader->getUploadedFileName();
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************/
This is working 100% correctly i have tested this for pdf also.
Please try changing once.
Replace
if(file_exists($attachmentFilePath)){
With this
if(file_exists($attachmentFilePath) && is_file($attachmentFilePath)){
Because file_exists results to TRUE if the file OR the directory exists. My email being sent out would send a blank "Mail Attachment" file because the file upload input on my contact form was optional.

Sending messages with facebook xmpp api

I have copied and modified some of the facebook's given chat api code, now I want to send a message to my friend. I found that we send a xml <message from="" to=""> to send a message. But that did not happen. maybe it's because i don't know what to put on from and to attribs?
The Code:
<?php
$STREAM_XML = '<stream:stream '.
'xmlns:stream="http://etherx.jabber.org/streams" '.
'version="1.0" xmlns="jabber:client" to="chat.facebook.com" '.
'xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">';
$AUTH_XML = '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" '.
'mechanism="X-FACEBOOK-PLATFORM"></auth>';
$CLOSE_XML = '</stream:stream>';
$RESOURCE_XML = '<iq type="set" id="3">'.
'<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">'.
'<resource>fb_xmpp_script</resource></bind></iq>';
$SESSION_XML = '<iq type="set" id="4" to="chat.facebook.com">'.
'<session xmlns="urn:ietf:params:xml:ns:xmpp-session"/></iq>';
$START_TLS = '<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>';
$MESSAGE = '<message from="-cyberkiller.nishchal#chat.facebook.com" to="-nootan.ghimire#chat.facebook.com">
<body>This is the test message! Sent from App. by, "Nishchal"</body>
</message>';
function open_connection($server) {
$fp = fsockopen($server, 5222, $errno, $errstr);
if (!$fp) {
print "$errstr ($errno)<br>";
} else {
print "connnection open<br>";
}
return $fp;
}
function send_xml($fp, $xml) {
fwrite($fp, $xml);
}
function recv_xml($fp, $size=4096) {
$xml = fread($fp, $size);
if (!preg_match('/^</', $xml)) {
$xml = '<' . $xml;
}
if ($xml === "") {
return null;
}
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xml, $val, $index);
xml_parser_free($xml_parser);
return array($val, $index);
}
function find_xmpp($fp, $tag, $value=null, &$ret=null) {
static $val = null, $index = null;
do {
if ($val === null && $index === null) {
list($val, $index) = recv_xml($fp);
if ($val === null || $index === null) {
return false;
}
}
foreach ($index as $tag_key => $tag_array) {
if ($tag_key === $tag) {
if ($value === null) {
if (isset($val[$tag_array[0]]['value'])) {
$ret = $val[$tag_array[0]]['value'];
}
return true;
}
foreach ($tag_array as $i => $pos) {
if ($val[$pos]['tag'] === $tag && isset($val[$pos]['value']) &&
$val[$pos]['value'] === $value) {
$ret = $val[$pos]['value'];
return true;
}
}
}
}
$val = $index = null;
} while (!feof($fp));
return false;
}
function xmpp_connect($options, $access_token) {
global $STREAM_XML, $AUTH_XML, $RESOURCE_XML, $SESSION_XML, $CLOSE_XML, $START_TLS;
$fp = open_connection($options['server']);
if (!$fp) {
return false;
}
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp, 'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) {
return false;
}
send_xml($fp, $START_TLS);
if (!find_xmpp($fp, 'PROCEED', null, $proceed)) {
return false;
}
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp, 'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) {
return false;
}
send_xml($fp, $AUTH_XML);
if (!find_xmpp($fp, 'CHALLENGE', null, $challenge)) {
return false;
}
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_array);
$resp_array = array(
'method' => $challenge_array['method'],
'nonce' => $challenge_array['nonce'],
'access_token' => $access_token,
'api_key' => $options['app_id'],
'call_id' => 0,
'v' => '1.0',
);
$response = http_build_query($resp_array);
$xml = '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">'.
base64_encode($response).'</response>';
send_xml($fp, $xml);
if (!find_xmpp($fp, 'SUCCESS')) {
return false;
}
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp,'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'STREAM:FEATURES')) {
return false;
}
send_xml($fp, $RESOURCE_XML);
if (!find_xmpp($fp, 'JID')) {
return false;
}
send_xml($fp, $SESSION_XML);
if (!find_xmpp($fp, 'SESSION')) {
return false;
}
send_xml($fp, $MESSAGE);
if (!find_xmpp($fp, 'BODY')) {
return false;
}
send_xml($fp, $CLOSE_XML);
print ("Authentication complete<br>");
fclose($fp);
return true;
}
function get_access_token(){
$token=new Facebook(array("AppId"=>"my app id","AppSecret"=>"my app secret"));
$token=$facebook->getAccessToken();
return $token;
}
function _main() {
require_once("facebook.php");
$app_id='app id';
$app_secret='app secret';
$my_url = "http://localhost/message.php";
$uid = 'cyberkiller.nishchal#chat.facebook.com';
$access_token = get_access_token();
$options = array(
'uid' => $uid,
'app_id' => $app_id,
'server' => 'chat.facebook.com',
);
if (xmpp_connect($options, $access_token)) {
print "Done<br>";
} else {
print "An error ocurred<br>";
}
}
_main();
so what do I need to do to send a message to that user through this, i tried to create a xml with the message but got strucked there, can any one please suggest something, When I run the code, socket enable crypto is being executed after that it is taking some time like 20 secs, then it displays an error occured, do I have to remove the send_xml($fp,$STREAM_XML); for the second time after the stream_socket_enable_crypto($fp, false, STREAM_CRYPTO_METHOD_TLS_CLIENT);
I changed the second parameter of this call to false because I don't have an ssl connection, what should I do next?
Use Facebook ID instead of the url username.Get it by requesting http://graph.facebook.com/{username}
Then replace it on "from" and "to" attributes.Also remove the hyphen on "from" attribute, or just remove all of it (from my experience its still going to work).Hyphen on "to" attribute is mandatory.

Merging times in php

I'm trying to find the best way to merges times ... working on a schedule where users have 2 things :
Availabilities and Assigned Hours for X days.
The structure is the same for both and it look like this :
For a specific date let say (2012-10-07) the availability :
[2012-10-07]
[0][start_time] => 08:30
[end_time] => 13:30
[1][start_time] => 16:30
[end_time] => 23:30
Now for that specific day , he might be assigned and the result of my query look like :
[2012-10-07][0][start_time] => 08:30
[end_time] => 09:30
[1][start_time] => 10:30
[end_time] => 11:30
[2][start_time] => 17:00
[end_time] => 18:30
The results of the merge should look like :
[2012-10-07] [0][start_time]=> 08:30
[start_time]=> 09:30
[assigned]=> true
[1][start_time]=> 09:30
[start_time]=> 10:30
[assigned]=> false
[2][start_time]=> 10:30
[start_time]=> 11:30
[assigned]=> true
[3][start_time]=> 11:30
[start_time]=> 13:30
[assigned]=> false
[4][start_time]=> 16:30
[start_time]=> 17:00
[assigned]=> false
[5][start_time]=> 16:30
[start_time]=> 17:00
[assigned]=> false
[6][start_time]=> 17:00
[start_time]=> 18:30
[assigned]=> true
[7][start_time]=> 18:30
[start_time]=> 23:30
[assigned]=> false
Now when joining both on the calendar the availabilities are in green(false) and assigned in red (assigned = true) .
What i did was loop on availabilities , convert the start/end time to UNIX timestamps and then loop on each assigned time and converted to UNIX timestamps .
Then testing all cases if the time is inside the availability or if its outside , add a temp array and loop while no changes are made to the final array .
(Because each time i generate a new time i have to loop again on the assigned hours)
it works but i dont like the way I'm doing it ... is there a better way ?
UPDATE :
For those who want to see the full working code here it is :
function removeSessionsFromSchedule($schedule,$remove){
$modified = false;
if(is_array($schedule) && count($schedule) > 0 && is_array($remove) && count($remove) > 1) {
if($modified) {
break;
}
$pos = 0;
$countdispo = count($dispo);
foreach($schedule as $s => $dispo) {
$pos = 0;
$countdispo = count($dispo);
foreach($dispo as $d) {
$abs = $remove[$s];
$counter = 0;
// dispo debut/end
$dis_s = strtotime($d['heure_debut']);
$dis_e = strtotime($d['heure_fin']);
if(is_array($abs) && count($abs) > 0) {
foreach($abs as $a) {
// absence start/end
$abs_s = strtotime($a['heure_debut']);
$abs_e = strtotime($a['heure_fin']);
// (2) [a_s]---[ds - de]---[a_e]
if($abs_s <= $dis_s && $abs_e >= $dis_e) {
// delete availabilities
unset($schedule[$s][$pos]);
$modified = false;
}
// (7)[as == ds] && [ae < de]
else if($abs_s == $dis_s && $abs_e < $dis_e) {
unset($schedule[$s][$pos]);
$schedule[$s][$pos] = $d;
$schedule[$s][$pos]['heure_debut'] = date("H:i",$abs_e);
$schedule[$s][$pos]['heure_fin'] = date("H:i",$dis_e);
$modified = true;
break;
}
// (6) [ds -de] --- [as ae] return dispo as is
else if($abs_s >= $dis_e){
unset($schedule[$s][$pos]);
$schedule[$s][$pos] =$d;
$modified = false;
}
// (5)[as ae] [ds -de] --- return dispo as is
else if($abs_e <= $dis_s){
unset($schedule[$s][$pos]);
$schedule[$s][$pos]= $d;
$modified = false;
}
// (1)[ds] --- [as] --- [ae] --- [de] (duplicate dis with new times)
else if($abs_s > $dis_s && $abs_e <= $dis_e) {
// new times as : // s1 = ds-as && s2 = ae-de
unset($schedule[$s][$pos]);
$schedule[$s][$pos] =$d;
$schedule[$s][$pos+1] =$d;
$schedule[$s][$pos]['heure_debut'] = date("H:i",$dis_s);
$schedule[$s][$pos]['heure_fin'] = date("H:i",$abs_s);
$schedule[$s][$pos + 1]['heure_debut'] = date("H:i",$abs_e);
$schedule[$s][$pos + 1]['heure_fin'] = date("H:i",$dis_e);
//$pos++;
$modified = true;
break;
}
// (3)[as] -- [ds] --- [ae] -- [de]
else if($abs_s < $dis_s && $abs_e < $dis_e) {
unset($schedule[$s][$pos]);
$schedule[$s][$pos] =$d;
$schedule[$s][$pos]['heure_debut'] = date("H:i",$abs_e);
$schedule[$s][$pos]['heure_fin'] = date("H:i",$dis_e);
$modified = true;
break;
}
// (4) [ds]---[as]--- [de]--- [ae]
else if($abs_s > $dis_s && $abs_s < $dis_e && $abs_e > $dis_e) {
unset($schedule[$s][$pos]);
$schedule[$s][$pos] =$d;
$schedule[$s][$pos]['heure_debut'] = date("H:i",$dis_s);
$schedule[$s][$pos]['heure_fin'] = date("H:i",$abs_s);
$modified = true;
break;
}
else {$modified = false ;}
}
} else {$modified =false;}
$pos++;
}
}
}
else {$modified = false;}
if($modified) {
$schedule = removeSessionsFromSchedule($schedule,$remove);
}
return $schedule;
}
The Function that will merge the times :
function mergeSessionFromSchedule($schedule ,$seances) {
$sessions = removeSessionsFromSchedule($schedule,$seances);
$mergedSessions = array_merge_recursive($sessions , $seances);
foreach($mergedSessions as $s => $val) {
$sortedSessions[$s] = subval_sort_by_time($val,'heure_debut');
}
return $sortedSessions ;
}
Helpers :
function subval_sort_by_time($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtotime($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
Here is my solution:
<?php
class SessionHandler {
private $keys = array();
private $times = array();
private $slots = array();
private $merged = array();
function __construct($available, $assigned) {
$this->times = array(
'available' => $available,
'assigned' => $assigned
);
$this->slots = array(
'available' => array(),
'assigned' => array(),
'excluded' => array()
);
$this->getKeys($this->times['available']);
$this->loadSessions($this->keys[0], $this->keys[1]);
}
private function getKeys($arr) {
if (count($arr)) {
$this->keys = array_keys($arr[0]);
} else {
throw new Exception('Invalid array format');
}
}
private function loadSessions($start, $end) {
foreach ($this->times as $type => $periods) {
foreach ($periods as $hours) {
$this->slots[$type][] = $hours[$start].'-'.$hours[$end];
$this->merged[] = strtotime($hours[$start]);
$this->merged[] = strtotime($hours[$end]);
}
}
$this->merged = array_unique($this->merged);
sort($this->merged);
$hours = $this->times['available'];
for ($i = 0; $i < count($hours) - 1; $i++) {
$this->slots['excluded'][] = $hours[$i][$end].'-'.$hours[$i + 1][$start];
}
}
public function mergeSessions() {
$result = array();
for ($i = 0; $i < count($this->merged) - 1; $i++) {
$start_hour = date('H:i', $this->merged[$i]);
$end_hour = date('H:i', $this->merged[$i + 1]);
$slot = $start_hour . '-' . $end_hour;
if (!in_array($slot, $this->slots['excluded'])) {
$assigned = in_array($slot, $this->slots['assigned']);
$result[] = array(
$this->keys[0] => $start_hour,
$this->keys[1] => $end_hour,
'assigned' => $assigned ? "true" : "false"
);
}
}
return($result);
}
}
$availability = array(
'2012-10-07' => array(
array('start_time' => '08:30', 'end_time' => '13:30'),
array('start_time' => '16:30', 'end_time' => '23:30')
)
);
$assignments = array(
'2012-10-07' => array(
array('start_time' => '08:30', 'end_time' => '09:30'),
array('start_time' => '10:30', 'end_time' => '11:30'),
array('start_time' => '17:00', 'end_time' => '18:30')
)
);
$sessions = array();
foreach ($availability as $day => $available) {
$assigned = isset($assignments[$day]) ? $assignments[$day] : array();
$SH = new SessionHandler($available, $assigned);
$sessions[$day] = $SH->mergeSessions();
}
?>
<!DOCTYPE html>
<html>
<body>
<pre><?php print_r($sessions) ?></pre>
</body>
</html>