public function actionIndex()
 {
     if (isset($_GET['queue_id']) && !empty($_GET['queue_id'])) {
         $criteria = new CDbCriteria();
         $criteria->compare("queue_id", $_GET['queue_id']);
         BlackListedMobile::model()->deleteAll($criteria);
         Yii::app()->user->setFlash('error', '<strong><i class="fa fa-warning"></i> Black listed mobile numbers deleted!</strong>.Deleted mobile numbers can never be retrieved.');
         $this->redirect(Yii::app()->request->baseUrl . "/blacklist/default");
     }
 }
 public function actionIndex($mobileNumber)
 {
     header("Content-Type: application/json");
     $jsonMessage = array();
     $mobileNumber = doubleval($mobileNumber);
     $isBlackListed = BlackListedMobile::model()->exists("mobile_number = :mobile_number", array('mobile_number' => $mobileNumber));
     if ($isBlackListed) {
         $jsonMessage = array("status" => "blacklisted");
     } else {
         $jsonMessage = array("status" => "clean");
     }
     echo json_encode($jsonMessage);
 }
 public function download()
 {
     $fileName = $this->model->claimAccountName . ' - ' . date("Y-m-d") . '-All-entries';
     header("Pragma: public");
     header("Expires: 0");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Cache-Control: private", false);
     header("Content-Type: application/octet-stream");
     header("Content-Disposition: attachment; filename=\"{$fileName}.csv\";");
     header("Content-Transfer-Encoding: binary");
     $criteria = new CDbCriteria();
     $criteria->compare("account_id", $this->model->account_id);
     $criteria->order = "date_created DESC";
     $criteria->distinct = true;
     $records = Records::model()->findAll($criteria);
     $isFirst = true;
     foreach ($records as $curRecord) {
         $data = json_decode($curRecord->claimData, true);
         $rowData = "";
         $allowPrint = true;
         if ($isFirst) {
             //print heads
             $headers = "";
             $keys = array_keys($data);
             $headers = implode(",", $keys) . "\n";
             echo $headers;
             $isFirst = false;
         }
         /*check if mobile number exists at blacklist mobile nums*/
         $mobileNumMatch = preg_grep('/0?7\\d{9}/', $data);
         if (count($mobileNumMatch) > 0) {
             $mobileNumContainer = array_values($mobileNumMatch)[0];
             $criteria = new CDbCriteria();
             $criteria->compare('mobile_number', $mobileNumContainer);
             $allowPrint = !BlackListedMobile::model()->exists($criteria);
         }
         if ($allowPrint) {
             foreach ($data as $curRowData) {
                 $rowData = $rowData . "\"{$curRowData}\",";
             }
         }
         $rowData = str_replace(chr(194), " ", $rowData);
         //prepare data
         if ($allowPrint) {
             echo $rowData . "\n";
         }
     }
 }
 public static function extractMultiDimensional($rawMulti)
 {
     $resultArr = array();
     foreach ($rawMulti as $currentMulti) {
         if (isset($currentMulti['claimData'])) {
             $currentMulti = json_decode($currentMulti['claimData'], true);
             $tempContainer = array_values($currentMulti);
             $mobileNumContainer = MobileNumberExtractor::extractMobileNumbers($tempContainer);
             /*check if present in table blacklist*/
             $criteria = new CDbCriteria();
             $criteria->compare("mobile_number", $mobileNumContainer);
             if (!BlackListedMobile::model()->exists($criteria)) {
                 $resultArr[] = $mobileNumContainer;
             }
         }
     }
     return $resultArr;
 }
 public function actionIndex()
 {
     set_time_limit(10 * 60);
     // 10 minutes
     Yii::import("application.models.*");
     $totalCount = BlackListedMobile::model()->count();
     $offset = 0;
     while ($totalCount >= $offset) {
         $criteria = new CDbCriteria();
         $criteria->offset = $offset;
         $criteria->addCondition('trim(mobile_number) NOT REGEXP \'^0?7[0-9]{9}$\'');
         $currentModel = BlackListedMobile::model()->find($criteria);
         echo "Evaluating {$currentModel->mobile_number} \n";
         $currentModel->mobile_number = trim($currentModel->mobile_number);
         if (!preg_match('/^0?7\\d{9}$/', $currentModel->mobile_number)) {
             echo "invalid mobile number : deleting {$currentModel->mobile_number} \n";
             $currentModel->delete();
         }
         $offset++;
     }
 }
 public function actionIndex()
 {
     $fileName = 'blacklisted-mobile-add' . date("Y-m-d");
     header("Pragma: public");
     header("Expires: 0");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Cache-Control: private", false);
     header("Content-Type: text/plain");
     header("Content-Disposition: attachment; filename=\"{$fileName}.txt\";");
     header("Content-Transfer-Encoding: binary");
     $allBlackLIstedMObilecount = BlackListedMobile::model()->count();
     $offset = 0;
     $limit = 50000;
     do {
         $results = Yii::app()->db->createCommand("select mobile_number from black_listed_mobile LIMIT {$limit} OFFSET {$offset}")->queryAll();
         foreach ($results as $value) {
             echo $value['mobile_number'] . PHP_EOL;
         }
         $offset = $offset + $limit;
     } while ($offset <= $allBlackLIstedMObilecount);
     die;
 }
<?php

$totalDncRecords = BlackListedMobile::model()->count();
?>
<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="navbar-inner">
        <div class="container">
            <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </a>

            <!-- Be sure to leave the brand out there if you want it shown -->
            <a class="brand" href="/"><?php 
echo Yii::app()->name;
?>
</a>

            <div class="nav-collapse">
                <?php 
$this->widget('zii.widgets.CMenu', array('htmlOptions' => array('class' => 'pull-right nav'), 'submenuHtmlOptions' => array('class' => 'dropdown-menu'), 'itemCssClass' => 'item-test', 'encodeLabel' => false, 'items' => array(array('label' => 'Dashboard', 'url' => array('/site/index'), 'visible' => Yii::app()->user->getId() === 'administrator'), array('label' => 'DNC Records ' . '<span class="label label-info">' . $totalDncRecords . '</span>', 'url' => array('/blackListedMobile/admin'), 'visible' => Yii::app()->user->getId() === 'administrator'), array('label' => 'Client Portal', 'url' => array('/client_portal/default'), 'visible' => !Yii::app()->user->isGuest), array('label' => 'De-dup Records ' . '<span class="label label-success">' . WhitelistJobQueue::model()->count() . '</span>', 'url' => array('/de-dupe'), 'visible' => Yii::app()->user->getId() === 'administrator'), array('label' => 'IP Firewall', 'url' => "http://ip.dncsystem.website/", 'visible' => Yii::app()->user->getId() === 'administrator'), array('label' => 'Message board', 'url' => array('/messageBoard/updateStatus'), 'visible' => Yii::app()->user->getId() === 'administrator'), array('label' => 'Login', 'url' => array('/site/login'), 'visible' => Yii::app()->user->isGuest), array('label' => 'Logout (' . Yii::app()->user->name . ')', 'url' => array('/site/logout'), 'visible' => !Yii::app()->user->isGuest))));
?>
            </div>
        </div>
    </div>
</div>

<div class="subnav navbar navbar-fixed-top">
    <div class="navbar-inner">
        <div class="container">
 public function actionExportAll()
 {
     $fileName = 'All-blacklisted-records';
     header("Pragma: public");
     header("Expires: 0");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Cache-Control: private", false);
     header("Content-Type: application/octet-stream");
     header("Content-Disposition: attachment; filename=\"{$fileName}.csv\";");
     header("Content-Transfer-Encoding: binary");
     $criteria1 = new CDbCriteria();
     $criteria1->group = "mobile_number";
     $totalCount = BlackListedMobile::model()->count($criteria1);
     $offset = 0;
     $limit = 5000;
     do {
         $criteria = new CDbCriteria();
         $criteria->offset = $offset;
         $criteria->limit = $limit;
         $models = BlackListedMobile::model()->findAll($criteria);
         foreach ($models as $currentModel) {
             echo $currentModel->mobile_number . PHP_EOL;
         }
         $offset = $offset + $limit;
     } while ($totalCount > $offset);
 }
 public function actionIndex()
 {
     Yii::import("application.models.*");
     //get a queued file
     $criteria = new CDbCriteria();
     $criteria->addInCondition("status", array("IDLE", "REQUEUE"));
     /* @var $currentQueue WhitelistJobQueue*/
     $currentQueue = WhitelistJobQueue::model()->find($criteria);
     //if no queued file die()
     if (!$currentQueue) {
         echo "No files in queue";
         die;
     }
     // else continue as usuall
     $currentQueue->status = WhitelistJobQueue::$JOBQUEUE_STATUS_ON_GOING;
     $currentQueue->save(false);
     //get contents
     $currentCsvFile = new SplFileObject($currentQueue->filename);
     $currentCsvFile->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
     //get total number of lines
     $currentCsvFile->seek(PHP_INT_MAX);
     $linesTotal = $currentCsvFile->key();
     $currentQueue->total_records = $linesTotal;
     $currentQueue->save(false);
     $currentCsvFile->rewind();
     $currentCsvFile->next();
     //foreach content , lookup in the blacklist record
     $index = 0;
     foreach ($currentCsvFile as $content) {
         if ($currentCsvFile->key() === 0) {
             continue;
         }
         $currentQueue->processed_record = ++$index;
         $currentQueue->save(false);
         $currentMobileNumber = $content[0];
         $curMobileObj = new WhiteListedMobile();
         //cleaning time
         $currentMobileNumber = trim($currentMobileNumber);
         $currentMobileNumber = rtrim($currentMobileNumber);
         $currentMobileNumber = ltrim($currentMobileNumber);
         $curMobileObj->mobile_number = $currentMobileNumber;
         $curMobileObj->queue_id = $currentQueue->queue_id;
         $criteria2 = new CDbCriteria();
         $criteria2->addSearchCondition("mobile_number", $currentMobileNumber);
         $isOpted = BlackListedMobile::model()->exists($criteria2);
         //if opted , set status error
         if ($isOpted) {
             $curMobileObj->status = WhiteListedMobile::$WHITELISTEDMOBILE_STATUS_ERROR;
         } else {
             //else status ok
             $curMobileObj->status = WhiteListedMobile::$WHITELISTEDMOBILE_STATUS_OK;
         }
         $curMobileObj->save();
         echo "{$curMobileObj->mobile_number}  : {$curMobileObj->status} \n";
     }
     //done
     $currentQueue->status = WhitelistJobQueue::$JOBQUEUE_STATUS_DONE;
     $currentQueue->date_done = date("Y-m-d H:i:s");
     //set done datetime to now()
     $currentQueue->save();
 }
 public function download()
 {
     $fileName = $this->model->claimAccountName . ' - ' . date("Y-m-d") . '-All-entries';
     header("Pragma: public");
     header("Expires: 0");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Cache-Control: private", false);
     header("Content-Type: application/octet-stream");
     header("Content-Disposition: attachment; filename=\"{$fileName}.csv\";");
     header("Content-Transfer-Encoding: binary");
     // $criteria = new CDbCriteria();
     // $criteria->compare("account_id",$this->model->account_id );
     // $criteria->order = "date_created DESC";
     // $criteria->distinct = true;
     // $records = Records::model()->findAll($criteria);
     $records = $this->retrieveDataRecords();
     $isFirst = true;
     $tempfile = tempnam(sys_get_temp_dir(), "tempDownload");
     $filehandle = fopen($tempfile, "r+");
     foreach ($records as $curRecord) {
         $data = json_decode($curRecord->claimData, true);
         $firstname = "";
         if (isset($data['First name'])) {
             $firstname = $data['First name'];
         } else {
             if (isset($data['First Name'])) {
                 $firstname = @$data['First Name'];
             } else {
                 if (isset($data['Firstname'])) {
                     $firstname = @$data['Firstname'];
                 }
             }
         }
         $otherPassengerNames = "";
         if (isset($data['Other Passenger name'])) {
             $otherPassengerNames = $data['Other Passenger name'];
         } else {
             if (isset($data['Other Passenger'])) {
                 $otherPassengerNames = $data['Other Passenger'];
             } else {
                 if (isset($data['Other Passenger Name'])) {
                     $otherPassengerNames = $data['Other Passenger Name'];
                 }
             }
         }
         $emailAddress = "";
         if (isset($data['Email'])) {
             $emailAddress = $data['Email'];
         } else {
             if (isset($data['email'])) {
                 $emailAddress = $data['email'];
             }
         }
         $airline = "";
         if (isset($data["Airline"])) {
             $airline = $data["Airline"];
         }
         $address1 = "";
         if (isset($data['address1'])) {
             $address1 = $data['address1'];
         }
         $reasonForDelay = "";
         if (isset($data['Reason of delay'])) {
             $reasonForDelay = $data['Reason of delay'];
         } else {
             if (isset($data['Reason for Delay'])) {
                 $reasonForDelay = $data['Reason for Delay'];
             }
         }
         $mobileNumber = "";
         if (isset($data['Mobile No.'])) {
             $mobileNumber = $_data['Mobile No.'];
         } else {
             if (isset($data['Mobile Number'])) {
                 $mobileNumber = $data['Mobile Number'];
             }
         }
         $flightDate = "";
         if (isset($data["Flight Date"])) {
             $flightDate = $data["Flight Date"];
         } else {
             if (isset($data["Flight date"])) {
                 $flightDate = $data["Flight Date"];
             }
         }
         $reArrangedData = array($data['Date Submitted'], $data['Title'], $firstname, $data['Surname'], intval($data['address1']), $data['address1'], $data['address2'], $data['city'], $data['zip'], $data['Date of Birth'], $emailAddress, $mobileNumber, OtherPassengerUtility::computeTotalNumOfPassenger($otherPassengerNames), OtherPassengerUtility::getAdditionalPassengerNames($otherPassengerNames), OtherPassengerUtility::getAdditionalPassengerEmails($otherPassengerNames), $data['Hours'], $data['Minutes'], $data["Flight Number"], $flightDate, $airline, $data["Departure Airport"], $data["Arrival Airport"], $data["Actual Arrival"], $data["Actual Departure"], $data["Flight Distance"], $data["Scheduled Arrival"], $data["Scheduled Departure"], $data["Flight Status (km)"], $reasonForDelay);
         $rowData = "";
         $allowPrint = true;
         if ($isFirst) {
             //print heads
             $headers = "";
             $keys = array("Date Submitted", "Title", "First Name", "Surname", "House Number/Name", "Address 1", "Address 2", "Town/City", "Postcode", "DOB", "Email", "Mobile Number", "Total Number Passengers", "Additional Passenger Names", "Additional Passenger Emails", "Length of Delay (Hours)", "Length of Delay (Minutes)", "Flight Number", "Flight Date", "Airline", "Departure Airport", "Arrival Airport", "Actual Arrival Date/Time", "Actual Departure Date/Time", "Flight Distance", "Scheduled Arrival Date/Time", "Scheduled Departure Date/Time", "Delayed/Cancelled", "Reason For Failure");
             $headers = implode(",", $keys) . "\n";
             echo $headers;
             $isFirst = false;
         }
         /*check if mobile number exists at blacklist mobile nums*/
         $mobileNumMatch = preg_grep('/0?7\\d{9}/', $reArrangedData);
         if (count($mobileNumMatch) > 0) {
             $mobileNumContainer = array_values($mobileNumMatch)[0];
             $criteria = new CDbCriteria();
             $criteria->compare('mobile_number', $mobileNumContainer);
             $allowPrint = !BlackListedMobile::model()->exists($criteria);
         }
         if ($allowPrint) {
             $tempVals = array_values($reArrangedData);
             if ($this->model->account_id == 4 && !empty($tempVals[1]) && !empty($tempVals[2])) {
                 /*check if title , firstname and lastname contains data*/
                 fputcsv($filehandle, $reArrangedData);
             }
             if ($this->model->account_id != 4) {
                 fputcsv($filehandle, $reArrangedData);
             }
         }
     }
     rewind($filehandle);
     fpassthru($filehandle);
     unlink($tempfile);
     die;
 }
    public function actionIndex()
    {
        $uploadedFile = CUploadedFile::getInstanceByName("blackListedFile");
        if (isset($_GET['downloadSampleFile'])) {
            $headers = array("Mobilephone");
            $contents = array(array("447123456789"), array("447123456455"), array("447123456321"));
            $tempFile = new SplTempFileObject();
            $tempFile->fputcsv($headers);
            foreach ($contents as $currentLine) {
                $tempFile->fputcsv($currentLine);
            }
            $tempFile->rewind();
            header("Content-type: text/csv");
            header("Content-Disposition: attachment; filename=SampleFile.csv");
            header("Pragma: no-cache");
            header("Expires: 0");
            $tempFile->fpassthru();
            die;
        }
        if (isset($_POST['singleBlackList']) && !empty($_POST['singleBlackList'])) {
            $newMobileNum = new BlackListedMobile();
            $newMobileNum->mobile_number = $_POST['singleBlackList'];
            $newMobileNum->queue_id = 1;
            if ($newMobileNum->save()) {
                Yii::app()->user->setFlash('success', '<strong>New blacklist mobile numberSaved!</strong>');
            } else {
                Yii::app()->user->setFlash('error', '<strong>Error!</strong>' . CHtml::errorSummary($newMobileNum));
            }
        }
        if (isset($_POST['massiveTextArea']) && !empty($_POST['massiveTextArea'])) {
            /*@TODO get total now , using randomQueue  */
            $queueName = $_POST['randomQueue'] ? $_POST['randomQueue'] : 'Task : upload - ' . rand(0, 9999);
            $criteriaJobQueue = new CDbCriteria();
            $criteriaJobQueue->compare("queue_name", $queueName);
            $jobQueueModl = JobQueue::model()->find($criteriaJobQueue);
            /*@TODO $total_before*/
            $total_before = 0;
            if (!$jobQueueModl) {
                $jobQueueModl = new JobQueue();
                //@TODO declare above ,
                $jobQueueModl->queue_name = $queueName;
                $jobQueueModl->save(false);
                //pre save
            } else {
                $criteriaTotalBefore = new CDbCriteria();
                $criteriaTotalBefore->compare("queue_id", $jobQueueModl->queue_id);
                $total_before = BlackListedMobile::model()->count($criteriaTotalBefore);
            }
            /*write posted textarea to file*/
            $tp = tempnam(Yii::getPathOfAlias('application.data'), "tempWrite");
            $tempName = $tp . '.csv';
            $linecount = 0;
            $tempContainer2 = explode("\n", $_POST['massiveTextArea']);
            $tempContainer2 = array_filter($tempContainer2);
            $linecount = count($tempContainer2);
            file_put_contents($tempName, implode(PHP_EOL, $tempContainer2));
            // $handle = fopen($tempName, "r");
            // while(!feof($handle)){
            //     $line = fgets($handle);
            //     ++$linecount;
            // }
            // fclose($handle);
            $jobQueueModl->filename = $tempName;
            //ignore this
            $jobQueueModl->status = JobQueue::$JOBQUEUE_STATUS_PRELOADED;
            /*check number files' number of line*/
            // Total_records ,
            $jobQueueModl->total_records = $linecount;
            $jobQueueModl->processed_record = $linecount;
            /*update job queue record*/
            if ($jobQueueModl->save()) {
                $filePath = $tempName;
                /*load to database*/
                $tempFile2 = tempnam(__DIR__, "tempContainer");
                $appendCommand = sprintf('cat "%s" | gawk \'{print $0",0%s"}\'  > "%s" ', $filePath, $jobQueueModl->queue_id, $tempFile2);
                system($appendCommand);
                system("mv \"{$tempFile2}\" \"{$filePath}\"");
                $sqlCommand = <<<EOL
LOAD DATA LOCAL INFILE "%s"
INTO TABLE black_listed_mobile
FIELDS TERMINATED BY "%s"
LINES TERMINATED BY "%s"
IGNORE 0 LINES
(mobile_number,queue_id)
EOL;
                $sqlCommand = sprintf($sqlCommand, $filePath, ',', '\\n');
                $mainCommand = "mysql  --user=dncsyste_dnc --password=hitman052529 --database=dncsyste_dnc -e '{$sqlCommand}'";
                exec($mainCommand);
                $criteriaTotalBefore = new CDbCriteria();
                $criteriaTotalBefore->compare("queue_id", $jobQueueModl->queue_id);
                /* $total_now*/
                $total_now = BlackListedMobile::model()->count($criteriaTotalBefore);
                if (Yii::app()->request->isAjaxRequest) {
                    header("Content-Type: application/json");
                    $numOfInsertedData = $total_now - $total_before;
                    $numOfInsertedData = $numOfInsertedData <= 0 ? 0 : $numOfInsertedData;
                    $numOfDeletedData = $linecount - ($total_now - $total_before);
                    $numOfDeletedData = $numOfDeletedData <= 0 ? 0 : $numOfDeletedData;
                    $jsonResult = array("numOfInsertedData" => $numOfInsertedData, "numOfDeletedData" => $numOfDeletedData);
                    echo json_encode($jsonResult);
                    die;
                } else {
                    Yii::app()->user->setFlash('success', '<strong>File Imported!</strong>You have successfully imported new blacklisted mobile number. ');
                }
            } else {
                Yii::app()->user->setFlash('error', CHtml::errorSummary($newQueueFile));
            }
        }
        if ($uploadedFile) {
            set_time_limit(0);
            $newFileLocation = Yii::getPathOfAlias("application.uploaded_files") . DIRECTORY_SEPARATOR . rand(0, 9999) . '-' . $uploadedFile->name;
            //save new queue file
            $newQueueFile = new JobQueue();
            $uploadedFile->saveAs($newFileLocation);
            $newQueueFile->queue_name = "Task : " . $uploadedFile->name . ' - ' . rand(0, 9999);
            $newQueueFile->filename = $newFileLocation;
            $newQueueFile->status = JobQueue::$JOBQUEUE_STATUS_PRELOADED;
            /*check number files' number of line*/
            $linesTotal = 0;
            $handle = fopen($newQueueFile->filename, "r");
            while (!feof($handle)) {
                $line = fgets($handle);
                ++$linesTotal;
            }
            fclose($handle);
            $newQueueFile->total_records = $linesTotal;
            $newQueueFile->processed_record = $linesTotal;
            if ($newQueueFile->save()) {
                $filePath = $newQueueFile->filename;
                $tempFile2 = tempnam(__DIR__, "tempContainer");
                $appendCommand = sprintf('gawk \'{print $0",0%s"}\' "%s"  > "%s"', $newQueueFile->queue_id, $filePath, $tempFile2);
                system($appendCommand);
                system("mv \"{$tempFile2}\" \"{$filePath}\"");
                /*append queue identification for blacklist*/
                $rawContents = file_get_contents($filePath);
                //		print_r( explode("\n",$rawContents)  );
                //		die();
                $sqlCommand = <<<EOL
LOAD DATA LOCAL INFILE "%s"
INTO TABLE black_listed_mobile
FIELDS TERMINATED BY "%s"
LINES TERMINATED BY "%s"
IGNORE 0 LINES
(mobile_number,queue_id)
EOL;
                $sqlCommand = sprintf($sqlCommand, $filePath, ',', '\\n');
                $mainCommand = "mysql  --user=dncsyste_dnc --password=hitman052529 --database=dncsyste_dnc -e '{$sqlCommand}'";
                exec($mainCommand);
                $undoLink = "<a href='" . Yii::app()->getBaseUrl(true) . "/blacklist/delete?queue_id={$newQueueFile->queue_id}' onClick='return confirm(\"Are you sure you want to delete this ?\")'> Undo Action  </a>";
                Yii::app()->user->setFlash('success', '<strong>File Imported!</strong>You have successfully imported new blacklisted mobile number. ' . $undoLink);
            } else {
                Yii::app()->user->setFlash('error', CHtml::errorSummary($newQueueFile));
            }
        }
        $this->render('index');
    }
Beispiel #12
0
<?php

/* @var $this DefaultController */
$this->breadcrumbs = array($this->module->id);
$criteria2 = new CDbCriteria();
$criteria2->compare("origin", "client");
$counttot = BlackListedMobile::model()->count($criteria2);
$label = "<span class=\"badge badge-info pull-right\">{$counttot}</span>";
$this->menu = array(array('label' => 'Mobile Opted from Client ' . $label, 'url' => Yii::app()->getBaseUrl(true) . "/whitelist/default"));
?>

<style type="text/css">
.list-view div.view {
	border: none;
	border-top: solid 1px #DDDDDD;
	border-bottom: solid 1px #DDDDDD;
}

</style>

<h1>
	Opt out mobile number <br>
	<small>List of mobile numbers who opted out coming from client source.</small>
</h1>
<?php 
$this->widget('zii.widgets.CListView', array('id' => "listviewData", 'dataProvider' => $dataProvider, 'itemView' => '_view'));
 public function actionMobile()
 {
     if (isset($_REQUEST['accountID'])) {
         $accountMdl = Accounts::model()->findByPk($_REQUEST['accountID']);
         $fileName = $accountMdl->claimAccountName . ' - ' . date("Y-m-d") . '-all-mobilenumbers';
         header("Pragma: public");
         header("Expires: 0");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Cache-Control: private", false);
         header("Content-Type: application/octet-stream");
         header("Content-Disposition: attachment; filename=\"{$fileName}.csv\";");
         header("Content-Transfer-Encoding: binary");
         $criteria = new CDbCriteria();
         $criteria->compare("account_id", $_REQUEST['accountID']);
         $criteria->order = "date_created DESC";
         $records = Records::model()->findAll($criteria);
         $isFirst = true;
         foreach ($records as $curRecord) {
             $data = json_decode($curRecord->claimData, true);
             if ($isFirst) {
                 //print heads
                 echo "Mobile Number\n";
                 $isFirst = false;
             }
             //retrieve mobile number
             $arrayVals = array_values($data);
             $extractedMobile = MobileNumberExtractor::extractMobileNumbers($arrayVals);
             if ($extractedMobile != false) {
                 /* check if present at blacklist*/
                 $crt = new CDbCriteria();
                 $crt->compare('mobile_number', $extractedMobile);
                 if (!BlackListedMobile::model()->exists($crt)) {
                     echo $extractedMobile . PHP_EOL;
                 }
             }
         }
     } else {
         throw new CHttpException(404, "Yikes , You forgot to pass in the Account ID");
     }
 }
    public function actionIndex()
    {
        $dncFile = CUploadedFile::getInstanceByName("dncFile");
        if (isset($_POST['manualCheck']) && !empty($_POST['manualCheck'])) {
            //write the massive input to a csv file . process it like a whitelistjobqueue
            $criteria = new CDbCriteria();
            $criteria->compare("mobile_number", $_POST['manualCheck']);
            // $criteria->addSearchCondition("mobile_number", $_POST['manualCheck']);
            $mobileIsWhiteListed = BlackListedMobile::model()->exists($criteria);
            if ($mobileIsWhiteListed) {
                Yii::app()->user->setFlash('error', '<strong>Mobile Number opted out!</strong> The mobile number opted out before.');
            } else {
                Yii::app()->user->setFlash('success', '<strong>Mobile Number is Clean!</strong> The mobile number has not been opted yet.');
            }
        } else {
            if (isset($_POST['massiveTextArea'])) {
                //write the posted manual file  to a CSV file
                $tempName = tempnam(Yii::getPathOfAlias('application.tempWrite'), "tempWrite");
                $tempName = $tempName . '.csv';
                $mobileNumsArr = explode("\n", $_POST['massiveTextArea']);
                $mobileNumsArr = array_filter($mobileNumsArr);
                //
                $tempNumsContainer = implode("\n", $mobileNumsArr);
                file_put_contents($tempName, $tempNumsContainer);
                $linecount = count($mobileNumsArr);
                $criteria = new CDbCriteria();
                $criteria->compare("queue_name", $_POST['copyPasteFileName']);
                $whiteListjob = WhitelistJobQueue::model()->find($criteria);
                if (!$whiteListjob) {
                    $whiteListjob = new WhitelistJobQueue();
                    $whiteListjob->filename = $tempName;
                    if (isset($_POST['copyPasteFileName'])) {
                        $whiteListjob->queue_name = $_POST['copyPasteFileName'];
                    } else {
                        $whiteListjob->queue_name = 'Uploaded-' . date("Y.m.d.H.i.s");
                    }
                }
                $whiteListjob->status = WhitelistJobQueue::$JOBQUEUE_STATUS_IDLE;
                //Add scan total
                $whiteListjob->total_records = intval($whiteListjob->total_records) + intval($linecount);
                $whiteListjob->processed_record = intval($whiteListjob->processed_record) + $linecount;
                $whiteListjob->status = WhitelistJobQueue::$JOBQUEUE_STATUS_DONE;
                //status to done
                if ($whiteListjob->save()) {
                    //insert queueid sa file firstColumn,
                    $tempDump = tempnam(sys_get_temp_dir(), "temp");
                    $insertQueueidColCommand = "gawk '{print \"{$whiteListjob->queue_id},0\"\$0}' {$tempName} > {$tempDump}";
                    exec($insertQueueidColCommand);
                    exec("mv \"{$tempDump}\" \"{$tempName}\"  ");
                    //insert the whitelisted data to database;
                    $filePath = $tempName;
                    $sqlCommand = <<<EOL
LOAD DATA LOCAL INFILE "%s"
INTO TABLE white_listed_mobile
FIELDS TERMINATED BY "%s"
LINES TERMINATED BY "%s"
IGNORE 0 LINES
(queue_id,mobile_number)
EOL;
                    $sqlCommand = sprintf($sqlCommand, $filePath, ',', '\\n');
                    $mainCommand = "mysql  --user=dncsyste_dnc --password=hitman052529 --database=dncsyste_dnc -e '{$sqlCommand}'";
                    exec($mainCommand);
                    $referenceLink = Yii::app()->getBaseUrl(true) . "/dnc/" . $whiteListjob->queue_id;
                    Yii::app()->user->setFlash('success', '<strong>File Uploaded!</strong> Please click the link to download your cleaned mobile numbers . ' . CHtml::link('Reference Link', $referenceLink));
                } else {
                    Yii::app()->user->setFlash('error', CHtml::errorSummary($whiteListjob));
                }
            } else {
                if ($dncFile) {
                    $newFileLocation = Yii::getPathOfAlias("application.uploaded_files") . DIRECTORY_SEPARATOR . uniqid();
                    $whileListjob = new WhitelistJobQueue();
                    $dncFile->saveAs($newFileLocation);
                    $whileListjob->queue_name = $dncFile->name;
                    $whileListjob->filename = $newFileLocation;
                    $whileListjob->status = WhitelistJobQueue::$JOBQUEUE_STATUS_IDLE;
                    //add scan total
                    $queueFile = new SplFileObject($whileListjob->filename);
                    //read file
                    $queueFile->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
                    $queueFile->seek(PHP_INT_MAX);
                    $linesTotal = $queueFile->key();
                    $whileListjob->total_records = $linesTotal;
                    $whileListjob->processed_record = $linesTotal;
                    $whileListjob->status = WhitelistJobQueue::$JOBQUEUE_STATUS_DONE;
                    //status to done
                    if ($whileListjob->save()) {
                        //insert queueid sa file firstColumn,
                        $tempDump = tempnam(sys_get_temp_dir(), "temp");
                        exec("head -1500000 {$newFileLocation} > {$tempDump}");
                        //cut first 1m 500 k
                        exec("gawk '{print \"{$whileListjob->queue_id},0\"\$0}' {$tempDump} > {$newFileLocation}");
                        //insert queueid
                        $queueFile = null;
                        $queueFile = new SplFileObject($newFileLocation);
                        //read file
                        $queueFile->seek(PHP_INT_MAX);
                        $linesTotal = $queueFile->key();
                        $whileListjob->filename = $newFileLocation;
                        $whileListjob->total_records = $linesTotal;
                        $whileListjob->processed_record = $linesTotal;
                        $whileListjob->save();
                        $sqlCommand = <<<EOL
LOAD DATA LOCAL INFILE "%s"
INTO TABLE white_listed_mobile
FIELDS TERMINATED BY "%s"
LINES TERMINATED BY "%s"
IGNORE 0 LINES
(queue_id,mobile_number)
EOL;
                        $sqlCommand = sprintf($sqlCommand, $newFileLocation, ',', '\\n');
                        $mainCommand = "mysql  --user=dncsyste_dnc --password=hitman052529 --database=dncsyste_dnc -e '{$sqlCommand}'";
                        $result = exec($mainCommand);
                        //unlink($tempDump);
                        $referenceLink = Yii::app()->getBaseUrl(true) . "/dnc/" . $whileListjob->queue_id;
                        Yii::app()->user->setFlash('success', '<strong>File Uploaded!</strong> Please click the link to download your cleaned mobile numbers . ' . CHtml::link('Reference Link', $referenceLink));
                    } else {
                        Yii::app()->user->setFlash('error', CHtml::errorSummary($whileListjob));
                    }
                }
            }
        }
        Yii::app()->user->setFlash('info', '<strong><i class="fa fa-info-circle"></i></strong> Please use the following format  : 07#########.');
        $this->render('index');
    }