loadModel('Cmsusers'); $this->loadModel('Usergroups'); $this->loadModel('CmsuserUsergroups'); } public function preMain($schedule = null) { if (!$schedule) { $this->out(); $this->err('Missing the parameter \'schedule\''); $this->out('Please set the parameter along with the command.'); $this->out(); $this->out('eg :- backend start pre main "*/60 * * * *"'); $this->out(); $this->out('* * * * *'); $this->out('| | | | |'); $this->out('| | | | |'); $this->out('| | | | \----- day of week (0 - 6) (0 to 6 are Sunday to Saturday,'); $this->out('| | | | or use names)'); $this->out('| | | \---------- month (1 - 12)'); $this->out('| | \--------------- day of month (1 - 31)'); $this->out('| \-------------------- hour (0 - 23)'); $this->out('\------------------------- min (0 - 59)'); $this->out(); $schedule = $this->in('Please pass in the schedule in the above mentioned format'); $this->clear(); } $schedule = trim($schedule); if ($this->validateSchedule($schedule)) { $this->out('Setting up...'); $cron = $schedule . ' ' . USER_COUNTRY_NAME_CODE; if ($this->cronjobExists(USER_COUNTRY_NAME_CODE)) { $this->out('Existing backend job found. Removing ...'); $removeCommand = "crontab -l | grep -v '" . USER_COUNTRY_NAME_CODE . "' | crontab -"; shell_exec($removeCommand); $this->out("Removed existing backend job!"); } $this->appendCronjob($cron); $this->out('New backend job added successfully!'); } } // */10 * * * cd /var/www/html && bin/cake processData public function main() { $this->out('Start'); $plan_id_array = $this->objectToArray(json_decode(RTG_PLAN_ID)); $total_record_processed = 0; foreach($plan_id_array as $index=>$stripePlanId){ \Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY); $Subscriptions = \Stripe\Subscription::all( array( 'limit' => 110, // in the first time, put 5 then 10, 15, 20 etc....till 50 'created' => array( 'gte' => strtotime('-40 min'), 'lte' => strtotime('0 min') ), //'starting_after' => 'sub_BQdvHBBf8lfjsR', "plan" => $stripePlanId ) ); /* echo "
";
        	 print_r( $Subscriptions->__toArray(true));
        	  
        	echo "
"; */ foreach ($Subscriptions->data as $subscription) { // Do something with $subscription //$subscription->id $customerObj = \Stripe\Customer::retrieve($subscription->customer); $customer = $customerObj->__toArray(true); //$customer = $customerArray['sources']['data'][0]; $cmsuser = []; $isRecordExist = $this->checkemail($customer['email']); if(!$isRecordExist){ //check success subscription in last 50 mins $successfulCharge = false; $chargeList = \Stripe\Charge::all( array( 'limit' => 110, // in the first time, put 5 then 10, 15, 20 etc....till 50 'created' => array( 'gte' => strtotime('-50 min'), 'lte' => strtotime('0 min') ), "failure_code"=>null, "customer" => $customer['id'] ) ); foreach ($chargeList->data as $charge) { // Do something with $subscription if(empty($charge->failure_code)) { $successfulCharge = true; break; } } /* echo "
";
        			print_r($successfulCharge);exit; */
        			
        			if($successfulCharge){
        				
        				$total_record_processed++;
        				
	        			$cmsuser = $this->Cmsusers->newEntity();
	        			$password = rand(100000,999999);
	        			$cmsuser = $this->createUser($cmsuser,["email" => $customer['email'],
	        					"password" => $password,
	        					"address_zip" => "",
	        					"stripe_customer_id" => $customer['id'],
	        					"phone" => "",
	        					"cardholder_name" => "",
	        					"permission_version" => "1",
	        					"ip" => "",
	        					"is_first_login" => "1",
	        					"package_id" => "2",
	        					"img_path" => "",
	        					"username" => $customer['email'],
	        					"language" => "en",
	        					"retype_password" => $password,
	        			]);
	        
	        			$customerName = explode("@",$customer['email']);
	        				
	        			if ($this->Cmsusers->save($cmsuser)) {
	        
	        				// add User To User Group
	        				$this->addUserToUserGroup($cmsuser->id, USER_GROUP_ID);
	        				// add User To Default Packages
	        				$this->addUserToPackages($cmsuser->id,PACKAGE_ID);
	        				$this->addUserToPackages($cmsuser->id,PACKAGE_WAVE_1_ID);
	        
	        				$template_content = array(
	        						'firstname' => $customerName[0],
	        						'user_email'=> $customer['email'],
	        						'password' => $password,
	        						'loginurl' => APP_SERVER_HOST_URL
	        				);
	        				//echo "Going to send email to :::".$customer['email'];
	        				$this->sendEmail(MANDRILL_TEMPLATE_USER_CREATION, $template_content, $cmsuser->email);
	        					
	        			}else{
	        				// echo "::::::No data added----".$customer['email']."
\n"; } } }else{ // do nothing } } } //insert logs into process logs //$total_record_processed $this->saveLogs("REG",$total_record_processed); /* echo "Customer process completed..."; exit; */ $this->out('End'); $this->Cmsusers->shellLog(date('Y-m-d H:i:s'), "main","main"); } private function checkemail($email) { $result = false; $table_Cmsusers = TableRegistry::get("Cmsusers"); $defaultCmsusers = $table_Cmsusers->find('all') ->select(['id','email']) ->where(['Cmsusers.email'=>$email]) ->first(); // return $defaultCmsusers; if(!empty($defaultCmsusers)){ $result = true; } return $result; } public function checkUserByEmailAndStripeId($email,$stripe_customer_id) { $resultId = 0; if(!empty($email)){ $table_Cmsusers = TableRegistry::get("Cmsusers"); $defaultCmsusers = $table_Cmsusers->find('all') ->select(['id','email']) ->where(['Cmsusers.email'=>$email, 'Cmsusers.stripe_customer_id'=>$stripe_customer_id]) ->first(); if(!empty($defaultCmsusers)){ $resultId = $defaultCmsusers->id; } } return $resultId; } private function addUserToUserGroup($user_id, $usergroup_id) { $table_user_groups_user = TableRegistry::get("CmsuserUsergroups"); $entity = $table_user_groups_user->newEntity(); $entity->cms_user_id = $user_id; $entity->usergroup_id = $usergroup_id; if($table_user_groups_user->save($entity)){ return true; } else { return false; } } public function addUserToPackages($user_id, $package_id) { $table_member_packages = TableRegistry::get("MemberPackages"); $entity = $table_member_packages->newEntity(); $entity->member_id = $user_id; $entity->package_id = $package_id; $entity->status = 1; $entity->created_on = date('Y-m-d h:i:s'); if($table_member_packages->save($entity)){ return true; } else { return false; } } private function objectToArray($d) { if (is_object($d)) $d = get_object_vars($d); return is_array($d) ? array_map(__METHOD__, $d) : $d; } private function saveLogs($process_name,$number_of_record_processed){ $logTable = TableRegistry::get("ProcessLogs"); $entity = $logTable->newEntity(); $entity->process_name = $process_name; $entity->number_of_record_processed = $number_of_record_processed; $entity->created_on = date('Y-m-d h:i:s'); $logTable->save($entity); } private function saveStripeCustsomerLog($type,$stripe_customer_id){ $logTable = TableRegistry::get("StripeCustomerLogs"); $entity = $logTable->newEntity(); $entity->type = $type; $entity->stripe_customer_id = $stripe_customer_id; $entity->activity_datetime = date('Y-m-d h:i:s'); $logTable->save($entity); } public function failSubscription() { $this->out('Start failure'); // $plan_id_array = $this->objectToArray(json_decode(RTG_PLAN_ID)); $total_record_processed = 0; //if(!empty($plan_id_array)){ // foreach($plan_id_array as $index=>$stripePlanId){ //$this->saveLogs("FS1",$total_record_processed); \Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY); // $Subscriptions = \Stripe\Subscription::all( // array( // 'limit' => 110, // in the first time, put 5 then 10, 15, 20 etc....till 50 // 'created' => array( // 'gte' => strtotime('-10 min'), // 'lte' => strtotime('0 min') // ), // // "cancel_at_period_end" => true, // "plan" => $stripePlanId, // //'starting_after' => 'sub_BQdvHBBf8lfjsR', // ) // ); $Subscriptions = \Stripe\Charge::all( array( 'limit' => 110, // in the first time, put 5 then 10, 15, 20 etc....till 50 'created' => array( 'gte' => strtotime('-15 min'), 'lte' => strtotime('0 min') ) ) ); foreach ($Subscriptions->data as $subscription) { // Do something with $subscription if(!empty($subscription->failure_code)) { $customerObj = \Stripe\Customer::retrieve($subscription->customer); $customer = $customerObj->__toArray(true); $cmsuser = []; $user_id = $this->checkUserByEmailAndStripeId($customer['email'],$customer['id']); if(!empty($user_id)) { $availableCmsUserGroups = $this->CmsuserUsergroups->find('all',[ 'conditions'=>[ 'CmsuserUsergroups.cms_user_id'=>$user_id, 'CmsuserUsergroups.usergroup_id'=>USER_GROUP_ID ] ]); if(!empty($availableCmsUserGroups->toArray())){ $total_record_processed++; $this->CmsuserUsergroups->deleteAll( [ 'CmsuserUsergroups.cms_user_id' => $user_id, 'CmsuserUsergroups.usergroup_id' => USER_GROUP_ID ], false ); $this->saveStripeCustsomerLog(1,$customer['id']); } } } // } // } } //$total_record_processed $this->saveLogs("FSB",$total_record_processed); $this->out('End failure'); } public function successCharge() { $this->out('Start success'); // $plan_id_array = $this->objectToArray(json_decode(RTG_PLAN_ID)); $total_record_processed = 0; // if(!empty($plan_id_array)){ // foreach($plan_id_array as $index=>$stripePlanId){ \Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY); $chargeList = \Stripe\Charge::all( array( 'limit' => 110, // in the first time, put 5 then 10, 15, 20 etc....till 50 'created' => array( 'gte' => strtotime('-17 min'), 'lte' => strtotime('0 min') ), "failure_code"=>null, ) ); foreach ($chargeList->data as $subscription) { // Do something with $subscription //$subscription->id $customerObj = \Stripe\Customer::retrieve($subscription->customer); $customer = $customerObj->__toArray(true); //$customer = $customerArray['sources']['data'][0]; $cmsuser = []; // Check Cmsuser table for this user $user_id = $this->checkUserByEmailAndStripeId($customer['email'],$customer['id']); if(!empty($user_id)){ // $this->loadModel('CmsuserUsergroups'); // check user_id in CmsuserUsergroups table $availableCmsUserGroups = $this->CmsuserUsergroups->find('all',[ 'conditions'=>[ 'CmsuserUsergroups.cms_user_id'=>$user_id, 'CmsuserUsergroups.usergroup_id'=>USER_GROUP_ID ] ]); // pr($availableCmsUserGroups); die; if(empty($availableCmsUserGroups->toArray())) { $total_record_processed++; // add User To User Group if($this->addUserToUserGroup($user_id, USER_GROUP_ID)){ $template_content = array( 'loginurl' => APP_SERVER_HOST_URL ); $this->saveStripeCustsomerLog(2,$customer['id']); //echo "Going to send email to :::".$customer['email']; $this->sendEmail(MANDRILL_TEMPLATE_USER_REACTIVATION, $template_content, $customer['email']); } } } } //} // } //$total_record_processed $this->saveLogs("CRG",$total_record_processed); $this->out('End success'); $this->Cmsusers->shellLog(date('Y-m-d H:i:s'), "successCharge","successCharge"); } public function checkSubscription(){ $plan_id_array = $this->objectToArray(json_decode(RTG_PLAN_ID)); $total_record_processed = 0; foreach($plan_id_array as $index=>$stripePlanId){ \Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY); $Subscriptions = \Stripe\Subscription::all( array( 'limit' => 110, // in the first time, put 5 then 10, 15, 20 etc....till 50 'created' => array( 'gte' => strtotime('-25 min'), 'lte' => strtotime('0 min') ), //'starting_after' => 'sub_BQdvHBBf8lfjsR', "plan" => $stripePlanId ) ); /* echo "
";
    		 print_r( $Subscriptions->__toArray(true));
    		  
    		echo "
"; */ foreach ($Subscriptions->data as $subscription) { // Do something with $subscription //$subscription->id $customerObj = \Stripe\Customer::retrieve($subscription->customer); $customer = $customerObj->__toArray(true); //$customer = $customerArray['sources']['data'][0]; $cmsuser = []; $isRecordExist = $this->checkemail($customer['email']); if(!$isRecordExist){ $total_record_processed++; $cmsuser = $this->Cmsusers->newEntity(); $password = rand(100000,999999); $cmsuser = $this->createUser($cmsuser,["email" => $customer['email'], "password" => $password, "address_zip" => "", "stripe_customer_id" => $customer['id'], "phone" => "", "cardholder_name" => "", "permission_version" => "1", "ip" => "", "is_first_login" => "1", "package_id" => "2", "img_path" => "", "username" => $customer['email'], "language" => "en", "retype_password" => $password, ]); $customerName = explode("@",$customer['email']); if ($this->Cmsusers->save($cmsuser)) { // add User To User Group $this->addUserToUserGroup($cmsuser->id, USER_GROUP_ID); // add User To Default Packages $this->addUserToPackages($cmsuser->id,PACKAGE_ID); $this->addUserToPackages($cmsuser->id,PACKAGE_WAVE_1_ID); $template_content = array( 'firstname' => $customerName[0], 'user_email'=> $customer['email'], 'password' => $password, 'loginurl' => APP_SERVER_HOST_URL ); //echo "Going to send email to :::".$customer['email']; $this->sendEmail(MANDRILL_TEMPLATE_USER_CREATION, $template_content, $cmsuser->email); }else{ // echo "::::::No data added----".$customer['email']."
\n"; } }else{ // do nothing } } } } private function createUser($cmsuser,$data) { $cmsuser = $this->Cmsusers->patchEntity($cmsuser, $data); $cmsuser->reset_password_token = ''; $cmsuser->created_on = date('Y-m-d H:i:s'); // date('Y-m-d H:i:s', strtotime("-61 day")); // $cmsuser->updated_on = date('Y-m-d H:i:s'); $cmsuser->status = STATUS_ACTIVE; $cmsuser->company_id = 8; return $cmsuser; } function validateSchedule($schedule) { $scheduleParamArray = preg_split('/\s+/', $schedule); $count = count($scheduleParamArray); if ($count != 5) { $this->error("Invalid schedule"); } return true; } function cronjobExists($command) { $cronjob_exists = false; $crontab = null; exec('crontab -l', $crontab); if (isset($crontab) && is_array($crontab)) { foreach ($crontab as $tab) { if (strpos($tab, $command) !== false) { $cronjob_exists = true; } } } return $cronjob_exists; } function appendCronjob($command) { $output = null; if (is_string($command) && !empty($command)) { $executingCommand = 'echo -e "`crontab -l`\n' . $command . '" | crontab -'; exec($executingCommand, $output); } return $output; } //For closeing tickets that are not replied for more than 7 days public function closeTicket() { $closed_time = CLOSE_TICKET_TIME -1; $date = date("Y-m-d H:i:s",strtotime('-'.$closed_time.' days')); $supportTable = TableRegistry::get('supports'); $supports = $supportTable->find()->where(['reply_date <'=> $date, 'status'=>1])->limit(20); foreach($supports as $support){ $support->status = SUPPORT_STATUS_CLOSED; $supportTable->save($support); $template_content = [ 'ticket_id'=>$support->id ]; $this->sendEmail(CLOSE_TICKET, $template_content, $support->email,$support->title); } $this->Cmsusers->shellLog(date('Y-m-d H:i:s'), "closeTicket","closeTicket"); } //For archieving tickets that are not replied for more than 20 days function archieveTicket(){ $archive_time = ARCHIEVE_TICKET_TIME -1; $date = date("Y-m-d H:i:s",strtotime('-'.$archive_time .' days')); $supportTable = TableRegistry::get('supports'); $supports = $supportTable->find()->where(['reply_date <'=> $date, 'status'=>2])->limit(20); $current_time = $this->getSystemCurrentTimeStamp(); foreach($supports as $closedsupportObj){ $archievesupportTable = TableRegistry::get('supports_archieved'); $archievesupportObj = $archievesupportTable->newEntity(); $archievesupportObj->id = $closedsupportObj->id; $cms_user_id = $archievesupportObj->cms_user_id = $closedsupportObj->cms_user_id; // remove auto increment and assign direct object in one line $archievesupportObj->priority = $closedsupportObj->priority; $archievesupportObj->parent_id = $closedsupportObj->parent_id; $archievesupportObj->user_type = $closedsupportObj->user_type; $archievesupportObj->email = $closedsupportObj->email; $archievesupportObj->name = $closedsupportObj->name; $archievesupportObj->title = $closedsupportObj->title; $archievesupportObj->description = $closedsupportObj->description; $file_name = $archievesupportObj->file_name = $closedsupportObj->file_name; $archievesupportObj->status = SUPPORT_STATUS_ARCHIEVED; $archievesupportObj->is_read = $closedsupportObj->is_read; $archievesupportObj->reply_date = $closedsupportObj->reply_date; $archievesupportObj->created_on = !empty($closedsupportObj->created_on) ? $closedsupportObj->created_on : $current_time; if($archievesupportTable->save($archievesupportObj)){ $supportTable->delete($closedsupportObj); if (!is_dir(WWW_ROOT.'media/companies/'.$cms_user_id.'/archieved/')) { mkdir(WWW_ROOT.'media/companies/'.$cms_user_id.'/archieved/', 0777, true); } if(!empty($file_name)){ $active_dir = WWW_ROOT.'media/companies/'.$cms_user_id.'/tickets/'.$file_name; $archieve_dir = WWW_ROOT.'media/companies/'.$cms_user_id.'/archieved/'.$file_name; if (copy( $active_dir, $archieve_dir )) { unlink($active_dir); } } } } $this->Cmsusers->shellLog(date('Y-m-d H:i:s'), "archieveTicket","archieveTicket"); } }