/** * List events by connected users in specified time period * @param int $connectedTo events of users connected to this user * @param int $days days in the future * @return int database cacehe */ public function listEventsFuture($connectedTo, $days) { require_once FRAMEWORK_PATH . 'models/relationships.php'; $relationships = new Relationships($this->registry); $idsSQL = $relationships->getIDsByUser($connectedTo); $sql = "SELECT p.name as creator_name, e.* FROM events e, profile p WHERE p.user_id=e.creator AND e.event_date >= CURDATE() AND e.event_date <= DATE_ADD(CURDATE(), INTERVAL {$days} DAY ) AND e.creator IN ({$idsSQL}) "; $cache = $this->registry->getObject('db')->cacheQuery($sql); return $cache; }
private function pendingRelationships() { if ($this->registry->getObject('authenticate')->isLoggedIn()) { require_once FRAMEWORK_PATH . 'models/relationships.php'; $relationships = new Relationships($this->registry); $pending = $relationships->getRelationships(0, $this->registry->getObject('authenticate')->getUser()->getUserID(), 0); $this->registry->getObject('template')->buildFromTemplates('header.tpl.php', 'friends/pending.tpl.php', 'footer.tpl.php'); $this->registry->getObject('template')->getPage()->addTag('pending', array('SQL', $pending)); } else { $this->registry->errorPage('Please login', 'Please login to manage pending connections'); } }
/** * Returns the list of worksheets inside the archive * * The keys of the array should be the titles of the worksheets * The values of the array are the names of the XML worksheet files inside the archive * * @param Relationships $relationships * @param string $path * * @return array */ public function getWorksheetPaths(Relationships $relationships, $path) { $xml = new \XMLReader(); $xml->open($path); $paths = []; while ($xml->read()) { if (\XMLReader::ELEMENT === $xml->nodeType && 'sheet' === $xml->name) { $rId = $xml->getAttributeNs('id', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); $paths[$xml->getAttribute('name')] = $relationships->getWorksheetPath($rId); } } return $paths; }
/** * View all users connections * @param int $user * @return void */ private function viewAll($user) { if ($this->registry->getObject('authenticate')->isLoggedIn()) { require_once FRAMEWORK_PATH . 'models/relationships.php'; $relationships = new Relationships($this->registry); $all = $relationships->getByUser($user, false, 0); $this->registry->getObject('template')->buildFromTemplates('header.tpl.php', 'friends/all.tpl.php', 'footer.tpl.php'); $this->registry->getObject('template')->getPage()->addTag('all', array('SQL', $all)); require_once FRAMEWORK_PATH . 'models/profile.php'; $p = new Profile($this->registry, $user); $name = $p->getName(); $this->registry->getObject('template')->getPage()->addTag('connecting_name', $name); } else { $this->registry->errorPage('Please login', 'Please login to view a users connections'); } }
public function execute(&$params) { // make sure this is a valid model type if (!is_subclass_of($this->config['modelClass'], 'X2Model')) { return array(false, ""); } if (!isset($this->config['attributes']) || empty($this->config['attributes'])) { return array(false, ""); } // verify that if create relationship option was set, that a relationship can be made if ($this->parseOption('createRelationship', $params)) { $acceptedModelTypes = X2Model::getModelTypesWhichSupportRelationships(); if (!in_array($this->config['modelClass'], $acceptedModelTypes)) { return array(false, Yii::t('x2flow', 'Relationships cannot be made with records ' . 'of type {type}.', array('{type}' => $this->config['modelClass']))); } if (!isset($params['model'])) { // no model passed to trigger return array(false, ''); } if (!in_array(get_class($params['model']), $acceptedModelTypes)) { return array(false, Yii::t('x2flow', 'Relationships cannot be made with records ' . 'of type {type}.', array('{type}' => get_class($params['model'])))); } } $model = new $this->config['modelClass'](); $model->setScenario('X2FlowCreateAction'); if ($this->setModelAttributes($model, $this->config['attributes'], $params) && $model->save()) { if ($this->parseOption('createRelationship', $params)) { Relationships::create(get_class($params['model']), $params['model']->id, get_class($model), $model->id); } return array(true, Yii::t('studio', 'View created record: ') . $model->getLink()); } else { $errors = $model->getErrors(); return array(false, array_shift($errors)); } }
/** * Set common template tags for all profile aspects * @param int $user the user id * @return void */ private function commonTemplateTags($user) { // get a random sample of 6 friends. require_once FRAMEWORK_PATH . 'models/relationships.php'; $relationships = new Relationships($this->registry); $cache = $relationships->getByUser($user, true, 6); $this->registry->getObject('template')->getPage()->addTag('profile_friends_sample', array('SQL', $cache)); // get the name and photo of the user require_once FRAMEWORK_PATH . 'models/profile.php'; $profile = new Profile($this->registry, $user); $name = $profile->getName(); $photo = $profile->getPhoto(); $uid = $profile->getID(); $this->registry->getObject('template')->getPage()->addTag('profile_name', $name); $this->registry->getObject('template')->getPage()->addTag('profile_photo', $photo); $this->registry->getObject('template')->getPage()->addTag('profile_user_id', $uid); // clear the profile $profile = ""; }
/** * Add a record to record relationship * * A record can be a contact, opportunity, or account. This function is * called via ajax from the Relationships Widget. */ public function actionAddRelationship() { //check if relationship already exits if (isset($_POST['ModelName']) && isset($_POST['ModelId']) && isset($_POST['RelationshipModelName']) && isset($_POST['RelationshipModelId'])) { $modelName = $_POST['ModelName']; $modelId = $_POST['ModelId']; $relationshipModelName = $_POST['RelationshipModelName']; $relationshipModelId = $_POST['RelationshipModelId']; $model = $this->getModelFromTypeAndId($modelName, $modelId); if (!Yii::app()->controller->checkPermissions($model, 'edit')) { $this->denied(); } $relationshipModel = $this->getModelFromTypeAndId($relationshipModelName, $relationshipModelId); if (!Yii::app()->controller->checkPermissions($relationshipModel, 'view')) { $this->denied(); } if (isset($_POST['mutual']) && $_POST['mutual'] == 'true') { $_POST['secondLabel'] = $_POST['firstLabel']; } $relationship = new Relationships(); $relationship->firstType = $_POST['ModelName']; $relationship->firstId = $_POST['ModelId']; $relationship->firstLabel = $_POST['firstLabel']; $relationship->secondType = $_POST['RelationshipModelName']; $relationship->secondId = $_POST['RelationshipModelId']; $relationship->secondLabel = $_POST['secondLabel']; if ($relationship->hasDuplicates()) { echo 'duplicate'; Yii::app()->end(); } if ($relationship->save()) { echo 'success'; Yii::app()->end(); } else { echo 'failure'; Yii::app()->end(); } } else { throw new CHttpException(400, Yii::t('app', 'Bad Request')); } }
/** * Compose a new message, and process new message submissions * @parm int $reply message ID this message is in reply to [optional] only used to pre-populate subject and recipient * @return void */ private function newMessage($reply = 0) { $this->registry->getObject('template')->buildFromTemplates('header.tpl.php', 'messages/create.tpl.php', 'footer.tpl.php'); require_once FRAMEWORK_PATH . 'models/relationships.php'; $relationships = new Relationships($this->registry); if (isset($_POST) && count($_POST) > 0) { $network = $relationships->getNetwork($this->registry->getObject('authenticate')->getUser()->getUserID()); $recipient = intval($_POST['recipient']); if (in_array($recipient, $network)) { // this additional check may not be something we require for private messages? require_once FRAMEWORK_PATH . 'models/message.php'; $message = new Message($this->registry, 0); $message->setSender($this->registry->getObject('authenticate')->getUser()->getUserID()); $message->setRecipient($recipient); $message->setSubject($this->registry->getObject('db')->sanitizeData($_POST['subject'])); $message->setMessage($this->registry->getObject('db')->sanitizeData($_POST['message'])); $message->save(); // email notification to the recipient perhaps?? // confirm, and redirect $url = $this->registry->getObject('url')->buildURL(array('messages'), '', false); $this->registry->redirectUser($url, 'Message sent', 'The message has been sent'); } else { $this->registry->errorPage('Invalid recipient', 'Sorry, you can only send messages to your recipients'); } } else { $cache = $relationships->getByUser($this->registry->getObject('authenticate')->getUser()->getUserID()); $this->registry->getObject('template')->getPage()->addTag('recipients', array('SQL', $cache)); if ($reply > 0) { require_once FRAMEWORK_PATH . 'models/message.php'; $message = new Message($this->registry, $reply); if ($message->getRecipient() == $this->registry->getObject('authenticate')->getUser()->getUserID()) { $this->registry->getObject('template')->getPage()->addAdditionalParsingData('recipients', 'ID', $message->getSender(), 'opt', "selected='selected'"); $this->registry->getObject('template')->getPage()->addTag('subject', 'Re: ' . $message->getSubject()); } else { $this->registry->getObject('template')->getPage()->addTag('subject', ''); } } else { $this->registry->getObject('template')->getPage()->addTag('subject', ''); } } }
/** * Build a users stream * @param int $user the user whose network we want to stream * @param int $offset - useful if we add in an AJAX based "view more statuses" feature * @return void */ public function buildStream($user, $offset = 0) { // prepare an array $network = array(); // use the relationships model to get relationships require_once FRAMEWORK_PATH . 'models/relationships.php'; $relationships = new Relationships($this->registry); $network = $relationships->getNetwork($user); // Add a zero element; so if network is empty the IN part of the query won't fail $network[] = 0; $network = implode(',', $network); // query the statuses table $sql = "SELECT t.type_reference, t.type_name, s.*, UNIX_TIMESTAMP(s.posted) as timestamp, p.name as poster_name, r.name as profile_name FROM statuses s, status_types t, profile p, profile r WHERE t.ID=s.type AND p.user_id=s.poster AND r.user_id=s.profile AND ( p.user_id={$user} OR r.user_id={$user} OR ( p.user_id IN ({$network}) AND r.user_id IN ({$network}) ) ) ORDER BY s.ID DESC LIMIT {$offset}, 20"; $this->registry->getObject('db')->executeQuery($sql); if ($this->registry->getObject('db')->numRows() > 0) { $this->empty = false; // iterate through the statuses, adding the ID to the IDs array, making the time friendly, and saving the stream while ($row = $this->registry->getObject('db')->getRows()) { $row['friendly_time'] = $this->generateFriendlyTime($row['timestamp']); $this->IDs[] = $row['ID']; $this->stream[] = $row; } } }
public function run() { Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->getBaseUrl() . '/css/gridview/jquery.yiigridview.js'); $relationships = Relationships::model()->findAllByAttributes(array('firstType' => 'quotes', 'secondType' => 'contacts', 'secondId' => $this->contactId)); echo '<div id="quotes-form">'; echo '<div id="wide-quote-form" class="wide form" style="overflow: visible;">'; echo '<span style="font-weight:bold; font-size: 1.5em;">' . Yii::t('quotes', "Quotes") . '</span>'; echo '<br /><br />'; // get a list of products for adding to quotes $products = Product::model()->findAll(array('select' => 'id, name')); $productNames = array(0 => ''); foreach ($products as $product) { $productNames[$product->id] = $product->name; } $quotes = Quote::model()->findAllByAttributes(array('associatedContacts' => $this->contactId)); foreach ($quotes as $quote) { $products = Product::model()->findAll(array('select' => 'id, name, price')); $quoteProducts = QuoteProduct::model()->findAllByAttributes(array('quoteId' => $quote->id)); // find associated products and their quantities $quotesProducts = QuoteProduct::model()->findAllByAttributes(array('quoteId' => $quote->id)); $orders = array(); // array of product-quantity pairs $total = 0; // total price for the quote foreach ($quotesProducts as $qp) { $price = $qp->price * $qp->quantity; if ($qp->adjustmentType == 'percent') { $price += $price * ($qp->adjustment / 100); $qp->adjustment = "{$qp->adjustment}%"; } else { $price += $qp->adjustment; } $orders[] = array('name' => $qp->name, 'id' => $qp->productId, 'unit' => $qp->price, 'quantity' => $qp->quantity, 'adjustment' => $qp->adjustment, 'price' => $price); $order = end($orders); $total += $order['price']; } $dataProvider = new CArrayDataProvider($orders, array('keyField' => 'name', 'sort' => array('attributes' => array('name', 'unit', 'quantity', 'price')), 'pagination' => array('pageSize' => false))); $newProductId = "new_product_" . $quote->id; $this->render('viewQuotes', array('quote' => $quote, 'contactId' => $this->contactId, 'dataProvider' => $dataProvider, 'products' => $products, 'productNames' => $productNames, 'orders' => $quoteProducts, 'total' => $total)); } // Mini Create Quote Form $model = new Quote(); $this->render('createQuote', array('model' => $model, 'contactId' => $this->contactId, 'productNames' => $productNames)); echo "</div>"; echo "</div>"; }
/** * Creates a new model. * * If creation is successful, the browser will be redirected to the 'view' page. * * @param bool $quick If true, this indicates the action is being requested via AJAX */ public function actionCreate($quick = false, $duplicate = false) { $model = new Quote(); if ($duplicate && !isset($_POST['Quote'])) { $copiedModel = Quote::model()->findByPk($duplicate); if (!empty($copiedModel)) { foreach ($copiedModel->attributes as $name => $value) { if ($name != 'id') { $model->{$name} = $value; } } $model->setLineItems($this->duplicateLineItems($copiedModel), false, true); } } $users = User::getNames(); if ($quick && !Yii::app()->request->isAjaxRequest) { throw new CHttpException(400); } $currency = Yii::app()->params->currency; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Quote'])) { $model->setX2Fields($_POST['Quote']); $model->currency = $currency; $model->createDate = time(); $model->lastUpdated = $model->createDate; $model->createdBy = Yii::app()->user->name; $model->updatedBy = $model->createdBy; if (empty($model->name)) { $model->name = ''; } if (isset($_POST['lineitem'])) { $model->lineItems = $_POST['lineitem']; } if (!$model->hasLineItemErrors) { if ($model->save()) { $model->createEventRecord(); $model->createActionRecord(); $model->saveLineItems(); if (!$quick) { $this->redirect(array('view', 'id' => $model->id)); } else { if (isset($_GET['recordId']) && isset($_GET['recordType'])) { $recordId = $_GET['recordId']; $recordType = $_GET['recordType']; $relatedModel = X2Model::model($_GET['recordType'])->findByPk($recordId); // tie record to quote if ($relatedModel) { $relate = new Relationships(); $relate->firstId = $model->id; $relate->firstType = "Quote"; $relate->secondId = $relatedModel->id; $relate->secondType = $recordType; $relate->save(); $model->createAssociatedAction(X2Model::getAssociationType(get_class($relatedModel)), $relatedModel->id); } } return; } } } } // get products $products = Product::activeProducts(); $viewData = array('model' => $model, 'users' => $users, 'products' => $products, 'quick' => $quick); if (!$quick) { $this->render('create', $viewData); } else { if ($model->hasErrors() || $model->hasLineItemErrors) { // Sneak into the response that validation failed via setting // the response code manually: header('HTTP/1.1 400 Validation Error'); } $this->renderPartial('create', $viewData, false, true); } }
public function actionAddContact($id) { $users = User::getNames(); unset($users['admin']); unset($users['']); foreach (Groups::model()->findAll() as $group) { $users[$group->id] = $group->name; } $contacts = Contacts::getAllNames(); unset($contacts['0']); $model = $this->loadModel($id); $contacts = Sales::editContactArray($contacts, $model); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Sales'])) { $temp = $model->associatedContacts; $tempArr = $model->attributes; $model->attributes = $_POST['Sales']; $arr = $_POST['Sales']['associatedContacts']; foreach ($arr as $contactId) { $rel = new Relationships(); $rel->firstType = 'Contacts'; $rel->firstId = $contactId; $rel->secondType = 'Sales'; $rel->secondId = $model->id; $rel->save(); } $model->associatedContacts = Sales::parseContacts($arr); $temp .= " " . $model->associatedContacts; $model->associatedContacts = $temp; $changes = $this->calculateChanges($tempArr, $model->attributes); $model = $this->updateChangelog($model, $changes); if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('addContact', array('model' => $model, 'users' => $users, 'contacts' => $contacts, 'action' => 'Add')); }
/** * Transfers all relationships of $model to $this */ public function mergeRelationships(X2Model $model, $logMerge = false) { $ret = array(); $modelType = get_class($model); $targetModelType = get_class($this); if ($logMerge) { $ids = Yii::app()->db->createCommand()->select('id')->from('x2_relationships')->where('firstType = :type AND firstId = :id', array(':type' => $modelType, ':id' => $model->id))->queryColumn(); if (!empty($ids)) { $ret['first'] = $ids; } $ids = Yii::app()->db->createCommand()->select('id')->from('x2_relationships')->where('secondType = :type AND secondId = :id', array(':type' => $modelType, ':id' => $model->id))->queryColumn(); if (!empty($ids)) { $ret['second'] = $ids; } } Relationships::model()->updateAll(array('firstId' => $this->id, 'firstType' => $targetModelType), 'firstType = :type AND firstId = :id', array(':type' => $modelType, ':id' => $model->id)); Relationships::model()->updateAll(array('secondId' => $this->id, 'secondType' => $targetModelType), 'secondType = :type AND secondId = :id', array(':type' => $modelType, ':id' => $model->id)); return $ret; }
/** * find path between to nodes * * @todo Add handling for relationships * @todo Add algorithm parameter * * @example curl -H Accept:application/json -H Content-Type:application/json -d '{ "to": "http://localhost:9999/node/3" }' -X POST http://localhost:9999/node/1/pathfinder * * @throws \Neo4j\Exception\HttpException * @throws \Neo4j\Exception\NotFoundException * * @param Node $toNode * @param int|null $maxDepth * @param Relationships|null $relationships * @param string|null $singlePath * * @return array */ public function findPaths(Node $toNode, $maxDepth = null, Relationships $relationships = null, $singlePath = null) { $this->_pathFinderData['to'] = $this->_db->getBaseUri() . 'node' . '/' . $toNode->getId(); if ($maxDepth) { $this->_pathFinderData['max depth'] = $maxDepth; } if ($singlePath) { $this->_pathFinderData['single path'] = $singlePath; } if ($relationships) { $this->_pathFinderData['relationships'] = $relationships->get(); } list($response, $http_code) = Request::post($this->getUri() . '/pathfinder', $this->_pathFinderData); if ($http_code == 404) { throw new \Neo4j\Exception\NotFoundException(); } if ($http_code != 200) { throw new \Neo4j\Exception\HttpException("http code: " . $http_code . ", response: " . print_r($response, true)); } $paths = array(); foreach ($response as $result) { $paths[] = Path::inflateFromResponse($this->_db, $result); } if (empty($paths)) { throw new \Neo4j\Exception\NotFoundException(); } return $paths; }
public function testMergeRelationships() { $contact = $this->contact('testAnyone'); $otherContact = $this->contact('testUser'); $thirdContact = $this->contact('testUser_unsent'); $rel = new Relationships(); $rel->firstType = $rel->secondType = 'Contacts'; $rel->firstId = $contact->id; $rel->secondId = $otherContact->id; $rel->save(); $rel = new Relationships(); $rel->firstType = $rel->secondType = 'Contacts'; $rel->secondId = $contact->id; $rel->firstId = $thirdContact->id; $rel->save(); $model = new Contacts(); foreach ($contact->attributes as $key => $val) { if ($key != 'id' && $key != 'nameId') { $model->{$key} = $val; } } $model->save(); $this->assertEquals(1, count($model->getRelatedX2Models(true))); $this->assertEquals(2, count($contact->getRelatedX2Models(true))); $mergeData = $model->mergeRelationships($contact, true); $this->assertEquals(0, count($contact->getRelatedX2Models(true))); $this->assertEquals(3, count($model->getRelatedX2Models(true))); $model->unmergeRelationships($contact->id, $mergeData); $this->assertEquals(2, count($contact->getRelatedX2Models(true))); $this->assertEquals(1, count($model->getRelatedX2Models(true))); }
public function testRelationships() { // Delete a relationship from the fixture data: $this->action = 'relationships_get'; $ch = $this->getCurlHandle('DELETE', array('{_class}' => 'Contacts', '{_id}' => $this->contacts('testFormula')->id, '{_relatedId}' => $this->relationships('blackMesaContact')->id), 'admin'); $oldRelationship = $this->relationships('blackMesaContact')->getAttributes(array('id', 'secondType', 'secondId')); $oldRelationId = $this->relationships('blackMesaContact')->id; $response = curl_exec($ch); $this->assertEmpty($response); $this->assertResponseCodeIs(204, $ch); $this->assertFalse((bool) Relationships::model()->findByPk($oldRelationId)); // Re-create it from fixture data: $this->action = 'relationships'; $ch = $this->getCurlHandle('POST', array('{_class}' => 'Contacts', '{_id}' => $this->contacts('testFormula')->id), 'admin', $oldRelationship); $response = curl_exec($ch); $this->assertResponseCodeIs(201, $ch); // Create it again just to test that validation works (don't set w/same ID) $ch = $this->getCurlHandle('POST', array('{_class}' => 'Contacts', '{_id}' => $this->contacts('testFormula')->id), 'admin', $oldRelationship); $response = json_decode(curl_exec($ch), 1); $this->assertResponseCodeIs(201, $ch); // Create it once more but with a nonexistent ID to test that validation works $oldRelationship['secondId'] = 2424242; $ch = $this->getCurlHandle('POST', array('{_class}' => 'Contacts', '{_id}' => $this->contacts('testFormula')->id), 'admin', $oldRelationship); $response = json_decode(curl_exec($ch), 1); $this->assertResponseCodeIs(422, $ch); }
public function actionCreateRecords() { $contact = new Contacts(); $account = new Accounts(); $opportunity = new Opportunity(); $users = User::getNames(); if (isset($_POST['Contacts']) && isset($_POST['Accounts']) && isset($_POST['Opportunity'])) { $contact->setX2Fields($_POST['Contacts']); $account->setX2Fields($_POST['Accounts']); $opportunity->setX2Fields($_POST['Opportunity']); $validAccount = true; if ($account->validate() == false) { $validAccount = false; // validate other models so that the user gets feedback $contact->validate(); $opportunity->validate(); } if ($validAccount) { $allValid = true; $a = $this->createAccount($account, $account->attributes, '1'); // Contact and Opportunity require Account id for lookup field $contact->company = Fields::nameId($account->name, $account->id); if ($contact->validate() == false) { $allValid = false; } $c = $this->createContact($contact, $contact->attributes, '1'); $opportunity->accountName = Fields::nameId($account->name, $account->id); $opportunity->contactName = Fields::nameId($contact->name, $contact->id); if ($opportunity->validate() == false) { $allValid = false; } $o = $this->createOpportunity($opportunity, $opportunity->attributes, '1'); if ($allValid && $c && $a && $o) { // all records created? Relationships::create('Contacts', $contact->id, 'Accounts', $account->id); Relationships::create('Opportunity', $opportunity->id, 'Contacts', $contact->id); Relationships::create('Opportunity', $opportunity->id, 'Accounts', $account->id); if (isset($_GET['ret'])) { if ($_GET['ret'] == 'contacts') { $this->redirect(array("/contacts/contacts/view", 'id' => $contact->id)); } else { if ($_GET['ret'] == 'accounts') { $this->redirect(array("/accounts/accounts/view", 'id' => $account->id)); } else { if ($_GET['ret'] == 'opportunities') { $this->redirect(array("/opportunities/opportunities/view", 'id' => $opportunity->id)); } } } } else { $this->redirect(array("/contacts/contacts/view", $contact->id)); } } else { // otherwise clean up $types = array('account' => 'Accounts', 'contact' => 'Contacts', 'opportunity' => 'Opportunity'); foreach ($types as $model => $type) { if (${$model} && isset(${$model}->id)) { $modelId = ${$model}->id; ${$model}->delete(); // delete all new actions and events from creating/deleting records foreach (array('Actions', 'Events') as $meta) { X2Model::model($meta)->deleteAllByAttributes(array('associationId' => $modelId, 'associationType' => $type)); } } } } } } $this->render('createRecords', array('contact' => $contact, 'account' => $account, 'opportunity' => $opportunity, 'users' => $users)); }
private function formRelationships() { if ($this->registry->getObject('authenticate')->isLoggedIn() == true) { require_once FRAMEWORK_PATH . 'models/relationships.php'; $relationships = new Relationships($this->registry); $types = $relationships->getTypes(true); $this->registry->getObject('template')->addTemplateBit('form_relationship', 'members/form_relationship.tpl.php'); $this->registry->getObject('template')->getPage()->addPPTag('relationship_types', array('SQL', $types)); } else { $this->registry->getObject('template')->getPage()->addTag('form_relationship', '<!-- relationship types dropdown -->'); } }
public function testAfterDelete() { $contact = $this->contact('testAnyone'); $otherContact = $this->contact('testUser'); $this->assertFalse($contact->relationships->hasRelationship($otherContact)); $contact->relationships->createRelationship($otherContact); $this->assertTrue($contact->relationships->hasRelationship($otherContact)); $rel = $contact->relationships->getRelationship($otherContact); $this->assertNotNull($rel); $contact->delete(); $this->assertFalse($otherContact->relationships->hasRelationship($contact)); $this->assertNull(Relationships::model()->findByPk($rel->id)); }
public function hasRelationship($target) { $rel1 = Relationships::model()->countByAttributes(array('firstType' => get_class($this->owner), 'firstId' => $this->owner->id, 'secondType' => get_class($target), 'secondId' => $target->id)); $rel2 = Relationships::model()->countByAttributes(array('firstType' => get_class($target), 'firstId' => $target->id, 'secondType' => get_class($this->owner), 'secondId' => $this->owner->id)); return $rel1 || $rel2; }
/** * Clear out records associated with this quote before deletion. */ public function beforeDelete() { QuoteProduct::model()->deleteAllByAttributes(array('quoteId' => $this->id)); // for old relationships generated with incorrect type name Relationships::model()->deleteAllByAttributes(array('firstType' => 'quotes', 'firstId' => $this->id)); // generate action record for history $contact = $this->contact; if (!empty($contact)) { $action = new Actions(); $action->associationType = 'contacts'; $action->type = 'quotesDeleted'; $action->associationId = $contact->id; $action->associationName = $contact->name; $action->assignedTo = Yii::app()->getSuModel()->username; $action->completedBy = Yii::app()->getSuModel()->username; $action->createDate = time(); $action->dueDate = time(); $action->completeDate = time(); $action->visibility = 1; $action->complete = 'Yes'; $action->actionDescription = "Deleted Quote: <span style=\"font-weight:bold;\">{$this->id}</span> {$this->name}"; // Save after deletion of the model so that this action itself doensn't get deleted $action->save(); } return parent::beforeDelete(); }
?> . </td> <td style="text-align: justify"><?php echo $parent->name; ?> </td> <td style="text-align: center"><?php echo $parent->idno; ?> </td> <td style="text-align: center"><?php echo $parent->alive == 1 ? 'Yes' : 'No'; ?> </td> <td style="text-align: center"><?php echo Relationships::model()->returnRelationship($parent->relationship); ?> </td> <td style="text-align: center"><?php echo $parent->mobileno; ?> </td> <td style="text-align: justify"><?php echo $parent->postaladdress; ?> </td> </tr> <?php } ?> <?php
/** * REST-ful API method for adding and removing relationships between records. */ public function actionRelationship() { $rType = Yii::app()->request->requestType; switch ($rType) { case 'GET': // Look up relationships on a model $attr = array('firstType' => $_GET['model']); $relationships = Relationships::model()->findAllByAttributes(array_merge(array_intersect_key($_GET, array_flip(Relationships::model()->safeAttributeNames)), $attr)); if (empty($relationships)) { $this->_sendResponse(404, Yii::t('api', 'No relationships found.')); } else { $this->_sendResponse(200, array_map(function ($r) { return $r->attributes; }, $relationships), 1); } case 'POST': // Add a new relationship to model $relationship = new Relationships('api'); $relationship->attributes = $_POST; $relationship->firstType = $_GET['model']; if ($relationship->validate()) { $existingRelationship = Relationships::model()->findByAttributes(array_intersect_key($relationship->attributes, array_flip(array('firstType', 'secondType', 'firstId', 'secondId')))); if ($existingRelationship) { $this->_sendResponse(200, Yii::t('api', 'Such a relationship already exists.')); } if ($relationship->save()) { $this->_sendResponse(200, Yii::t('api', 'Successfully saved a relationship.')); } else { $this->_sendResponse(500, Yii::t('api', 'Failed to save relationship record for unknown reason.')); } } else { $this->response['modelErrors'] = $relationship->errors; $this->_sendResponse(400, $this->validationMsg('create', $relationship)); } break; case 'DELETE': if (!isset($_GET['secondType'], $_GET['firstId'], $_GET['secondId'])) { $this->_sendResponse(400, Yii::t('api', 'Cannot delete; no parameters specified for finding a relationship record to delete.')); } $relationships = Relationships::model()->findAllByAttributes(array_merge(array('firstType' => $_GET['model']), array_intersect_key($_GET, array_flip(Relationships::model()->attributeNames())))); if (empty($relationships)) { $this->_sendResponse(404, Yii::t('api', 'No relationships deleted; none were found matching specfied parameters.')); } $n_d = 0; $n_d_t = count($relationships); foreach ($relationships as $model) { $n_d += $model->delete() ? 1 : 0; } if ($n_d == $n_d_t) { $this->_sendResponse(200, Yii::t('api', '{n} relationships deleted.', array('{n}' => $n_d))); } else { $this->_sendResponse(500, Yii::t('api', 'One or more relationships could not be deleted.')); } break; default: $this->_sendResponse(400, Yii::t('api', 'Request type not supported for this action.')); break; } }
public function actionQuickDelete($id) { $model = $this->loadModel($id); if ($model) { // delete associated actions Actions::model()->deleteAllByAttributes(array('associationId' => $id, 'associationType' => 'quotes')); // delete product relationships QuoteProduct::model()->deleteAllByAttributes(array('quoteId' => $id)); // delete contact relationships Relationships::model()->deleteAllByAttributes(array('firstType' => 'quotes', 'firstId' => $id, 'secondType' => 'contacts')); $name = $model->name; // generate history $contact = Contacts::model()->findByPk($_GET['contactId']); $action = new Actions(); $action->associationType = 'contacts'; $action->type = 'quotes'; $action->associationId = $contact->id; $action->associationName = $contact->name; $action->assignedTo = Yii::app()->user->getName(); $action->completedBy = Yii::app()->user->getName(); $action->createDate = time(); $action->dueDate = time(); $action->completeDate = time(); $action->visibility = 1; $action->complete = 'Yes'; $action->actionDescription = "Deleted Quote: <span style=\"font-weight:bold;\">{$model->id}</span> {$model->name}"; $action->save(); $this->cleanUpTags($model); $model->delete(); } else { throw new CHttpException(400, Yii::t('app', 'Invalid request. Please do not repeat this request again.')); } if ($_GET['contactId']) { Yii::app()->clientScript->scriptMap['*.js'] = false; $contact = Contacts::model()->findByPk($_GET['contactId']); $this->renderPartial('quoteFormWrapper', array('model' => $contact), false, true); } }
?> </td> <td style="text-align: center"><?php echo $child->idno; ?> </td> <td style="text-align: center"><?php echo $child->dob; ?> </td> <td style="text-align: center"><?php echo $child->alive == 1 ? "Yes" : "No"; ?> </td> <td style="text-align: center"><?php echo Relationships::model()->returnRelationship($child->relationship); ?> </td> </tr> <?php } ?> <?php } ?> </table> <?php } ?> </div>
/** * * @param type $id * @return string */ public function returnRelationship($id) { $model = Relationships::model()->findByPk($id); return empty($model) ? null : $model->relationship; }
public static function editContactArray($arr, $model) { $rels = Relationships::model()->findAllByAttributes(array('firstType' => 'Contacts', 'secondType' => 'Opportunity', 'secondId' => $model->id)); $pieces = array(); foreach ($rels as $relationship) { $contact = X2Model::model('Contacts')->findByPk($relationship->firstId); if (isset($contact)) { $pieces[$relationship->firstId] = $contact->name; } } unset($arr[0]); foreach ($pieces as $id => $contact) { if (isset($arr[$id])) { unset($arr[$id]); } } return $arr; }
/** * Called by the duplicate checker when discarding the new record. */ public function actionDiscardNew() { if (isset($_POST['id'])) { $ref = $_POST['ref']; // Referring action $action = $_POST['action']; $oldId = $_POST['id']; if ($ref == 'create' && is_null($action) || $action == 'null') { echo CHtml::encode($oldId); return; } elseif ($ref == 'create') { $oldRecord = X2Model::model('Contacts')->findByPk($oldId); if (isset($oldRecord)) { $oldRecord->disableBehavior('X2TimestampBehavior'); Relationships::model()->deleteAllByAttributes(array('firstType' => 'Contacts', 'firstId' => $oldRecord->id)); Relationships::model()->deleteAllByAttributes(array('secondType' => 'Contacts', 'secondId' => $oldRecord->id)); if ($action == 'hideThis') { $oldRecord->dupeCheck = 1; $oldRecord->assignedTo = 'Anyone'; $oldRecord->visibility = 0; $oldRecord->doNotCall = 1; $oldRecord->doNotEmail = 1; $oldRecord->save(); $notif = new Notification(); $notif->user = '******'; $notif->createdBy = Yii::app()->user->getName(); $notif->createDate = time(); $notif->type = 'dup_discard'; $notif->modelType = 'Contacts'; $notif->modelId = $oldId; $notif->save(); return; } elseif ($action == 'deleteThis') { $oldRecord->delete(); return; } } } elseif (isset($_POST['newId'])) { $newId = $_POST['newId']; $oldRecord = X2Model::model('Contacts')->findByPk($oldId); $oldRecord->disableBehavior('X2TimestampBehavior'); $newRecord = Contacts::model()->findByPk($newId); $newRecord->disableBehavior('X2TimestampBehavior'); $newRecord->dupeCheck = 1; $newRecord->save(); if ($action === '') { $newRecord->delete(); echo CHtml::encode($oldId); return; } else { if (isset($oldRecord)) { if ($action == 'hideThis') { $oldRecord->dupeCheck = 1; $oldRecord->assignedTo = 'Anyone'; $oldRecord->visibility = 0; $oldRecord->doNotCall = 1; $oldRecord->doNotEmail = 1; $oldRecord->save(); $notif = new Notification(); $notif->user = '******'; $notif->createdBy = Yii::app()->user->getName(); $notif->createDate = time(); $notif->type = 'dup_discard'; $notif->modelType = 'Contacts'; $notif->modelId = $oldId; $notif->save(); } elseif ($action == 'deleteThis') { Relationships::model()->deleteAllByAttributes(array('firstType' => 'Contacts', 'firstId' => $oldRecord->id)); Relationships::model()->deleteAllByAttributes(array('secondType' => 'Contacts', 'secondId' => $oldRecord->id)); Tags::model()->deleteAllByAttributes(array('type' => 'Contacts', 'itemId' => $oldRecord->id)); Actions::model()->deleteAllByAttributes(array('associationType' => 'Contacts', 'associationId' => $oldRecord->id)); $oldRecord->delete(); } } echo CHtml::encode($newId); } } } }
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. ********************************************************************************/ Yii::app()->clientScript->registerScript('updateWorkflow', "\n\nfunction startWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/startStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n\nfunction completeWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/completeStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n\nfunction revertWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/revertStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n", CClientScript::POS_HEAD); Yii::app()->clientScript->registerScript('detailVewFields', "\nfunction showField(field,focus){\n\t// \$(field).css('background','red');\n\t\$(field).find('.detail-field').hide();\n\t\$(field).find('.detail-form').show();\n\tif(focus)\n\t\t\$(field).find('input').focus();\n\thighlightSave();\n}\nfunction highlightSave() {\n\t\$('#save-changes').css('background','yellow');\n}\n", CClientScript::POS_HEAD); Yii::app()->clientScript->registerScript('stopEdit', ' $(document).ready(function(){ $("td#description a").click(function(e){ e.stopPropagation(); }); }); '); $relationships = Relationships::model()->findAllByAttributes(array('firstType' => 'quotes', 'firstId' => $model->id, 'secondType' => 'contacts')); $associatedContacts = array(); foreach ($relationships as $relationship) { $contact = Contacts::model()->findByPk($relationship->secondId); $associatedContacts[] = CHtml::link($contact->name, array('contacts/view', 'id' => $contact->id)); } $associatedContacts = implode(', ', $associatedContacts); ?> <div class="x2-layout"> <div class="formSection"> <div class="formSectionHeader"> <span class="sectionTitle">Basic Information</span> </div> <div class="tableWrapper">
/** * Remove a record with the same ID, save the model attributes in the container, and increment * the count of imported records * @param X2Model $model * @param array $modelContainer Array of validated models attributes * @param array $importedIds Array of ids from imported models */ protected function saveImportedModel(X2Model $model, $modelName, &$modelContainer, &$importedIds) { if (!empty($model->id)) { $lookup = X2Model::model(str_replace(' ', '', $modelName))->findByPk($model->id); if (isset($lookup)) { Relationships::model()->deleteAllByAttributes(array('firstType' => $modelName, 'firstId' => $lookup->id)); Relationships::model()->deleteAllByAttributes(array('secondType' => $modelName, 'secondId' => $lookup->id)); $lookup->delete(); unset($lookup); } } // Save our model & create the import records and // relationships. Passing $validate=false to CActiveRecord.save // because validation has already happened at this point $modelContainer[$modelName][] = $model->attributes; $_SESSION['imported']++; $importedIds[] = $model->id; }