Add Custom Class
Permalink
Hi guys,
I'm having problem calling a custom class I created inside my package.
packages/alphlineweb_api/controllers/single_page/api.php
packages/alphlineweb_api/src/WebService/ApiAuthenticate.php
I always get
Whoops \ Exception \ ErrorException (E_ERROR)
Class 'Concrete\Package\AlphlinewebApi\Src\Webservice\ApiAuthenticate' not found
when I try to call this line
$call_response = ApiAuthenticate::generateToken($_REQUEST['user'],$_REQUEST['pass'],$_REQUEST['group']);
I'm having problem calling a custom class I created inside my package.
packages/alphlineweb_api/controllers/single_page/api.php
<?php namespace Concrete\Package\AlphlinewebApi\Controller\SinglePage; use Concrete\Core\Page\Controller\PageController, Concrete\Package\AlphlinewebApi\Src\Webservice\ApiAuthenticate, Loader; class Api extends PageController{ private $request_vars; private $data; private $http_accept; private $method; public function view($method, $id = null){ $request_method = strtolower($_SERVER['REQUEST_METHOD']); if($request_method == 'put' || $request_method == 'delete'){ // Make a blank array called $_PUT $_REQUEST = array();
Viewing 15 lines of 307 lines. View entire code block.
<?php namespace Concrete\Package\AlphlinewebApi\Controller\SinglePage; use Concrete\Core\Page\Controller\PageController, Concrete\Package\AlphlinewebApi\Src\Webservice\ApiAuthenticate, Loader; class Api extends PageController{ private $request_vars; private $data; private $http_accept; private $method; public function view($method, $id = null){ $request_method = strtolower($_SERVER['REQUEST_METHOD']); if($request_method == 'put' || $request_method == 'delete'){ // Make a blank array called $_PUT $_REQUEST = array(); // Read contents from the standard input buffer //covert to $_PUT parse_str(file_get_contents("php://input"),$_REQUEST); } $by = ($id) ? 'ByID' : ''; $this->data = $_REQUEST; $this->method = $request_method; switch($request_method){ case 'get': if($this->allowedMethods($method)){ if(substr_count($method,'List') > 0){ // The Page/User/File List methods can // recieve the following data: // - filters // - column : string (ak_fist_name) // - modifier : string ('LIKE') // - value : string/num ('Chad') // // - num : number (12) $call = new $method(); $func = $request_method; if(is_array($_REQUEST['filters'])){ foreach($_REQUEST['filters'] as $filter){ $column = $filter['column']; $modifier = $filter['modifier']; $value = $filter['value']; $string = "$column $modifier '$value'"; $call->filter(false,"$string"); } } $call_list = $call->$func(); if(is_array($call_list)){ foreach($call_list as $item){ if(substr_count($method,'Page') > 0){ $nh = Loader::helper('navigation'); $atts = $item->getSetCollectionAttributes(); $call_response['title'] = $item->getCollectionName(); $call_response['description'] = $item->getCollectionDescription(); $call_response['id'] = $item->getCollectionID(); $call_response['path'] = $nh->getLinkToCollection($item); if(is_array($_REQUEST['attributes'])){ foreach($_REQUEST['attributes'] as $label=>$attribute){ $call_response[$label] = $item->getAttribute($attribute); } } }elseif(substr_count($method,'File') > 0){ $item_version = $item->getVersion(); $atts = $item_version->getAttributeList(); }else{ $call_response[] = $item; } } } }elseif(substr_count($method,'Info') > 0){ // UserInfo object behaves differently than the other models // this function requires attributes input in order to have // any output $func = $request_method.$by; $call_object = $method::$func($id); if(is_array($_REQUEST['attributes'])){ $call_response = array(); foreach($_REQUEST['attributes'] as $label=>$attribute){ $call_action = $request_method.$attribute; $call_response[$label] = $call_object->$call_action(); } } }elseif(substr_count($method,'Custom') > 0){ //Custom->model,Custom->method,Custom->package $auth = ApiAuthenticate::checkToken($_REQUEST['token']); if($auth['id']) { $model = $_REQUEST['model']; $package = $_REQUEST['package']; $class = $_REQUEST['class']; $func = $_REQUEST['funct']; Loader::model($model,$package); $call_object = new $class(); if(is_array($_REQUEST['filters'])){ foreach($_REQUEST['filters'] as $filter){ $column = $filter['column']; $modifier = $filter['modifier']; $value = $filter['value']; $string = "$column $modifier '$value'"; $call_object->filter(false,"$string"); } } if($func){ $call_response = $call_object->$func($_REQUEST['value']); $call_response = $call_object; } }else{ $this->getResponse('401',$auth['error']); exit; } }elseif(substr_count($method,'Authenticate') > 0){ $this->getResponse('200', $_REQUEST['user'].'-'.$_REQUEST['pass']); //exit; $call_response = ApiAuthenticate::generateToken($_REQUEST['user'],$_REQUEST['pass'],$_REQUEST['group']); print $call_response; }else{ // Page::getByID($id), User::getByUserID($id), File::getByID($id) $call = new $method(); if($method == 'User' && $request_method == 'get'){ $func = $request_method.'By'.ucfirst($method).'ID'; }else{ $func = $request_method.$by; } $call_response = $call->$func($id); } $this->getResponse('200',$call_response); exit; }else{ $this->getResponse('405','ERROR: this method is not allowed'); exit; } break; case 'put': if($this->allowedMethods($method)){ $auth = ApiAuthenticate::checkToken($_REQUEST['token']); if($auth['id']) { if(substr_count($method,'Custom') > 0){ $model = $_REQUEST['model']; $package = $_REQUEST['package']; $class = $_REQUEST['class']; $func = $_REQUEST['funct']; Loader::model($model,$package); $call_object = new $class(); if($func){ $call_response = $call_object->$func($_REQUEST['value']); }else{ $call_response = $call_object; } }elseif(substr_count($method,'User') > 0){ Loader::model('userinfo'); $ui = UserInfo::getByID($id); if($ui->uID){ if(is_array($_REQUEST['attributes'])){ $call_response = array(); foreach($_REQUEST['attributes'] as $label=>$attribute){ $ak = UserAttributeKey::getByHandle(str_replace(' ','_',strtolower($label))); if($ak){ $ui->setAttribute($ak,$attribute); } } } $call_response = 'SUCCESS'; }else{ $call_response = 'ERROR: no user found matching this ID'; $this->getResponse('400',$call_response); exit; } }elseif(substr_count($method,'Page') > 0){ $p = Page::getByID($id); if($p->getCollectionID()){ if(is_array($_REQUEST['attributes'])){ $call_response = array(); foreach($_REQUEST['attributes'] as $label=>$attribute){ $ak = UserAttributeKey::getByHandle(str_replace(' ','_',strtolower($label))); if($ak){ $p->setAttribute($ak,$attribute); } } } $call_response = 'SUCCESS'; }else{ $call_response = 'ERROR: no Page found matching this ID'; $this->getResponse('400',$call_response); exit; } } $this->getResponse('200',$call_response); }else{ $this->getResponse('401',$auth['error']); exit; } }else{ $this->getResponse('405','ERROR: this method is not allowed'); exit; } break; case 'delete': if(substr_count($method,'Custom') > 0){ //Custom->model,Custom->method,Custom->package $auth = ApiAuthenticate::checkToken($_REQUEST['token']); if($auth['id']) { $model = $_REQUEST['model']; $package = $_REQUEST['package']; $class = $_REQUEST['class']; $func = $_REQUEST['funct']; Loader::model($model,$package); $call_object = new $class(); if($func){ $call_response = $call_object->$func($_REQUEST['value']); }else{ $call_response = $call_object; } $this->getResponse('200',$call_response); }else{ $this->getResponse('401',$auth['error']); exit; } } break; case 'post': if($this->allowedMethods($method)){ if(substr_count($method,'Custom') > 0){ //Custom->model,Custom->method,Custom->package $auth = ApiAuthenticate::checkToken($_REQUEST['token']); if($auth['id']) { $model = $_REQUEST['model'] . '_api'; $package = $_REQUEST['package']; $class = $_REQUEST['class'] . '_api'; $func = $_REQUEST['funct']; Loader::model($model,$package); $call_object = new $class(); try{ if($func){ //$call_response = $call_object->$func($_REQUEST['value']); $call_response = $call_object->$func($_POST); }else{ $call_response = $call_object; } }catch(Exception $ex){ $this->getResponse('400','ERROR: Invalid parameter(s)'); exit; } $this->getResponse('200',$call_response); }else{ $this->getResponse('401',$auth['error']); exit; } } }else{ $this->getResponse('405','ERROR: this method is not allowed'); exit; } break; } exit; } private function getResponse($code=null,$response=null){ switch($code){ case '405': header('HTTP/1.1 405 Method Not Allowed'); break; case '401': header('HTTP/1.1 401 Unauthorized'); break; case '400': header('HTTP/1.1 400 Bad Request'); break; case '230': header('HTTP/1.1 230 Authentication Successful'); break; case '202': header('HTTP/1.1 202 Accepted'); break; case '201': header('HTTP/1.1 201 Created'); break; case '200': header('HTTP/1.1 200 OK'); break; } if($_REQUEST['return'] == 'html'){ print $response; }else{ print @json_encode($response); } } private function allowedMethods($method){ $method_list = array( 'Authenticate', 'Custom', 'User', 'UserInfo', 'Page', 'File', 'UserList', 'PageList', 'FileList', 'Group' ); if(in_array($method,$method_list)){ return true; }else{ return false; } } private function requestConnect(){ } } ?>
packages/alphlineweb_api/src/WebService/ApiAuthenticate.php
<?php namespace Concrete\Package\AlphlinewebApi\Src\Webservice; use \Concrete\Core\Foundation\Object; use Loader; use Config; use Events; use Page; use Permissions; use User; use UserAttributeKey; use UserInfo; class ApiAuthenticate extends Object{ var $error_message; public function checkToken($token=null){ if(!$token){
Viewing 15 lines of 214 lines. View entire code block.
<?php namespace Concrete\Package\AlphlinewebApi\Src\Webservice; use \Concrete\Core\Foundation\Object; use Loader; use Config; use Events; use Page; use Permissions; use User; use UserAttributeKey; use UserInfo; class ApiAuthenticate extends Object{ var $error_message; public function checkToken($token=null){ if(!$token){ return array('error'=>'ERROR: this method requires a valid API token!'); } $db = Loader::db(); $uID = $db->getOne("SELECT uID FROM alphlinewebApiAuth WHERE token = ?", array($token)); $ui = UserInfo::getByID($uID); if (is_object($ui)){ $key = $ui->getAttribute('c5_api_key'); } if($key == $token){ return array('id'=>$uID,'error'=>null); }else{ return array('error'=>'ERROR: this auth key appears to be invalid!'); } } public static function generateToken($username, $password, $group = 'Administrators'){ $error = t('ERROR: A username and password are required.'); return $error; $ip = Loader::helper('validation/ip'); $vs = Loader::helper('validation/strings'); $loginData['success']=0; if ((!$vs->notempty($username)) || (!$vs->notempty($password))) { if (USER_REGISTRATION_WITH_EMAIL_ADDRESS) { $error = t('ERROR: An email address and password are required.'); } else { $error = t('ERROR: A username and password are required.'); } return $error; } $u = new User($username, $password); if ($u->isError()) { switch($u->getError()) { case USER_NON_VALIDATED: $error = t('ERROR: This account has not yet been validated. Please check the email associated with this account and follow the link it contains.'); break; case USER_INVALID: if (USER_REGISTRATION_WITH_EMAIL_ADDRESS) { $error = t('ERROR: Invalid email address or password.'); } else { $error = t('ERROR: Invalid username or password.'); } break; case USER_INACTIVE: $error = t('ERROR: This user is inactive. Please contact us regarding this account.'); break; } return $error; } else { $ui = UserInfo::getByID($u->uID); $uo = $ui->getUserObject(); //return $uo; $groups = $uo->uGroups; //if(in_array($group,$groups) || $uo->superUser == 1){ if(is_object($uo) || $uo->superUser == 1){ $key = $ui->getAttribute('c5_api_key'); if($key){ return $key; }else{ $token = ApiAuthenticate::createUniqueID(); $uID = $u->uID; $db = Loader::db(); $db->Execute("INSERT INTO alphlinewebApiAuth (token,uID) VALUES (?,?)",array($token,$uID)); Loader::model('attribute/categories/user'); $ak = UserAttributeKey::getByHandle('c5_api_key'); $ui->setAttribute($ak,$token); $u->setUserForeverCookie(); // $loginData['success']=1; //$loginData['msg']=t('Login Successful'); //$loginData['uID'] = intval($u->getUserID()); return $token; } }else{ $error = t("ERROR: This user does not have $group privileges."); return $error; } } } protected function finishLogin( $loginData=array() ) { $u = new User(); //if ($this->post('uMaintainLogin')) { $u->setUserForeverCookie(); //} if (count($this->locales) > 0) { if (Config::get('LANGUAGE_CHOOSE_ON_LOGIN') && $this->post('USER_LOCALE') != '') { $u->setUserDefaultLanguage($this->post('USER_LOCALE')); } } // Verify that the user has filled out all // required items that are required on register // That means users logging in after new user attributes // have been created and required will be prompted here to // finish their profile $this->set('invalidRegistrationFields', false); Loader::model('attribute/categories/user'); $ui = UserInfo::getByID($u->getUserID()); $aks = UserAttributeKey::getRegistrationList(); $unfilledAttributes = array(); foreach($aks as $uak) { if ($uak->isAttributeKeyRequiredOnRegister()) { $av = $ui->getAttributeValueObject($uak); if (!is_object($av)) { $unfilledAttributes[] = $uak; } } } if ($this->post('completePartialProfile')) { foreach($unfilledAttributes as $uak) { $e1 = $uak->validateAttributeForm(); if ($e1 == false) { $this->error->add(t('The field "%s" is required', $uak->getAttributeKeyName())); } else if ($e1 instanceof ValidationErrorHelper) { $this->error->add($e1); } } if (!$this->error->has()) { // the user has needed to complete a partial profile, and they have done so, // and they have no errors. So we save our profile data against the account. foreach($unfilledAttributes as $uak) { $uak->saveAttributeForm($ui); $unfilledAttributes = array(); } } } if (count($unfilledAttributes) > 0) { $u->logout(); $this->set('invalidRegistrationFields', true); $this->set('unfilledAttributes', $unfilledAttributes); } $txt = Loader::helper('text'); $rcID = $this->post('rcID'); $nh = Loader::helper('validation/numbers'); //set redirect url if ($nh->integer($rcID)) { $nh = Loader::helper('navigation'); $rc = Page::getByID($rcID); $url = $nh->getLinkToCollection($rc, true); $loginData['redirectURL'] = $url; }elseif( strlen($rcID) ){ $rcID = trim($rcID, '/'); $nc2 = Page::getByPath('/' . $rcID); if (is_object($nc2) && !$nc2->isError()) { $loginData['redirectURL'] = BASE_URL . DIR_REL . '/' . DISPATCHER_FILENAME . '/' . $rcID; } } /* //full page login redirect (non-ajax login) if( strlen($loginData['redirectURL']) && $_REQUEST['format']!='JSON' ){ header('Location: ' . $loginData['redirectURL']); exit; } */ $dash = Page::getByPath("/dashboard", "RECENT"); $dbp = new Permissions($dash); Events::fire('on_user_login',$this); //End JSON Login if($_REQUEST['format']=='JSON') return $loginData; //should administrator be redirected to dashboard? defaults to yes if not set. $adminToDash=intval(Config::get('LOGIN_ADMIN_TO_DASHBOARD')); //Full page login, standard redirection $u = new User(); // added for the required registration attribute change above. We recalc the user and make sure they're still logged in if ($u->isRegistered()) { if ($u->config('NEWSFLOW_LAST_VIEWED') == 'FIRSTRUN') { $u->saveConfig('NEWSFLOW_LAST_VIEWED', 0); } if ($loginData['redirectURL']) { //make double secretly sure there's no caching going on header("Cache-Control: no-store, no-cache, must-revalidate"); header("Pragma: no-cache"); header('Expires: Fri, 30 Oct 1998 14:19:41 GMT'); //in the past $this->externalRedirect( $loginData['redirectURL'] ); }else if ( $dbp->canRead() && $adminToDash ) { $this->redirect('/dashboard'); } else { //options set in dashboard/users/registration $login_redirect_cid=intval(Config::get('LOGIN_REDIRECT_CID')); $login_redirect_mode=Config::get('LOGIN_REDIRECT'); //redirect to user profile if( $login_redirect_mode=='PROFILE' && ENABLE_USER_PROFILES ){ $this->redirect( '/profile/', $u->uID ); //redirect to custom page }elseif( $login_redirect_mode=='CUSTOM' && $login_redirect_cid > 0 ){ $redirectTarget = Page::getByID( $login_redirect_cid ); if(intval($redirectTarget->cID)>0) $this->redirect( $redirectTarget->getCollectionPath() ); else $this->redirect('/'); //redirect home }else $this->redirect('/'); } } } public function createUniqueID(){ $length = 32; $characters = '123456789BCDFGHJKLMNPQRSTVWXZ'; $string = ''; for ($p = 0; $p < $length; $p++) { $string .= substr($characters, rand() % strlen($characters), 1); } return $string; } }
I always get
Whoops \ Exception \ ErrorException (E_ERROR)
Class 'Concrete\Package\AlphlinewebApi\Src\Webservice\ApiAuthenticate' not found
when I try to call this line
$call_response = ApiAuthenticate::generateToken($_REQUEST['user'],$_REQUEST['pass'],$_REQUEST['group']);