PHP App::log Examples

PHP App::log - 30 examples found. These are the top rated real world PHP examples of App::log extracted from open source projects. You can rate examples to help us improve the quality of examples.
 public function diagnosticAction()
 {
     if (!$this->getRequest()->isGet()) {
         throw new UnexpectedException("Resquest must be GET");
     }
     $transactionId = $this->_getTransactionId();
     try {
         $result = $this->_service->load($transactionId);
         if ($result->status == WatcherModel::STATUS_FINISHED) {
             // Check permissions
             $this->_helper->allowed('read', $result);
             $events = $result->getEventList();
             $event = array_pop($events);
             // Return async response
             $data = $event->eventData;
             $code = $data['message']['execResult']['code'];
             $reason = $data['message']['execResult']['reason'];
             if ($code == "0") {
                 $this->view->result = $reason;
             } else {
                 $this->view->AsyncException = new External\Model\AsyncErrorModel(array('exceptionId' => $code, 'text' => $reason));
             }
         }
     } catch (Exception $e) {
         \App::log()->warn($e);
     }
 }
Example #2
0
 /**
  * Performs an authentication attempt
  *
  * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
  * @return Zend_Auth_Result
  */
 public function authenticate()
 {
     if (empty($this->_request) || empty($this->_response)) {
         require_once 'Zend/Auth/Adapter/Exception.php';
         throw new Zend_Auth_Adapter_Exception('Request and Response objects must be set before calling ' . 'authenticate()');
     }
     $header = $this->_request->getHeader('Authorization');
     if (empty($header)) {
         return $this->_challengeClient();
     }
     $parts = array_filter(explode(' ', $header));
     if ($parts < 2) {
         return $this->_challengeClient();
     }
     $scheme = array_shift($parts);
     $creds = implode(' ', $parts);
     if (empty($this->_schemes[$scheme])) {
         throw new Zend_Auth_Adapter_Exception('Unsupported authentication scheme (' . $scheme . ')');
     }
     $result = call_user_func($this->_schemes[$scheme], trim($creds), $this->_request);
     if (empty($result)) {
         \App::log()->debug("Authentication failed using scheme: " . @$this->_schemes[$scheme]);
         \App::log()->debug("Authentication failed using creds: " . @$creds);
         return $this->_challengeClient();
     } else {
         if ($result instanceof Zend_Auth_Result) {
             return $result;
         } else {
             return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $result);
         }
     }
 }
 public function isValid($value)
 {
     if (!$this->getType()) {
         throw new Application\Exceptions\InvalidArgumentException('Not organization type defined.');
     }
     if (is_string($value)) {
         try {
             $newValue = Application\Service\OrgService::getInstance()->getTypeById($value);
         } catch (Exception $e) {
             \App::log()->warn($e);
             $this->_error(self::INVALID_DATA, $value);
             return false;
         }
     } else {
         if ($value instanceof Application\Model\OrgModelAbstract) {
             $newValue = $value::ORG_TYPE;
         }
     }
     if (!is_string($value) || !$newValue) {
         $this->_error(self::INVALID_DATA, $newValue);
         return false;
     }
     if ($newValue != $this->getType()) {
         $this->_error(self::NOT_VALID_ORG_TYPE, $newValue);
         return false;
     }
     return true;
 }
 public function diagnosticAction()
 {
     if (!$this->getRequest()->isGet()) {
         throw new UnexpectedException("Resquest must be GET");
     }
     $transactionId = $this->_getTransactionId();
     $result = $this->_service->load($transactionId);
     if (!$result) {
         throw new NotFoundException("Resource {$transactionId} not found");
     }
     try {
         if ($result->status == WatcherModel::STATUS_FINISHED) {
             // Check permissions
             $this->_helper->allowed('read', $result);
             $events = $result->getEventList();
             $event = array_pop($events);
             // Return async response
             $data = $event->eventData;
             $code = $data['message']['execResult']['code'];
             $reason = $data['message']['execResult']['reason'];
             if ($code == "0") {
                 $this->view->result = $reason;
             } else {
                 $this->view->result = "ERROR";
                 $this->view->reason = "[{$code}] " . $reason;
             }
         }
     } catch (Exception $e) {
         \App::log()->warn($e);
     }
 }
 /**
  * Route shutdown hook -- Check for router exceptions
  *
  * @param Zend_Controller_Request_Abstract $request
  */
 public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
 {
     $auth = Zend_Auth::getInstance();
     $orgService = \Application\Service\OrgService::getInstance();
     $identity = $auth->getIdentity();
     //Bypass other auth methods
     if ($identity['authType'] != App_Controller_Plugin_Auth::AUTH_TYPE_AUTH_TOKEN) {
         return;
     }
     $front = Zend_Controller_Front::getInstance();
     $bs = $front->getParam('bootstrap');
     // Fetch logs and apply the token to them
     $multilog = $bs->getPluginResource('multiplelog');
     if (empty($identity['impersonation']) || empty($identity['impersonation']['orgId'])) {
         return;
     }
     $orgId = $identity['impersonation']['orgId'];
     $userSrv = UserService::getInstance();
     \App::log()->info($identity['username'] . " is running as " . $orgId . " admin");
     $user = $userSrv->loadByUsername($identity['username']);
     $userSrv->generateImpersonatedUser($user, $identity['impersonation']);
     foreach ($multilog->getLogs() as $log) {
         $log->setEventItem('impersonated', "as {$orgId} admin");
         $log->setEventItem('impersonatedOrgId', "{$orgId}");
         $log->setEventItem('username', $identity['username'] . " as {$orgId} admin");
     }
     //         Application\Model\Mapper\ProtoAbstractMapper::$accountingUserId .= "_impersonated";
     Application\Model\Mapper\ProtoAbstractMapper::$organizationId = $orgId;
     App_ListFilter::addDefaultExtraData('impersonated_org', $orgId);
     $org = OrgService::getInstance()->load($orgId);
     \App::getOrgUserLogged($org);
 }
Example #6
0
 /**
  * Perform backup
  * @return string
  */
 public static function create()
 {
     $collection = new Collection();
     $locations = Helper::getPreparedLocations();
     foreach ($locations as $type => $dirs) {
         foreach ($dirs as $name => $path) {
             Helper::checkr($path, $collection);
         }
     }
     if (count($collection->getNotReadable()) || count($collection->getNotWritable())) {
         $e = new PermissionException();
         $e->setCollection($collection);
         throw $e;
     }
     try {
         Helper::mkdir(self::getPath(), true);
         foreach ($locations as $type => $dirs) {
             $backupFullPath = self::getPath() . '/' . $type . '/';
             Helper::mkdir($backupFullPath, true);
             foreach ($dirs as $name => $path) {
                 Helper::copyr($path, $backupFullPath . $name);
             }
         }
     } catch (\Exception $e) {
         App::log('Backup creation failed. Disk full?');
         self::cleanUp();
         throw new FsException($e->getMessage());
     }
     return self::getPath();
 }
Example #7
0
 public function forceExit()
 {
     if (APPLICATION_ENV != "testing") {
         Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
     }
     $plugins = Zend_Controller_Front::getInstance()->getPlugins();
     $broker = new Zend_Controller_Plugin_Broker();
     $broker->setRequest(Zend_Controller_Front::getInstance()->getRequest());
     $broker->setResponse(Zend_Controller_Front::getInstance()->getResponse());
     foreach ($plugins as $index => $plugin) {
         $broker->registerPlugin($plugin, $index);
     }
     try {
         $broker->postDispatch($broker->getRequest());
     } catch (Exception $e) {
         \App::log()->crit('Error executing "postDispatch" after stream');
         \App::log()->crit($e);
     }
     try {
         $broker->dispatchLoopShutdown();
     } catch (Exception $e) {
         \App::log()->crit('Error executing "dispatchLoopShutdown" after stream');
         \App::log()->crit($e);
     }
     if (APPLICATION_ENV !== 'testing') {
         exit;
     }
 }
 /**
  * @throws ForbiddenException
  * @throws Zend_Controller_Exception
  * @param  string                           $privilege
  * @param  \Application\Model\ModelAbstract $resource
  */
 public function direct($privilege = null, $resource = null)
 {
     if ($privilege && $resource instanceof App_ListFilter_CollectionAbstract) {
         $default = $this->_getDefault($privilege, $resource);
         if ($default !== NULL) {
             foreach ($resource->getFilters() as $filter) {
                 $field = $filter->getFieldName();
                 try {
                     $pr = $privilege . "_" . $field;
                     if ($default && !$this->_privilegeExists($pr, $resource)) {
                         continue;
                     }
                     $this->_allowed($pr, $resource);
                 } catch (Exception $exc) {
                     if ($this->getThrowExOnNotAllowed()) {
                         throw new NotAllowedException("User has no permission to filter by {$field}");
                     }
                     \App::log()->debug("User has no permission to filter by {$field}");
                     $resource->removeFiltersByFieldName($field);
                 }
             }
         }
     }
     return $this;
 }
 /**
  * Route shutdown hook -- Check for router exceptions
  *
  * @param Zend_Controller_Request_Abstract $request
  */
 public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
 {
     try {
         if ($request->getControllerName() == 'error') {
             return;
         }
         $auth = Zend_Auth::getInstance();
         if (!$auth->hasIdentity()) {
             return;
         }
         $identity = $auth->getIdentity();
         if (!isset($identity['authType'])) {
             $this->_forceLogout($request, "Unexpected fatal error: Unknown auth method.", 500);
             return;
         }
         if (!isset(self::$zones[$identity['authType']])) {
             self::$zones[$identity['authType']] = array();
         }
         if (!$this->_checkAllowedZone(self::$zones[$identity['authType']], $request->getModuleName(), $request->getControllerName(), $request->getActionName())) {
             $this->_forceLogout($request, $identity['authType'] . " not allowed to access to module '" . $request->getModuleName() . "', controller '" . $request->getControllerName() . "', action '" . $request->getActionName() . "'.");
         }
     } catch (Exception $exc) {
         \App::log()->err($exc);
         $this->_forceLogout($request, "Unexpected fatal error: " . $exc->getMessage(), 500);
     }
 }
 public static function performUpgrade()
 {
     \App::log()->info("Retriving life cycle templates.");
     $mapper = TemplateMapper::getInstance();
     try {
         $templateList = self::retrieveLifeCycleTemplates();
     } catch (Exception $e) {
         \App::log()->info($e->getMessage());
         \App::log()->info("Error retriving life cycle templates. Aborting templates upgrade.");
         return;
     }
     \App::log()->info($templateList->getCount() . " templates to upgrade.");
     foreach ($templateList->getItems() as $template) {
         try {
             \App::log()->info("Upgrading life cycle template " . $template->id . "...");
             $lifeCycle = self::upgradeLifeCycle($template);
             $mapper->update(self::upgradeLifeCycleTemplate($template, $lifeCycle));
             \App::log()->info("Template " . $template->id . " upgraded succefully.");
         } catch (App_MigrationTool_TemplatesTo24_Exception $e) {
             \App::log()->info($e->getMessage());
         }
     }
     \App::log()->info("Life cycle templates upgraded succefully.");
     return true;
 }
 public function isValid($value)
 {
     $this->_messages = array();
     try {
         $org = OrgService::getInstance()->load($value);
     } catch (Application\Exceptions\InvalidArgumentException $e) {
         \App::log()->info($e);
         $message = $this->_createMessage(self::ERROR_INVALID_ORG_TYPE, $value);
         $this->_messages[self::ERROR_INVALID_ORG_TYPE] = $message;
         return false;
     } catch (Application\Exceptions\GlobalServiceException $e) {
         \App::log()->info($e);
         $message = $this->_createMessage(self::ERROR_ON_CONNECTION, $value);
         $this->_messages[self::ERROR_ON_CONNECTION] = $message;
         return false;
     }
     if (!isset($org)) {
         $message = $this->_createMessage(self::ERROR_ORGANIZATION_NOT_FOUND, $value);
         $this->_messages[self::ERROR_ORGANIZATION_NOT_FOUND] = $message;
         return false;
     }
     if (!is_string($org->getType())) {
         $message = $this->_createMessage(self::ERROR_INVALID_TYPE, $value);
         $this->_messages[self::ERROR_INVALID_TYPE] = $message;
         return false;
     }
     if ($this->getOrganizationType() !== null && $this->getOrganizationType() !== $org->getType()) {
         $message = $this->_createMessage(self::ERROR_INVALID_ORG_TYPE, $value);
         $this->_messages[self::ERROR_INVALID_ORG_TYPE] = $message;
         return false;
     }
     return true;
 }
 /**
  * Route shutdown hook -- Check for router exceptions
  *
  * @param Zend_Controller_Request_Abstract $request
  */
 public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
 {
     try {
         // Avoid error override! :S
         if (count($this->getResponse()->getException())) {
             return;
         }
         $auth = Zend_Auth::getInstance();
         if (!$auth->hasIdentity()) {
             $this->_forceLogout($request, "No session");
             return;
         }
         $sessionId = Zend_Session::getId();
         $sessMapper = Application\Model\Mapper\SessionMapper::getInstance();
         $session = $sessMapper->findOneById($sessionId);
         if (!$session) {
             return;
         }
         if (isset($session['logout'])) {
             $this->_forceLogout($request, isset($session['logout']['message']) ? $session['logout']['message'] : "External logout", isset($session['logout']['code']) ? $session['logout']['code'] : PermissionCodes::AUTH_ANOTHER_SESSION_STARTED);
             return;
         }
     } catch (Exception $exc) {
         \App::log()->err("MESSAGE BROADCAST: " . $exc->getMessage());
         $this->_forceLogout($request, "Unexpected fatal error: " . $exc->getMessage(), 500);
         return;
     }
 }
Example #13
0
	public final function rollback($log = false) {
		if ($log) {
			App::log('Something went wrong for ' . $this->type . '. Rolling back.');
		}
		foreach ($this->done as $item) {
			Helper::copyr($item['src'], $item['dst'], false);
		}
	}
 /**
  * Get an specific report by its Id
  */
 public function getAction()
 {
     $params = $this->getRequest()->getQuery();
     $params['id'] = $this->getRequest()->getParam('id');
     $params['reportType'] = $params['id'];
     // Mapping report name (a mistake on spec)
     if ($params['id'] === 'charges_detail_monthly') {
         $params['id'] = ReportModel::EXPENSE_DETAIL_MONTHLY;
         $params['reportType'] = ReportModel::EXPENSE_DETAIL_MONTHLY;
     } else {
         if ($params['id'] === 'charges_detail_daily') {
             $params['id'] = ReportModel::EXPENSE_DETAIL_DAILY;
             $params['reportType'] = ReportModel::EXPENSE_DETAIL_DAILY;
         }
     }
     // Check report permissions by type
     $dumpReport = new ReportModel();
     $dumpReport->setType($params['id']);
     try {
         $this->_helper->allowed('read', $dumpReport);
     } catch (ForbiddenException $ex) {
         \App::log()->crit($ex);
         if ($dumpReport->getResourceId() == 'report') {
             \App::log()->crit("Invalid report type: " . $params['id']);
         }
         throw new NotAllowedException('List report Operation is not allowed: Customer is not allowed');
     }
     // Check report params
     $this->_reportSrv->validateParams($params['id'], $params);
     // Check report organization
     if (isset($params['orgId'])) {
         try {
             $org = OrgService::getInstance()->load($params['orgId']);
         } catch (Exception $ex) {
             throw new \Application\Exceptions\InvalidArgumentException("Invalid parameter value: " . ReportFilterFields::ORGANIZATION . ". Supported values are customer-xxxxx");
         }
         if (empty($org)) {
             throw new NotFoundException("Resource " . ReportFilterFields::ORGANIZATION . " does not exists");
         }
         try {
             $this->_helper->allowed('read', $org);
         } catch (ForbiddenException $ex) {
             throw new NotAllowedException('List report Operation is not allowed: Customer is not allowed');
         }
     }
     // Check report exists
     if (!$this->_reportSrv->validateReportExists($params)) {
         throw new \Application\Exceptions\NotFoundException("Resource report does not exist");
     }
     // Prepare report download
     $downloadToken = new DownloadTokenModel();
     $downloadToken->params = $params;
     $downloadToken->controller = 'report';
     $downloadToken->action = 'get';
     $this->_downloadTokenSrv->create($downloadToken);
     $this->view->resultURL = $downloadToken->url;
 }
Example #15
0
 protected function _processErrors()
 {
     $errors = libxml_get_errors();
     foreach ($errors as $err) {
         $this->_addError($this->_createError($err));
     }
     $parseErrors = implode("\n", $this->_errors);
     \App::log()->warn("File parser. some errors in XML file: \n" . $parseErrors);
 }
 public function cancellation($contractId, CancellationSteeringModel $model)
 {
     $data = $this->_mapModelToPybeModel($model);
     $data['%contractid%'] = $contractId;
     $result = $this->_getPybeService()->callMethod($this::CANCEL_METHOD, $data);
     $httpResponse = $this->_getPybeService()->getLastResult();
     $this->_checkResponseResult($httpResponse, 'Pybe error: steering activation');
     \App::log()->info('Mapper: successfully cancellation operation');
     return new CancellationResponseModel($result);
 }
 public function clean($tags = array())
 {
     if ($this->_lifetime < 1) {
         return $this;
     }
     $tags = $this->_createCacheTags($tags);
     \App::log()->info("Cleaning " . $this->_itemClass . " cache. Tags: " . implode(', ', $tags));
     \App::cache()->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, $tags);
     return $this;
 }
 public function findOneByToken($token, $filter = array())
 {
     \App::log()->debug("Find one by token: {$token}");
     $data = $this->_findOne(array('rawData.Zend_Auth.storage.token' => $token) + $filter);
     \App::log()->debug("Find one by token: {$token}. Result: " . var_export($data, true));
     if (is_array($data)) {
         $data = $this->_mapMongoModelToModel($data);
         return $data;
     }
 }
Example #19
0
 public static function checkVersion($newVersionArray, $newVersionString)
 {
     $currentVersionArray = \OC_Util::getVersion();
     $currentVersion = \OC_Util::getVersionString();
     $difference = intval($newVersionArray[0]) - intval($currentVersionArray[0]);
     if ($difference > 1 || $difference < 0 || version_compare($currentVersion, $newVersionString) > 0) {
         $message = (string) App::$l10n->t('Not possible to update %s to %s. Downgrading or skipping major releases is not supported.', array($currentVersion, implode('.', $newVersionArray)));
         App::log($message);
         throw new \Exception($message);
     }
 }
 public function testUpdate()
 {
     $sim = $this->_service->load("00000000000000000015");
     do {
         $newCustomField1 = "testingServiceUpdateCustom-" . microtime(true);
     } while ($sim->getCustomField_1() == $newCustomField1);
     $sim->simType = SimModel::SIM_TYPE_GLOBAL;
     $sim->simModel = "MotorolX23";
     $sim->setApns(array());
     $sim->staticIpAddress = null;
     $sim->staticIpApnIndex = null;
     $sim->setAlias('aaaa');
     $sim->setCustomField_1($newCustomField1);
     $sim->setRegionId(-1);
     try {
         $this->_service->update($sim);
     } catch (\Exception $e) {
         \App::log()->debug($e);
         throw $e;
     }
     $simModified = $this->_service->load("00000000000000000015");
     $oldData = $sim->exportData();
     $newData = $simModified->exportData();
     unset($oldData['apns']);
     unset($newData['apns']);
     unset($oldData['staticIpApnIndex']);
     unset($newData['staticIpApnIndex']);
     unset($oldData['staticIpAddress']);
     unset($newData['staticIpAddress']);
     unset($oldData['expenseMonthly']['voiceFee']);
     unset($newData['expenseMonthly']['voiceFee']);
     unset($oldData['expenseMonthly']['smsFee']);
     unset($newData['expenseMonthly']['smsFee']);
     unset($oldData['expenseMonthly']['dataFee']);
     unset($newData['expenseMonthly']['dataFee']);
     unset($oldData['expenseMonthly']['totalFee']);
     unset($newData['expenseMonthly']['totalFee']);
     unset($oldData['expenseMonthly']['other']);
     unset($newData['expenseMonthly']['other']);
     unset($oldData['expenseMonthly']['total']);
     unset($newData['expenseMonthly']['total']);
     unset($oldData['expenseMonthly']['voiceGroupWarning']);
     unset($newData['expenseMonthly']['voiceGroupWarning']);
     unset($oldData['expenseMonthly']['smsGroupWarning']);
     unset($newData['expenseMonthly']['smsGroupWarning']);
     unset($oldData['expenseMonthly']['dataGroupWarning']);
     unset($newData['expenseMonthly']['dataGroupWarning']);
     unset($oldData['expenseMonthly']['totalGroupWarning']);
     unset($newData['expenseMonthly']['totalGroupWarning']);
     unset($oldData['regionId']);
     unset($newData['regionId']);
     $this->assertEquals($oldData, $newData);
 }
Example #21
0
 public static function getPackage($url, $version)
 {
     self::$package = App::getBackupBase() . $version;
     if (preg_match('/\\.zip$/i', $url)) {
         $type = '.zip';
     } elseif (preg_match('/(\\.tgz|\\.tar\\.gz)$/i', $url)) {
         $type = '.tgz';
     } elseif (preg_match('/\\.tar\\.bz2$/i', $url)) {
         $type = '.tar.bz2';
     } else {
         throw new \Exception('Unable to extract package ' . $url . ': unknown format');
     }
     self::$package = self::$package . $type;
     try {
         // Reuse already downloaded package
         if (!file_exists(self::$package)) {
             if (self::fetch($url) === false) {
                 throw new \Exception("Error storing package content");
             }
             App::log('Downloaded ' . filesize(self::$package) . ' bytes.', \OCP\Util::DEBUG);
         } else {
             App::log('Use already downloaded package ' . self::$package . '. Size is ' . filesize(self::$package) . ' bytes.', \OCP\Util::DEBUG);
         }
         $extractDir = self::getPackageDir($version);
         Helper::mkdir($extractDir, true);
         $archive = \OC_Archive::open(self::$package);
         if (!$archive || !$archive->extract($extractDir)) {
             throw new \Exception(self::$package . " extraction error");
         }
     } catch (\Exception $e) {
         App::log('Retrieving ' . $url);
         self::cleanUp($version);
         throw $e;
     }
     //  Prepare extracted data
     //  to have '3rdparty', 'apps' and 'core' subdirectories
     $baseDir = $extractDir . '/' . self::PACKAGE_ROOT;
     if (!file_exists($baseDir)) {
         App::log('Expected fresh sources in ' . $baseDir . '. Nothing is found. Something is wrong with OC_Archive.');
         App::log($extractDir . ' content: ' . implode(' ', scandir($extractDir)));
         if ($type === '.zip' && !extension_loaded('zip')) {
             $hint = App::$l10n->t('Please ask your server administrator to enable PHP zip extension.');
         }
         throw new \Exception(self::$package . " extraction error. " . $hint);
     }
     include $baseDir . '/version.php';
     Helper::checkVersion($OC_Version, $OC_VersionString);
     $sources = Helper::getSources($version);
     rename($baseDir . '/' . Helper::THIRDPARTY_DIRNAME, $sources[Helper::THIRDPARTY_DIRNAME]);
     rename($baseDir . '/' . Helper::APP_DIRNAME, $sources[Helper::APP_DIRNAME]);
     rename($baseDir, $sources[Helper::CORE_DIRNAME]);
 }
 /**
  * Attempt to parse the file and return an array
  * with the results.
  */
 public function parse()
 {
     $list = array();
     $errors = array();
     if ($this->checkFile()) {
         try {
             $fd = fopen($this->_fileName, 'r');
         } catch (Exception $e) {
             // File isn't readable
             $this->_addError(self::createReadingFileError());
             return false;
         }
         $sep = \App_Parser_CsvParser::getCsvSeparator($fd);
         $iter = 0;
         while (($line = fgetcsv($fd, 256, $sep)) !== false) {
             $line = array_map('trim', $line);
             if (count($line) <= 1 && empty($line[0])) {
                 continue;
             }
             $iter++;
             $record = array();
             if (count($line) !== 2) {
                 $this->_addError(self::createUnknownFileTypeError());
                 \App::log()->info("MSISDN files must have 2 columns. It is not a MSISDN file.");
                 fclose($fd);
                 return false;
             }
             list($record['icc'], $record['msisdn']) = $line;
             if (($valid = $this->validateRecord($record)) === true) {
                 $list[] = $record;
             } else {
                 $valid->line = $iter;
                 if (!empty($record['icc'])) {
                     $valid->entity = 'icc';
                     $valid->entityId = $record['icc'];
                 }
                 $this->_addError($valid);
             }
         }
         fclose($fd);
     } else {
         // File isn't readable
         $this->_addError(self::createReadingFileError());
         return false;
     }
     if (!empty($this->_errors)) {
         $errors = implode("\n", $this->_errors);
         \App::log()->warn("File some errors in CSV file: \n" . $errors);
     }
     $this->_itemParsedCount = $iter;
     return $this->identifyList($list, 'msisdn', 'preinventory_associate_msisdn');
 }
Example #23
0
 /**
  * Validate element value
  *
  * @param  array   $data
  * @param  mixed   $context
  * @return boolean
  */
 public function isValid($data, $context = null, $removeNotPresentFields = false)
 {
     if ($context && isset($context['organizationId']) && $context['organizationId']) {
         $orgId = $context['organizationId'];
         try {
             $orgType = Application\Service\OrgService::getInstance()->getTypeById($orgId);
             $this->setOrgType($orgType);
         } catch (Exception $e) {
             \App::log()->warn($e);
         }
     }
     return parent::isValid($data, $context, $removeNotPresentFields);
 }
Example #24
0
 public function testLog()
 {
     $logPath = App::getConfig('log_path', null);
     $this->assertNotEquals(null, $logPath, "log_path is not defined in config");
     $logFileName = '_test.log_';
     $logFile = $logPath . DIRECTORY_SEPARATOR . $logFileName;
     if (file_exists($logFile)) {
         unlink($logFile);
     }
     App::log('hello', $logFileName);
     $this->assertFileExists($logFile, "Cannot create log file: {$logFile}");
     unlink($logFile);
 }
Example #25
0
 public function getLog()
 {
     if (!isset($this->log)) {
         $this->log = App::log('alarm');
         $this->log->addPriority('AUDIT', 9);
         $this->log->addPriority('NORMAL', 10);
         $this->log->addPriority('WARNING', 11);
         $this->log->addPriority('MINOR', 12);
         $this->log->addPriority('MAJOR', 13);
         $this->log->addPriority('CRITICAL', 14);
     }
     return $this->log;
 }
 /**
  * Closed at production environment, available at development
  */
 public function emailAction()
 {
     $this->_develOnly();
     $data = $this->_helper->requestData();
     $mail = new App_Mail();
     $mail->setViewScript('welcome');
     $mail->addTo($data['mail'], $data['name']);
     try {
         $mail->send();
     } catch (Exception $e) {
         App::log($e, Zend_Log::CRIT);
     }
 }
 public function pushEntityId($watcher, $entityId)
 {
     if (is_string($watcher)) {
         $watcher = $this->load($watcher);
     }
     if (!$watcher instanceof WatcherModel) {
         throw new InvalidArgumentException("Watcher required");
     }
     if (!$entityId) {
         throw new InvalidArgumentException("EntityId required");
     }
     $this->getMapper()->pushEntityId($watcher, $entityId);
     \App::log()->info("{WATCHERS}{PUSH} Added new {$watcher->entityType} (ID: {$entityId}) to Watcher (ID: {$watcher->id})");
 }
Example #28
0
 /**
  * Send a text to Slack via Incomming webhook
  *
  * @param $text
  * @return mixed|void
  */
 public function send($text)
 {
     if (isset($this->_requestData['silent'])) {
         return;
     }
     $payloadData = ['text' => $text];
     $payloadStr = json_encode($payloadData);
     //        var_dump($payloadStr);
     curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $payloadStr);
     curl_setopt($this->_curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($payloadStr)));
     $response = curl_exec($this->_curl);
     \App::log($response, 'slack.log');
     return $response;
 }
 /**
  * Attempt to parse the file and return an array
  * with the results.
  *
  * CSV row:
  * [0] zoneGroupId (old zones)
  * [1] zoneSubId (new zones)
  */
 public function parse()
 {
     $list = array();
     $errors = array();
     if ($this->checkFile()) {
         try {
             $fd = fopen($this->_fileName, 'r');
         } catch (Exception $e) {
             // File isn't readable
             $this->_addError(self::createReadingFileError());
             return false;
         }
         $sep = $this->_separator;
         $iter = 0;
         while (($line = fgetcsv($fd, 1024, $sep)) !== false) {
             $iter++;
             $record = array();
             $n = count($line);
             if ($n === 1 && empty($line[0])) {
                 continue;
             }
             if ($n < 2) {
                 $this->_addError(self::createUnknownFileTypeError());
                 \App::log()->info("Zone files must have at least 2 columns.");
                 fclose($fd);
                 return false;
             }
             $line = array_map('trim', $line);
             $record = array('zoneGroupId' => $line[0], 'zoneSubId' => $line[1]);
             if (($valid = $this->validateRecord($record)) === true) {
                 if (!isset($list[$record['zoneGroupId']]) || !is_array($list[$record['zoneGroupId']])) {
                     $list[$record['zoneGroupId']] = array();
                 }
                 $list[$record['zoneGroupId']][] = $record['zoneSubId'];
             } else {
                 $valid->line = $iter;
                 $this->_addError($valid);
             }
         }
         fclose($fd);
     } else {
         $this->_addError(self::createReadingFileError());
         return false;
     }
     if (!empty($this->_errors)) {
         $errors = implode("\n", $this->_errors);
         \App::log()->warn("File some errors in Zone file: \n" . $errors);
     }
     return $list;
 }
Example #30
0
 protected function _findOne($id)
 {
     $result = $this->_getPybeService()->callMethod($this::GET_METHOD, array('%id%' => $id));
     $httpResponse = $this->_getPybeService()->getLastResult();
     try {
         $this->_checkResponseResult($httpResponse, 'Pybe error: findOne function');
     } catch (PybeException $ex) {
         if ($httpResponse->getStatus() == 404) {
             throw new NotFoundException("Model not found using Id {$id}", $httpResponse->getStatus());
         }
         throw $ex;
     }
     \App::log()->info('Mapper: successfully obtained element ' . $id);
     return $result;
 }