/** * (non-PHPdoc) * @see DetailsPageAbstract::saveItem() */ public function saveItem($sender, $param) { $results = $errors = array(); try { Dao::beginTransaction(); $task = null; if (isset($param->CallbackParameter->id) && !($task = Task::get(trim($param->CallbackParameter->id))) instanceof Task) { throw new Exception('Invalid Task passed in!'); } if (!isset($param->CallbackParameter->instructions) || ($instructions = trim($param->CallbackParameter->instructions)) === '') { throw new Exception('Instructions are required!'); } if (!isset($param->CallbackParameter->customerId) || !($customer = Customer::get(trim($param->CallbackParameter->customerId))) instanceof Customer) { throw new Exception('Invalid Customer Passed in!'); } $tech = isset($param->CallbackParameter->techId) ? UserAccount::get(trim($param->CallbackParameter->techId)) : null; $order = isset($param->CallbackParameter->orderId) ? Order::get(trim($param->CallbackParameter->orderId)) : null; $dueDate = new UDate(trim($param->CallbackParameter->dueDate)); $status = isset($param->CallbackParameter->statusId) ? TaskStatus::get(trim($param->CallbackParameter->statusId)) : null; if (!$task instanceof Task) { $task = Task::create($customer, $dueDate, $instructions, $tech, $order); } else { $task->setCustomer($customer)->setDueDate($dueDate)->setInstructions($instructions)->setTechnician($tech)->setFromEntityId($order instanceof Order ? $order->getId() : '')->setFromEntityName($order instanceof Order ? get_class($order) : '')->setStatus($status)->save(); } // $results['url'] = '/task/' . $task->getId() . '.html?' . $_SERVER['QUERY_STRING']; $results['item'] = $task->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * getting the response * * @param UDate $time * * @return SimpleXMLElement */ protected function _getResponse(UDate $time) { Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); //TODO $response = new SimpleXMLElement('<Response />'); $response->addAttribute('Time', trim($time)); $response->addAttribute('TimeZone', trim($time->getTimeZone()->getName())); return $response; }
/** * Gets the user by id or current user * * @url GET /$id * @url GET /current */ public function getUser($id = null) { if ($id) { $user = UserAccount::get($id); // possible user loading method } else { $user = Core::getUser(); } return $user instanceof UserAccount ? $user->getJson() : array(); // serializes object into JSON }
/** * deactive a user * * @param unknown $sender * @param unknown $params * * @throws Exception */ public function deleteUser($sender, $param) { $results = $errors = array(); try { if (!isset($param->CallbackParameter->userId) || !($userAccount = UserAccount::get(trim($param->CallbackParameter->userId))) instanceof UserAccount) { throw new Exception("Invalid user account passed for deletion!"); } $results = $userAccount->setActive(false)->save()->getJson(); } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
public function saveUser($sender, $params) { $results = $errors = array(); try { Dao::beginTransaction(); if (!isset($params->CallbackParameter->firstName) || ($firstName = trim($params->CallbackParameter->firstName)) === '') { throw new Exception('System Error: firstName is mandatory!'); } if (!isset($params->CallbackParameter->lastName) || ($lastName = trim($params->CallbackParameter->lastName)) === '') { throw new Exception('System Error: lastName is mandatory!'); } if (!isset($params->CallbackParameter->userName) || ($userName = trim($params->CallbackParameter->userName)) === '') { throw new Exception('System Error: userName is mandatory!'); } if (!isset($params->CallbackParameter->roleid) || !($role = Role::get($params->CallbackParameter->roleid)) instanceof Role) { throw new Exception('System Error: role is mandatory!'); } $newpassword = trim($params->CallbackParameter->newpassword); if (!isset($params->CallbackParameter->userid) || !($userAccount = UserAccount::get($params->CallbackParameter->userid)) instanceof UserAccount) { $userAccount = new UserAccount(); $person = new Person(); if ($newpassword === '') { throw new Exception('System Error: new password is mandatory!'); } $newpassword = sha1($newpassword); } else { $person = $userAccount->getPerson(); if ($newpassword === '') { $newpassword = $userAccount->getPassword(); } else { $newpassword = sha1($newpassword); } } //double check whether the username has been used $users = UserAccount::getAllByCriteria('username=? and id!=?', array($userName, $userAccount->getId()), false, 1, 1); if (count($users) > 0) { throw new Exception('Username(=' . $userName . ') has been used by another user, please choose another one!'); } $person->setFirstName($firstName)->setLastName($lastName)->save(); $userAccount->setUserName($userName)->setPassword($newpassword)->setPerson($person)->save(); $results = $userAccount->clearRoles()->addRole($role)->getJson(); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); $errors[] = $ex->getMessage(); } $params->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * (non-PHPdoc) * @see BPCPageAbstract::_preGetEndJs() */ protected function _preGetEndJs() { parent::_preGetEndJs(); $order = $tech = $customer = null; if (isset($_REQUEST['customerId']) && !($customer = Customer::get(trim($_REQUEST['customerId']))) instanceof Customer) { die('Invalid Customer provided!'); } if (isset($_REQUEST['orderId']) && !($order = Order::get(trim($_REQUEST['orderId']))) instanceof Order) { die('Invalid Order provided!'); } if (isset($_REQUEST['techId']) && !($tech = UserAccount::get(trim($_REQUEST['techId']))) instanceof UserAccount) { die('Invalid Technician provided!'); } $statusIds = array(); if (isset($_REQUEST['statusIds']) && ($statusIds = trim($_REQUEST['statusIds'])) !== '') { $statusIds = array_map(create_function('$a', 'return intval(trim($a));'), explode(',', $statusIds)); } $allstatuses = isset($_REQUEST['allstatuses']) && intval(trim($_REQUEST['allstatuses'])) === 1; $preSetData = array('statuses' => array(), 'order' => $order instanceof Order ? $order->getJson() : array(), 'technician' => $tech instanceof UserAccount ? $tech->getJson() : array(), 'customer' => $customer instanceof Customer ? $customer->getJson() : array(), 'meId' => Core::getUser()->getId(), 'noDueDateStatusIds' => array()); $statuses = array(); foreach (TaskStatus::getAll() as $status) { $statuses[] = $statusJson = $status->getJson(); if (($noDueDateChecking = in_array(intval($status->getId()), TaskStatus::getClosedStatusIds())) === true) { $preSetData['noDueDateStatusIds'][] = $status->getId(); } if (count($statusIds) > 0) { if (in_array(intval($status->getId()), $statusIds)) { $preSetData['statuses'][] = $statusJson; } } else { if ($allstatuses === false && !$noDueDateChecking) { $preSetData['statuses'][] = $statusJson; } } } if (count($statusIds) > 0 && count($preSetData['statuses']) === 0) { die('Invalide Task Status provided.'); } $js = "pageJs"; $js .= ".setOpenInFancyBox(" . (isset($_REQUEST['blanklayout']) && intval(trim($_REQUEST['blanklayout'])) === 1 && (isset($_REQUEST['nosearch']) && intval($_REQUEST['nosearch']) === 1) ? 'false' : 'true') . ")"; $js .= ".setStatuses(" . json_encode($statuses) . ")"; $js .= ".setPreSetData(" . json_encode($preSetData) . ")"; $js .= ";"; return $js; }
private static function _setRunningUser($preFix = '', $debug = false) { self::_log('== Set Running User : '******'', $preFix); Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); self::_log('UserAccount(ID=' . Core::getUser()->getId() . ')', '', $preFix . self::TAB); if (!isset(self::$_api['URL']) || ($apiUrl = trim(self::$_api['URL'])) === '') { throw new Exception('No API URL set!'); } if (!isset(self::$_api['token']) || ($token = trim(self::$_api['token'])) === '') { self::_log('!! no token yet, need to get token.', '', $preFix . self::TAB); $url = $apiUrl . 'UserAccount/login'; $data = json_encode(array('username' => Core::getUser()->getUserName(), 'password' => Core::getUser()->getPassword())); self::_postJson($url, $data, $preFix . self::TAB, $debug); if (trim(self::$_api['token']) === '') { throw new Exception('Invalid token'); } } }
public function changePersonInfo($sender, $param) { $results = $errors = array(); try { if (!isset($param->CallbackParameter->firstName) || ($firstName = trim($param->CallbackParameter->firstName)) === '') { throw new Exception("Invalid firstName!"); } if (!isset($param->CallbackParameter->lastName) || ($lastName = trim($param->CallbackParameter->lastName)) === '') { throw new Exception("Invalid lastName!"); } Core::getUser()->getPerson()->setFirstName($firstName)->setLastName($lastName)->save(); Core::setUser(UserAccount::get(Core::getUser()->getId()), Core::getRole()); $results['succ'] = true; } catch (Exception $ex) { $errors[] = $ex->getMessage(); } $param->ResponseData = StringUtilsAbstract::getJson($results, $errors); }
/** * runner * @param string $debug */ public static function run($debug = false) { try { self::$_debug = $debug; Dao::beginTransaction(); Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); $start = self::_debug("Start to run " . __CLASS__ . ' =================== '); $assetIds = self::_findAllOverdueAssets(); $assetIds = array_merge($assetIds, self::_findAllZombieAssets()); self::_deleteAssets($assetIds); self::_debug("Finished to run " . __CLASS__ . ' =================== ', self::NEW_LINE, "", $start); Dao::commitTransaction(); } catch (Exception $ex) { Dao::rollbackTransaction(); self::_debug("***** ERROR: " . $ex->getMessage()); self::_debug($ex->getTraceAsString()); } }
/** * The runner * * @param string $preFix * @param string $debug */ public static function run($outputFileDir, $preFix = '', $debug = false) { $start = self::_log('## START ##############################', __CLASS__ . '::' . __FUNCTION__, $preFix); self::$_outputFileDir = trim($outputFileDir); self::_log('GEN FILE TO: ' . self::$_outputFileDir, '', $preFix . self::TAB); self::$_imageDirName = self::$_imageDirName . '_' . UDate::now()->format('Y_m_d_H_i_s'); Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); $now = UDate::now(); $settings = self::_getSettings($preFix . self::TAB, $debug); $lastUpdatedTime = UDate::zeroDate(); if (isset($settings['lastUpdatedTime']) && trim($settings['lastUpdatedTime']) !== '') { $lastUpdatedTime = new UDate(trim($settings['lastUpdatedTime'])); } self::_log('GOT LAST SYNC TIME: ' . trim($lastUpdatedTime), '', $preFix); $products = self::_getData($lastUpdatedTime, $preFix . self::TAB, $debug); if (count($products) > 0) { $files = self::_genCSV($lastUpdatedTime, array_values($products), $preFix . self::TAB, $debug); self::_zipFile($files, $preFix, $debug); self::_setSettings('lastUpdatedTime', trim($now), $preFix, $debug); } else { self::_log('NO changed products found after: "' . trim($lastUpdatedTime) . '".', '', $preFix); } self::_log('## FINISH ##############################', __CLASS__ . '::' . __FUNCTION__, $preFix, $start); }
<?php require_once dirname(__FILE__) . '/../../bootstrap.php'; Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); $productIds = Dao::getResultsNative('select distinct id from product where active = 1', array(), PDO::FETCH_ASSOC); foreach ($productIds as $row) { try { $output = ''; $cmd = 'php ' . dirname(__FILE__) . '/pricematch.php ' . $row['id']; $output = ExecWaitTimeout($cmd, 10); // exec($cmd, $output); echo print_r($output, true) . "\n"; } catch (Exception $e) { echo $e->getMessage() . "\n"; } } /** * Execute a command and kill it if the timeout limit fired to prevent long php execution * * @see http://stackoverflow.com/questions/2603912/php-set-timeout-for-script-with-system-call-set-time-limit-not-working * * @param string $cmd Command to exec (you should use 2>&1 at the end to pipe all output) * @param integer $timeout * @return string Returns command output */ function ExecWaitTimeout($cmd, $timeout = 5) { echo $cmd . "\n"; $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")); $pipes = array(); $timeout += time();
private static function _login() { //Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT), Core::getRole()); $username = UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)->getUserName(); $password = UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)->getPassword(); //$username = Core::getUser()->getUserName(); //$password = Core::getUser()->getPassword(); if (!isset(self::$_api['URL']) || ($apiUrl = trim(self::$_api['URL'])) === '') { throw new Exception('No API URL set!'); } $url = $apiUrl . 'UserAccount/login'; $data = json_encode(array('username' => $username, 'password' => $password)); self::_postJson($url, $data); if (trim(self::$_api['token']) === '') { throw new Exception('Invalid token'); } }
/** * validates the token * * @param unknown $token * @param bool $showHeader * * @throws Exception * @return APIService */ private function _validateToken($token, $showHeader = false) { if ($showHeader) { header("WWW-Authenticate: Basic realm=\"" . $this->_realm . "\""); } if (($token = trim($token)) === '') { throw new Exception('Invalid access, please login first!', 401); } $key = $this->_getTokenKey(); $ciphertext_dec = base64_decode($token); $iv_size = $this->_getTokenVISize(); $iv_dec = substr($ciphertext_dec, 0, $iv_size); $ciphertext_dec = substr($ciphertext_dec, $iv_size); $plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec); $this->log('decrypted token: "' . $plaintext_dec . '"', __CLASS__ . '::' . __FUNCTION__, '## '); $information = explode('|', $plaintext_dec); $this->log('got information: "' . preg_replace("/[\n\r]/", " ", print_r($information, true)), __CLASS__ . '::' . __FUNCTION__, self::TAB); if (!isset($information[1]) || preg_match('/^\\d{4}-\\d{2}-\\d{2}\\ \\d{2}:\\d{2}:\\d{2}$/', $fromDate = trim($information[1])) !== 1) { $this->log('invalid fromDate!', '', self::TAB); throw new Exception('Invalid token, please login first!'); } $fromDate = new UDate($fromDate); $this->log('Got fromDate: ' . $fromDate, '', self::TAB); if (!isset($information[2]) || preg_match('/^\\d{4}-\\d{2}-\\d{2}\\ \\d{2}:\\d{2}:\\d{2}$/', $toDate = trim($information[2])) !== 1) { $this->log('invalid toDate!', '', self::TAB); throw new Exception('Invalid token, please login first!!'); } $toDate = new UDate($toDate); $this->log('Got toDate: ' . $toDate, '', self::TAB); $now = UDate::now(); $this->log('Got NOW: ' . $now, '', self::TAB); if ($now->after($toDate) || $now->before($fromDate)) { $this->log('Token expired.', '', self::TAB); throw new Exception('Token expired.'); } if (!isset($information[0]) || !($userAccount = UserAccount::get(trim($information[0]))) instanceof UserAccount) { $this->log('Invalid useraccount.', '', self::TAB); throw new Exception('Invalid token, please login first.'); } $role = null; if (count($roles = $userAccount->getRoles()) > 0) { $role = $roles[0]; } $this->log('Got User: '******'', self::TAB); Core::setUser($userAccount, $role); return $this; }
/** * get category info by magento-b2b productCategory id * * @param string $systemid * * @return string * @soapmethod */ public function getCategory($systemid) { $response = $this->_getResponse(UDate::now()); try { $systemid = intval(trim($systemid)); Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); //TODO $obj = ProductCategory::get($systemid); if (!$obj instanceof ProductCategory) { throw new Exception('category with system id "' . $systemid . '" does not exist.'); } $response['status'] = self::RESULT_CODE_SUCC; $this->addCData('category', json_encode($obj->getJson()), $response); } catch (Exception $e) { $response['status'] = self::RESULT_CODE_FAIL; $this->addCData('error', $e->getMessage(), $response); } return trim($response->asXML()); }
/** * Writting the Session Data * * @param string $sessionId The sesison ID * @param string $sessionData The sesison data * * @return Session|null */ public static function write($sessionId, $sessionData) { $user = ($user = Core::getUser()) instanceof UserAccount ? $user : UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT); Core::setUser($user, Core::getRole()); $session = ($session = self::getSession($sessionId)) instanceof Session ? $session : new Session(); return $session->setKey($sessionId)->setData($sessionData)->save(); }