public function execute() { $updateTime = date('Y-m-d H:i:s', $this->lastRun); $select = $this->dbService->select(); $select->from('project')->joinInner('task', 'task.projectid = project.id', new Zend_Db_Expr('task.id as taskid'))->where("task.updated > ?", $updateTime); $projects = $this->dbService->fetchObjects('Project', $select); $done = array(); foreach ($projects as $project) { if (in_array($project->id, $done)) { continue; } $done[] = $project->id; echo "Updating time for project #{$project->id} " . $project->title . "\n"; $this->projectService->updateProjectEstimate($project); } $select = $this->dbService->select(); $select->from('project')->joinInner('feature', 'feature.projectid = project.id', new Zend_Db_Expr('feature.id as featureid'))->where("feature.updated > ?", $updateTime); $projects = $this->dbService->fetchObjects('Project', $select); foreach ($projects as $project) { if (in_array($project->id, $done)) { continue; } $done[] = $project->id; echo "Updating time for project #{$project->id} " . $project->title . "\n"; $this->projectService->updateProjectEstimate($project); } }
/** * Get a feed * * @param int $id * @return Feed */ public function getFeed($url) { $feed = $this->dbService->getByField(array('url' => $url), 'Feed'); $update = $feed == null || strtotime($feed->updated) < time() - 60 * 15; if ($feed == null) { $feed = new Feed(); } if ($update) { $this->log->debug("Loading feed {$url}"); // make the request! // $feed->content = $content = null; try { $client = Zend_Feed::getHttpClient(); $client->setUri($url); $response = $client->request('GET'); if ($response->getStatus() !== 200) { throw new Zend_Feed_Exception('Feed failed to load, got response code ' . $response->getStatus()); } $content = $response->getBody(); } catch (Exception $zfe) { $this->log->err("Failed loading feed from {$url}"); return $content; } $feed->content = $content; $feed->url = $url; $this->dbService->saveObject($feed); } return $feed; }
public function deletefavouriteAction() { $fav = $this->byId(null, 'PanelFavourite'); if ($fav) { $this->dbService->delete($fav); } echo $this->ajaxResponse($fav->id); }
/** * Get the items that need to appear in the project listing */ public function projectlistAction() { // $project = $this->projectService->getProject((int) $this->_getParam('projectid')); $project = $this->projectService->getProject((int) $this->_getParam('projectid')); $this->view->invoices = $this->dbService->getObjects('Invoice', array('projectid=' => $project->id)); $this->view->model = $project; $this->renderRawView('invoice/ajax-invoice-list.php'); }
/** * Given a username and password, * validates the user and returns the * new object. * @param $username thename of the user * @param $password the entered password * @param $userClass The class of the expected user * @return boolean whether auth was successful */ public function authenticate($username, $password, $userClass = 'User') { $fields = array('username' => $username); $user = $this->dbService->getByField($fields, $userClass); if ($user != null && $user->id) { // check the salted password $storedPass = sha1($password . $user->salt); if ($storedPass == $user->password) { return $user; } } return false; }
/** * Get all the items in a given path. If it is a directory, * a string value is entered. If it is a file, a File object * is entered. * * ArrayObject( * 0 => 'string', * 1 => File{} * 2 => 'etc' * ) * * @param string $path * @return ArrayObject */ public function listDirectory($path) { // Get all the directories $list = new ArrayObject(); $listFrom = $this->fileRoot . $this->normalizePath($path); try { $dir = new DirectoryIterator($listFrom); } catch (Exception $e) { return $list; } foreach ($dir as $entry) { /* @var $entry DirectoryIterator */ if ($entry->isDot()) { continue; } if (is_dir($this->fileRoot . $this->normalizePath($path) . DIRECTORY_SEPARATOR . $entry->getFilename())) { $list->append($entry->getFilename()); } } $conditions = array('path' => $this->normalizePath($path)); if (za()->getUser()->getRole() == User::ROLE_EXTERNAL) { $conditions = array('isprivate' => 0); } $results = $this->dbService->getManyByFields($conditions, 'File'); foreach ($results as $file) { $list->append($file); } return $list; }
/** * Gets a collection of objects that existed at a particular point in time * * @param mixed $objects * @param datetime $from * @param datetime $to * @param string $label */ public function getObjectSnapshot($type, $date, $filter = array()) { $versionType = $type . 'Version'; $filter = array(); $filter['validfrom < '] = $date; $filter['versioncreated > '] = $date; $versions = $this->dbService->getObjects($versionType, $filter); // because we're after a snapshot, it might be the case that there // are some objects that are 'live' that haven't had a version created // in the period we're interested in. So we're looking for objects // that were created BEFORE the date we're interested in, but don't // have a date in the 'valid' range $ids = array(); foreach ($versions as $v) { $ids[] = $v->recordid; } $filter = array('versioncreated < ' => $date); if (count($ids)) { $filter['id NOT'] = $ids; } $live = $this->dbService->getObjects($type, $filter); foreach ($live as $liveObject) { $liveObject->recordid = $liveObject->id; $versions[] = $liveObject; } return $versions; }
/** * Save a contact against a given client object * * * @param array|Contact $params * @return Contact */ public function saveContact($params) { $contact = null; try { $this->dbService->beginTransaction(); // Get an existing one $contact = $this->dbService->saveObject($params, 'Contact'); // check for a user object to also update if ($contact->id) { $user = $this->userService->getUserByField('contactid', $contact->id); if ($user) { $params = array('firstname' => $contact->firstname, 'lastname' => $contact->lastname, 'email' => $contact->email); $this->userService->updateUser($user, $params); } } $this->trackerService->track('update-contact', $contact->id, null, null, print_r($params, true)); $this->dbService->commit(); } catch (Exception $e) { $this->dbService->rollback(); $this->log->err("Failed creating contact for params " . print_r($params, true) . ": " . $e->getMessage()); $contact = null; throw $e; } return $contact; }
public function find($sync, $filename = null, $token = null, $minW = -1, $minH = -1) { //check cache $cacheKey = $token === null ? json_encode(md5($filename)) : $token; $cached = $this->_db->get($cacheKey); if ($cached !== null) { return json_decode($cached); } if ($sync === false || $filename === false) { return ['token' => $cacheKey]; } $image = $this->loadGDImage($filename); //perform web search $parts = explode('://', $filename); $isFile = count($parts) === 1 || $parts[0] === 'file'; if ($isFile) { $post = ['image_url' => '', 'encoded_image' => new \CURLFile(str_replace('file://', '', $filename)), 'image_content' => '', 'filename' => '', 'hl' => 'en']; $res = $this->curl('https://images.google.com/searchbyimage/upload', $post, true); preg_match('/^Location: (.+)\\n/Usmi', $res, $m); $resultsUrl = trim($m[1]); } else { $res = $this->curl('https://images.google.com/searchbyimage?image_url=' . urlencode($filename) . '&encoded_image=&image_content=&filename=&hl=en', [], true); preg_match('/^Location: (.+)\\n/Usmi', $res, $m); $resultsUrl = trim($m[1]); } $imageUrls = array_slice($this->search($resultsUrl), 0, static::MAX_LOAD_IMAGES); //check found files $result = $this->process($image, $imageUrls, $minW, $minH); $this->_db->set($cacheKey, json_encode($result)); return $result; }
/** * Delete the tags for the given object * * @param object $item */ public function deleteTags($item) { $type = mb_strtolower(get_class($item)); $id = (int) $item->id; // okay, delete ahoy $this->dbService->delete('tag', 'itemtype=' . $this->dbService->quote($type) . ' and itemid=' . $id); }
/** * Instantiate with Web so the module has access to models and output * * @param Web $w; */ public function __construct(Web &$w, $module_config = null) { if (!empty($module_config)) { $this->module_config = $module_config; } parent::__construct($w); }
/** * Set the status of an expense. */ public function setExpenseStatus(Expense $expense, $status) { $expense->status = $status; $expense->approver = za()->getUser()->getUsername(); $this->dbService->beginTransaction(); $this->dbService->saveObject($expense); $this->trackerService->track('expense-status-changed', $expense->approver . ' set status to ' . $status); $this->dbService->commit(); }
/** * Make a user an admin * * @param NovemberUser $user */ public function setUserRole(CrmUser $user, $role = null) { if (!$role) { $role = User::ROLE_USER; } $user->role = $role; $this->trackerService->track('set-role', $role . '_user-' . $user->id . '_by-' . za()->getUser()->getId()); $this->dbService->updateObject($user); }
/** * Delete a feature and all sub features. */ public function deleteFeature(Feature $feature) { $this->dbService->beginTransaction(); $childFeatures = $this->getChildFeatures($feature); foreach ($childFeatures as $child) { $this->deleteFeature($child); } $this->dbService->delete($feature); $this->dbService->commit(); }
/** * Shortcut to getting an object by id * * @param int $id * @param string $type * @return mixed */ protected function byId($id = null, $type = '') { if (is_null($id)) { $id = $this->_getParam('id'); } if ($type == '') { $type = $this->modelType(); } if (!$id) { return null; } return $this->dbService->getById((int) $id, $type); }
/** * Constructor * * @param $w */ function __construct(Web &$w) { parent::__construct($w); // add standard aspects if (property_exists($this, "_modifiable") && !property_exists($this, "_remove_modifiable")) { $this->_modifiable = new AspectModifiable($this); } if (property_exists($this, "_versionable") && !property_exists($this, "_remove_versionable")) { $this->_versionable = new AspectVersionable($this); } if (property_exists($this, "_searchable") && !property_exists($this, "_remove_searchable")) { $this->_searchable = new AspectSearchable($this); } }
/** * Remove access from a particular item * * @param object $item the item to remove access from * @param String $user The user to remove access for * @param String $role The role to remove (optional) */ public function removeAccess($item, $user, $role = null) { if (!$item) { throw new Exception("Cannot remove access from null object"); } $fields = array('itemid' => $item->id, 'itemtype' => get_class($item), 'authority' => $user->getUsername()); if ($role != null) { $fields['role'] = $role; } $existing = $this->dbService->getByField($fields, 'UserRole'); if ($existing != null) { // delete away $this->dbService->delete($existing); } }
/** * Create a task from a feature * * @param array $params * @return Task */ public function createTaskFromFeature($params, $createFrom = null) { // If called directly, we don't need to worry about // using the createFrom object. if ($params instanceof Feature) { $createFrom = $params; } /* @var $createFrom Feature */ $data = array(); $data['title'] = $createFrom->title; $data['description'] = $createFrom->description; $data['estimated'] = $createFrom->estimated * za()->getConfig('day_length', 8); $data['userid'] = array(za()->getUser()->getUsername()); $data['projectid'] = $createFrom->projectid; return $this->dbService->saveObject($data, 'Task'); }
/** * Generates the appropriate query for returning a list of issues * * @param array $where * @return arrayobject */ protected function getList($type, $where = array()) { $query = $this->_getParam('query'); if (mb_strlen($query) >= 2) { $where[] = new Zend_Db_Expr("title like " . $this->dbService->quote('%' . $query . '%') . " OR description like " . $this->dbService->quote('%' . $query . '%')); } // Handle this up here otherwise a model object might take $sortDir = $this->_getParam('sortorder', $this->_getParam('dir', 'desc')); if ($sortDir == 'up' || $sortDir == 'asc') { $sortDir = 'asc'; } else { $sortDir = 'desc'; } // now just iterate parameters $params = $this->_getAllParams(); unset($params['title']); unset($params['sortorder']); $dummyObj = new $type(); // get all the type's parameters $fields = $dummyObj->unBind(); foreach ($fields as $name => $val) { // if we have a param with $name, add it to the filter $val = ifset($params, $name, null); if (!is_null($val)) { $where[$name . ' ='] = $val; } } // If not a User, can only see non-private issues if (za()->getUser()->getRole() == User::ROLE_EXTERNAL) { if (isset($fields['isprivate'])) { $where['isprivate='] = 0; } if (isset($fields['clientid'])) { $client = $this->clientService->getUserClient(za()->getUser()); $where['clientid='] = $client->id; } } $sort = $this->_getParam('sortname', $this->_getParam('sort', 'updated')); $sort .= ' ' . $sortDir; $this->view->totalCount = $this->dbService->getObjectCount($where, $type); $currentPage = ifset($params, 'page', 1); $this->view->listSize = $this->_getParam('rp', za()->getConfig('project_list_size', 10)); if ($this->_getParam("unlimited")) { $currentPage = null; } return $this->dbService->getObjects($type, $where, $sort, $currentPage, $this->view->listSize); }
public function saveFeature($feature) { $this->dbService->updateObject($feature); }
/** * There's some built in services that we're going to load first. * * @return an array of services created */ private function loadDefaultServices() { $services = new ArrayObject(); $dbService = new DbService(); if (isset($this->config['services']['DbService'])) { $dbService->configure($this->config['services']['DbService']); } $this->injector->registerService($dbService); $services[] = $dbService; $service = new TypeManager(); if (isset($this->config['services']['TypeManager'])) { $service->configure(ifset($this->config['services'], 'TypeManager', array())); } $this->injector->registerService($service); $services[] = $service; $service = new SearchService(); if (isset($this->config['services']['SearchService'])) { $service->configure($this->config['services']['SearchService']); } $this->injector->registerService($service); $services[] = $service; $authService = new AuthService(); if (isset($this->config['services']['AuthService'])) { $authService->configure($this->config['services']['AuthService']); } $this->injector->registerService($authService); $services[] = $authService; $authComponent = new AuthComponent(); if (isset($this->config['services']['AuthComponent'])) { $authComponent->configure($this->config['services']['AuthComponent']); } $this->injector->registerService($authComponent); $services[] = $authComponent; $tasksService = new ScheduledTasksService(); $this->injector->registerService($tasksService); $services[] = $tasksService; $accessService = new AccessService(); $this->injector->registerService($accessService); $services[] = $accessService; $cacheService = new CacheService(); $this->injector->registerService($cacheService); $services[] = $cacheService; if (isset($this->config['services']['CacheService'])) { $cacheService->configure($this->config['services']['CacheService']); } $service = new VersioningService(); $this->injector->registerService($service); $services[] = $service; if (isset($this->config['services']['VersioningService'])) { $service->configure($this->config['services']['VersioningService']); } return $services; }
/** * Saves an issue to the database * * @param array|Issue $params */ public function saveIssue($params, $doNotify = true) { $issue = null; $sendNotification = false; if (is_array($params)) { $existingId = ifset($params, 'id'); } else { $existingId = $params->id; } if (!$existingId) { $sendNotification = true; } $oldIssue = null; // If there's an existing one, save it in the history if ($existingId) { $oldIssue = $this->getIssue($existingId); $this->versioningService->createVersion($oldIssue); } // If saving a new one, we want to $issue = $this->dbService->saveObject($params, 'Issue'); // Okay, now check if it's on a project or not $project = null; if (!$issue->projectid) { // Get the project $client = $this->clientService->getClient($issue->clientid); if (!$client) { throw new Exception("No client exists with ID {$issue->clientid}"); } $project = $this->clientService->getClientSupportProject($client); if (!$project) { throw new Exception("Missing client details for request {$issue->title}"); } $issue->projectid = $project->id; $this->dbService->updateObject($issue); } else { $project = $this->projectService->getProject($issue->projectid); } // make sure it's assigned to someone if (!mb_strlen($issue->userid)) { if (!$project) { $project = $this->projectService->getProject($issue->projectid); } $issue->userid = $project->manager; $this->dbService->updateObject($issue); } // Check to see if the assignee has a watch, if not, add one $assignedTo = $this->userService->getByName($issue->userid); if ($assignedTo) { $existing = $this->notificationService->getWatch($assignedTo, $issue->id, 'Issue'); if (!$existing) { $this->notificationService->createWatch($assignedTo, $issue->id, 'Issue'); } } $this->log->debug("Saving request, notify {$issue->userid} = " . $sendNotification); $this->trackerService->track('create-issue', $issue->id); // now send a notification to those users in the // group assigned to the project the issue was just saved against. if ($sendNotification && $doNotify) { // create and assign a task to whoever was assigned to the issue // by default if ($assignedTo && false) { // Create the task $task = new Task(); $task->projectid = $issue->projectid; $task->userid = array($assignedTo->username); $task->title = 'Respond to request "' . $issue->title . '"'; $task->description = "Please investigate this request:\r\n\r\n" . $issue->description; $task->category = 'Support'; $task->due = date('Y-m-d H:i:s', strtotime('+2 days')); // $task = $this->projectService->saveTask($task, false, true); // $this->itemLinkService->linkItems($issue, $task); } $this->log->debug("Notifying users about new request {$issue->title}"); $this->notifyOfNewIssue($issue); // Add a watch for the current user. Note that it might be null if // this issue is created from an email $user = za()->getUser(); if ($user) { $this->notificationService->createWatch($user, $issue->id, 'Issue'); } } if ($issue->status == Issue::STATUS_CLOSED) { // remove notifications $subscribers = $this->notificationService->getSubscribers($issue); foreach ($subscribers as $username => $item) { $user = $this->userService->getUserByField('username', $username); if ($user) { $this->notificationService->removeWatch($user, $issue->id, 'Issue'); } } } // See if the status has changed and notify the creator if ($oldIssue != null && $oldIssue->status != $issue->status && $doNotify) { try { $this->notifyOfUpdatedIssue($oldIssue, $issue); } catch (Exception $e) { $this->log->warn("Failed to notify of request update"); } } return $issue; }
public function __construct(\Web $w) { parent::__construct($w); $this->addLogger(LogService::$system_logger); }
public function __construct(Web $w) { parent::__construct($w); $this->initTransport(); }
/** * Get tracker entries * * @param unknown_type $where * @return unknown */ public function getEntries($where, $page = null, $number = null) { return $this->dbService->getObjects('TrackerEntry', $where, 'id desc', $page, $number); }
/** * Remove a watch * * @param CrmUser $user * @param int $id * @param string $type */ public function removeWatch($user, $id, $type) { // just delete direct, no need to get the // object first... $this->dbService->delete('itemwatch', "userid=" . $this->dbService->quote($user->username) . " AND itemid={$id} AND itemtype='{$type}'"); }
/** * Clear object cache completely! * */ function clearCache() { self::$_cache = array(); self::$_cache2 = array(); }
function __construct(Web $w) { parent::__construct($w); session_set_save_handler(array($this, "open"), array($this, "close"), array($this, "read"), array($this, "write"), array($this, "destroy"), array($this, "gc")); register_shutdown_function('session_write_close'); }