Esempio n. 1
0
function pg($t)
{
    global $pdo;
    $tm = new TransactionManager($pdo);
    $txn1 = $tm->txn_scope();
    $pdo->query("INSERT INTO job (func) VALUES ('baz')");
    $txn2 = $tm->txn_scope();
    $pdo->query("INSERT INTO job (func) VALUES ('bab')");
    $txn2->commit();
    $txn1->commit();
    $stmt = $pdo->query('SELECT * FROM job');
    $rows = $stmt->fetch(PDO::FETCH_ASSOC);
    $t->is(sizeof($rows), 2);
    $stmt->closeCursor();
}
Esempio n. 2
0
 public static function process($exception)
 {
     if (class_exists('TransactionManager')) {
         TransactionManager::rollback();
     }
     $params = array('class' => $class = get_class($exception), 'message' => $exception->getMessage(), 'file' => str_replace(ROOT, 'ROOT', $exception->getFile()), 'line' => $exception->getLine(), 'trace' => $exception->getTraceAsString());
     $textError = self::_text($params);
     if (Configure::read('debug') == 0) {
         Object::log($textError);
         switch (true) {
             case $class === 'DatabaseError':
                 return Object::cakeError('error503', array(array('code' => 503, 'name' => 'Service Unavailable', 'message' => '')));
             case isset($exception->httpCode):
                 $error = $exception->httpCode === 403 ? 'forbidden' : 'error' . $exception->httpCode;
                 return Object::cakeError($error);
         }
         return Object::cakeError('error500', array(array('code' => 500, 'name' => 'An Internal Error Has Occurred', 'message' => '')));
     } else {
         if (php_sapi_name() == 'cli') {
             echo $textError;
         } else {
             header('Content-Type: text/html; charset=UTF-8');
             echo self::_html($params);
         }
     }
 }
 public static function getInstance()
 {
     if (!self::$instance) {
         self::$instance = new TransactionManager();
     }
     return self::$instance;
 }
Esempio n. 4
0
 public function testStartedByOther()
 {
     TransactionManager::begin($this->Model->useDbConfig);
     $this->Model->save($this->Model->create());
     $this->assertEqual($this->_getBehavior()->log, array());
     TransactionManager::rollback($this->Model->useDbConfig);
 }
    /**
     * @static
     * @return TransactionManager
     */
    public static function getInstance() {
        if (!isset(self::$manager)) {
            self::$manager = new DefaultTransactionManager();
        }

        return self::$manager;
    }
 /**
  * gets the group that this user's friends belong to 
  */
 public function getGroupFor($type)
 {
     $groupType = $type . 'Group';
     $groupTypeID = $type . 'GroupID';
     if ($this->owner->{$groupTypeID}) {
         return $this->owner->{$groupType}();
     }
     $title = $this->owner->Email . ' ' . $type;
     $group = SimpleMemberList::get()->filter(array('Title' => $title))->first();
     if ($group && $group->exists()) {
         $this->owner->{$groupTypeID} = $group->ID;
         return $group;
     } else {
         $group = $this->transactionManager->runAsAdmin(function () use($title) {
             $group = SimpleMemberList::create();
             $group->Title = $title;
             $group->write();
             return $group;
         });
         if ($group) {
             $this->owner->{$groupTypeID} = $group->ID;
         }
         return $group;
     }
 }
 /**
  * For event in shared context:
  * Node.@images.add.post
  *
  * @param NodeRef $nodeRef      NodeRef Being Added
  * @param Node    $node         Node Being added
  * @param null    $notUsed      Paramater passed in via Events::trigger, but set to null, and not used.
  * @param bool    $asyncRebuild Wether to rebuildThumbnails asyncronously or not (defaults to true)
  *
  * @return void
  */
 public function processAdd(NodeRef $nodeRef, Node $node, $notUsed = null, $asyncRebuild = true)
 {
     $node = $this->RegulatedNodeService->getByNodeRef($nodeRef, new NodePartials('', '#original.fields'));
     //-----------
     // Build CMS thumbnail separately so that it's ready when this action completes.
     $file = $this->FileService->retrieveFileFromNode($node->getElement(), $node->getOutTag('#original')->TagLinkNodeRef);
     if ($file === null) {
         throw new Exception('File cannot be retrieved for Node');
     }
     $cmsThumb = $this->ImageService->createAndStoreThumbnail($node->getElement(), $this->imagesThumbnailCmsSize, $file->getLocalPath(), $this->ImageService->filenameForNode($node));
     $tag = new Tag($cmsThumb->getElement()->getSlug(), $cmsThumb->Slug, '#thumbnails', $this->imagesThumbnailCmsSize, $this->imagesThumbnailCmsSize);
     $node->replaceOutTags('#thumbnails', array($tag));
     $this->RegulatedNodeService->edit($node);
     if ($asyncRebuild) {
         // commit so the node is ready for the worker
         $this->TransactionManager->commit()->begin();
         //-----------
         // Rebuild thumbnails asynchronously
         $workerParams = array('nodeRef' => '' . $node->getNodeRef(), 'forceRebuildExisting' => false);
         $this->GearmanService->doBackgroundJob('ImagesWorker', 'rebuildThumbnails', $workerParams, 'high');
     } else {
         $this->ImageService->rebuildMissingThumbnails($node->getNodeRef(), false);
     }
     // remove storage facility generated temp file
     @unlink($file->getLocalPath());
 }
 public static function commit($datasource = 'default')
 {
     $result = parent::commit($datasource);
     if ($result) {
         self::$commited[] = $datasource;
     }
     return $result;
 }
 public function buildThumbnails(NodeRef $nodeRef, Node $node)
 {
     // commit so the node is ready for the worker
     $this->TransactionManager->commit()->begin();
     //-----------
     // Rebuild thumbnails asynchronously
     $workerParams = array('nodeRef' => '' . $nodeRef, 'forceRebuildExisting' => false);
     $this->GearmanService->doBackgroundJob('ImagesWorker', 'rebuildThumbnails', $workerParams, 'high');
 }
 public function run($request)
 {
     if (!$this->transactionManager) {
         Injector::inst()->inject($this);
     }
     $this->transactionManager->runAsAdmin(function () {
         $members = DataList::create('Member');
         foreach ($members as $member) {
             if (!$member->Username) {
                 list($username) = explode('@', $member->Email);
                 $member->Username = preg_replace('/\\W+/', '_', $username);
                 echo "Updating '{$username}' <br/>\n";
                 $member->write();
             } else {
                 echo "{$member->Username} already set <br/>\n";
             }
         }
     });
 }
 protected function getConnection(DataSourceMetaData $datasource)
 {
     $transaction = TransactionManager::getInstance()->getTransaction($datasource->name);
     $connectionName = $transaction->assembleResourceName(get_class($datasource), $datasource->name);
     $connection = $transaction->findResource($connectionName);
     if (!isset($connection)) {
         $connection = $this->getExtension('initializeConnection')->initialize($this, $datasource);
         if (!$datasource->temporary) {
             $transaction->registerResource($connectionName, $connection);
             $transaction->registerActionCallback(new ConnectionTransactionActionCallback($datasource->name));
         }
     }
     return $connection;
 }
 /**
  * Vote for a particular post
  * 
  * @param DataObject $post 
  */
 public function vote(DataObject $post, $dir = 1)
 {
     $member = $this->securityContext->getMember();
     if ($member->VotesToGive <= 0) {
         $post->RemainingVotes = 0;
         return $post;
     }
     // we allow multiple votes - as many as the user has to give! unless
     // configured not to...
     $currentVote = null;
     if ($this->singleVotes) {
         $votes = $post->currentVotesByUser();
         if (count($votes)) {
             $currentVote = $votes[0];
         }
     }
     if (!$currentVote) {
         $currentVote = MicroPostVote::create();
         $currentVote->UserID = $member->ID;
         $currentVote->PostID = $post->ID;
     }
     $currentVote->Direction = $dir > 0 ? 1 : -1;
     $currentVote->write();
     $list = DataList::create('MicroPostVote');
     $upList = $list->filter(array('PostID' => $post->ID, 'Direction' => 1));
     $post->Up = $upList->count();
     $downList = $list->filter(array('PostID' => $post->ID, 'Direction' => -1));
     $post->Down = $downList->count();
     $owner = $post->Owner();
     if (!$post->OwnerID || !$owner || !$owner->exists()) {
         $owner = Security::findAnAdministrator();
     }
     // write the post as the owner, and calculate some changes for the author
     $this->transactionManager->run(function () use($post, $currentVote, $member) {
         $author = $post->Owner();
         if ($author && $author->exists() && $author->ID != $member->ID) {
             if ($currentVote->Direction > 0) {
                 $author->Up += 1;
             } else {
                 $author->Down += 1;
             }
             $author->write();
         }
         $post->write();
     }, $owner);
     $this->rewardMember($member, -1);
     $post->RemainingVotes = $member->VotesToGive;
     return $post;
 }
Esempio n. 13
0
function in_transactin($t)
{
    $pdo = Utils::setup();
    $tm = new TransactionManager($pdo);
    $t->ok(!$tm->in_transaction());
    $tm->txn_begin();
    $t->ok($tm->in_transaction());
    $tm->txn_commit();
    $t->ok(!$tm->in_transaction());
}
 public function process()
 {
     $fromTime = $this->since ? $this->since : 0;
     $members = $this->members;
     $nextId = array_shift($members);
     $this->members = $members;
     $member = Member::get()->byID($nextId);
     $microBlogService = $this->microBlogService;
     // if we don't have a 'since' time, we need to only scan from 'now' onwards, to prevent _every_
     // post from being collected
     if (!$fromTime) {
         $fromTime = time();
     }
     $since = date('Y-m-d 00:00:00', $fromTime);
     if ($member && $member->ID) {
         $this->transactionManager->run(function () use($microBlogService, $since, $member) {
             $posts = $microBlogService->globalFeed(array('ParentID' => 0, 'ThreadOwnerID:not' => $member->ID, 'Created:GreaterThan' => $since), $orderBy = 'ID DESC', $since = null, $number = 10, $markViewed = false);
             if (!count($posts)) {
                 return;
             }
             $content = SSViewer::execute_template('DigestEmail', ArrayData::create(array('Posts' => $posts, 'Member' => $member)));
             $content = HTTP::absoluteURLs($content);
             $config = SiteConfig::current_site_config();
             $mail = new Email();
             $mail->setTo($member->Email);
             $mail->setBody($content);
             $mail->setSubject($config->Title . ' digest');
             if ($config->FromEmail) {
                 $mail->setFrom($config->FromEmail);
             }
             $mail->send();
         }, $member);
     }
     $this->currentStep++;
     if (count($members) == 0) {
         if (!$this->sendTime) {
             $this->sendTime = '23:55:00';
         }
         $nextTime = $this->type == 'weekly' ? '+1 week' : '+1 day';
         $nextDate = date('Y-m-d ' . $this->sendTime, strtotime($nextTime));
         $nextJob = new MicroPostDigestJob(time(), $this->type, $this->groupId, $this->sendTime);
         singleton('QueuedJobService')->queueJob($nextJob, $nextDate);
         $this->isComplete = true;
     }
 }
 * Created by PhpStorm.
 * User: agustin
 * Date: 27/07/2015
 * Time: 12:34
 */
$path_to_IncludeClases = "../com/payhub/ws/extra/includeClasses.php";
include_once $path_to_IncludeClases;
//Defining the Web Service URL
$WsURL = "https://sandbox-api.payhub.com/api/v2/";
$oauth_token = "2a5d6a73-d294-4fba-bfba-957a4948d4a3";
//Defining data for the SALE transaction
// Merchant data (obtained from the payHub Virtual Terminal (3rd party integration)
$merchant = new Merchant();
$merchant->setOrganizationId(10074);
$merchant->setTerminalId(134);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
//$result = $transaction->getRiskFraudSettings();
//var_dump($result);
$risk = new RiskFraudSettings();
$trnVolSet = new TrnVolSet();
$trnVolSet->setChecked(false);
$optionAndValue = new OptionAndValue();
$optionAndValue->setOption(2);
$optionAndValue->setValue(5000);
$trnVolSet->setDaysTrnAmountMoreThan($optionAndValue);
$risk->setTransactionVolumeSettings($trnVolSet);
$result = $transaction->patchRiskFraudSettings($risk);
if (is_array($result)) {
    var_dump($result);
} else {
    $result = $transaction->getRiskFraudSettings();
<?php

/**
 * Created by PhpStorm.
 * User: agustin
 * Date: 27/07/2015
 * Time: 12:34
 */
$path_to_IncludeClases = "../com/payhub/ws/extra/includeClasses.php";
include_once $path_to_IncludeClases;
//Defining the Web Service URL
$WsURL = "https://sandbox-api.payhub.com/api/v2/";
$oauth_token = "2a5d6a73-d294-4fba-bfba-957a4948d4a3";
//Defining data for the SALE transaction
// Merchant data (obtained from the payHub Virtual Terminal (3rd party integration)
$merchant = new Merchant();
$merchant->setOrganizationId(10074);
$merchant->setTerminalId(134);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
$result = $transaction->getGeneralSettings();
var_dump($result);
Esempio n. 17
0
 /**
  * blcLink::save()
  * Save link data to DB.
  *
  * @return bool True if saved successfully, false otherwise.
  */
 function save()
 {
     global $wpdb, $blclog;
     /** @var wpdb $wpdb */
     if (!$this->valid()) {
         return false;
     }
     //A link can't be broken and treated as a warning at the same time.
     if ($this->broken && $this->warning) {
         $this->warning = false;
     }
     //Make a list of fields to be saved and their values in DB format
     $values = array();
     foreach ($this->field_format as $field => $format) {
         $values[$field] = $this->{$field};
     }
     $values = $this->to_db_format($values);
     if ($this->is_new) {
         TransactionManager::getInstance()->commit();
         //BUG: Technically, there should be a 'LOCK TABLES wp_blc_links WRITE' here. In fact,
         //the plugin should probably lock all involved tables whenever it parses something, lest
         //the user (ot another plugin) modify the thing being parsed while we're working.
         //The problem with table locking, though, is that parsing takes a long time and having
         //all of WP freeze while the plugin is working would be a Bad Thing. Food for thought.
         //Check if there's already a link with this URL present
         $q = $wpdb->prepare("SELECT link_id FROM {$wpdb->prefix}blc_links WHERE url = %s", $this->url);
         $existing_id = $wpdb->get_var($q);
         if (!empty($existing_id)) {
             //Dammit.
             $this->link_id = $existing_id;
             $this->is_new = false;
             return true;
         }
         //Insert a new row
         $q = sprintf("INSERT INTO {$wpdb->prefix}blc_links( %s ) VALUES( %s )", implode(', ', array_keys($values)), implode(', ', array_values($values)));
         //FB::log($q, 'Link add query');
         $blclog->debug(__CLASS__ . ':' . __FUNCTION__ . ' Adding a new link. SQL query:' . "\n", $q);
         $rez = $wpdb->query($q) !== false;
         if ($rez) {
             $this->link_id = $wpdb->insert_id;
             $blclog->debug(__CLASS__ . ':' . __FUNCTION__ . ' Database record created. ID = ' . $this->link_id);
             //FB::info($this->link_id, "Link added");
             //If the link was successfully saved then it's no longer "new"
             $this->is_new = false;
         } else {
             $blclog->error(__CLASS__ . ':' . __FUNCTION__ . ' Error adding link', $this->url);
             //FB::error($wpdb->last_error, "Error adding link {$this->url}");
         }
         return $rez;
     } else {
         if ($this->isOptionLinkChanged !== true) {
             TransactionManager::getInstance()->start();
         }
         $this->isOptionLinkChanged = false;
         //Generate the field = dbvalue expressions
         $set_exprs = array();
         foreach ($values as $name => $value) {
             $set_exprs[] = "{$name} = {$value}";
         }
         $set_exprs = implode(', ', $set_exprs);
         //Update an existing DB record
         $q = sprintf("UPDATE {$wpdb->prefix}blc_links SET %s WHERE link_id=%d", $set_exprs, intval($this->link_id));
         //FB::log($q, 'Link update query');
         $blclog->debug(__CLASS__ . ':' . __FUNCTION__ . ' Updating a link. SQL query:' . "\n", $q);
         $rez = $wpdb->query($q) !== false;
         if ($rez) {
             //FB::log($this->link_id, "Link updated");
             $blclog->debug(__CLASS__ . ':' . __FUNCTION__ . ' Link updated.');
         } else {
             $blclog->error(__CLASS__ . ':' . __FUNCTION__ . ' Error updating link', $this->url);
             //FB::error($wpdb->last_error, "Error updating link {$this->url}");
         }
         return $rez;
     }
 }
Esempio n. 18
0
 /**
  * The main worker function that does all kinds of things.
  *
  * @return void
  */
 function work()
 {
     global $blclog;
     //Close the session to prevent lock-ups.
     //PHP sessions are blocking. session_start() will wait until all other scripts that are using the same session
     //are finished. As a result, a long-running script that unintentionally keeps the session open can cause
     //the entire site to "lock up" for the current user/browser. WordPress itself doesn't use sessions, but some
     //plugins do, so we should explicitly close the session (if any) before starting the worker.
     if (session_id() != '') {
         session_write_close();
     }
     if (!$this->acquire_lock()) {
         //FB::warn("Another instance of BLC is already working. Stop.");
         $blclog->info('Another instance of BLC is already working. Stop.');
         return;
     }
     if ($this->server_too_busy()) {
         //FB::warn("Server is too busy. Stop.");
         $blclog->warn('Server load is too high, stopping.');
         return;
     }
     $this->start_timer();
     $blclog->info('work() starts');
     $max_execution_time = $this->conf->options['max_execution_time'];
     /*****************************************
     						Preparation
     		******************************************/
     // Check for safe mode
     if (blcUtility::is_safe_mode()) {
         // Do it the safe mode way - obey the existing max_execution_time setting
         $t = ini_get('max_execution_time');
         if ($t && $t < $max_execution_time) {
             $max_execution_time = $t - 1;
         }
     } else {
         // Do it the regular way
         @set_time_limit($max_execution_time * 2);
         //x2 should be plenty, running any longer would mean a glitch.
     }
     //Don't stop the script when the connection is closed
     ignore_user_abort(true);
     //Close the connection as per http://www.php.net/manual/en/features.connection-handling.php#71172
     //This reduces resource usage.
     //(Disable when debugging or you won't get the FirePHP output)
     if (!headers_sent() && (defined('DOING_AJAX') && constant('DOING_AJAX')) && (!defined('BLC_DEBUG') || !constant('BLC_DEBUG'))) {
         @ob_end_clean();
         //Discard the existing buffer, if any
         header("Connection: close");
         ob_start();
         echo 'Connection closed';
         //This could be anything
         $size = ob_get_length();
         header("Content-Length: {$size}");
         ob_end_flush();
         // Strange behaviour, will not work
         flush();
         // Unless both are called !
     }
     //Load modules for this context
     $moduleManager = blcModuleManager::getInstance();
     $moduleManager->load_modules('work');
     $target_usage_fraction = $this->conf->get('target_resource_usage', 0.25);
     //Target usage must be between 1% and 100%.
     $target_usage_fraction = max(min($target_usage_fraction, 1), 0.01);
     /*****************************************
     				Parse posts and bookmarks
     		******************************************/
     $orphans_possible = false;
     $still_need_resynch = $this->conf->options['need_resynch'];
     if ($still_need_resynch) {
         //FB::log("Looking for containers that need parsing...");
         $max_containers_per_query = 50;
         $start = microtime(true);
         $containers = blcContainerHelper::get_unsynched_containers($max_containers_per_query);
         $get_containers_time = microtime(true) - $start;
         while (!empty($containers)) {
             //FB::log($containers, 'Found containers');
             $this->sleep_to_maintain_ratio($get_containers_time, $target_usage_fraction);
             foreach ($containers as $container) {
                 $synch_start_time = microtime(true);
                 //FB::log($container, "Parsing container");
                 $container->synch();
                 $synch_elapsed_time = microtime(true) - $synch_start_time;
                 $blclog->info(sprintf('Parsed container %s[%s] in %.2f ms', $container->container_type, $container->container_id, $synch_elapsed_time * 1000));
                 //Check if we still have some execution time left
                 if ($this->execution_time() > $max_execution_time) {
                     //FB::log('The allotted execution time has run out');
                     blc_cleanup_links();
                     $this->release_lock();
                     return;
                 }
                 //Check if the server isn't overloaded
                 if ($this->server_too_busy()) {
                     //FB::log('Server overloaded, bailing out.');
                     blc_cleanup_links();
                     $this->release_lock();
                     return;
                 }
                 //Intentionally slow down parsing to reduce the load on the server. Basically,
                 //we work $target_usage_fraction of the time and sleep the rest of the time.
                 $this->sleep_to_maintain_ratio($synch_elapsed_time, $target_usage_fraction);
             }
             $orphans_possible = true;
             $start = microtime(true);
             $containers = blcContainerHelper::get_unsynched_containers($max_containers_per_query);
             $get_containers_time = microtime(true) - $start;
         }
         //FB::log('No unparsed items found.');
         $still_need_resynch = false;
     } else {
         //FB::log('Resynch not required.');
     }
     /******************************************
     				    Resynch done?
     		*******************************************/
     if ($this->conf->options['need_resynch'] && !$still_need_resynch) {
         $this->conf->options['need_resynch'] = $still_need_resynch;
         $this->conf->save_options();
     }
     /******************************************
     				    Remove orphaned links
     		*******************************************/
     if ($orphans_possible) {
         $start = microtime(true);
         $blclog->info('Removing orphaned links.');
         blc_cleanup_links();
         $get_links_time = microtime(true) - $start;
         $this->sleep_to_maintain_ratio($get_links_time, $target_usage_fraction);
     }
     //Check if we still have some execution time left
     if ($this->execution_time() > $max_execution_time) {
         //FB::log('The allotted execution time has run out');
         $blclog->info('The allotted execution time has run out.');
         $this->release_lock();
         return;
     }
     if ($this->server_too_busy()) {
         //FB::log('Server overloaded, bailing out.');
         $blclog->info('Server load too high, stopping.');
         $this->release_lock();
         return;
     }
     /*****************************************
     						Check links
     		******************************************/
     $max_links_per_query = 30;
     $start = microtime(true);
     $links = $this->get_links_to_check($max_links_per_query);
     $get_links_time = microtime(true) - $start;
     while ($links) {
         $this->sleep_to_maintain_ratio($get_links_time, $target_usage_fraction);
         //Some unchecked links found
         //FB::log("Checking ".count($links)." link(s)");
         $blclog->info("Checking " . count($links) . " link(s)");
         //Randomizing the array reduces the chances that we'll get several links to the same domain in a row.
         shuffle($links);
         $transactionManager = TransactionManager::getInstance();
         $transactionManager->start();
         foreach ($links as $link) {
             //Does this link need to be checked? Excluded links aren't checked, but their URLs are still
             //tested periodically to see if they're still on the exclusion list.
             if (!$this->is_excluded($link->url)) {
                 //Check the link.
                 //FB::log($link->url, "Checking link {$link->link_id}");
                 $link->check(true);
             } else {
                 //FB::info("The URL {$link->url} is excluded, skipping link {$link->link_id}.");
                 $link->last_check_attempt = time();
                 $link->save();
             }
             //Check if we still have some execution time left
             if ($this->execution_time() > $max_execution_time) {
                 //FB::log('The allotted execution time has run out');
                 $blclog->info('The allotted execution time has run out.');
                 $this->release_lock();
                 return;
             }
             //Check if the server isn't overloaded
             if ($this->server_too_busy()) {
                 //FB::log('Server overloaded, bailing out.');
                 $blclog->info('Server load too high, stopping.');
                 $this->release_lock();
                 return;
             }
         }
         $transactionManager->commit();
         $start = microtime(true);
         $links = $this->get_links_to_check($max_links_per_query);
         $get_links_time = microtime(true) - $start;
     }
     //FB::log('No links need to be checked right now.');
     $this->release_lock();
     $blclog->info('work(): All done.');
     //FB::log('All done.');
 }
Esempio n. 19
0
 /**
  * Parse the container for links and save the results to the DB.
  *
  * @return void
  */
 function synch()
 {
     //FB::log("Parsing {$this->container_type}[{$this->container_id}]");
     //Remove any existing link instance records associated with the container
     $this->delete_instances();
     //Load the wrapped object, if not done already
     $this->get_wrapped_object();
     //FB::log($this->fields, "Parseable fields :");
     //Iterate over all parse-able fields
     foreach ($this->fields as $name => $format) {
         //Get the field value
         $value = $this->get_field($name);
         if (empty($value)) {
             //FB::log($name, "Skipping empty field");
             continue;
         }
         //FB::log($name, "Parsing field");
         //Get all parsers applicable to this field
         $parsers = blcParserHelper::get_parsers($format, $this->container_type);
         //FB::log($parsers, "Applicable parsers");
         if (empty($parsers)) {
             continue;
         }
         $base_url = $this->base_url();
         $default_link_text = $this->default_link_text($name);
         //Parse the field with each parser
         foreach ($parsers as $parser) {
             //FB::log("Parsing $name with '{$parser->parser_type}' parser");
             $found_instances = $parser->parse($value, $base_url, $default_link_text);
             //FB::log($found_instances, "Found instances");
             $transactionManager = TransactionManager::getInstance();
             $transactionManager->start();
             //Complete the link instances by adding container info, then save them to the DB.
             foreach ($found_instances as $instance) {
                 $instance->set_container($this, $name);
                 $instance->save();
             }
             $transactionManager->commit();
         }
     }
     $this->mark_as_synched();
 }
<?php

/**
 * Created by PhpStorm.
 * User: agustin
 * Date: 28/07/2015
 * Time: 15:40
 */
$path_to_IncludeClases = "../com/payhub/ws/extra/includeClasses.php";
include_once $path_to_IncludeClases;
//Defining the Web Service URL
$WsURL = "https://staging-api.payhub.com/api/v2/";
$oauth_token = "107d74ab-4a18-4713-88ff-69bd05710086";
//Defining data for the SALE transaction
// Merchant data (obtained from the payHub Virtual Terminal (3rd party integration)
$merchant = new Merchant();
$merchant->setOrganizationId(10127);
$merchant->setTerminalId(215);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
$result = $transaction->getAllCustomerForRecurringBillInformation();
var_dump($result);
$montly_s->monthly_type = "E";
$montly_s->monthly_each_days = array(15);
$start = new DateTime("2016-1-29");
$start = $start->format('Y-m-d');
$type = "O";
$endDate = new DateTime("2016-8-29");
$endDate = $endDate->format('Y-m-d');
$scheduleSandE = new ScheduleSartAndEnd();
$scheduleSandE->start_date = $start;
$scheduleSandE->end_date_type = $type;
$scheduleSandE->end_date = $endDate;
$schedule = new Schedule($scheduleSandE, $montly_s);
$schedule->schedule_type = "M";
$schedule->bill_generation_interval = 1;
$recurringBill = new RecurringBill($merchant, $customer, $bill, $card_data, $schedule);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
$response = $transaction->doRecurringBill($recurringBill);
if ($response->getErrors() == null) {
    $transactionId = $response->getLastRecurringBillResponse()->getRecurringBillId();
    $statusInfo = $response->getStatusInformation();
    var_dump($statusInfo);
    echo "Updating...";
    $canUpdate = $transaction->updateRecurringBillStatus($transactionId);
    if ($canUpdate) {
        $statusUpdated = $transaction->getRecurringBillInformation($transactionId);
        if ($statusUpdated->getErrors() == null) {
            var_dump($statusUpdated->getStatusInformation());
        }
    }
} else {
    var_dump($response->getErrors());
Esempio n. 22
0
<?php

/**
 * Created by PhpStorm.
 * User: agustin
 * Date: 28/07/2015
 * Time: 12:56
 */
$path_to_IncludeClases = "../com/payhub/ws/extra/includeClasses.php";
include_once $path_to_IncludeClases;
//Defining the Web Service URL
$WsURL = "https://staging-api.payhub.com/api/v2/";
$oauth_token = "107d74ab-4a18-4713-88ff-69bd05710086";
//Defining data for the SALE transaction
// Merchant data (obtained from the payHub Virtual Terminal (3rd party integration)
$merchant = new Merchant();
$merchant->setOrganizationId(10127);
$merchant->setTerminalId(215);
$void = new VoidTransaction($merchant, '{someSaleId}');
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
if ($result->getErrors() == null) {
    $transactionId = $result->getVerifyResponse()->getVoidId();
    $result2 = $transaction->getVoidInformation($transactionId);
    var_dump($result2);
} else {
    var_dump($result->getErrors());
}
Esempio n. 23
0
//Credit card data
$card_data = new CardData();
$card_data->setCardNumber("5466410004374507");
$card_data->setCardExpiryDate("202011");
$card_data->setCvvData("998");
$card_data->setBillingAddress1("2350 Kerner Blvd");
$card_data->setBillingAddress2("On the corner");
$card_data->setBillingCity("San Rafael");
$card_data->setBillingState("CA");
$card_data->setBillingZip("99997-0003");
// Customer data
$customer = new Customer();
$customer->setFirstName("First");
$customer->setLastName("Contact");
$customer->setCompanyName("Payhub Inc");
$customer->setJobTitle("Software Engineer");
$customer->setEmailAddress("*****@*****.**");
$customer->setWebAddress("http://payhub.com");
$customer->setPhoneNumber("(415) 479 1349");
$customer->setPhoneExt("123");
$customer->setPhoneType("M");
$object = new Verify($merchant, $customer, $card_data);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
$result = $transaction->doVerify($object);
if ($result->getErrors() == null) {
    $transactionId = $result->getVerifyResponse()->getVerifyId();
    $result2 = $transaction->getVerifyInformation($transactionId);
    var_dump($result2);
} else {
    var_dump($result->getErrors());
}
Esempio n. 24
0
<?php

error_reporting(E_ALL ^ E_NOTICE);
$input = array_merge($_REQUEST, $_GET, $_POST);
$url = 'http://localhost/payline/_example/pay.php';
$api = '';
require_once '../src/Payline.php';
$pay = new ATofighi\Payline($api);
$transactions = new TransactionManager();
$views = new ViewManager();
$views->globalData['input_amount'] = $input['amount'];
$views->globalData['url'] = $url;
switch ($input['action']) {
    case 'check':
        $r = $pay->get($input['trans_id'], $input['id_get']);
        if ($r == 1) {
            $tr = $transactions->get($input['id_get']);
            if ($tr) {
                if ($tr['status'] == 1) {
                    $views->display('layout', ['title' => 'خطا', 'error' => 'این تراکنش قبلا انجام شده بود!']);
                } else {
                    $tr['status'] = 1;
                    $tr['trans'] = $input['trans_id'];
                    $transactions->put($input['id_get'], $tr);
                    $views->display('layout', ['title' => 'سپاس', 'ok' => 'تراکنش با موفقیت انجام شد!']);
                }
            } else {
                $views->display('layout', ['title' => 'خطا', 'error' => 'تراکنش منقضی شده است.']);
            }
        } else {
            $views->display('layout', ['title' => 'خطا', 'error' => $pay->getError($r)]);
$card_data = new CardData();
$card_data->setCardNumber("5466410004374507");
$card_data->setCardExpiryDate("202011");
$card_data->setCvvData("998");
$card_data->setBillingAddress1("2350 Kerner Blvd");
$card_data->setBillingAddress2("On the corner");
$card_data->setBillingCity("San Rafael");
$card_data->setBillingState("CA");
$card_data->setBillingZip("99997-0003");
// Customer data
$customer = new Customer();
$customer->setFirstName("First");
$customer->setLastName("Contact");
$customer->setCompanyName("Payhub Inc");
$customer->setJobTitle("Software Engineer");
$customer->setEmailAddress("*****@*****.**");
$customer->setWebAddress("http://payhub.com");
$customer->setPhoneNumber("(415) 479 1349");
$customer->setPhoneExt("123");
$customer->setPhoneType("M");
$object = new Sale($merchant, $customer, $bill, $card_data);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
$result = $transaction->doSale($object);
if ($result->getErrors() == null) {
    $transactionId = $result->getSaleResponse()->getSaleId();
    $datos = "{\"order\": {\"id\": 465, \"invoice\":\"MyIncoice\", \"lines\": [{\"City\": \"Cordoba\"}, {\"Neighborhood\": \"Nueva Cordoba\"}]}}";
    $resultMetadata = $transaction->addMetaData($datos, TransactionType::Sale, $transactionId);
    var_dump($resultMetadata);
} else {
    var_dump($result->getErrors());
}
<?php

/**
 * Created by PhpStorm.
 * User: agustin
 * Date: 29/07/2015
 * Time: 11:16
 */
$path_to_IncludeClases = "../com/payhub/ws/extra/includeClasses.php";
include_once $path_to_IncludeClases;
//Defining the Web Service URL
$WsURL = "https://staging-api.payhub.com/api/v2/";
$oauth_token = "107d74ab-4a18-4713-88ff-69bd05710086";
//Defining data for the SALE transaction
// Merchant data (obtained from the payHub Virtual Terminal (3rd party integration)
$merchant = new Merchant();
$merchant->setOrganizationId(10127);
$merchant->setTerminalId(215);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
$response = $transaction->getRecurringBillInformation("1186");
var_dump($response);
 * Created by PhpStorm.
 * User: agustin
 * Date: 27/07/2015
 * Time: 12:34
 */
$path_to_IncludeClases = "../com/payhub/ws/extra/includeClasses.php";
include_once $path_to_IncludeClases;
//Defining the Web Service URL
$WsURL = "https://sandbox-api.payhub.com/api/v2/";
$oauth_token = "2a5d6a73-d294-4fba-bfba-957a4948d4a3";
//Defining data for the SALE transaction
// Merchant data (obtained from the payHub Virtual Terminal (3rd party integration)
$merchant = new Merchant();
$merchant->setOrganizationId(10074);
$merchant->setTerminalId(134);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
$ur = $transaction->getAllUserRoles();
$roleId = $ur->getUserRoles()[1]->getRoleId();
$rs = new RoleSettings();
$rs = $transaction->getUserRolesById($roleId);
//var_dump($rs);
$rs->setFirstDefaultScreen(2);
$rs->setRoleName("testFromPHP");
$rs->getReports()->setChecked(true);
$rs->getReports()->getReportOptions()->setCustom(false);
$result = $transaction->postUserRoles($rs);
if (is_array($result)) {
    //var_dump($result);
} else {
    $result = $transaction->getAllUserRoles();
    //var_dump($result);
Esempio n. 28
0
function pass_arbitrary_caller_info($t)
{
    $pdo = Utils::setup();
    $tm = new TransactionManager($pdo);
    $caller = array('file' => 'hoge.php', 'line' => 1);
    $txn = $tm->txn_scope($caller);
    set_error_handler('_error_handler2');
    $txn = null;
    restore_error_handler();
}
Esempio n. 29
0
 public static function destructs()
 {
     self::$__instances = array();
 }
<?php

/**
 * Created by PhpStorm.
 * User: agustin
 * Date: 27/07/2015
 * Time: 12:34
 */
$path_to_IncludeClases = "../com/payhub/ws/extra/includeClasses.php";
include_once $path_to_IncludeClases;
//Defining the Web Service URL
$WsURL = "https://sandbox-api.payhub.com/api/v2/";
$oauth_token = "2a5d6a73-d294-4fba-bfba-957a4948d4a3";
//Defining data for the SALE transaction
// Merchant data (obtained from the payHub Virtual Terminal (3rd party integration)
$merchant = new Merchant();
$merchant->setOrganizationId(10074);
$merchant->setTerminalId(134);
$transaction = new TransactionManager($merchant, $WsURL, $oauth_token);
$wh = new WebhookConfiguration();
$wh->setMobileHub(false);
$wh->setBatchIsActive(false);
$result = $transaction->patchWebhookConfiguration($wh);
if (is_array($result)) {
    var_dump($result);
} else {
    $result = $transaction->getWebhookConfiguration();
    var_dump($result);
}