Example #1
0
 /**
  * シングル・サインオンの結果を元にDBのユーザ情報を更新する。
  *
  * @param array $userInfo
  */
 public static function updateUserData($userInfo)
 {
     // userInfoは以下のデータを含む
     //
     // [
     //     sub         => iit0001,
     //     updated_at  => 1424903837,
     //     email       => tekezo@iit.jp,
     //     name        => iit0001,
     //     family_name => Takayama,
     //     given_name  => Fumihiko,
     // ]
     if (!isset($userInfo['sub'])) {
         return;
     }
     $user_id = $userInfo['sub'];
     $updates = array();
     $params = array(':user_id' => $user_id);
     if (isset($userInfo['email'])) {
         $updates[] = 'email = :email';
         $params[':email'] = $userInfo['email'];
     }
     $user_name = (isset($userInfo['family_name']) ? $userInfo['family_name'] : '') . ' ' . (isset($userInfo['given_name']) ? $userInfo['given_name'] : '');
     $user_name = trim($user_name);
     if ($user_name) {
         $updates[] = 'user_name = :user_name';
         $params[':user_name'] = $user_name;
     }
     if (!empty($updates)) {
         $sql = 'UPDATE user SET ' . join(',', $updates) . ' WHERE user_id = :user_id';
         \R::exec($sql, $params);
     }
 }
 public function testRun()
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_SENT);
     //Create 2 sent notifications, and set one with a date over a week ago (8 days ago) for the modifiedDateTime
     $emailMessage = EmailMessageTestHelper::createDraftSystemEmail('My Email Message', $super);
     $emailMessage->folder = $folder;
     $saved = $emailMessage->save();
     $this->assertTrue($saved);
     $modifiedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 8);
     $sql = "Update item set modifieddatetime = '" . $modifiedDateTime . "' where id = " . $emailMessage->getClassId('Item');
     R::exec($sql);
     $emailMessage2 = EmailMessageTestHelper::createDraftSystemEmail('My Email Message 2', $super);
     $emailMessage2->folder = $folder;
     $saved = $emailMessage2->save();
     $this->assertTrue($saved);
     $this->assertEquals(2, count(EmailMessage::getAll()));
     $job = new ClearSentNotificationsEmailJob();
     $this->assertTrue($job->run());
     $emailMessages = EmailMessage::getAll();
     $this->assertEquals(1, count($emailMessages));
     $this->assertEquals($emailMessage2->id, $emailMessages[0]->id);
 }
 public function process(array $documents, &$context)
 {
     $franchiseIds = [];
     $franchiseIds[] = self::mediaToKey($context->media);
     foreach ($context->relationData as $relation) {
         if ($relation['media'] != $context->media->media) {
             continue;
         }
         if ($relation['type'] == MediaRelation::Character) {
             continue;
         }
         if (BanHelper::isFranchiseCouplingBanned($relation['media'], $relation['mal_id'], $context->media->media, $context->media->mal_id)) {
             continue;
         }
         $franchiseIds[] = self::mediaToKey($relation);
     }
     foreach (R::findAll('media', 'media||mal_id IN (' . R::genSlots($franchiseIds) . ')', $franchiseIds) as $relatedMedia) {
         $franchiseIds[] = $relatedMedia->franchise;
     }
     $franchiseId = reset($franchiseIds);
     $media =& $context->media;
     $media->franchise = $franchiseId;
     R::store($media);
     $query = 'UPDATE media SET franchise = ? WHERE franchise IN (' . R::genSlots($franchiseIds) . ')';
     R::exec($query, array_merge([$franchiseId], $franchiseIds));
 }
Example #4
0
 public function testRunAndProcessStuckJobs()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $emailAddress = new Email();
     $emailAddress->emailAddress = '*****@*****.**';
     Yii::app()->user->userModel->primaryEmail = $emailAddress;
     $saved = Yii::app()->user->userModel->save();
     $this->assertTrue($saved);
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $monitorJob = new MonitorJob();
     $this->assertEquals(0, count(JobInProcess::getAll()));
     $this->assertEquals(0, count(Notification::getAll()));
     $jobInProcess = new JobInProcess();
     $jobInProcess->type = 'Test';
     $this->assertTrue($jobInProcess->save());
     //Should make createdDateTime long enough in past to trigger as stuck.
     $createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 1000);
     $sql = "Update item set createddatetime = '" . $createdDateTime . "' where id = " . $jobInProcess->getClassId('Item');
     R::exec($sql);
     $jobInProcess->forget();
     $monitorJob->run();
     $this->assertEquals(1, count(Notification::getAll()));
     //Confirm an email was sent
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(1, Yii::app()->emailHelper->getSentCount());
 }
Example #5
0
 /**
  * Deletes all job logs where the modifiedDateTime was more than 1 week ago.
  * Runs operation in bulk to improve performance when large jobLogs are present.
  *
  * @see BaseJob::run()
  */
 public function run()
 {
     $oneWeekAgoTimeStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 7);
     $sql = 'DELETE from item, joblog using joblog inner join item on ' . 'item.id = joblog.item_id where joblog.enddatetime <= "' . $oneWeekAgoTimeStamp . '"';
     R::exec($sql);
     return true;
 }
Example #6
0
 public function testRun()
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     //Create 2 imports, and set one with a date over a week ago (8 days ago) for the modifiedDateTime
     $import = new Import();
     $serializedData['importRulesType'] = 'ImportModelTestItem';
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import->getTempTableName());
     $modifiedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 8);
     $sql = "Update item set modifieddatetime = '" . $modifiedDateTime . "' where id = " . $import->getClassId('Item');
     R::exec($sql);
     $staleImportId = $import->id;
     $import2 = new Import();
     $serializedData['importRulesType'] = 'ImportModelTestItem';
     $import2->serializedData = serialize($serializedData);
     $this->assertTrue($import2->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import2->getTempTableName());
     $this->assertEquals(2, count(Import::getAll()));
     $row = R::getRow('show tables like "' . $import->getTempTableName() . '"');
     $this->assertNotEmpty($row);
     $job = new ImportCleanupJob();
     $this->assertTrue($job->run());
     $row = R::getRow('show tables like "' . $import->getTempTableName() . '"');
     $this->assertEmpty($row);
     $imports = Import::getAll();
     $this->assertEquals(1, count($imports));
     $this->assertEquals($import2->id, $imports[0]->id);
 }
Example #7
0
 public static function tearDownAfterClass()
 {
     R::exec('drop table if exists testimporttable');
     R::exec('drop table if exists testimporttable2');
     R::exec('drop table if exists testimporttable3');
     R::exec('drop table if exists testimporttable4');
     parent::tearDownAfterClass();
 }
Example #8
0
 /**
  * Given a event, perform the deletion of activityItems related to the event sender.
  * @param CEvent $event
  */
 public function deleteActivityItems(CEvent $event)
 {
     $model = $event->sender;
     assert('$model instanceof Item');
     $itemId = $model->getClassId('Item');
     $sql = 'DELETE from activity_item where item_id = ' . $itemId;
     R::exec($sql);
 }
 private function checkInstall($b)
 {
     require sprintf('%s/bites/%s/config.php', \ROOT, $b->name);
     \R::exec("show tables like '{$install['table']}'");
     if (!\R::$adapter->getAffectedRows()) {
         require sprintf('%s/bites/%s/schema.php', \ROOT, $b->name);
     }
 }
 /**
  * Insert item into modelcreationapisync table
  * @param $serviceName
  * @param $modelId
  * @param $modelClassName
  * @param $dateTime
  */
 public static function insertItem($serviceName, $modelId, $modelClassName, $dateTime)
 {
     assert('is_string($serviceName)');
     assert('is_int($modelId)');
     assert('is_string($dateTime)');
     $sql = "INSERT INTO " . self::TABLE_NAME . " VALUES (null, '{$serviceName}', '{$modelId}', '{$modelClassName}', '{$dateTime}')";
     R::exec($sql);
 }
Example #11
0
 /**
  * Given a model and external system id, update the external system id in the database for that model
  * @param object $model
  * @param string $externalSystemId
  */
 public static function updateByModel(RedBeanModel $model, $externalSystemId)
 {
     assert('$externalSystemId == null || is_string($externalSystemId)');
     $columnName = self::EXTERNAL_SYSTEM_ID_COLUMN_NAME;
     $tableName = $model::getTableName(get_class($model));
     RedBeanColumnTypeOptimizer::externalIdColumn($tableName, $columnName);
     R::exec("update " . $tableName . " set {$columnName} = '" . $externalSystemId . "' where id = " . $model->id);
 }
Example #12
0
 public static function delete($tableName, $conditions)
 {
     $single = [];
     foreach ($conditions as $key => $value) {
         $single[] = $key . ' = ?';
     }
     $query = sprintf('DELETE FROM %s WHERE %s', $tableName, join(' AND ', $single));
     R::exec($query, array_values($conditions));
 }
Example #13
0
function droptables()
{
    R::exec('SET FOREIGN_KEY_CHECKS=0;');
    foreach (R::$writer->getTables() as $t) {
        R::exec("drop table if exists`{$t}`");
        R::exec("drop view if exists`{$t}`");
    }
    R::exec('SET FOREIGN_KEY_CHECKS=1;');
}
Example #14
0
 public static function deleteRowsFromAllTablesExceptLog()
 {
     assert('RedBeanDatabase::isSetup()');
     $tableNames = DatabaseCompatibilityUtil::getAllTableNames();
     foreach ($tableNames as $tableName) {
         if ($tableName != 'log') {
             R::exec("delete from {$tableName}");
         }
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     $super = SecurityTestHelper::createSuperAdmin();
     SecurityTestHelper::createUsers();
     $account = AccountTestHelper::createAccountByNameForOwner('anAccount2', Yii::app()->user->userModel);
     $task = TaskTestHelper::createTaskWithOwnerAndRelatedAccount('startTask', $super, $account);
     $task->delete();
     R::exec('delete from activity_item');
 }
 public function after_update()
 {
     // check if amount == 0
     if ($this->amount <= 0) {
         R::trash($this->bean);
         return;
     }
     // check if merging two entries is possible
     $mergeTo = R::findOne('bank_locker', " param = ? AND user_id = ? AND item_id = ? AND id != ?", array($this->param, $this->user->id, $this->item->id, $this->id));
     if ($mergeTo != false) {
         R::exec("UPDATE bank_locker SET amount = ? WHERE id = ?", array($this->amount + $mergeTo->amount, $this->id));
         R::trash($mergeTo);
     }
 }
Example #17
0
 public function testRun()
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     //Create 2 export items, and set one with a date over a week ago (8 days ago) for the modifiedDateTime
     $exportItem = new ExportItem();
     $exportItem->isCompleted = 0;
     $exportItem->exportFileType = 'csv';
     $exportItem->exportFileName = 'test';
     $exportItem->modelClassName = 'Account';
     $exportItem->serializedData = serialize(array('test', 'test2'));
     $this->assertTrue($exportItem->save());
     $fileContent = new FileContent();
     $fileContent->content = 'test';
     $exportFileModel = new ExportFileModel();
     $exportFileModel->fileContent = $fileContent;
     $exportFileModel->name = $exportItem->exportFileName . ".csv";
     $exportFileModel->type = 'application/octet-stream';
     $exportFileModel->size = strlen($fileContent->content);
     $this->assertTrue($exportFileModel->save());
     $exportFileModel1Id = $exportFileModel->id;
     $exportItem->exportFileModel = $exportFileModel;
     $this->assertTrue($exportItem->save());
     $modifiedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 8);
     $sql = "Update item set modifieddatetime = '" . $modifiedDateTime . "' where id = " . $exportItem->getClassId('Item');
     R::exec($sql);
     // Second exportItem, that shouldn't be deleted.
     $exportItem2 = new ExportItem();
     $exportItem2->isCompleted = 0;
     $exportItem2->exportFileType = 'csv';
     $exportItem2->exportFileName = 'test';
     $exportItem2->modelClassName = 'Account';
     $exportItem2->serializedData = serialize(array('test', 'test2'));
     $this->assertTrue($exportItem2->save());
     $fileContent2 = new FileContent();
     $fileContent2->content = 'test';
     $exportFileModel2 = new ExportFileModel();
     $exportFileModel2->fileContent = $fileContent2;
     $exportFileModel2->name = $exportItem->exportFileName . ".csv";
     $exportFileModel2->type = 'application/octet-stream';
     $exportFileModel2->size = strlen($fileContent->content);
     $this->assertTrue($exportFileModel2->save());
     $exportFileModel2Id = $exportFileModel2->id;
     $exportItem2->exportFileModel = $exportFileModel2;
     $this->assertTrue($exportItem2->save());
     $job = new ExportCleanupJob();
     $this->assertTrue($job->run());
     $exportItems = ExportItem::getAll();
     $this->assertEquals(1, count($exportItems));
     $this->assertEquals($exportItem2->id, $exportItems[0]->id);
 }
 public function save()
 {
     $rules = array('customer_id' => 'required|', 'payment_amount' => 'required|numeric', 'payment_memo' => 'required');
     $filters = array('payment_memo' => 'trim|sanitize_string', 'payment_amount' => 'trim|sanitize_string|numeric', 'customer_id' => 'trim|numeric');
     $postValues = $gump->filter($this->{$postarray}, $filters);
     $validated = $gump->validate($gump->filter($postValues, $filters), $rules);
     $this->payment_amount = $postValues['payment_amount'];
     $this->payment_memo = $postValues['payment_memo'];
     $this->who_is_getting_paid = $postValues['customer_id'];
     if ($validated === TRUE) {
         R::begin();
         try {
             /*Payment Add*/
             $payment = R::findOne('user', ' id = ? and created_by=? ', array($this->who_is_getting_paid, $this->who_is_paying));
             $current_balance = $payment->balance2;
             $reseller_balance = R::dispense("reseller_balance");
             $reseller_balance->user_id = $this->who_is_getting_paid;
             $reseller_balance->amount = $this->{$payment_amount};
             $reseller_balance->load_by = $this->who_is_paying;
             $reseller_balance->note = $this->comments;
             $reseller_balance->ip = $_SERVER["REMOTE_ADDR"];
             $reseller_balance->updated = CURRENT_DTT;
             if ($this->payment_type == "add") {
                 $payment->balance2 = $payment->balance2 + $this->payment_amount;
                 $payment->return_payment = 0;
                 //add
                 R::exec("CALL preparestatement({$this->who_is_paying},{$this->payment_amount},{$current_balance},{$this->who_is_getting_paid},'debit','{$this->payment_memo}')");
             } elseif ($this->payment_type == "return") {
                 $payment->balance2 = $payment->balance2 - $this->payment_amount;
                 $payment->return_payment = 1;
                 //return
                 R::exec("CALL preparestatement({$this->who_is_paying},{$this->payment_amount},{$current_balance},{$this->who_is_getting_paid},'credit','{$this->payment_memo}')");
             }
             R::save($payment);
             R::save($reseller_balance);
             R::commit();
         } catch (Exception $e) {
             R::rollback();
             $this->setError("" . $e->getMessage());
         }
     } else {
         $this->setError($gump->get_readable_errors(true));
     }
     if ($this->getError() == "") {
         $this->fails = FALSE;
     } else {
         $this->fails = TRUE;
     }
 }
 public function testImportDataAnalysisResults()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $import = new Import();
     $serializedData['importRulesType'] = 'Tasks';
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     $accountTableName = Account::getTableName('Account');
     $contactTableName = Contact::getTableName('Contact');
     $opportunityTableName = Opportunity::getTableName('Opportunity');
     $account1 = AccountTestHelper::createAccountByNameForOwner('account1', $super);
     $account2 = AccountTestHelper::createAccountByNameForOwner('account2', $super);
     $account3 = AccountTestHelper::createAccountByNameForOwner('account3', $super);
     $contact1 = ContactTestHelper::createContactByNameForOwner('contact1', $super);
     $contact2 = ContactTestHelper::createContactByNameForOwner('contact2', $super);
     $contact3 = ContactTestHelper::createContactByNameForOwner('contact3', $super);
     $opportunity1 = OpportunityTestHelper::createOpportunityByNameForOwner('opportunity1', $super);
     $opportunity2 = OpportunityTestHelper::createOpportunityByNameForOwner('opportunity2', $super);
     $opportunity3 = OpportunityTestHelper::createOpportunityByNameForOwner('opportunity3', $super);
     //Make models externally linked for testing.
     ImportTestHelper::updateModelsExternalId($account2, 'ACC');
     ImportTestHelper::updateModelsExternalId($contact2, 'CON');
     ImportTestHelper::updateModelsExternalId($opportunity2, 'OPP');
     ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import->getTempTableName(), Yii::getPathOfAlias('application.modules.tasks.tests.unit.files'));
     R::exec("update " . $import->getTempTableName() . " set column_0 = " . $account3->id . " where id != 1 limit 3");
     R::exec("update " . $import->getTempTableName() . " set column_2 = " . $contact3->id . " where id != 1 limit 4");
     R::exec("update " . $import->getTempTableName() . " set column_4 = " . $opportunity3->id . " where id != 1 limit 5");
     $mappingData = array('column_0' => ImportMappingUtil::makeModelDerivedColumnMappingData('AccountDerived', IdValueTypeMappingRuleForm::ZURMO_MODEL_ID), 'column_1' => ImportMappingUtil::makeModelDerivedColumnMappingData('AccountDerived'), 'column_2' => ImportMappingUtil::makeModelDerivedColumnMappingData('ContactDerived', IdValueTypeMappingRuleForm::ZURMO_MODEL_ID), 'column_3' => ImportMappingUtil::makeModelDerivedColumnMappingData('ContactDerived'), 'column_4' => ImportMappingUtil::makeModelDerivedColumnMappingData('OpportunityDerived', IdValueTypeMappingRuleForm::ZURMO_MODEL_ID), 'column_5' => ImportMappingUtil::makeModelDerivedColumnMappingData('OpportunityDerived'));
     $serializedData = unserialize($import->serializedData);
     $serializedData['mappingData'] = $mappingData;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     $importRules = ImportRulesUtil::makeImportRulesByType('Tasks');
     $config = array('pagination' => array('pageSize' => 2));
     //This test csv has a header row.
     $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config);
     //Run data analyzer
     $importDataAnalyzer = new ImportDataAnalyzer($importRules, $dataProvider);
     foreach ($mappingData as $columnName => $columnMappingData) {
         $importDataAnalyzer->analyzeByColumnNameAndColumnMappingData($columnName, $columnMappingData);
     }
     $messagesData = $importDataAnalyzer->getMessagesData();
     $compareData = array('column_0' => array(array('message' => '3 record(s) will be updated and 7 record(s) will be skipped during import.', 'sanitizerUtilType' => 'AccountDerivedIdValueType', 'moreAvailable' => false)), 'column_1' => array(array('message' => '3 record(s) will be updated and 7 record(s) will be skipped during import.', 'sanitizerUtilType' => 'AccountDerivedIdValueType', 'moreAvailable' => false)), 'column_2' => array(array('message' => '4 record(s) will be updated and 6 record(s) will be skipped during import.', 'sanitizerUtilType' => 'ContactDerivedIdValueType', 'moreAvailable' => false)), 'column_3' => array(array('message' => '3 record(s) will be updated and 7 record(s) will be skipped during import.', 'sanitizerUtilType' => 'ContactDerivedIdValueType', 'moreAvailable' => false)), 'column_4' => array(array('message' => '5 record(s) will be updated and 5 record(s) will be skipped during import.', 'sanitizerUtilType' => 'OpportunityDerivedIdValueType', 'moreAvailable' => false)), 'column_5' => array(array('message' => '3 record(s) will be updated and 7 record(s) will be skipped during import.', 'sanitizerUtilType' => 'OpportunityDerivedIdValueType', 'moreAvailable' => false)));
     $this->assertEquals($compareData, $messagesData);
     $importInstructionsData = $importDataAnalyzer->getImportInstructionsData();
     $compareInstructionsData = array();
     $this->assertEquals($compareInstructionsData, $importInstructionsData);
 }
Example #20
0
 public static function setupRedBean()
 {
     try {
         if (!self::$_redBeanInitialized) {
             self::$_redBeanInitialized = true;
             R::setup(Config::get('database_dsn'), Config::get('database_user'), Config::get('database_password'));
             R::freeze(true);
             R::exec('SET NAMES utf8');
             define('REDBEAN_MODEL_PREFIX', '\\Sop\\Model\\');
         }
     } catch (\Exception $e) {
         \Sop\Log::error(__FILE__, __LINE__, 'Failed to setup database connection');
         throw $e;
     }
 }
Example #21
0
 public static function removeChild($table, $parentBean, $bean)
 {
     //we still need 2 separate queries because the parent's left_id can't be updated...
     R::begin();
     try {
         R::trash($bean);
         R::exec('UPDATE ' . $table . ' SET left_id = left_id-2 WHERE left_id > ?', array($bean->right_id));
         R::exec('UPDATE ' . $table . ' SET right_id = right_id-2 WHERE right_id >= ?', array($bean->right_id));
         $parentBean->right_id -= 2;
         R::commit();
     } catch (Exception $e) {
         R::rollback();
         throw $e;
     }
 }
Example #22
0
 static function save_sqlite($unique_keys = array(), $data, $table_name = 'data')
 {
     if (count($data) == 0) {
         return;
     }
     $table = R::dispense($table_name);
     // convert special types
     foreach ($data as &$value) {
         if ($value instanceof DateTime) {
             $new_value = clone $value;
             $new_value->setTimezone(new DateTimeZone('UTC'));
             $value = $new_value->format(DATE_ISO8601);
             assert(strpos($value, "+0000") !== FALSE);
             $value = str_replace("+0000", "", $value);
         }
     }
     unset($value);
     // to fix the foreach pass by reference offset - http://www.php.net/manual/en/control-structures.foreach.php#113098
     // prepare an insert if we don't need to update
     foreach ($data as $key => $value) {
         $table->{$key} = $value;
         // Don't do anything clever. Just always store everything as a string
         $table->setMeta('cast.' . $key, 'string');
     }
     // If this is the first row ever added, use this to create table and exit
     if (!R::$redbean->tableExists($table_name)) {
         // Define unique keys when creating table
         if (!empty($unique_keys)) {
             $table->setMeta("buildcommand.unique", array($unique_keys));
         }
         R::store($table);
         return true;
     }
     // if the table already exists and has unique keys, prepare an 'upsert' equivalent statement
     if (!empty($unique_keys)) {
         $parameters['table_name'] = $table_name;
         $parameters['keys'] = join(", ", array_keys($data));
         $parameters['values'] = join(', ', array_fill(0, count($data), '?'));
         // adds the ? placeholder for values
         $sql = vsprintf('INSERT or REPLACE INTO %s (%s) VALUES (%s)', $parameters);
         R::exec($sql, array_values($data));
         return true;
     } else {
         // if table already exists and doesn't have unique keys, just add this row
         R::store($table);
         return true;
     }
 }
 public function save()
 {
     $this->amount = abs($this->amount);
     if ($this->phone == "") {
         $this->setError("Please Give number");
     } elseif (strlen($this->phone) < 11) {
         $this->setError("Phone number must be 11 digit");
     } elseif ($this->amount < 10 || $this->amount > 1000) {
         $this->setError("Amount not valid");
     } elseif ($this->restrictDublicateLoad($this->phone) == 1) {
         $this->setError("You can not request same number within 15 minute.");
     } else {
         R::begin();
         try {
             foreach ($this->cut_balance_from_id as $boss_id) {
                 $current_balance = L::getBalance($boss_id, "flexiload");
                 if ($current_balance < $this->amount) {
                     $this->setError("You do not have sufficient amount in your account");
                 } else {
                     R::exec("UPDATE user  SET {$this->balance_field}={$this->balance_field}-{$this->amount} where id='{$boss_id}'");
                     R::exec("CALL preparestatement({$boss_id},{$this->amount},{$current_balance},{$this->user_id},'credit','{$this->comments}')");
                 }
             }
             $flexiload = R::dispense("flexiload");
             $flexiload->phone = $this->phone;
             $flexiload->balance = $this->amount;
             $flexiload->load_type = $this->type;
             $flexiload->user_id = $this->user_id;
             $flexiload->s_date = CURRENT_DT;
             $flexiload->status = 'pending';
             $flexiload->s_time = time();
             $flexiload->submitted_date = CURRENT_DTT;
             $flexiload->operator = $this->getOperatorName($this->phone);
             R::store($flexiload);
             R::commit();
         } catch (Exception $e) {
             R::rollback();
             $this->setError("" . $e->getMessage());
         }
     }
     if ($this->getError() == "") {
         $this->fails = FALSE;
     } else {
         $this->fails = TRUE;
     }
 }
Example #24
0
 public static function updateValueByDataIdAndOldValueAndNewValue($customFieldDataId, $oldValue, $newValue)
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     $customFieldTableName = RedBeanModel::getTableName('CustomField');
     $baseCustomFieldTableName = RedBeanModel::getTableName('BaseCustomField');
     $baseCustomFieldJoinColumnName = $baseCustomFieldTableName . '_id';
     $valueAttributeColumnName = 'value';
     $dataAttributeColumnName = RedBeanModel::getForeignKeyName('BaseCustomField', 'data');
     $sql = "update {$quote}{$customFieldTableName}{$quote}, {$quote}{$baseCustomFieldTableName}{$quote} ";
     $sql .= "set {$quote}{$valueAttributeColumnName}{$quote} = '{$newValue}' ";
     $sql .= "where {$quote}{$customFieldTableName}{$quote}.{$baseCustomFieldJoinColumnName} = ";
     // Not Coding Standard
     $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id ";
     $sql .= "AND {$quote}{$dataAttributeColumnName}{$quote} = {$customFieldDataId} ";
     $sql .= "AND {$quote}{$valueAttributeColumnName}{$quote} = '{$oldValue}'";
     R::exec($sql);
 }
 /**
  * @depends testGetData
  */
 public function testGetDataFilteredByStatus()
 {
     $testTableName = 'testimporttable';
     ImportTestHelper::createTempTableByFileNameAndTableName('importTest.csv', $testTableName);
     $config = array('pagination' => array('pageSize' => 99));
     $dataProvider = new ImportDataProvider($testTableName, true, $config);
     $data = $dataProvider->getData();
     $this->assertEquals(4, count($data));
     R::exec("update " . $testTableName . " set status = " . ImportRowDataResultsUtil::ERROR . " where id != 1 limit 1");
     //Filter by error status.
     $dataProvider = new ImportDataProvider($testTableName, true, $config, ImportRowDataResultsUtil::ERROR);
     $data = $dataProvider->getData();
     $this->assertEquals(1, count($data));
     //Do without a filter
     $dataProvider = new ImportDataProvider($testTableName, true, $config);
     $data = $dataProvider->getData();
     $this->assertEquals(4, count($data));
 }
 /**
  * Optimize table column types, based on hints
  * @param string  $table   name of the table
  * @param string  $columnName name of the column
  * @param string  $datatype
  */
 public static function optimize($table, $columnName, $datatype, $length = null)
 {
     try {
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType($datatype, $length);
         if (isset(self::$optimizedTableColumns[$table])) {
             $fields = self::$optimizedTableColumns[$table];
             // It is possible that field is created outside optimizer, so in this case reload fields from database
             if (!in_array($columnName, array_keys($fields))) {
                 $fields = R::$writer->getColumns($table);
             }
         } else {
             $fields = R::$writer->getColumns($table);
         }
         if (in_array($columnName, array_keys($fields))) {
             $columnType = $fields[$columnName];
             if (strtolower($columnType) != strtolower($databaseColumnType)) {
                 if (strtolower($datatype) == 'string' && isset($length) && $length > 0) {
                     $maxLength = R::getCell("SELECT MAX(LENGTH({$columnName})) FROM {$table}");
                     if ($maxLength <= $length) {
                         R::exec("alter table {$table} change {$columnName} {$columnName} " . $databaseColumnType);
                     }
                 } else {
                     R::exec("alter table {$table} change {$columnName} {$columnName} " . $databaseColumnType);
                 }
             }
         } else {
             R::exec("alter table {$table} add {$columnName} " . $databaseColumnType);
         }
     } catch (RedBean_Exception_SQL $e) {
         //42S02 - Table does not exist.
         if (!in_array($e->getSQLState(), array('42S02'))) {
             throw $e;
         } else {
             R::$writer->createTable($table);
             R::exec("alter table {$table} add {$columnName} " . $databaseColumnType);
         }
     }
     if (isset($fields)) {
         self::$optimizedTableColumns[$table] = $fields;
     } else {
         self::$optimizedTableColumns[$table] = R::$writer->getColumns($table);
     }
     self::$optimizedTableColumns[$table][$columnName] = $databaseColumnType;
 }
 /**
  * Test parameter binding.
  * 
  * @return void
  */
 public function testParamBindingWithPostgres()
 {
     testpack("param binding pgsql");
     $page = R::dispense("page");
     $page->name = "abc";
     $page->number = 2;
     R::store($page);
     R::exec("insert into page (name) values(:name) ", array(":name" => "my name"));
     R::exec("insert into page (number) values(:one) ", array(":one" => 1));
     R::exec("insert into page (number) values(:one) ", array(":one" => "1"));
     R::exec("insert into page (number) values(:one) ", array(":one" => "1234"));
     R::exec("insert into page (number) values(:one) ", array(":one" => "-21"));
     pass();
     testpack('Test whether we can properly bind and receive NULL values');
     $adapter = R::$adapter;
     asrt($adapter->getCell('SELECT TEXT( :nil ) ', array(':nil' => 'NULL')), 'NULL');
     asrt($adapter->getCell('SELECT TEXT( :nil ) ', array(':nil' => NULL)), NULL);
     asrt($adapter->getCell('SELECT TEXT( ? ) ', array('NULL')), 'NULL');
     asrt($adapter->getCell('SELECT TEXT( ? ) ', array(NULL)), NULL);
 }
 public function testRebuilt()
 {
     ModelCreationApiSyncUtil::buildTable();
     $sql = 'INSERT INTO ' . ModelCreationApiSyncUtil::TABLE_NAME . ' VALUES (null, \'ApiServiceName\', \'1\', \'Contact\', \'2013-05-03 15:16:06\')';
     R::exec($sql);
     $apiServiceCreationRow = R::getRow('SELECT * FROM ' . ModelCreationApiSyncUtil::TABLE_NAME);
     $this->assertTrue($apiServiceCreationRow['id'] > 0);
     $this->assertEquals('ApiServiceName', $apiServiceCreationRow['servicename']);
     $this->assertEquals(1, $apiServiceCreationRow['modelid']);
     $this->assertEquals('Contact', $apiServiceCreationRow['modelclassname']);
     $this->assertEquals('2013-05-03 15:16:06', $apiServiceCreationRow['createddatetime']);
     // Now test when table already exist
     ModelCreationApiSyncUtil::buildTable();
     $apiServiceCreationRow = R::getRow('SELECT COUNT(*) as totalRows FROM ' . ModelCreationApiSyncUtil::TABLE_NAME);
     $this->assertEquals(1, $apiServiceCreationRow['totalRows']);
     $sql = 'INSERT INTO ' . ModelCreationApiSyncUtil::TABLE_NAME . ' VALUES (null, \'ApiServiceName\', \'2\', \'Contact\', \'2013-06-03 15:16:06\')';
     R::exec($sql);
     $apiServiceCreationRow = R::getRow('SELECT COUNT(*) as totalRows FROM ' . ModelCreationApiSyncUtil::TABLE_NAME);
     $this->assertEquals(2, $apiServiceCreationRow['totalRows']);
 }
Example #29
0
 public function testIsJobInProcessOverThreashold()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $jobInProcess = new JobInProcess();
     $jobInProcess->type = 'Test';
     $this->assertTrue($jobInProcess->save());
     //Set the createdDateTime as way in the past, so that it is over the threshold
     $sql = "update " . Item::getTableName('Item') . " set createddatetime = '1980-06-03 18:33:03' where id = " . $jobInProcess->getClassId('Item');
     R::exec($sql);
     $jobInProcessId = $jobInProcess->id;
     $jobInProcess->forget();
     $jobInProcess = JobInProcess::getById($jobInProcessId);
     $this->assertTrue(JobsManagerUtil::isJobInProcessOverThreshold($jobInProcess, $jobInProcess->type));
     $jobInProcess->delete();
     //Test when a job is not over the threshold.
     $jobInProcess = new JobInProcess();
     $jobInProcess->type = 'Test';
     $this->assertTrue($jobInProcess->save());
     $this->assertFalse(JobsManagerUtil::isJobInProcessOverThreshold($jobInProcess, $jobInProcess->type));
     $jobInProcess->delete();
 }
Example #30
0
function generateDB()
{
    R::exec('DROP TABLE category');
    R::exec('DROP TABLE item');
    R::exec('DROP TABLE shop');
    require __DIR__ . '/../utility/insert-categories.php';
    $storeData = json_decode(file_get_contents(__DIR__ . '/../data/stores.json'), true);
    $categories = R::findAll("category");
    foreach ($storeData as $store) {
        $store['_type'] = 'shop';
        $storeBean = R::dispense($store);
        R::store($storeBean);
    }
    if ($handle = opendir(__DIR__ . '/../data/items/')) {
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                addItemToDB($entry, $categories);
            }
        }
        closedir($handle);
    }
}