public function addPost() { $rules = array('name' => 'required|min:3|max:128', 'description' => 'required', 'file' => 'mimes:jpg,gif,png'); $logo = ''; $name = Input::get('name'); $description = Input::get('description'); $author_id = Input::get('author_id'); $tags = Input::get('tags'); if (Input::hasFile('file')) { $file = Input::file('file'); $ext = $file->guessClientExtension(); $filename = $file->getClientOriginalName(); $file->move(public_path() . '/data', md5(date('YmdHis') . $filename) . '.' . $ext); $logo = md5(date('YmdHis') . $filename) . '.' . $ext; } $new_group = array('name' => $name, 'description' => $description, 'author_id' => $author_id, 'views' => 0, 'logo' => $logo, 'tags' => $tags); $v = Validator::make($new_group, $rules); if ($v->fails()) { // redirect back to the form with // errors, input and our currently // logged in user return Redirect::to('events/add')->with('user', Auth::user())->withErrors($v)->withInput(); } // create the new post $group = new Events($new_group); $group->save(); // redirect to viewing our new post return Redirect::to('events/view/' . $group->id); }
function addDetailedCalendar($st, $et, $sub, $ade, $dscr, $loc, $color, $tz) { $ret = array(); try { $event = new Events(); $event->title = mysql_real_escape_string($sub); $event->starttime = php2MySqlTime(js2PhpTime($st)); $event->endtime = php2MySqlTime(js2PhpTime($et)); $event->isalldayevent = mysql_real_escape_string($ade); $event->description = mysql_real_escape_string($dscr); $event->location = mysql_real_escape_string($loc); $event->color = mysql_real_escape_string($color); if ($event->save() == false) { $ret['IsSuccess'] = false; $ret['Msg'] = $event->error(); } else { $ret['IsSuccess'] = true; $ret['Msg'] = 'add success'; $ret['Data'] = $event->id; } } catch (Exception $e) { $ret['IsSuccess'] = false; $ret['Msg'] = $e->getMessage(); } return $ret; }
public function run($id) { $formModel = new EventCommentPublisherFormModel(); $profile = Yii::app()->params->profile; $model = $this->controller->lookUpModel($id, 'Events'); $this->controller->dataUrl = Yii::app()->request->url; if ($model->checkPermissions('view')) { if (isset($_POST['EventCommentPublisherFormModel'])) { $formModel->setAttributes($_POST['EventCommentPublisherFormModel']); if (isset($_FILES['EventCommentPublisherFormModel'])) { $model->photo = CUploadedFile::getInstance($model, 'photo'); } if ($formModel->validate()) { $event = new Events(); $event->setAttributes(array('visibility' => X2PermissionsBehavior::VISIBILITY_PUBLIC, 'user' => $profile->username, 'type' => 'structured-feed', 'associationType' => 'Events', 'associationId' => $id, 'text' => $formModel->text, 'photo' => $formModel->photo), false); if ($event->save()) { $formModel->text = ''; if (!isset($_FILES['EventCommentPublisherFormModel'])) { } else { Yii::app()->end(); } } else { throw new CHttpException(500, implode(';', $event->getAllErrorMessages())); } } } $dataProvider = new CActiveDataProvider('Events', array('criteria' => array('order' => 'timestamp ASC', 'condition' => "type in ('comment', 'structured-feed') AND \n associationType='Events' AND associationId={$id}"), 'pagination' => array('pageSize' => 30))); $this->controller->render($this->pathAliasBase . 'views.mobile.viewEvent', array('model' => $model, 'dataProvider' => $dataProvider, 'formModel' => $formModel)); } else { $this->controller->denied(); } }
/** * Ajax Api for getting event types */ public function postCreateEvent() { $title = Input::get('title'); $start = Input::get('start'); $end = Input::get('end'); $allDay = Input::get('allDay'); $category = Input::get('category'); $content = Input::get('content'); $school_id = $this->getSchoolId(); if ($allDay == "true") { $allDay = 1; } else { $allDay = 0; } $event = new Events(); $event->title = $title; $event->start = date($start); $event->end = date($end); $event->allday = $allDay; $event->category = $category; $event->content = $content; $event->school_id = $school_id; if ($event->save()) { $response = array('status' => 'Success', 'result' => array('events' => $event)); return Response::json($response); } else { $response = array('status' => 'Failed', 'result' => array('events' => 'none')); return Response::json($response); } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Events(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Events'])) { $model->attributes = $_POST['Events']; if ($model->save()) { $this->redirect(array('view', 'id' => $model->eid)); } } $this->render('create', array('model' => $model)); }
public function addEvent($attr, $image) { $model = new Events(); $model->setAttributes($attr); $model->created_at = time(); $model->updated_at = time(); $model->status = 1; $model->images = $image; if ($model->save(FALSE)) { return TRUE; } return FALSE; }
/** * Új eseményt ír ki a megadott tantárgyhoz. * @param int $id A tantárgy azonosítója */ public function actionCreate($id) { if (Yii::app()->user->getId() == null) { throw new CHttpException(403, "Ezt a funkciót csak regisztrált felhasználók használhatják"); } $model = new Events('insert'); $model->time = $_POST["time"]; $model->type = $_POST["type"]; $model->notes = $_POST["notes"]; $model->subject_id = $id; $model->save(); $this->redirect(Yii::app()->createUrl("event/list", array("id" => $id))); }
public function postCreate() { $event = new Events(); $event->title = Input::get('title'); $event->content = Input::get('content'); $event->upload = Input::get('upload') == 'true' ? true : false; $event->type = 'event'; $event->status = 'draft'; if ($event->save()) { return Redirect::to($this->route)->with('msg_success', Lang::get('messages.events_create', array('title' => $event->title))); } else { return Redirect::to($this->route)->with('msg_error', Lang::get('messages.events_create_err', array('title' => $event->title))); } }
static function addEvent($inputs) { $event = new Events(); $event->name = $inputs['eventName']; $event->event_description = $inputs['eventDescription']; $event->event_date = date("Y-m-d", strtotime($inputs['eventDate'])); $event->area = $inputs['eventLocation']; $event->type = $inputs['eventType']; $event->state = $inputs['state']; $event->city = $inputs['city']; $event->created_by = Session::get('userId'); $event->created_at = date("Y-m-d H:i:s"); $event->save(); return $event; }
public function actionIndex() { $event = new Events(); $event->attributes = $_GET; if (!isset($_GET['content_id'])) { $content = Content::model()->findByAttributes(array('slug' => Cii::get($_GET, 'uri', NULL))); if ($content !== NULL) { $event->content_id = $content->id; } } if ($event->save()) { Yii::app()->end(); } return $this->returnError(400, NULL, $event->getErrors()); }
protected static function sendEvent($event, $type, $description) { $message = new Events(); if (!$type) { $type = 'Не передан тип'; } if (!$description) { $description = 'Отсутствует описание'; } $message->type = $type; $message->event_id = $event; $message->description = $description; $message->timestamp = time(); $message->status = self::STATUS_ACTIVE; $message->save(); return $message->id; }
public function run() { $model = new EventPublisherFormModel(); $profile = Yii::app()->params->profile; if (isset($_POST['EventPublisherFormModel'])) { $model->setAttributes($_POST['EventPublisherFormModel']); if (isset($_FILES['EventPublisherFormModel'])) { $model->photo = CUploadedFile::getInstance($model, 'photo'); } //AuxLib::debugLogR ('validating'); if ($model->validate()) { //AuxLib::debugLogR ('valid'); $event = new Events(); $event->setAttributes(array('visibility' => X2PermissionsBehavior::VISIBILITY_PUBLIC, 'user' => $profile->username, 'type' => 'structured-feed', 'text' => $model->text, 'photo' => $model->photo), false); if ($event->save()) { if (!isset($_FILES['EventPublisherFormModel'])) { //AuxLib::debugLogR ('saved'); $this->controller->redirect($this->controller->createAbsoluteUrl('/profile/mobileActivity')); } else { echo CJSON::encode(array('redirectUrl' => $this->controller->createAbsoluteUrl('/profile/mobileActivity'))); Yii::app()->end(); } } else { //AuxLib::debugLogR ('invalid'); throw new CHttpException(500, implode(';', $event->getAllErrorMessages())); } } else { if (isset($_FILES['EventPublisherFormModel'])) { throw new CHttpException(500, implode(';', $event->getAllErrorMessages())); } //AuxLib::debugLogR ('invalid model'); //AuxLib::debugLogR ($model->getErrors ()); } } $this->controller->render($this->pathAliasBase . 'views.mobile.eventPublisher', array('profile' => $profile, 'model' => $model)); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model = $this->loadModel($id); if ($model->type == null) { $model->scenario = 'menu'; } $old_title = $model->name; $new_title = $old_title; if (isset($_POST['Docs'])) { $new_title = $_POST['Docs']['name']; } if (isset($_POST['Docs'])) { $model->attributes = $_POST['Docs']; $model->visibility = $_POST['Docs']['visibility']; if ($model->save()) { $this->titleUpdate($old_title, $new_title); $event = new Events(); $event->associationType = 'Docs'; $event->associationId = $model->id; $event->type = 'doc_update'; $event->user = Yii::app()->user->getName(); $event->visibility = $model->visibility; $event->save(); $this->redirect(array('update', 'id' => $model->id, 'saved' => true, 'time' => time())); } } $this->render('update', array('model' => $model)); }
public function actionDelete($id) { $model = $this->loadModel($id); if (Yii::app()->request->isPostRequest) { $event = new Events(); $event->type = 'record_deleted'; $event->associationType = $this->modelClass; $event->associationId = $model->id; $event->text = $model->name; $event->user = Yii::app()->user->getName(); $event->save(); Actions::model()->deleteAll('associationId=' . $id . ' AND associationType=\'x2Leads\''); $this->cleanUpTags($model); $model->delete(); } else { throw new CHttpException(400, Yii::t('app', 'Invalid request. Please do not repeat this request again.')); } // if AJAX request (triggered by deletion via admin grid view), we should not redirect // the browser if (!isset($_GET['ajax'])) { $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index')); } }
/** * Track when an email is viewed, a link is clicked, or the recipient unsubscribes * * Campaign emails include an img tag to a blank image to track when the message was opened, * an unsubscribe link, and converted links to track when a recipient clicks a link. * All those links are handled by this action. * * @param integer $uid The unique id of the recipient * @param string $type 'open', 'click', or 'unsub' * @param string $url For click types, this is the urlencoded URL to redirect to * @param string $email For unsub types, this is the urlencoded email address * of the person unsubscribing */ public function actionClick($uid, $type, $url = null, $email = null) { $now = time(); $item = CActiveRecord::model('X2ListItem')->with('contact', 'list')->findByAttributes(array('uniqueId' => $uid)); // It should never happen that we have a list item without a campaign, // but it WILL happen on any old db where x2_list_items does not cascade on delete // we can't track anything if the listitem was deleted, but at least prevent breaking links if ($item === null || $item->list->campaign === null) { if ($type == 'click') { // campaign redirect link click $this->redirect(urldecode($url)); } elseif ($type == 'open') { //return a one pixel transparent gif header('Content-Type: image/gif'); echo base64_decode('R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='); } elseif ($type == 'unsub' && !empty($email)) { Contacts::model()->updateAll(array('doNotEmail' => true), 'email=:email', array(':email' => $email)); X2ListItem::model()->updateAll(array('unsubscribed' => time()), 'emailAddress=:email AND unsubscribed=0', array('email' => $email)); $message = Yii::t('marketing', 'You have been unsubscribed'); echo '<html><head><title>' . $message . '</title></head><body>' . $message . '</body></html>'; } return; } $contact = $item->contact; $list = $item->list; $event = new Events(); $notif = new Notification(); $action = new Actions(); $action->completeDate = $now; $action->complete = 'Yes'; $action->updatedBy = 'API'; $skipActionEvent = true; if ($contact !== null) { $skipActionEvent = false; if ($email === null) { $email = $contact->email; } $action->associationType = 'contacts'; $action->associationId = $contact->id; $action->associationName = $contact->name; $action->visibility = $contact->visibility; $action->assignedTo = $contact->assignedTo; $event->associationId = $action->associationId; $event->associationType = 'Contacts'; if ($action->assignedTo !== '' && $action->assignedTo !== 'Anyone') { $notif->user = $contact->assignedTo; $notif->modelType = 'Contacts'; $notif->modelId = $contact->id; $notif->createDate = $now; $notif->value = $item->list->campaign->getLink(); } } elseif ($list !== null) { $action = new Actions(); $action->type = 'note'; $action->createDate = $now; $action->lastUpdated = $now; $action->completeDate = $now; $action->complete = 'Yes'; $action->updatedBy = 'admin'; $action->associationType = 'X2List'; $action->associationId = $list->id; $action->associationName = $list->name; $action->visibility = $list->visibility; $action->assignedTo = $list->assignedTo; } if ($type == 'unsub') { $item->unsubscribe(); // find any weblists associated with the email address and create unsubscribe actions // for each of them $sql = 'SELECT t.* FROM x2_lists as t JOIN x2_list_items as li ON t.id=li.listId WHERE li.emailAddress=:email AND t.type="weblist";'; $weblists = Yii::app()->db->createCommand($sql)->queryAll(true, array('email' => $email)); foreach ($weblists as $weblist) { $weblistAction = new Actions(); $weblistAction->disableBehavior('changelog'); //$weblistAction->id = 0; // this causes primary key contraint violation errors $weblistAction->isNewRecord = true; $weblistAction->type = 'email_unsubscribed'; $weblistAction->associationType = 'X2List'; $weblistAction->associationId = $weblist['id']; $weblistAction->associationName = $weblist['name']; $weblistAction->visibility = $weblist['visibility']; $weblistAction->assignedTo = $weblist['assignedTo']; $weblistAction->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . $email . " " . Yii::t('marketing', 'has unsubscribed') . "."; $weblistAction->save(); } $action->type = 'email_unsubscribed'; $notif->type = 'email_unsubscribed'; if ($contact === null) { $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . $item->emailAddress . ' ' . Yii::t('marketing', 'has unsubscribed') . "."; } else { $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . Yii::t('marketing', 'Contact has unsubscribed') . ".\n" . Yii::t('marketing', '\'Do Not Email\' has been set') . "."; } $message = Yii::t('marketing', 'You have been unsubscribed'); echo '<html><head><title>' . $message . '</title></head><body>' . $message . '</body></html>'; } elseif ($type == 'open') { //return a one pixel transparent gif header('Content-Type: image/gif'); echo base64_decode('R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='); // Check if it has been marked as opened already, or if the contact // no longer exists. If so, exit; nothing more need be done. if ($item->opened != 0) { Yii::app()->end(); } // This needs to happen before the skip option to accomodate the case of newsletters $item->markOpened(); if ($skipActionEvent) { Yii::app()->end(); } $action->disableBehavior('changelog'); $action->type = 'campaignEmailOpened'; $event->type = 'email_opened'; $notif->type = 'email_opened'; $event->save(); if ($contact === null) { $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . $item->emailAddress . ' ' . Yii::t('marketing', 'has opened the email') . "."; } else { $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . Yii::t('marketing', 'Contact has opened the email') . "."; } } elseif ($type == 'click') { // redirect link click $item->markClicked($url); $action->type = 'email_clicked'; $notif->type = 'email_clicked'; if ($contact === null) { $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . Yii::t('marketing', 'Contact has clicked a link') . ":\n" . urldecode($url); } else { $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . $item->emailAddress . ' ' . Yii::t('marketing', 'has clicked a link') . ":\n" . urldecode($url); } $this->redirect(urldecode($url)); } $action->save(); // if any of these hasn't been fully configured $notif->save(); // it will simply not validate and not be saved }
/** * Deletes an action * @param integer $id The id of the action */ public function actionDelete($id) { $model = $this->loadModel($id); if (Yii::app()->request->isPostRequest) { // $this->cleanUpTags($model); // now in TagBehavior $event = new Events(); $event->type = 'record_deleted'; $event->associationType = $this->modelClass; $event->associationId = $model->id; $event->text = $model->name; $event->visibility = $model->visibility; $event->user = Yii::app()->user->getName(); $event->save(); Events::model()->deleteAllByAttributes(array('associationType' => 'Actions', 'associationId' => $id, 'type' => 'action_reminder')); $model->syncGoogleCalendar('delete'); /* if(!is_numeric($model->assignedTo)) { // assigned to user $profile = Profile::model()->findByAttributes(array('username'=>$model->assignedTo)); if(isset($profile)) $profile->deleteGoogleCalendarEvent($model); // update action in Google Calendar if user has a Google Calendar } else { // Assigned to group $groups = Yii::app()->db->createCommand()->select('userId')->from('x2_group_to_user')->where("groupId={$model->assignedTo}")->queryAll(); foreach($groups as $group) { $profile = Profile::model()->findByPk($group['userId']); if(isset($profile)) $profile->deleteGoogleCalendarEvent($model); } */ $model->delete(); } else { throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.'); } // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if (!isset($_GET['ajax']) && !Yii::app()->request->isAjaxRequest) { $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index')); } else { if (!isset($_POST['gvSelection'])) { echo 'success'; } } }
/** * Make records of the email in every shape and form. * * This method is to be called only once the email has been sent. * * The basic principle behind what all is happening here: emails are getting * sent to people. Since the "To:" field in the inline email form is not * read-only, the emails could be sent to completely different people. Thus, * creating action and event records must be based exclusively on who the * email is addressed to and not the model from whose view the inline email * form (if that's how this model is being used) is submitted. */ public function recordEmailSent($makeEvent = true) { // The email record, with action header for display purposes: $emailRecordBody = $this->insertInBody(self::insertedPattern('ah', $this->actionHeader), 1, 1); $now = time(); $recipientContacts = array_filter($this->recipientContacts); if (!empty($this->targetModel)) { $model = $this->targetModel; if ((bool) $model) { if ($model->hasAttribute('lastActivity')) { $model->lastActivity = $now; $model->save(); } } $action = new Actions(); // These attributes will be the same regardless of the type of // email being sent: $action->completedBy = $this->userProfile->username; $action->createDate = $now; $action->dueDate = $now; $action->subject = $this->subject; $action->completeDate = $now; $action->complete = 'Yes'; $action->actionDescription = $emailRecordBody; // These attributes are context-sensitive and subject to change: $action->associationId = $model->id; $action->associationType = $model->module; $action->type = 'email'; $action->visibility = isset($model->visibility) ? $model->visibility : 1; $action->assignedTo = $this->userProfile->username; if ($this->modelName == 'Quote') { // Is an email being sent to the primary // contact on the quote? If so, the user is "issuing" the quote or // invoice, and it should have a special type. if (!empty($this->targetModel->contact)) { if (array_key_exists($this->targetModel->contact->email, $recipientContacts)) { $action->associationType = lcfirst(get_class($model)); $action->associationId = $model->id; $action->type .= '_' . ($model->type == 'invoice' ? 'invoice' : 'quote'); $action->visibility = 1; $action->assignedTo = $model->assignedTo; } } } if ($makeEvent && $action->save()) { $this->trackEmail($action->id); // Create a corresponding event record. Note that special cases // may have to be written in the method Events->getText to // accommodate special association types apart from contacts, // in addition to special-case-handling here. if ($makeEvent) { $event = new Events(); $event->type = 'email_sent'; $event->subtype = 'email'; $event->associationType = $model->myModelName; $event->associationId = $model->id; $event->user = $this->userProfile->username; if ($this->modelName == 'Quote') { // Special "quote issued" or "invoice issued" event: $event->subtype = 'quote'; if ($this->targetModel->type == 'invoice') { $event->subtype = 'invoice'; } $event->associationType = $this->modelName; $event->associationId = $this->modelId; } $event->save(); } } } // Create action history events and event feed events for all contacts that were in the // recipient list: if ($this->contactFlag) { foreach ($recipientContacts as $email => $contact) { $contact->lastActivity = $now; $contact->update(array('lastActivity')); $skip = false; $skipEvent = false; if ($this->targetModel && get_class($this->targetModel) === 'Contacts') { $skip = $this->targetModel->id == $contact->id; } else { if ($this->modelName == 'Quote') { // An event has already been made for issuing the quote and // so another event would be redundant. $skipEvent = $this->targetModel->associatedContacts == $contact->nameId; } } if ($skip) { // Only save the action history item/event if this hasn't // already been done. continue; } // These attributes will be the same regardless of the type of // email being sent: $action = new Actions(); $action->completedBy = $this->userProfile->username; $action->createDate = $now; $action->dueDate = $now; $action->completeDate = $now; $action->complete = 'Yes'; // These attributes are context-sensitive and subject to change: $action->associationId = $contact->id; $action->associationType = 'contacts'; $action->type = 'email'; $action->visibility = isset($contact->visibility) ? $contact->visibility : 1; $action->assignedTo = $this->userProfile->username; // Set the action's text to the modified email body $action->actionDescription = $emailRecordBody; // We don't really care about changelog events for emails; they're // set in stone anyways. $action->disableBehavior('changelog'); if ($action->save()) { // Now create an event for it: if ($makeEvent && !$skipEvent) { $event = new Events(); $event->type = 'email_sent'; $event->subtype = 'email'; $event->associationType = $contact->myModelName; $event->associationId = $contact->id; $event->user = $this->userProfile->username; $event->save(); } } } // Loop over contacts } // Conditional statement: do all this only if the flag to perform action history creation for all contacts has been set // At this stage, if email tracking is to take place, "$action" should // refer to the action history item of the one and only recipient contact, // because there has been only one element in the recipient array to loop // over. If the target model is a contact, and the one recipient is the // contact itself, the action will be as declared before the above loop, // and it will thus still be properly associated with that contact. }
public static function updateWorkflowChangelog(&$action, $changeType, &$model) { $changelog = new Changelog(); // $type = $action->associationType=='opportunities'?"Opportunity":ucfirst($action->associationType); $changelog->type = get_class($model); $changelog->itemId = $action->associationId; // $record=X2Model::model(ucfirst($type))->findByPk($action->associationId); // if(isset($record) && $record->hasAttribute('name')){ // $changelog->recordName=$record->name; // }else{ // $changelog->recordName=$type; // }X2Flow::trigger('WorkflowStageCompleteTrigger',array('workflow'=>'model'=>$model)); $changelog->recordName = $model->name; $changelog->changedBy = Yii::app()->user->getName(); $changelog->timestamp = time(); $changelog->oldValue = ''; $workflowName = $action->workflow->name; // $workflowName = Yii::app()->db->createCommand()->select('name')->from('x2_workflows')->where('id=:id',array(':id'=>$action->workflowId))->queryScalar(); $stageName = Yii::app()->db->createCommand()->select('name')->from('x2_workflow_stages')->where('workflowId=:id AND stageNumber=:sn', array(':sn' => $action->stageNumber, ':id' => $action->workflowId))->queryScalar(); $event = new Events(); $event->associationType = 'Actions'; $event->associationId = $action->id; $event->user = Yii::app()->user->getName(); if ($changeType === 'start') { //$trigger = 'WorkflowStartStageTrigger'; $event->type = 'workflow_start'; $changelog->newValue = 'Workflow Stage Started: ' . $stageName; } elseif ($changeType === 'complete') { //$trigger = 'WorkflowCompleteStageTrigger'; $event->type = 'workflow_complete'; $changelog->newValue = 'Workflow Stage Completed: ' . $stageName; } elseif ($changeType === 'revert') { //$trigger = 'WorkflowRevertStageTrigger'; $event->type = 'workflow_revert'; $changelog->newValue = 'Workflow Stage Reverted: ' . $stageName; } else { return; } /*X2Flow::trigger($trigger,array( 'workflow'=>$action->workflow, 'model'=>$model, 'stageNumber'=>$action->stageNumber, 'stageName'=>$stageName, ));*/ $event->save(); $changelog->save(); }
public function actionAddComment() { if (isset($_POST['id']) && isset($_POST['text']) && $_POST['text'] != '') { $id = $_POST['id']; $comment = $_POST['text']; $postModel = Events::model()->findByPk($id); if ($postModel === null) { throw new CHttpException(404, Yii::t('app', 'The requested post does not exist.')); } $commentModel = new Events(); $commentModel->text = $comment; $commentModel->user = Yii::app()->user->name; $commentModel->type = 'comment'; $commentModel->associationId = $postModel->id; $commentModel->associationType = 'Events'; $commentModel->timestamp = time(); if ($commentModel->save()) { $commentCount = X2Model::model('Events')->countByAttributes(array('type' => 'comment', 'associationType' => 'Events', 'associationId' => $postModel->id)); $postModel->lastUpdated = time(); $postModel->save(); $profileUser = Yii::app()->db->createCommand()->select('username')->from('x2_users')->where('id=:id', array(':id' => $postModel->associationId))->queryScalar(); // notify the owner of the feed containing the post you commented on (unless that person is you) if ($postModel->associationId != Yii::app()->user->getId()) { $postNotif = new Notification(); $postNotif->type = 'social_comment'; $postNotif->createdBy = $commentModel->user; $postNotif->modelType = 'Profile'; $postNotif->modelId = $postModel->associationId; // look up the username of the owner of the feed $postNotif->user = $profileUser; $postNotif->createDate = time(); $postNotif->save(); } // now notify the person whose post you commented on (unless they're the same person as the first notification) if ($profileUser != $postModel->user && $postModel->user != Yii::app()->user->name) { $commentNotif = new Notification(); $commentNotif->type = 'social_comment'; $commentNotif->createdBy = $commentModel->user; $commentNotif->modelType = 'Profile'; $commentNotif->modelId = $postModel->associationId; $commentNotif->user = $postModel->user; $commentNotif->createDate = time(); $commentNotif->save(); } } echo $commentCount; } else { echo ""; } }
protected function saveModel($event = false) { if (Input::get('id')) { $event = Events::find(Input::get('id')); } if (!$event) { $event = new Events(); } $event->name = Input::get('name'); $event->proposed_opening_time = Input::get('proposed_opening_time'); $event->proposed_closing_time = Input::get('proposed_closing_time'); $event->proposed_local_sponsors = Input::get('proposed_local_sponsors'); $event->promotional_activities = Input::get('promotional_activities'); $event->eval_financial_score = Input::get('eval_financial_score'); $event->eval_financial_text = Input::get('eval_financial_text'); $event->eval_marketing_score = Input::get('eval_marketing_score'); $event->eval_marketing_text = Input::get('eval_marketing_text'); $event->eval_travel_score = Input::get('eval_travel_score'); $event->eval_travel_text = Input::get('eval_travel_text'); $event->eval_production_score = Input::get('eval_production_score'); $event->eval_production_text = Input::get('eval_production_text'); $event->eval_extra_text = Input::get('eval_extra_text'); // new stuff 1 $event->curfew = Input::get('curfew'); $event->minimal_age_limit = Input::get('minimal_age_limit'); $event->alcohol_license = Input::get('alcohol_license'); $event->restrictions_on_merchandise_sales = Input::get('restrictions_on_merchandise_sales'); $event->sound_restrictions = Input::get('sound_restrictions'); $event->booked_for_setup_from = Input::get('booked_for_setup_from'); $event->booked_for_break_until = Input::get('booked_for_break_until'); // new stuff 2 $event->hotel1_name = Input::get('hotel1_name'); $event->hotel2_name = Input::get('hotel2_name'); $event->hotel1_website = Input::get('hotel1_website'); $event->hotel2_website = Input::get('hotel2_website'); $event->hotel1_travel_time_from_airport = Input::get('hotel1_travel_time_from_airport'); $event->hotel2_travel_time_from_airport = Input::get('hotel2_travel_time_from_airport'); $event->hotel1_travel_time_from_venue = Input::get('hotel1_travel_time_from_venue'); $event->hotel2_travel_time_from_venue = Input::get('hotel2_travel_time_from_venue'); $event->ticketsystem_enabled = Input::get('ticketsystem_enabled'); $event->currency_id = Input::get('currency_id'); $event->ticketsystem_recording_startdate = Input::get('ticketsystem_recording_startdate'); $event->ticketsystem_locked_for_promoter = Input::get('ticketsystem_locked_for_promoter'); $event->ticketsystem_autoremind_user_id = Input::get('ticketsystem_autoremind_user_id'); $event->ticketsystem_autoremind = Input::get('ticketsystem_autoremind'); $event->save(); if (Input::get('event_date')) { //error_log('Event date '.json_encode(Input::get('event_date'))); $input_date = strtotime(Input::get('event_date')); $date = $event->date()->first(); if ($date) { // update current date $date->datetime_start = date("Y-m-d H:i:s", $input_date); $date->datetime_end = date("Y-m-d H:i:s", $input_date); $date->update(); } else { // create new date $event_date = new Dates(['datetime_start' => date("Y-m-d H:i:s", $input_date), 'datetime_end' => date("Y-m-d H:i:s", $input_date)]); $event_date->save(); $event->date()->attach($event_date); } $response = Event::fire('event.datechanged', array($event)); } if (Input::get('contact_id')) { $event->contacts()->detach(Contact::find(Input::get('contact_id'))); $event->contacts()->attach(Contact::find(Input::get('contact_id'))); } if (Input::get('venue_id')) { $event->venues()->detach(Venue::find(Input::get('venue_id'))); $event->venues()->attach(Venue::find(Input::get('venue_id'))); } if (Input::get('company_id')) { $event->companies()->detach(Company::find(Input::get('company_id'))); $event->companies()->attach(Company::find(Input::get('company_id'))); } if (Input::get('promoter_id')) { $event->users()->detach(User::find(Input::get('promoter_id'))); $event->users()->attach(User::find(Input::get('promoter_id'))); } return $event; }
/** * * @return boolean whether or not to save */ public function afterSave() { $model = $this->getOwner(); $oldAttributes = $model->getOldAttributes(); if ($model->escalatedTo != '' && (!isset($oldAttributes['escalatedTo']) || $model->escalatedTo != $oldAttributes['escalatedTo'])) { $event = new Events(); $event->type = 'case_escalated'; $event->user = $this->updatedBy; $event->associationType = 'Services'; $event->associationId = $model->id; if ($event->save()) { $notif = new Notification(); $notif->user = $model->escalatedTo; $notif->createDate = time(); $notif->type = 'escalateCase'; $notif->modelType = 'Services'; $notif->modelId = $model->id; $notif->save(); } } parent::afterSave(); }
public function add_event() { try { $_arData = array(); $total_files = null; $eventType = Input::get("eventType"); $eventName = Input::get("eventName"); $eventShortTitle = Input::get("eventShortTitle"); $eventContent = Input::get("eventContent"); $eventVisible = Input::get("eventVisible"); if ($eventVisible == '1') { $eventVisible = '1'; } else { $eventVisible = '0'; } $_userData = Session::get('login'); $destinationPath_Events = 'asserts/images/Events'; $_countFiles = count(Input::file("fileTextImage")); $_number = 1; if (Input::hasfile('fileTextImage')) { $filename = Input::file("fileTextImage"); $total_files = $filename->getClientOriginalName(); $upload_success = $filename->move($destinationPath_Events, $total_files); } $filename_Banner = null; if (Input::hasfile('file')) { $file_Banner = Input::file("file"); $filename_Banner = $file_Banner->getClientOriginalName(); $upload_success_banner = $file_Banner->move($destinationPath_Events, $filename_Banner); } $newEvent = new Events(); $eventId = $this->geteventid(); $newEvent->eventId = $eventId; $newEvent->eventName = $eventName; $newEvent->eventShortTitle = $eventShortTitle; $newEvent->eventContent = $eventContent; $newEvent->eventType = $eventType; $newEvent->eventPictures = $filename_Banner; $newEvent->eventPicturesContent = $total_files; $newEvent->eventVisible = $eventVisible; $newEvent->eventDate = date("Y-m-d"); $newEvent->eventEditor = $_userData["username"]; $newEvent->eventCreatedDate = date("Y-m-d"); $newEvent->save(); } catch (Exception $_ex) { Log::error('Error Add New Event : ' . $_ex->getMessage()); Session::flash('error', '$$$ --- Error (' . $_ex->getMessage() . ') --- $$$'); } Session::flash('success', '$$$ --- Update Event Successfully --- $$$'); return Redirect::to('qlm-admin/add-new-event'); }
/** * Looks up notification criteria in x2_criteria relevant to this model * and field and performs the specified operation. * Soon to be eliminated in wake of x2flow automation system. * * @param string $fieldName the name of the current field * @param string $old the old value * @param string $new the new value */ public function checkNotificationCriteria($fieldName, $old, $new) { $model = $this->getOwner(); $modelClass = get_class($model); $allCriteria = Criteria::model()->findAllByAttributes(array('modelType' => $modelClass, 'modelField' => $fieldName)); foreach ($allCriteria as $criteria) { if ($criteria->comparisonOperator == "=" && $new == $criteria->modelValue || $criteria->comparisonOperator == ">" && $new >= $criteria->modelValue || $criteria->comparisonOperator == "<" && $new <= $criteria->modelValue || $criteria->comparisonOperator == "change" && $new != $old) { $users = preg_split('/[\\s,]+/', $criteria->users, null, PREG_SPLIT_NO_EMPTY); if ($criteria->type == 'notification') { foreach ($users as $user) { $event = new Events(); $event->user = $user; $event->associationType = 'Notification'; $event->type = 'notif'; $notif = new Notification(); $notif->type = 'change'; $notif->fieldName = $fieldName; $notif->modelType = get_class($model); $notif->modelId = $model->id; if ($criteria->comparisonOperator == 'change') { $notif->comparison = 'change'; // if the criteria is just 'changed' $notif->value = $new; // record the new value } else { $notif->comparison = $criteria->comparisonOperator; // otherwise record the operator type $notif->value = mb_substr($criteria->modelValue, 0, 250, 'UTF-8'); // and the comparison value } $notif->user = $user; $notif->createdBy = $this->editingUsername; $notif->createDate = time(); if ($notif->save()) { $event->associationId = $notif->id; $event->save(); } } } elseif ($criteria->type == 'action') { foreach ($users as $user) { $action = new Actions(); $action->assignedTo = $user; if ($criteria->comparisonOperator == "=") { $action->actionDescription = "A record of type " . $modelClass . " has been modified to meet {$criteria->modelField} {$criteria->comparisonOperator} {$criteria->modelValue}" . " by " . $this->editingUsername; } else { if ($criteria->comparisonOperator == ">") { $action->actionDescription = "A record of type " . $modelClass . " has been modified to meet {$criteria->modelField} {$criteria->comparisonOperator} {$criteria->modelValue}" . " by " . $this->editingUsername; } else { if ($criteria->comparisonOperator == "<") { $action->actionDescription = "A record of type " . $modelClass . " has been modified to meet {$criteria->modelField} {$criteria->comparisonOperator} {$criteria->modelValue}" . " by " . $this->editingUsername; } else { if ($criteria->comparisonOperator == "change") { $action->actionDescription = "A record of type " . $modelClass . " has had its {$criteria->modelField} field changed from " . $old . ' to ' . $new . ' by ' . $this->editingUsername; } } } } $action->dueDate = mktime('23', '59', '59'); $action->createDate = time(); $action->lastUpdated = time(); $action->updatedBy = 'admin'; $action->visibility = 1; $action->associationType = lcfirst($modelClass); $action->associationId = $model->id; $action->associationName = $model->name; $action->save(); } } elseif ($criteria->type == 'assignment') { $model->assignedTo = $criteria->users; if ($model->save()) { $event = new Events(); $event->type = 'notif'; $event->user = $model->assignedTo; $event->associationType = 'Notification'; $notif = new Notification(); $notif->user = $model->assignedTo; $notif->createDate = time(); $notif->type = 'assignment'; $notif->modelType = $modelClass; $notif->modelId = $model->id; if ($notif->save()) { $event->associationId = $notif->id; if ($this->createEvent) { $event->save(); } } } } } } }
public function actionNewReply() { if (isset($_POST['TopicReplies'])) { $model = $this->loadModel($_POST['TopicReplies']['topicId']); if (!$this->checkPermissions($model, 'view')) { $this->denied(); } $reply = new TopicReplies(); $reply->text = $_POST['TopicReplies']['text']; $reply->topicId = $_POST['TopicReplies']['topicId']; if ($reply->save()) { $event = new Events(); $event->visibility = 1; $event->associationType = 'TopicRepies'; $event->associationId = $reply->id; $event->user = Yii::app()->user->getName(); $event->type = 'topic_reply'; $event->save(); echo $reply->id; } } }
protected function createevent() { $required = array("event_name" => "Event Name", "event_description" => "Event Description", "date" => "Date", "event_type" => "Event Type"); global $user; if ($user->checkAdmin() == true) { if (isset($_POST)) { foreach ($required as $key => $value) { if (!isset($_POST[$key]) || $_POST[$key] == '' || $_POST[$key] == 'select') { echo $value . ' is Required<br/>'; return; } } echo 'Saving...'; global $objPDO; require_once $_SERVER['DOCUMENT_ROOT'] . '/cloud/model/events_class.php'; $name = mysql_real_escape_string(addslashes(strip_tags($_POST['event_name']))); $desc = mysql_real_escape_string(addslashes(strip_tags($_POST['event_description']))); $type = $_POST['event_type']; $date = $_POST['date']; $event = new Events($objPDO); $event->setEvent($name); $event->setDescription($desc); $event->setType($type); $event->setDate($date); $event->save(); echo '<meta http-equiv="Refresh" content="0;url=http://localhost/cloud/notice/events"/>'; } } else { header('Location:http://localhost/cloud'); } }
public function testMergeEvents() { $contact = $this->contact('testAnyone'); $event = new Events(); $event->type = 'record_updated'; $event->associationType = 'Contacts'; $event->associationId = $contact->id; $event->save(); $model = new Contacts(); foreach ($contact->attributes as $key => $val) { if ($key != 'id' && $key != 'nameId') { $model->{$key} = $val; } } $model->save(); $this->assertEquals(1, Yii::app()->db->createCommand()->select('COUNT(*)')->from('x2_events')->where('associationType = "Contacts" AND associationId = :id', array(':id' => $model->id))->queryScalar()); $this->assertEquals(1, Yii::app()->db->createCommand()->select('COUNT(*)')->from('x2_events')->where('associationType = "Contacts" AND associationId = :id', array(':id' => $contact->id))->queryScalar()); $mergeData = $model->mergeEvents($contact, true); $this->assertEquals(0, Yii::app()->db->createCommand()->select('COUNT(*)')->from('x2_events')->where('associationType = "Contacts" AND associationId = :id', array(':id' => $contact->id))->queryScalar()); $this->assertEquals(2, Yii::app()->db->createCommand()->select('COUNT(*)')->from('x2_events')->where('associationType = "Contacts" AND associationId = :id', array(':id' => $model->id))->queryScalar()); $model->unmergeEvents($contact->id, $mergeData); $this->assertEquals(1, Yii::app()->db->createCommand()->select('COUNT(*)')->from('x2_events')->where('associationType = "Contacts" AND associationId = :id', array(':id' => $contact->id))->queryScalar()); $this->assertEquals(1, Yii::app()->db->createCommand()->select('COUNT(*)')->from('x2_events')->where('associationType = "Contacts" AND associationId = :id', array(':id' => $model->id))->queryScalar()); }
public static function createEvent($input) { $started_at = empty($input['started_at']) ? 'no' : preg_split("/([\\/: ])/", $input['started_at']); $ended_at = empty($input['ended_at']) ? 'no' : preg_split("/([\\/: ])/", $input['ended_at']); $input = array('event_category_id' => $input['event_category_id'], 'city_id' => $input['city_id'], 'email' => $input['email'], 'creator_fname' => $input['creator_fname'], 'creator_lname' => $input['creator_fname'], 'creator_email' => $input['creator_email'], 'name' => $input['name'], 'user_id' => Auth::check() ? Auth::user()->id : '', 'stewardship' => $input['stewardship'], 'description' => $input['description'], 'location' => $input['location'], 'website_url' => $input['website_url'], 'social_media_urls' => $input['social_media_urls'], 'started_at' => $started_at == 'no' ? '' : mktime((int) $started_at[3], (int) $started_at[4], 0, (int) $started_at[0], (int) $started_at[1], (int) $started_at[2]), 'ended_at' => $ended_at == 'no' ? '' : mktime((int) $ended_at[3], (int) $ended_at[4], 0, (int) $ended_at[0], (int) $ended_at[1], (int) $ended_at[2])); $rules = array('event_category_id' => 'required', 'city_id' => 'required', 'creator_fname' => 'required', 'creator_lname' => 'required', 'creator_email' => 'required|email', 'email' => 'required|email', 'name' => 'required', 'stewardship' => 'required|min:5', 'description' => 'required|min:5', 'location' => 'required', 'started_at' => 'required', 'ended_at' => 'required'); $validator = Validator::make($input, $rules); if ($validator->fails()) { return $validator->errors()->all(); } else { try { // Mencatat pembuat target sosial if (Auth::check()) { $input['user_id'] = Auth::user()->id; } else { // Check apakah user ada di database $check_user = User::where('email', $input['creator_email']); if ($check_user->count() > 0) { $input['user_id'] = $check_user->pluck('id'); } else { // Membuat user baru dengan status draft (status:2) $post = new User(); $post->firstname = $input['creator_fname']; $post->lastname = $input['creator_lname']; $post->email = $input['creator_email']; $post->status = 2; $post->save(); $input['user_id'] = $post->id; } } unset($input['creator_fname']); unset($input['creator_lname']); unset($input['creator_email']); $event = new Events(); $event->fill($input); $event->save(); // digunakan untuk mengambil id user yang belum login if (!Auth::check()) { Session::put('update_id', $event->id); } // update $update = Events::find($event->id); $update->fill(array('slug' => Events::checkSlugName(Str::slug($input['name'])) > 0 ? strtolower(Str::slug($input['name'])) . $event->id : strtolower(Str::slug($input['name'])))); $update->save(); return "ok"; } catch (Exception $e) { return "no"; } } }
/** * Records a phone call as a notification. * * Given a phone number, if a contact matching that phone number exists, a * notification assigned to that contact's assignee will be created. * Software-based telephony systems such as Asterisk can thus immediately * notify sales reps of a phone call by making a cURL request to a url * formatted as follows: * * api/voip/data/[phone number] * * (Note: the phone number itself must not contain anything but digits, i.e. * no periods or dashes.) * * For Asterisk, one possible integration method is to insert into the * dialplan, at the appropriate position, a call to a script that uses * {@link http://phpagi.sourceforge.net/ PHPAGI} to extract the phone * number. The script can then make the necessary request to this action. * @param bool $actionHist If set to 1, create an action history item for the contact. */ public function actionVoip($actionHist = 0) { if (isset($_GET['data'])) { $matches = array(); if (preg_match('/\\d{10,}/', $_GET['data'], $matches)) { $number = ltrim($matches[0], '1'); $phoneCrit = new CDbCriteria(array('condition' => "modelType='Contacts' AND number LIKE :number", 'params' => array(':number' => "%{$number}%"))); $phoneCrit->join = 'join x2_contacts on modelId=x2_contacts.id AND ' . Contacts::model()->getHiddenCondition('x2_contacts'); $phoneNumber = PhoneNumber::model()->find($phoneCrit); if (!empty($phoneNumber)) { $contact = X2Model::model('Contacts')->findByPk($phoneNumber->modelId); if (isset($contact)) { $contact->disableBehavior('changelog'); $contact->updateLastActivity(); $assignees = array($contact->assignedTo); if ($contact->assignedTo == 'Anyone' || $contact->assignedTo == null) { $users = User::model()->findAll(); $assignees = array_map(function ($u) { return $u->username; }, $users); } $multiUser = count($assignees) > 1; $usersSuccess = array(); $usersFailure = array(); // Format the phone number: $formattedNumber = ''; $strNumber = (string) $number; $strl = strlen($strNumber); $formattedNumber = substr($strNumber, $strl - 4, $strl); $formattedNumber = substr($strNumber, $strl - 7, 3) . "-{$formattedNumber}"; if ($strl >= 10) { $formattedNumber = substr($strNumber, $strl - 10, 3) . "-{$formattedNumber}"; if ($strl > 10) { $formattedNumber = substr($strNumber, 0, $strl - 10) . "-{$formattedNumber}"; } } $time = time(); // Create notifications: foreach ($assignees as $user) { $notif = new Notification(); $notif->type = 'voip_call'; $notif->user = $user; $notif->modelType = 'Contacts'; $notif->modelId = $contact->id; $notif->value = $formattedNumber; $notif->createDate = $time; if ($notif->save()) { $usersSuccess[] = $user; } else { $usersFailure = array(); } } if ($actionHist) { // Create an action: $action = new Actions(); $action->assignedTo = 'Anyone'; $action->visibility = 1; $action->associationId = $contact->id; $action->associationType = 'contacts'; $action->associationName = $contact->name; $action->dueDate = $time; $action->createDate = $time; $action->completeDate = $time; $action->lastUpdated = $time; $action->type = 'call'; $action->complete = 'Yes'; $action->completedBy = 'Anyone'; $action->save(); $action->actionText = Yii::t('app', 'Phone system reported inbound call from contact.'); } $failure = count($usersSuccess) == 0; $partialFailure = count($usersFailure) > 0; if ($failure) { $message = 'Saving notifications failed.'; } else { /*X2Flow::trigger('RecordVoipInboundTrigger', array( 'model' => $contact, 'number' => $matches[0] ));*/ $message = 'Notifications created for user(s): ' . implode(',', $usersSuccess); if ($partialFailure) { $message .= '; saving notifications failed for users(s): ' . implode(',', $usersFailure); } } // Create an event record for the feed: $event = new Events(); $event->type = 'voip_call'; $event->associationType = get_class($contact); $event->associationId = $contact->id; $event->save(); $this->_sendResponse($failure ? 500 : 200, $message); } else { $this->_sendResponse(404, 'Phone number record refers to a contact that no longer exists.'); } } else { $this->_sendResponse(404, 'No matching phone number found.'); // $notif = new Notification; // $notif->type = 'voip_call'; // $notif->user = ?; // $notif->modelType = 'Contacts'; // $notif->value = $matches[0]; // $notif->createDate = time(); // $notif->save(); } } else { $this->_sendResponse(400, 'Invalid phone number format.'); } } else { $this->_sendResponse(400, 'Phone number required as "data" URL parameter.'); } }
/** * Marks the action complete and updates the record. * @param string $completedBy the user completing the action (defaults to currently logged in user) * @return boolean whether or not the action updated successfully */ public function complete($completedBy = null, $notes = null) { if ($completedBy === null) { $completedBy = Yii::app()->user->getName(); } if (!is_null($notes)) { $this->actionDescription .= "\n\n" . $notes; } $this->complete = 'Yes'; $this->completedBy = $completedBy; $this->completeDate = time(); $this->disableBehavior('changelog'); if ($result = $this->update()) { X2Flow::trigger('ActionCompleteTrigger', array('model' => $this, 'user' => $completedBy)); // delete the action reminder event X2Model::model('Events')->deleteAllByAttributes(array('associationType' => 'Actions', 'associationId' => $this->id, 'type' => 'action_reminder'), 'timestamp > NOW()'); $event = new Events(); $event->type = 'action_complete'; $event->visibility = $this->visibility; $event->associationType = 'Actions'; $event->user = Yii::app()->user->getName(); $event->associationId = $this->id; // notify the admin if ($event->save() && !Yii::app()->user->checkAccess('ActionsAdminAccess')) { $notif = new Notification(); $notif->type = 'action_complete'; $notif->modelType = 'Actions'; $notif->modelId = $this->id; $notif->user = '******'; $notif->createdBy = $completedBy; $notif->createDate = time(); $notif->save(); } } else { $this->validate(); //AuxLib::debugLogR ($this->getErrors ()); } $this->enableBehavior('changelog'); return $result; }
/** * Called when a Contact opens an email sent from Inline Email Form. Inline Email Form * appends an image to the email with src pointing to this function. This function * creates an action associated with the Contact indicating that the email was opened. * * @param integer $uid The unique id of the recipient * @param string $type 'open', 'click', or 'unsub' * */ public function actionEmailOpened($uid, $type) { // If the request is coming from within the web application, ignore it. $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; $baseUrl = Yii::app()->request->getBaseUrl(true); $fromApp = strpos($referrer, $baseUrl) === 0; if ($type == 'open' && !$fromApp) { $track = TrackEmail::model()->findByAttributes(array('uniqueId' => $uid)); if ($track && $track->opened == null) { $action = $track->action; if ($action) { $note = new Actions(); switch ($action->type) { case 'email_quote': case 'email_invoice': $subType = str_replace('email_', '', $action->type); $note->type = "emailOpened_{$subType}"; $quote = Quote::model()->findByPk($action->associationId); if ($quote instanceof Quote) { $contact = $quote->associatedContactsModel; if ($contact instanceof Contacts) { $note->associationType = 'contacts'; $note->associationId = $contact->id; } } break; default: $note->type = 'emailOpened'; $note->associationType = $action->associationType; $note->associationId = $action->associationId; } $now = time(); $note->createDate = $now; $note->lastUpdated = $now; $note->completeDate = $now; $note->complete = 'Yes'; $note->updatedBy = 'admin'; $note->associationName = $action->associationName; $note->visibility = $action->visibility; $note->assignedTo = $action->assignedTo; $note->actionDescription = Yii::t('marketing', 'Contact has opened the email sent on '); $note->actionDescription .= Formatter::formatLongDateTime($action->createDate) . "<br>"; $note->actionDescription .= $action->actionDescription; if ($note->save()) { $event = new Events(); $event->type = 'email_opened'; switch ($action->type) { case 'email_quote': $event->subtype = 'quote'; break; case 'email_invoice': $event->subtype = 'invoice'; break; default: $event->subtype = 'email'; } $contact = isset($quote) && $quote instanceof Quote ? $quote->associatedContactsModel : X2Model::model('Contacts')->findByPk($action->associationId); if (isset($contact)) { $event->user = $contact->assignedTo; } $event->associationType = 'Contacts'; $event->associationId = isset($contact) ? $contact->id : $note->associationId; if ($action->associationType == 'services') { $case = X2Model::model('Services')->findByPk($action->associationId); if (isset($case) && is_numeric($case->contactId)) { $event->associationId = $case->contactId; } elseif (isset($case)) { $event->associationType = 'Services'; $event->associationId = $case->id; } } $event->save(); $track->opened = $now; $track->update(); } } } } //return a one pixel transparent png header('Content-Type: image/png'); echo base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAAXNSR0IArs4c6QAAAAJiS0dEAP+Hj8y/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAC0lEQVQI12NgYAAAAAMAASDVlMcAAAAASUVORK5CYII='); }