How to paginate results with Horde Imap Client? - php

I have a problem, I am currently doing a search by date range of maximum 10 days and the issue is that if there are more than 10 messages or there is a total of 38 messages it takes 4 to 5 minutes to load the data, so I wanted to know if there is a way to bring it paginated directly when doing the query in Horde.
public function connect($username, $password, $hostname, $port, $ssl, $folder, $debug = 0, $cache = 0)
{
$opt = [
'username' => $username,
'password' => $password,
'hostspec' => $hostname,
'port' => $port,
'secure' => $ssl,
];
if ($debug) $opt['debug'] = Log::debug("message");
if ($cache) $opt['cache'] = array(
'backend' => new \Horde_Imap_Client_Cache_Backend_Cache(array(
'cacheob' => new Horde_Cache(new Horde_Cache_Storage_File(array(
'dir' => '/tmp/hordecache'
)))
))
);
static::$folder = 'INBOX';
try {
return static::$client = new \Horde_Imap_Client_Socket($opt);
} catch (\Horde_Imap_Client_Exception $e) {
// Any errors will cause an Exception.
dd('Error');
}
}
public function searchSince($date_string)
{
try {
$query = new Horde_Imap_Client_Search_Query();
$query->dateSearch(
new Horde_Imap_Client_DateTime($date_string), Horde_Imap_Client_Search_Query::DATE_SINCE
);
$results = static::$client->search(static::$folder,$query);
} catch (\Exception $th) {
dd('Since Mail');
}
if ($results) {
static::$var = $results['match']->ids;
return true;
}
return false;
}
//I get the header data of each message (subject, date, uid, from, client name)
public function next(){
if ($var = next(static::$var)) {
static::$id = $var;
$headers = HordeImap::fetchHeaders(static::$id);
static::$clientName = $headers->getHeader('From')->getAddressList(true)->first()->__get('personal');
static::$fromEmail = $headers->getHeader('From')->getAddressList(true)->first()->__get('bare_address');
static::$subject = $headers->getHeader('subject')->__get('value');
$emailDate = $headers->getHeader('Date')->__get('value');
$unixTimestamp = strtotime($emailDate);
static::$emailDate = date('Y-m-d H:i:s',$unixTimestamp);
return true;
}
return false;
}
Controller
$mailb = new HordeImap();
$mailb->connect($userMail->client,$userMail->secret_token,$userMail->server,$userMail->port,'ssl','INDEX',1);
$msgs = $mailb->searchSince(date('d F Y', strtotime(date("Y-m-d", time()) . " -10 days")));
static::$mailbox = [];
if($msgs) while($mailb->next()){
static::$mailbox[] = [
'uid' => $mailb::$id,
'from' => $mailb::$fromEmail,
'client'=> $mailb::$clientName,
'date' => $mailb::$emailDate,
'subject'=> $mailb::$subject,
];
}
// I page the array once I have obtained all the contents.
$page = null;
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = static::$mailbox instanceof Collection ? static::$mailbox : Collection::make(static::$mailbox);
dd(new LengthAwarePaginator($items->forPage($page, 5), $items->count(), 5, null, []));

Related

How to use this php class

I need to use the functions of this class,I wrote a code but the output was empty,need echo data from all functions.
I correctly entered the connection requirements,script use Json-rpc for request,The port is open on the server
I don't know how to use this class
my class
<?php
require_once("jsonrpc.inc");
class IBSjsonrpcClient {
function IBSjsonrpcClient($server_ip="127.0.0.1", $auth_name="user", $auth_pass="pass", $auth_type="ADMIN", $server_port="1237", $timeout=1800){
$this->client = new jsonrpc_client($server_ip. ':' . $server_port);
$this->auth_name = $auth_name;
$this->auth_pass = $auth_pass;
$this->auth_type = $auth_type;
$this->timeout = $timeout;
}
function sendRequest($server_method, $params_arr){
/*
Send request to $server_method, with parameters $params_arr
$server_method: method to call ex admin.addNewAdmin
$params_arr: an array of parameters
*/
$params_arr["auth_name"] = $this->auth_name;
$params_arr["auth_pass"] = $this->auth_pass;
$params_arr["auth_type"] = $this->auth_type;
$response = $this->client->send($server_method, $params_arr, $this->timeout);
$result = $this->__returnResponse($response);
unset($response);
return $result;
}
function __returnResponse($response){
if ($response == FALSE)
return $this->__returnError("Error occured while connecting to server");
else if ($response->faultCode() != 0)
return $this->__returnError($response->faultString());
else
return $this->__returnSuccess($response->value());
}
function __returnError($err_str){
return array(FALSE, $err_str);
}
function __returnSuccess($value){
return array(TRUE, $value);
}
function getUserInfoByUserID($user_id){
return $this->sendRequest("user.getUserInfo", array("user_id"=>(string)$user_id));
}
function getUserInfoByNormalUserName($normal_username){
return $this->sendRequest("user.getUserInfo", array("normal_username"=>$normal_username));
}
function getBasicUserInfoByNormalUserName($normal_username){### for Zahedan Telecom, ticket 34083
$result = $this->sendRequest("user.getUserInfo", array("normal_username"=>$normal_username));
if(!$result[0]){
return $result;
}
$info = $result[1];
return array(
"user_id" => $info["basic_info"]["user_id"],
"normal_username" => $info["attrs"]["normal_username"],
"remaining_days" => $info["remaining_days"],
"remaining_mega_bytes" => $info["remaining_mega_bytes"],
"credit" => $info["basic_info"]["credit"],
"group_name" => $info["basic_info"]["group_name"]
);
}
function getUserInfoBySerial($serial){
return $this->sendRequest("user.getUserInfo", array("serial"=>$serial));
}
function addNewUser($count, $credit, $isp_name, $group_name, $credit_comment=""){
return $this->sendRequest("user.addNewUsers", array(
"count" => $count,
"credit" => $credit,
"isp_name" => $isp_name,
"group_name" => $group_name,
"credit_comment" => $credit_comment
));
}
function setNormalUserAuth($user_id, $username, $password){
return $this->setUserAttributes($user_id, array(
"normal_user_spec" => array(
"normal_username"=>$username,
"normal_password"=>$password,
)
));
}
}
?>
example code for use function in class but empty array
<?php
require "ibs-jsonrpc-client.php";
$ibs = new IBSjsonrpcClient();
$a = $ibs->getBasicUserInfoByNormalUserName("user1");
print_r($a);
?>

How to connect to redis with class

In my project, I have defined two classes Datasource and RedisHelper in Datasource.php file.
Datasource is for getting data from redis.
RedisHelper is for connecting redis.
Here is code of Datasource.php:
<?php
namespace common;
class Datasource {
public static $redises = array();
public function __construct() {}
public static function getRedis($config_name = NULL, $server_region = 'default') {
global $config;
$redis_config = $config['redis'][$config_name];
try {
self::$redises[$config_name] = RedisHelper::instance($config_name, $redis_config, $server_region);
} catch (Exception $e) {
self::$redises[$config_name] = null;
}
return self::$redises[$config_name];
}
}
class RedisHelper {
private $_config_name = "";
private $_redis_config = null;
private $_server_region = null;
public $timeout = 1;
private $_redis = null;
private static $instances = array();
private static $connect_error = 0;
private $call_error = 0;
private function __construct($config_name, $redis_config, $server_region) {
if ($config_name && $redis_config && $server_region) {
$this->_config_name = $config_name;
$this->_redis_config = $redis_config;
$this->_server_region = $server_region;
$this->timeout = isset($this->_redis_config[$server_region]['timeout']) ? $this->_redis_config[$server_region]['timeout'] : $this->timeout;
try {
$this->_redis = new \redis();
$this->_redis->connect($this->_redis_config[$server_region]['host'], $this->_redis_config[$server_region]['port'], $this->timeout);
} catch (Exception $e) {
$this->_redis = null;
}
} else {
$this->_redis = null;
}
}
public static function instance($config_name, $redis_config, $server_region) {
if (!$config_name || !$redis_config) {
return false;
}
$only_key = $config_name . ':' . $server_region;
if (!isset(self::$instances[$only_key])) {
try {
self::$instances[$only_key] = new RedisHelper($config_name, $redis_config, $server_region);
self::$connect_error = 0;
} catch (Exception $e) {
if (self::$connect_error < 2) {
self::$connect_error += 1;
return RedisHelper::instance($config_name, $redis_config, $server_region);
} else {
self::$connect_error = 0;
self::$instances[$only_key] = new RedisHelper(false, false, false);
}
}
}
$redis_config_info = array();
if ($redis_config && isset($redis_config[$server_region]) && isset($redis_config[$server_region]['password'])) {
$redis_config_info = $redis_config[$server_region];
unset($redis_config_info['password']);
}
self::$connect_error = 0;
return self::$instances[$only_key];
}
}
Here is redis.ini.php file:
<?php
$config['redis']['instance1'] = array(
'default' => array(
'host' => '127.0.0.1',
'port' => '6379',
'timeout' => 5,
'pconnect' => 1,
'password' => '',
)
);
$config['redis']['instance2'] = array(
'default' => array(
'host' => '127.0.0.1',
'port' => '6379',
'timeout' => 5,
'pconnect' => 1,
'password' => '',
)
);
Now I want to connect redis with classes, Here is my html code:
<body style="height:100%" >
<div><h3>haha</h3></div>
<?php
include "o1ws1v/class/common/Datasource.php";
include 'o1ws1v/conf/redis.ini.php';
$redis_obj = common\Datasource::getRedis('instance1');
$value = $redis_obj->get("xie");
echo "get key xie is:".$value."\n";
?>
</body>
But It works fail. $redis_obj is nothing in my console. Who can help me?

Guzzle async POST requests not being sent

I'm trying to make 4 async search calls (POST HTTP request) to search 4 database tables at the same time, then wait for all of them to finish (asynchronously), combine the results and return them to the user.
Here is my code:
public static function async_search($search_words)
{
$curl = new CurlMultiHandler();
$client = new Client([
'base_uri' => 'https://mytestapi.com/',
'timeout' => 0,
]);
$finished_promisesArr = array(
'search1' => 0,
'search2' => 0,
'search3' => 0,
'search4' => 0,
);
$bodyArr = array(
'search_words' => $search_words,
);
$search1_promise = $client->requestAsync('POST', 'search1', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
echo 'got response';
$finished_promisesArr['search1'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search1'] = 1;
}
);
$search2_promise = $client->requestAsync('POST', 'search2', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search2'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search2'] = 1;
}
);
$search3_promise = $client->requestAsync('POST', 'searchCompanies', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search3'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search3'] = 1;
}
);
$search4_promise = $client->requestAsync('POST', 'searchCompaniesByIndustries', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search4'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search4'] = 1;
}
);
$promisesAggregate = GuzzleHttp\Promise\all([$search1_promise, $search2_promise, $search3_promise, $search4_promise]);
foreach ($promisesAggregate as $agg) {
$curl->tick();
}
$keep_running = true;
while ($keep_running) {
$all_processes_finished = true;
foreach ($finished_promisesArr as $promise => $status) {
if (!$status) {
$all_processes_finished = false;
}
}
if ($all_processes_finished) {
$keep_running = false;
}
}
return array();
}
Please ignore the empty array in the result and the fact that I'm not doing anything with the response.
I've got logs on the server methods and they're not even being called, and the loop continues to run infinitely.
Note that when I use the request method instead of requestAsync I do get the correct result.
Any ideas here?
Thank's!
Just call $promisesAggregate->wait() after you get it from GuzzleHttp\Promise\all function.
It means the same as your code, but does it right (your wait code calls ->tick() only once and this is the mistake).

mongodb update exception 'document fragment is too large'

Updating my collection record field with 'MongoBinData', exception is triggered:
"document fragment is too large: 21216456, max: 16777216"
I find some web discussion about 'allowDiskUse:true' for aggregate, but nothing ubout 'update'.
Here a part of code in PHP:
try {
$criteria = array( '_id' => $intReleaseId);
$fileData = file_get_contents( $_FILES[ $fileKey]["tmp_name"]);
$mongoBinData = new MongoBinData( $fileData, MongoBinData::GENERIC)
$docItem['data'] = $mongoBinData;
$docItem['fileType'] = $strFileType;
$docItem['fileSize'] = $intFileSize;
$docItem['fileExtension'] = $strFileExtension;
$docItem['fileName'] = $strFileName;
$options = array( "upsert" => true,
'safe' => true, 'fsync' => true,
'allowDiskUse' => true ); // this option doesn't change anything
$reportJson = self::GetCollection('releases')->update( $criteria, $docItem, $options);
...
MongoDb release is db version v3.0.6
Some idea ?
Self resolved.
Use gridFS is immediate and simple.
$_mongo = new MongoClient();
$_db = $_mongo->selectDB($_mDbName);
$_gridFS = $_db->getGridFS();
/* */
function saveFileData($intReleaseId, $binData) {
$criteria = array( '_id' => $intReleaseId);
// if exist or not, remove previous value
try {
$_gridFS->remove( $criteria);
}
catch(Exception $e) {}
// store new file content
$storeByteCompleted = false;
try {
$reportId = $_gridFS->storeBytes(
$binData,
array("_id" => $intReleaseId));
if ($reportId == $intReleaseId) {
$storeByteCompleted = true;
}
catch(Exception $e) {}
return $storeByteCompleted;
}
function loadFileData($intReleaseId) {
$gridfsFile = null;
$binData = null;
try {
$gridfsFile = $_gridFS->get($intReleaseId);
}
catch(Exception $e) {}
if ($gridfsFile != null) {
$binData = $gridfsFile->getBytes()
}
return $binData;
}
That's all.

Upload and extract zip file in symfony 1.4

I want to upload zip file in symfony but failed to do so.
When i am uploading text ot pdf or excel file,image or single file then it is uploaded fine.
But when i tried to upload zip file it returns nothig and also there is no error log only blank page is appaear.
Im My form i have the following code.
class UploadSalaryForm extends BaseForm {
public function configure() {
// Note: Widget names were kept from old non-symfony version
$var = 'salary';
$this->setWidgets(array(
'EmpID' => new sfWidgetFormInputHidden(),
'seqNO' => new sfWidgetFormInputHidden(),
'MAX_FILE_SIZE' => new sfWidgetFormInputHidden(),
'ufile' => new sfWidgetFormInputFile(),
'txtAttDesc' => new sfWidgetFormInputText(),
'screen' => new sfWidgetFormInputHidden(),
'commentOnly' => new sfWidgetFormInputHidden(),
));
$this->setValidators(array(
'EmpID' => new sfValidatorNumber(array('required' => true, 'min'=> 0)),
'seqNO' => new sfValidatorNumber(array('required' => false, 'min'=> 0)),
'MAX_FILE_SIZE' => new sfValidatorNumber(array('required' => true)),
'ufile' => new sfValidatorFile(array('required' => false)),
//'ufile', new sfValidatorFileZip(array('required' => false)),
'txtAttDesc' => new sfValidatorString(array('required' => false)),
'screen' => new sfValidatorString(array('required' => true,'max_length' => 50)),
'commentOnly' => new sfValidatorString(array('required' => false)),
));
// set up your post validator method
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array(
'callback' => array($this, 'postValidate')
))
);
}
public function postValidate($validator, $values) {
// If seqNo given, ufile should not be given.
// If seqNo not given and commentsonly was clicked, ufile should be given
$attachId = $values['seqNO'];
$file = $values['ufile'];
$commentOnly = $this->getValue('commentOnly') == "1";
if (empty($attachId) && empty($file)) {
$message = sfContext::getInstance()->getI18N()->__('Upload file missing');
$error = new sfValidatorError($validator, $message);
throw new sfValidatorErrorSchema($validator, array('' => $error));
} else if (!empty($attachId) && $commentOnly && !empty($file)) {
$message = sfContext::getInstance()->getI18N()->__('Invalid input');
$error = new sfValidatorError($validator, $message);
throw new sfValidatorErrorSchema($validator, array('' => $error));
}
return $values;
}
/**
* Save employee contract
*/
public function save() {
$empNumber = $this->getValue('EmpID');
$attachId = $this->getValue('seqNO');
$empAttachment = false;
if (empty($attachId)) {
$q = Doctrine_Query::create()
->select('MAX(a.attach_id)')
->from('EmployeeAttachment a')
->where('a.emp_number = ?', $empNumber);
$result = $q->execute(array(), Doctrine::HYDRATE_ARRAY);
if (count($result) != 1) {
throw new PIMServiceException('MAX(a.attach_id) failed.');
}
$attachId = is_null($result[0]['MAX']) ? 1 : $result[0]['MAX'] + 1;
} else {
$q = Doctrine_Query::create()
->select('a.emp_number, a.attach_id')
->from('EmployeeAttachment a')
->where('a.emp_number = ?', $empNumber)
->andWhere('a.attach_id = ?', $attachId);
$result = $q->execute();
if ($result->count() == 1) {
$empAttachment = $result[0];
} else {
throw new PIMServiceException('Invalid attachment');
}
}
//
// New file upload
//
$newFile = false;
if ($empAttachment === false) {
$empAttachment = new EmployeeAttachment();
$empAttachment->emp_number = $empNumber;
$empAttachment->attach_id = $attachId;
$newFile = true;
}
$commentOnly = $this->getValue('commentOnly');
if ($newFile || ($commentOnly == '0')) {
$file = $this->getValue('ufile');
echo "file==".$file;
$tempName = $file->getTempName();
$empAttachment->size = $file->getSize();
$empAttachment->filename = $file->getOriginalName();
$empAttachment->attachment = file_get_contents($tempName);;
$empAttachment->file_type = $file->getType();
$empAttachment->screen = $this->getValue('screen');
$empAttachment->attached_by = $this->getOption('loggedInUser');
$empAttachment->attached_by_name = $this->getOption('loggedInUserName');
// emp_id and name
}
$empAttachment->description = $this->getValue('txtAttDesc');
$empAttachment->save();
}
}
But this code is only worked for single file not for zip file.
I want to upload and extract zip file.

Categories