/** * Get the admin users list * * @return Core_Model_Object */ public function getResultCollection() { $query = $this->_getQuery(); $query->resetQuery(); //reset the query params set, if any $query->queryCondition("c_user.firstname ASC", 'ORDER'); $query->queryColumn(array("c_user.*")); $query->queryTable($this->tbl_user . " AS c_user"); $read = $this->_getResource()->_getReadAdapter(); $count = $read->fetchOne($query->prepareCountQuery(), 'count'); $results = $read->fetchAll($query->prepareQuery()); $collection = array(); if (!empty($results)) { foreach ($results as $result) { $user = App_Main::getModel('admin/user', $result); $collection[] = $user; } } $resultColection = new Core_Model_Object(); $resultColection->setCollection($collection); $resultColection->setTotalCount($count); if ($this->getFilterValue('page')) { $resultColection->setPage($this->getFilterValue('page')); $resultColection->setLimit($this->getFilterValue('limit')); } return $resultColection; }
public function email_submitAction() { $request = $this->getRequest(); $email_template = $request->getParam('email_template') ? $request->getParam('email_template') : false; $websiteId = $request->getParam('website') ? $request->getParam('website') : false; $website = App_Main::getModel('core/website'); if ($websiteId) { $website->load($websiteId); } if (empty($email_template)) { echo 'Choose a template file to test'; return; } $email = App_Main::getModel('core/email'); $email->setFromEmail(App_Main::DEFAULT_MAIL_SENDER); $email->setFromName(App_Main::DEFAULT_MAIL_SENDER_NAME); $email->setType('html'); $email->setLocale($website->getLocale()); $email->setTheme($website->getTheme()); $email->setTemplate($email_template); $email->setToEmail('*****@*****.**'); $email->setToName('recipient name'); $email->setSubject('Email debugger :: Testing email'); $email->setTemplateVar(array('name' => 'recipient name', 'email' => '*****@*****.**', 'website_url' => $website->getBaseUrl('web'), 'status' => 'status', 'comments' => 'Notification comments')); echo $email->getBody(); }
/** * Check whether or not the module output is enabled * * @param string $moduleName Full module name * @return boolean */ public function isOutputEnabled($moduleName = null) { if ($moduleName === null) { $moduleName = $this->getModuleName(); } return !App_Main::getConfig('advanced-modules-disable-output-' . $moduleName); }
/** * Generic method to get the page url for a paginated list * * @return string */ public function getPageUrl($p) { $request = App_Main::getRequest(); $params = $request->getQuery(); $params['page'] = $p; return $this->getUrl('*/*/*', array('_use_rewrite' => true, '_query' => $params)); }
/** * Fixes CGI only one Status header allowed bug * * @link http://bugs.php.net/bug.php?id=36705 * */ public function sendHeaders() { if (!$this->canSendHeaders()) { App_Main::log('HEADERS ALREADY SENT: '); return $this; } if (substr(php_sapi_name(), 0, 3) == 'cgi') { $statusSent = false; foreach ($this->_headersRaw as $i => $header) { if (stripos($header, 'status:') === 0) { if ($statusSent) { unset($this->_headersRaw[$i]); } else { $statusSent = true; } } } foreach ($this->_headers as $i => $header) { if (strcasecmp($header['name'], 'status') === 0) { if ($statusSent) { unset($this->_headers[$i]); } else { $statusSent = true; } } } } parent::sendHeaders(); }
/** * Initial connect function to get the user details and also to check the user tocken */ public function connectAction() { $this->_getSession()->unsSignup(); $token = $this->getRequest()->getParam('token'); $host = $this->getRequest()->getParam('host'); //Load the user object with the bc-token $user = App_Main::getModel('stages/user')->load($token, 'bc_auth_token'); //login and redirect to homepage if the user is already registered if ($user->getId()) { $user->setSessionUser($user); echo Zend_Json::encode(array('redirect' => App_Main::getUrl(''))); return; } //Get the Basecamp connect object $bcConnect = new Connect_Basecamp($host, $token, 'X', 'xml'); $userXml = $bcConnect->getMe(); if (!empty($userXml['body']) && $userXml['status'] == '200 OK') { $userArray = App_Main::getHelper('stages')->XMLToArray($userXml['body']); $return = array('success' => 1, 'username' => $userArray['user-name'], 'firstname' => $userArray['first-name'], 'lastname' => $userArray['last-name'], 'avatar' => $userArray['avatar-url'], 'token' => $userArray['token']); $signUp = App_Main::getModel('core/object'); $signUp->setMode('bc_token_connect'); $signUp->setToken($token); $signUp->setHost($host); $this->_getSession()->setSignup($signUp); } else { $return = array('success' => 0); } echo Zend_Json::encode($return); }
/** * Get the request object * * @return Core_Controller_Request_Http */ protected function _getRequest() { if (!empty($this->_request)) { return $this->_request; } $this->_request = App_Main::getRequest(); return $this->_request; }
/** * Load the entity object with the entity id * The entity object will loaded form the entity table and the eav will be loaded * * @param int $entityId * @return pbject entity model */ public function loadEntity($entityId) { $entityInfo = $this->getResource()->getEntityInfo($entityId); if (!empty($entityInfo)) { $entity = App_Main::getModel($entityInfo['entity_model']); $entity->load($entityId); } return $entity; }
/** * Logic of custom rewrites * * @param Zend_Controller_Request_Http $request * @param Zend_Controller_Response_Http $response * @return Core_Model_Url */ public function rewrite(Zend_Controller_Request_Http $request = null, Zend_Controller_Response_Http $response = null) { if (is_null($request)) { $request = App_Main::getRequest(); } if (is_null($response)) { $response = App_Main::getResponse(); } $requestCases = array(); $requestPath = trim($request->getPathInfo(), '/'); /** * We need try to find rewrites information for both cases * More priority has url with query params */ if ($queryString = $this->_getQueryString()) { $requestCases[] = $requestPath . '?' . $queryString; $requestCases[] = $requestPath; } else { $requestCases[] = $requestPath; } $this->loadByRequestPath($requestCases); /** * Try to find rewrite by request path at first, if no luck - try to find by id_path */ if (!$this->getId()) { return false; } $request->setAlias(self::REWRITE_REQUEST_PATH_ALIAS, $this->getRequestPath()); $external = substr($this->getTargetPath(), 0, 6); $isPermanentRedirectOption = $this->hasOption('RP'); if ($external === 'http:/' || $external === 'https:') { if ($isPermanentRedirectOption) { header('HTTP/1.1 301 Moved Permanently'); } header("Location: " . $this->getTargetPath()); exit; } else { $targetUrl = $request->getBaseUrl() . '/' . $this->getTargetPath(); } $isRedirectOption = $this->hasOption('R'); if ($isRedirectOption || $isPermanentRedirectOption) { $targetUrl = $request->getBaseUrl() . '/' . $this->getTargetPath(); if ($isPermanentRedirectOption) { header('HTTP/1.1 301 Moved Permanently'); } header('Location: ' . $targetUrl); exit; } $targetUrl = $request->getBaseUrl() . '/' . $this->getTargetPath(); if ($queryString = $this->_getQueryString()) { $targetUrl .= '?' . $queryString; } $request->setRequestUri($targetUrl); $request->setPathInfo($this->getTargetPath()); return true; }
/** * Get messages array by message type */ public function getMessages($type = null) { if (empty($this->_messages)) { $this->_messages = App_Main::getSession()->getMessages(true); } if ($this->_messages->getItems($type)) { return $this->_messages->getItems($type); } return false; }
public function getLocaleData($locale = null) { if (empty($locale)) { $locale = App_Main::getWebsite()->getLocale(); } if (!empty($this->_translate[$locale])) { return $this->_translate[$locale]; } return false; }
/** * Validate hash against hashing method (with or without salt) * * @param string $password * @param string $hash * @return bool * @throws Exception */ public function validateHash($password, $hash) { $hashArr = explode(':', $hash); switch (count($hashArr)) { case 1: return $this->hash($password) === $hash; case 2: return $this->hash($hashArr[1] . $password) === $hashArr[0]; } App_Main::throwException('Invalid hash.'); }
protected function _toHtml() { $this->setText(''); foreach ($this->getSortedChildren() as $name) { $block = $this->getLayout()->getBlock($name); if (!$block) { App_Main::throwException('Invalid block: %s', $name); } $this->addText($block->toHtml()); } return parent::_toHtml(); }
/** * Get the visitor list * * @return type Core_Model_Object */ public function getResultCollection() { if (!empty($this->_collection)) { return $this->_collection; } $_resultCollection = App_Main::getSingleton('visitor/visitor')->getCollection()->getResultCollection(); if (empty($_resultCollection)) { $_resultCollection = array(); } $this->_collection = $_resultCollection; return $this->_collection; }
/** * Set the template file * * @param type $template * @return Core_Block_Email_Template */ public function setTemplate($template) { $fileName = App_Main::getBaseDir('locale') . DS . 'email' . DS . $this->getLocale() . DS . $template; if (file_exists($fileName)) { $this->setData('template', $fileName); } else { //no need to check file existance here as it will be checked durinng ->fetchview $fileName = App_Main::getBaseDir('locale') . DS . 'email' . DS . $this->_defaltLocale . DS . $template; $this->setData('template', $fileName); } return $this; }
/** * Get the cron jobs from databse * * @param array $filters * @return array */ public function getJobs($filters = array()) { $query = $this->_getQuery(); $query->resetQuery(); $filters['status'] = !isset($filters['status']) ? 1 : $filters['status']; $query->queryColumn(array("tbl_job.*")); foreach ($filters as $filter => $value) { if (empty($value)) { continue; } switch ($filter) { case 'name': $query->queryCondition("tbl_job.job_name LIKE '%" . $value . "%'"); break; case 'status': $query->queryCondition("tbl_job.status =" . $value); break; case 'is_scheduled': $query->queryCondition("tbl_job_schedule.scheduled_at > '" . date('Y-m-d H:i:s', time() - 10) . "'"); //keeps a 10s escape time $query->queryCondition("tbl_job_schedule.status ='" . Cron_Model_Cron::STATUS_PENDING . "'"); break; case 'is_schedule_active': $query->queryCondition("tbl_job_schedule.scheduled_at > '" . now() . "'"); $query->queryCondition("(tbl_job_schedule.status ='" . Cron_Model_Cron::STATUS_PENDING . "' || tbl_job_schedule.status ='" . Cron_Model_Cron::STATUS_RUNNING . "')"); break; case 'is_finished': $query->queryCondition("tbl_job_schedule.scheduled_at < '" . now() . "'"); $query->queryCondition("tbl_job_schedule.status ='" . Cron_Model_Cron::STATUS_SUCCESS . "'"); break; case 'is_running': $query->queryCondition("tbl_job_schedule.status ='" . Cron_Model_Cron::STATUS_RUNNING . "'"); break; case 'is_error': $query->queryCondition("tbl_job_schedule.status ='" . Cron_Model_Cron::STATUS_ERROR . "'"); break; } } $query->queryCondition("tbl_job.job_id", "GROUP"); $query->queryCondition("tbl_job_schedule.scheduled_at ASC", "ORDER"); $query->queryTable($this->tbl_cron_job . " AS tbl_job"); $query->queryTable("LEFT JOIN " . $this->tbl_cron_job_schedule . " AS tbl_job_schedule ON tbl_job_schedule.job_id = tbl_job.job_id"); $results = $this->_getReadAdapter()->fetchAll($query->prepareQuery()); $colection = array(); if (empty($results)) { return $colection; } foreach ($results as $result) { $result['schedules'] = $this->_getReadAdapter()->fetchAll("SELECT schedule_id, job_code, status, messages, created_at, scheduled_at, executed_at, finished_at FROM " . $this->tbl_cron_job_schedule . " WHERE job_id=" . $result['job_id'] . " AND scheduled_at >= '" . now() . "' ORDER BY scheduled_at ASC"); $colection[] = App_Main::getModel('cron/job', $result); } return $colection; }
/** * Add a new website * @return type */ public function website_addAction() { $websiteCode = $this->getRequest()->getParam('website_code'); $website = App_Main::getModel('core/website'); if (!$website->validateWebsiteCode($websiteCode)) { App_Main::getSession()->addError('The website code you have specified is invalid or is already existing. Please try a new one code'); $this->_redirect('backend/config/websites'); return; } $website->setData('code', $websiteCode); $website->setData('name', $this->getRequest()->getParam('website_name')); $website->save(); $this->_redirect('backend/config/index', array('website' => $website->getId())); }
/** * Check for unique attribute values * Queried over ajax */ public function check_uniqueAction() { $data = $this->getRequest()->getParam('check_data'); if (!empty($data)) { $eavEdit = App_Main::getModel('backend/eav_edit'); $response = $eavEdit->checkUniqueXmlEavData($data); } if ($this->getRequest()->isXmlHttpRequest()) { $this->getResponse()->setHeader('Content-Type', 'text/xml'); $this->getResponse()->setBody('<response_root>' . $response . '</response_root>'); } else { //code for html display.. } }
/** * Get the todos for the todolist from database * * @param Core_Model_Object $object * @return array Project_Model_Todo */ public function getTodos(Core_Model_Object $object) { if (!$object->getBcId()) { return array(); } $result = $this->_getReadAdapter()->fetchAll("SELECT * FROM " . $this->tbl_todo . " WHERE todolist_id=" . $object->getBcId()); if (!$result) { return array(); } $todos = array(); foreach ($result as $data) { $todos[] = App_Main::getModel('project/todo', $data); } return $todos; }
/** * Get time-entries for a project created already in Basecamp * Save the time entry info if it is not loaded into database * - description * - project_id * - todo_id * - person_id * - bc_date * - hours - bc_id * * @param integer $projectId basecamp project id * @param bool $fromBc * @return array milestones Project_Model_Time */ public function loadTimeFromBc($entityId, $type = 'project', $page = 0, $fromBc = true) { switch ($type) { case 'project': //load time for project $respXml = $this->getBcConnect()->getTimeEntriesForProject($entityId, $page); break; case 'todo': //load time for todo $respXml = $this->getBcConnect()->getTimeEntriesForTodoItem($entityId, $page); break; } if (empty($respXml['body'])) { return array(); } if ($respXml['pages'] < $page) { return array(); } //parse the response body into array $tArray = $this->_getHelper()->XMLToArray(simplexml_load_string($respXml['body'])); $timeEntries = array(); if (!empty($tArray['time-entry'])) { $tArray = !empty($tArray['time-entry']['id']) ? array($tArray['time-entry']) : $tArray['time-entry']; foreach ($tArray as $data) { if (empty($data['id'])) { continue; } $timeEntry = App_Main::getModel('project/time')->load($data['id'], 'bc_id'); $timeEntry->setDescription(substr($data['description'], 0, 254)); $timeEntry->setProjectId($data['project-id']); $timeEntry->setTodoId($data['todo-item-id']); $timeEntry->setPersonId($data['person-id']); $timeEntry->setBcDate($data['date']); $timeEntry->setHours($data['hours']); $timeEntry->setBcId($data['id']); if (!$timeEntry->getAddedDate()) { $timeEntry->setAddedDate(now()); } if (!$timeEntry->getId() || $timeEntry->getOrigData('todo_id') != $timeEntry->getTodoId() || $timeEntry->getOrigData('person_id') != $timeEntry->getPersonId() || $timeEntry->getOrigData('bc_date') != $timeEntry->getBcDate() || $timeEntry->getOrigData('hours') != $timeEntry->{$timeEntry}->getHours()) { //save time entry data $timeEntry->setUpdatedDate(now()); $timeEntry->save(); } $timeEntries[] = $timeEntry; } } return $timeEntries; }
/** * Get the Basecamp API connector object * * @return Connect_Basecamp */ public function getBcConnect() { //check for user session if (!($user = App_Main::getSession()->getUser())) { App_Main::throwException('User session not found. Please login to connect'); return; } //check for bc host and bc token in the user object if (!$user->getBcHost() || !$user->getBcAuthToken()) { App_Main::throwException('Unable to connect to BC::unable to find sufficient credentials'); return; } //load the bc connect api object if not loaded already if (!$this->_bcConnect) { $this->_bcConnect = new Connect_Basecamp($user->getBcHost(), $user->getBcAuthToken(), 'X', self::BC_CONNECT_FORMAT); } return $this->_bcConnect; }
/** * Try to login user in admin * * @param string $username * @param string $password * @param Core_Controller_Request_Http $request * @return Admin_Model_User|null */ public function login($username, $password, $request = null) { if (empty($username) || empty($password)) { return; } try { /* @var $user Admin_Model_User */ $user = App_Main::getModel('admin/user'); $user->login($username, $password); if ($user->getId()) { $session = App_Main::getSingleton('admin/session'); $session->setIsFirstVisit(true); $session->setUser($user); } else { throw App_Main::exception('Core', 'Invalid Username or Password.'); } } catch (Core_Exception $e) { if ($request && !$request->getParam('messageSent')) { App_Main::getSingleton('core/session')->addError($e->getMessage()); $request->setParam('messageSent', true); } } return $user; }
/** * Get todos for a project created already in Basecamp * * @param integer $todolistId basecamp project id * @param bool $fromBc * @return array milestones Project_Model_Todo */ public function loadTodosFromBc($todolistId, $projectId = null) { $respXml = $this->getBcConnect()->getTodoItemsForList($todolistId); if (empty($respXml['body'])) { return array(); } $tArray = $this->_getHelper()->XMLToArray(simplexml_load_string($respXml['body'])); $todos = array(); if (!empty($tArray['todo-item'])) { $tArray = !empty($tArray['todo-item']['id']) ? array($tArray['todo-item']) : $tArray['todo-item']; foreach ($tArray as $data) { if (empty($data['id'])) { continue; } $todo = App_Main::getModel('project/todo')->load($data['id'], 'bc_id'); $status = empty($data['completed']) || $data['completed'] == 'false' ? 0 : 1; $todo->setTitle(substr($data['content'], 0, 254)); $todo->setTodolistId($data['todo-list-id']); $todo->setBcId($data['id']); $todo->setBcStatus($status); $todo->setBcAddedDate(date('Y-m-d H:i:s', strtotime($data['created-on']))); $todo->setBcUpdatedDate(date('Y-m-d H:i:s', strtotime($data['updated-at']))); $todo->setCommentCount($data['comments-count']); if (!$todo->getAddedDate()) { $todo->setAddedDate(now()); } if (!$todo->getId() || $todo->getOrigData('todolist_id') != $todo->getTodolistId() || $todo->getOrigData('bc_status') != $todo->getBcStatus() || $todo->getOrigData('comment_count') != $todo->getCommentCount() || $todo->getOrigData('title') != $todo->getTitle()) { //save todo data $todo->setUpdatedDate(now()); $todo->save(); } $todos[] = $todo; } } return $todos; }
/** * Set the save handler, enalbes DB based handler only if the session table is found * * @return Core_Model_Resource_Session */ public function setSaveHandler() { if ($this->hasConnection()) { session_set_save_handler(array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc')); } else { session_save_path(App_Main::getBaseDir('session')); } return $this; }
/** * Process the cheduled cron jobs and execute them according to the current time * @todo make it possilbbe to specify the buffer time and then process the job so that the timings are exactly correct * * @return bool */ public function dispatch() { $this->getResource()->markMissedJobs(date('Y-m-d H:i:s', time() - 60 * self::SCHEDULE_AHEAD_FOR)); $dispatchStartTime = now(); $jobs = $this->getResource()->getScheduledCronJobs(); foreach ($jobs as $job) { $schedules = $job->getSchedules(); $schedule = !empty($schedules) ? array_shift($schedules) : false; if (!$schedule) { continue; } if (time() - strtotime($dispatchStartTime) > self::MAX_RUN_INTERVAL) { return; } //exit if the current running time exeeds maximum $scheduleId = $schedule['schedule_id']; $timeDiff = strtotime($schedule['scheduled_at']) - time(); if ($timeDiff > self::MAX_RUN_INTERVAL) { return; } //return if the time interval is greater than the max run time if ($timeDiff > 10) { $this->getResource()->updateJobStatus($scheduleId, self::STATUS_WAITING); sleep($timeDiff); } $this->getResource()->updateJobStatus($scheduleId, self::STATUS_RUNNING); $modelInstance = App_Main::getModel($job->getModule()); if ($job->getAction()) { $action = $job->getAction(); try { $modelInstance->{$action}(); } catch (Exception $e) { $this->getResource()->updateJobStatus($scheduleId, self::STATUS_ERROR, null, $e->__toString()); } } $this->getResource()->updateJobStatus($scheduleId, self::STATUS_SUCCESS); } $this->getResource()->markMissedJobs($dispatchStartTime); return true; }
// Session based API call. if ($session) { $uid = $facebook->getUser(); $me = $facebook->api('/me'); } // login or logout url will be needed depending on current user state. $loginUrl = $logoutUrl = null; if ($me) { $logoutUrl = $facebook->getLogoutUrl(); } else { $loginUrl = $facebook->getLoginUrl(); } // This call will always work since we are fetching public data. $naitik = $facebook->api('/naitik'); $appId = $facebook->getAppId(); $encodedSession = json_encode($session); $this->set(compact('loginUrl', 'logoutUrl', 'appId', 'encodedSession', 'me', 'uid', 'naitik')); } /** * 出力 * * @return void */ public function onOutput() { $this->display(); } } $options = array('cache' => array('type' => 'init', 'life' => 10)); App_Main::run('Page_Canvas_Index', $options);
/** * Delete selected admin user */ public function deleteAction() { $request = $this->getRequest(); if (!$request->getParam('id')) { return false; } $user = App_Main::getModel('admin/user', array('user_id' => $request->getParam('id'))); $user->delete(); $this->_redirect('admin/user'); }
/** * get the helper object * * @param string $name * @return Core_Helper_Abstract */ public function helper($name) { $helper = App_Main::getHelper($name); if (!$helper) { return false; } return $helper->setLayout($this); }
/** * Prepare the milestone data for JSON * * - type * - title * - ms_user * - ms_date * - bc_id * * @return array */ public function prepareDataForJson() { $msData = array(); $msData['type'] = $this->getType() ? $this->getType() : 'd'; $msData['title'] = $this->getTitle(); $msData['ms_user'] = $this->getUserResponsible(); $msData['ms_date'] = App_Main::getHelper('stages')->formatDateForJs(strtotime($this->getMilestoneDate())); $msData['bc_id'] = $this->getBcId(); return $msData; }
/** * Returns the REQUEST_URI taking into account * platform differences between Apache and IIS * * @param boolean $clean clean non UTF-8 characters * @return string */ public function getRequestUri($clean = false) { $uri = $this->_getRequest()->getRequestUri(); if ($clean) { $uri = App_Main::getHelper('core/string')->cleanString($uri); } return $uri; }