/**
  * Creates a new entry, puts the id into the session and
  * redirects back to the index page.
  */
 public function store()
 {
     if (Entry::canCreateOrEdit() === false) {
         return Redirect::route('entry.index')->withMessage("Sorry, the competition has now started and new entries cannot be created.");
     }
     $input = Input::all();
     $validator = Validator::make($input, Entry::$entry_rules);
     if ($validator->fails()) {
         return Redirect::route('entry.create')->withInput()->withErrors($validator);
     }
     DB::beginTransaction();
     $entry = new Entry();
     $entry->email = $input['email'];
     $entry->secret = Hash::make($input['secret']);
     $entry->confirmation = uniqid('', true);
     $entry->first_name = $input['first_name'];
     $entry->last_name = $input['last_name'];
     $entry->peer_group = $input['peer_group'];
     $entry->save();
     $matches = Match::all();
     foreach ($matches as $match) {
         $match_prediction = new MatchPrediction();
         $match_prediction->team_a = $match->team_a;
         $match_prediction->team_b = $match->team_b;
         $match_prediction->pool = $match->pool;
         $match_prediction->match_date = $match->match_date;
         $entry->matchPredictions()->save($match_prediction);
     }
     DB::commit();
     $this->sendConfirmationEmail($entry);
     $this->putEntryIdIntoSession($entry->id);
     return View::make('entry.edit')->with('entry', $entry);
 }
 public static function save($entry_id, $type, $user_id, $privacy)
 {
     $entry = new Entry();
     $entry->entry_id = $entry_id;
     $entry->type = $type;
     $entry->user_id = $user_id;
     $entry->privacy = $privacy;
     $entry->save();
     return $entry;
 }
Exemple #3
0
 public function postAdd($p, $z)
 {
     //	update Zoop::Form so that it it can handle consolidating the edit and view pages here
     $entry = new Entry();
     $entry->start = $_POST['start'];
     $entry->end = $_POST['end'];
     $entry->title = $_POST['title'];
     $entry->is_duration = isset($_POST['is_duration']) && $_POST['is_duration'] ? 1 : 0;
     $entry->save();
     $this->redirect('');
 }
Exemple #4
0
 public static function importEntry($path)
 {
     $parts = explode('/', $path);
     $info = explode('_', $parts[count($parts) - 2]);
     //	do the database part
     $entry = new Entry((int) $info[0]);
     $entry->name = $info[1];
     $entry->assignHeaders();
     $entry->save();
     //	do the file system part
     $entry->cacheContent();
 }
Exemple #5
0
 public static function importEntry($path)
 {
     $info = self::parsePath($path);
     //	do the database part
     $entry = new Entry((int) $info['id']);
     $entry->name = $info['name'];
     $entry->simple = $info['simple'];
     $entry->assignHeaders();
     $entry->save();
     //	do the file system part
     $entry->cacheContent();
 }
Exemple #6
0
 public static function importEntry($path)
 {
     $parts = explode('/', $path);
     $dir = $parts[count($parts) - 2];
     $id = (int) substr($dir, 0, strpos($dir, '_'));
     $name = substr($dir, strpos($dir, '_') + 1);
     //	do the database part
     $entry = new Entry($id);
     $entry->name = $name;
     $entry->assignHeaders();
     $entry->save();
     //	do the file system part
     $entry->cacheContent();
 }
Exemple #7
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store($logbook_id)
 {
     $logbook = Logbook::findOrFail($logbook_id);
     if ($logbook->user_id == Auth::user()->id or $logbook->user_id == 0) {
         $entry = new Entry(Input::only('title', 'body', 'started_at', 'finished_at', 'evidence_id', 'who', 'what', 'where', 'which', 'way', 'when', 'why'));
         $entry->logbook_id = $logbook->id;
         if ($entry->validate()) {
             $entry->save();
         } else {
             return View::make('entries.create', ['entry' => $entry, 'logbook' => $logbook])->withErrors($entry->validator());
         }
         return Redirect::to(route('logbooks.show', [$logbook->id]))->with('message', ['content' => 'Entry met succes aangemaakt!', 'class' => 'success']);
     } else {
         return Redirect::to(route('logbooks.show', [$logbook->id]))->with('message', ['content' => 'Geen rechten om entry weg te schrijven!', 'class' => 'danger']);
     }
 }
Exemple #8
0
 /**
  * @return void
  */
 public function actionCreate()
 {
     // create form
     $model = new Entry('create');
     // form is submitted
     if (isset($_POST['Entry'])) {
         $model->attributes = $_POST['Entry'];
         // save model & redirect to index
         if ($model->save()) {
             $model->resaveTags();
             // set flash
             Yii::app()->user->setFlash('success', 'The entry was created successfully.');
             // redirect to index
             $this->redirect(array('index'));
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function doPOST()
 {
     require_once DB_PATH . '/core/lib/entry.php';
     $id = intval($this->request->entry);
     try {
         $entry = new Entry($this->db, $id);
         if (!($this->auth->authenticated() && $entry->get('user') == $_SESSION['auth_id'])) {
             $entry->check_pass($_POST['password']);
         }
         $entry->update_tags($_POST['tags']);
         $entry->update('title', $_POST['title']);
         $entry->update('safe', intval($_POST['rating']));
         $entry->save();
         redirect('view', $id);
     } catch (Exception $e) {
         die($e->GetMessage());
         redirect('edit', $id);
     }
 }
 /**
  * Store a newly created resource in storage.
  * POST /entries
  *
  * @return Response
  */
 public function store()
 {
     // Validate input.
     $input = array('food' => Input::get('food'), 'servings' => Input::get('servings'));
     $rules = array('food' => 'required', 'servings' => array('required', 'numeric'));
     $validator = Validator::make($input, $rules);
     if ($validator->fails()) {
         $messages = $validator->messages();
         return Redirect::back()->withErrors($messages)->withInput();
     }
     // Store the input in an entry.
     $entry = new Entry();
     $entry->food_id = Input::get('food');
     $entry->user_id = Auth::user()->id;
     $entry->servings = Input::get('servings');
     if ($entry->save()) {
         return Redirect::route('entries.index');
     } else {
         return Redirect::back()->withInput();
     }
 }
Exemple #11
0
function updateEntry($id)
{
    if (is_null($id)) {
        Functions::setResponse(400);
    }
    $data = Functions::getJSONData();
    try {
        $c = new Entry($id);
        foreach ($c->getFields() as $field) {
            $value = Functions::elt($data, $field['name']);
            if (is_null($value)) {
                Functions::setResponse(400);
            }
            $c->set($field['name'], $value);
        }
        $c->set('id', $id);
        $c->save();
        return true;
    } catch (RuntimeException $e) {
        Functions::setResponse(404);
    }
}
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Entry();
     if (isset($_POST['amount']) && isset($_POST['invoice']) && isset($_POST['name'])) {
         $inventory_info = $_POST["name"];
         $inventory_info_arr = explode(":", $inventory_info);
         $inventory_id = intval($inventory_info_arr[0]);
         $inventory = Inventory::model()->findByPk($inventory_id);
         if ($inventory->id) {
             $inventory_id = $inventory->id;
             $model->inventory = $inventory_id;
             $model->item = $inventory->name . " - " . $inventory->model;
             $model->price = intval($_POST['price']);
             $model->amount = intval($_POST['amount']);
             $model->invoice = intval($_POST['invoice']);
             if ($model->save()) {
                 $this->redirect(array('/invoice/view', 'id' => $model->invoice));
             }
         } else {
             throw new Exception("Invalid Inventory ID");
         }
     }
     $this->render('/invoice/view', array('id' => $_POST['invoice']));
 }
Exemple #13
0
 public function actionEntry()
 {
     //关闭页面布局
     $this->layout = false;
     //创建表单模型
     $entry = new Entry();
     //如果是Post请求提交
     if (Yii::$app->request->getIsPost()) {
         //表单模型设置属性为post值
         $entry->setAttributes(Yii::$app->request->post());
         //表单模型数据验证
         if ($entry->validate()) {
             //正确即保存数据
             $result = $entry->save();
             //返回保存后的信息
             if ($result) {
                 var_dump($entry->attributes);
             } else {
                 var_dump($entry->getErrors());
             }
         } else {
             //返回错误提示
             var_dump($entry->getErrors());
         }
     } else {
         //如果不是Post请求,正常显示模板
         return $this->render('entry', ['model' => $entry]);
     }
 }
 protected function login(MessageStack $errors, Register $parameter_output, array $data)
 {
     $section = Section::loadFromHandle($this->parameters()->{'section'});
     $wheres = array();
     $joins = null;
     // Find fields:
     foreach ($section->fields as $field) {
         if ($field instanceof FieldMemberName) {
             $field_name = $field;
             $handle_name = $field->{'element-name'};
         } else {
             if ($field instanceof FieldMemberEmail) {
                 $field_email = $field;
                 $handle_email = $field->{'element-name'};
             } else {
                 if ($field instanceof FieldMemberPassword) {
                     $field_password = $field;
                     $handle_password = $field->{'element-name'};
                 }
             }
         }
     }
     if (!isset($field_email) or !isset($field_password)) {
         throw new Exception(__('Section does not contain required fields.'));
     }
     // Simulate data from cookie:
     if (empty($data) and $this->readSession()) {
         $session = $this->readSession();
         $fields = array($field_email->{'element-name'} => $session->email, $field_password->{'element-name'} => $session->login);
     } else {
         $this->deleteSession();
         $fields = $data['fields'];
     }
     // Apply default values:
     foreach ($this->parameters()->{'defaults'} as $name => $value) {
         if (!isset($fields[$name])) {
             $fields[$name] = $value;
         } else {
             if (is_string($fields[$name]) and $fields[$name] == '') {
                 $fields[$name] = $value;
             } else {
                 if (is_array($fields[$name]) and empty($fields[$name])) {
                     $fields[$name] = array($value);
                 }
             }
         }
     }
     // Apply override values:
     foreach ($this->parameters()->{'overrides'} as $name => $value) {
         if (is_array($fields[$name])) {
             $fields[$name] = array($value);
         } else {
             $fields[$name] = $value;
         }
     }
     // Find values:
     if (isset($field_name)) {
         $value_name = (isset($fields[$handle_name]) and strlen($fields[$handle_name]) > 0) ? $fields[$handle_name] : null;
     }
     if (isset($field_email)) {
         $value_email = (isset($fields[$handle_email]) and strlen($fields[$handle_email]) > 0) ? $fields[$handle_email] : null;
     }
     if (isset($field_password)) {
         $value_password = (isset($fields[$handle_password]) and strlen($fields[$handle_password]) > 0) ? $fields[$handle_password] : null;
     }
     if (is_null($value_email) and is_null($value_name) or is_null($value_password)) {
         throw new Exception(__('Missing login credentials.'));
     }
     // Build query:
     $where_password = array();
     $value_password = array('value' => $value_password, 'type' => 'is');
     $field_password->buildFilterQuery($value_password, $joins, $where_password, $parameter_output);
     if (isset($field_email) and !is_null($value_email)) {
         $where_email = $where_password;
         $value_email = array('value' => $value_email, 'type' => 'is');
         $field_email->buildFilterQuery($value_email, $joins, $where_email, $parameter_output);
         $wheres[] = '(' . implode("\nAND ", $where_email) . ')';
     }
     if (isset($field_name) and !is_null($value_name)) {
         $where_name = $where_password;
         $value_name = array('value' => $value_name, 'type' => 'is');
         $field_name->buildFilterQuery($value_name, $joins, $where_name, $parameter_output);
         $wheres[] = '(' . implode("\nAND ", $where_name) . ')';
     }
     array_unshift($wheres, null);
     $wheres = implode("\nOR ", $wheres);
     $query = "\nSELECT DISTINCT\n\te.*\nFROM\n\t`tbl_entries` AS e{$joins}\nWHERE\n\tFALSE{$wheres}\n\t\t\t";
     //echo '<pre>', htmlentities($query), '</pre>'; exit;
     // Find entry:
     $result = Symphony::Database()->query($query, array(), 'EntryResult');
     if (!$result->valid()) {
         throw new Exception(__('Invalid login credentials.'));
     }
     $entry = $result->current();
     $email = $entry->data()->{$handle_email}->value;
     $code = $entry->data()->{$handle_password}->code;
     $login = $this->driver->createToken($code, 'login');
     if ($this->parameters()->{'create-cookie'} == true) {
         $this->writeCookie($login, $email);
     }
     $event_name = $this->parameters()->{'root-element'};
     $parameter_output->{"event-{$event_name}.system.id"} = $entry->id;
     $parameter_output->{"event-{$event_name}.member.email"} = $email;
     $parameter_output->{"event-{$event_name}.member.login"} = $login;
     // Remove login fields:
     unset($fields[$handle_name], $fields[$handle_email], $fields[$handle_password]);
     // Set password as optional:
     $fields[$handle_password] = array('validate' => array('optional' => $this->driver->createToken($code, 'validate')), 'change' => array('optional' => $this->driver->createToken($code, 'change')));
     // Update fields:
     $entry->setFieldDataFromFormArray($fields);
     ###
     # Delegate: EntryPreCreate
     # Description: Just prior to creation of an Entry. Entry object provided
     Extension::notify('EntryPreCreate', '/frontend/', array('entry' => &$entry));
     $status = Entry::save($entry, $errors);
     if ($status != Entry::STATUS_OK) {
         throw new Exception(__('Entry encountered errors when saving.'));
     }
     ###
     # Delegate: EntryPostCreate
     # Description: Creation of an Entry. New Entry object is provided.
     Extension::notify('EntryPostCreate', '/frontend/', array('entry' => $entry));
 }
 public function cat_reset()
 {
     // This is a big one. Reset all the categories balances to 0 and does it in an
     // entry style, so it can be reversed.
     try {
         DB::transaction(function () {
             // first we save the monthly resetentry
             $e = new Entry();
             $e->uid = $this->user->uid;
             $e->paid_to = 0;
             $e->purchase_date = date('Y-m-d');
             $e->total_amount = 0;
             $e->description = 'Monthly Reset for ' . date('M Y');
             $e->type = 100;
             $e->save();
             foreach ($this->user->user_categories as $uc) {
                 $tmp = [];
                 if (in_array($uc->class, [20, 30])) {
                     $this->save_entry_section($uc->ucid, $e->entid, 2, $uc->balance);
                     if ($uc->class == 20) {
                         // we need to see if we need to alter overflow amt
                         if ($uc->balance < $uc->top_limit) {
                             $uc->saved += $uc->top_limit - $uc->balance;
                         } else {
                             // means spent more than what we budgeted for, we need to reduce the saved if there is some
                             if ($uc->saved > 0) {
                                 if ($uc->balance - $uc->top_limit > $uc->saved) {
                                     $uc->saved = 0.0;
                                 } else {
                                     $uc->saved = $uc->saved - ($uc->balance - $uc->top_limit);
                                 }
                             }
                         }
                         $tmp = ['balance' => 0.0, 'saved' => $uc->saved];
                     } else {
                         // set balance to 0 and save uc
                         $tmp['balance'] = 0.0;
                     }
                     DB::table('user_categories')->where('ucid', $uc->ucid)->update($tmp);
                 }
             }
         });
     } catch (Exception $e) {
         //dd($e->getMessage());
         return Response::json(array('status' => false, 'errors' => array('total' => 'There was a problem with the categories reset.')), 400);
     }
     return Response::json(array('success' => true), 200);
 }
Exemple #16
0
 public static function newEntry($program, $user, $prior_year = false)
 {
     $entry = new Entry();
     $entry->year = $program->year;
     $entry->Top_Company__c = $program->id;
     $entry->Account__c = $user->accountId;
     $entry->Contact__c = $user->contactId;
     if ($prior_year) {
         $entry->Information_Only__c = 'true';
         $entry->cansave = 'true';
     }
     foreach ($program->questions as $q) {
         $resp = new Response();
         $resp->setQuestion($q);
         $entry->addResponse($resp);
     }
     $entry->save();
     return $entry;
 }
Exemple #17
0
 public function saveData(MessageStack $errors, Entry $entry, $data = null)
 {
     $key = key($data);
     $fields = current($data);
     if (is_numeric($key)) {
         $joined = Entry::loadFromId($key);
         $section_handle = $joined->section;
         Entry::delete($key);
     } else {
         $section_handle = $key;
     }
     $joined = new Entry();
     $joined->section = $section_handle;
     // Find the current user ID or just any ID at all:
     if (isset(Administration::instance()->User) && Administration::instance()->User instanceof User) {
         $joined->user_id = Administration::instance()->User->id;
     } else {
         if (isset(Frontend::instance()->User) && Frontend::instance()->User instanceof User) {
             $joined->user_id = Frontend::instance()->User->id;
         } else {
             $joined->user_id = (int) Symphony::Database()->query("SELECT `id` FROM `tbl_users` ORDER BY `id` ASC LIMIT 1")->current()->id;
         }
     }
     // Set entry data:
     foreach ($fields as $field_handle => $value) {
         $joined->data()->{$field_handle} = $value;
     }
     //echo '<pre>'; var_dump($section_handle); exit;
     $status = Entry::save($joined, $errors);
     if ($status != Entry::STATUS_OK) {
         return $status;
     }
     $row = (object) array('entry_id' => $entry->id, 'joined_id' => $joined->id);
     try {
         Symphony::Database()->insert(sprintf('tbl_data_%s_%s', $entry->section, $this->{'element-name'}), (array) $row, Database::UPDATE_ON_DUPLICATE);
         return self::STATUS_OK;
     } catch (DatabaseException $e) {
         $errors->append(null, (object) array('message' => $e->getMessage(), 'code' => $e->getDatabaseErrorCode()));
     } catch (Exception $e) {
         $errors->append(null, (object) array('message' => $e->getMessage(), 'code' => $e->getCode()));
     }
     return self::STATUS_ERROR;
 }
 public function actionGenerate()
 {
     $names = file(getcwd() . "/protected/tests/names.txt");
     $streets = file(getcwd() . "/protected/tests/streets.txt");
     $name_arr = array();
     $street_arr = array();
     foreach ($names as $line) {
         $name = explode(" ", $line);
         $name_arr[] = trim($name[0]);
     }
     foreach ($streets as $line) {
         $street = explode(" ", $line);
         if (count($street) == 3) {
             $name1 = trim($street[0]);
             $name2 = trim($street[1]);
             $name3 = trim($street[2]);
             $street_arr[] = $name1 . " " . $name2 . " " . $name3 . ", Toronto";
         }
     }
     $limit = 1000000;
     for ($i = 0; $i < $limit; $i++) {
         set_time_limit(0);
         // resetting the MySQL timeout
         echo "Creating an invoice #{$i} <br/>";
         $invoice = new Invoice();
         $invoice->name = $name_arr[rand(0, count($name_arr) - 1)];
         $invoice->address = rand(1, 5000) . " " . $street_arr[rand(0, count($street_arr) - 1)];
         $y = 2012;
         //rand(2006,2012);
         if ($y < 2012) {
             $m = rand(1, 12);
         } else {
             $m = rand(1, 11);
         }
         $m = 11;
         $d = rand(1, 2);
         $invoice->date = date($y . '-' . $m . '-' . $d);
         $invoice->delivery_date = date($y . '-' . $m . '-' . $d);
         $invoice->phone1 = "647" . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9) . rand(1, 9);
         $invoice->delivery_date = date($y . '-' . $m . '-' . $d);
         $invoice->delivery_cost = rand(10, 50);
         if ($invoice->save()) {
             $number_of_items = rand(3, 9);
             for ($j = 0; $j < $number_of_items; $j++) {
                 $entry = new Entry();
                 $entry->invoice = $invoice->id;
                 $entry->inventory = rand(3, 2709);
                 $inventory = Inventory::model()->findByPk($entry->inventory);
                 if ($inventory) {
                     $entry->item = $inventory->name . " #" . $inventory->model;
                     $entry->quantity = rand(1, $inventory->quantity);
                     $entry->price = round($inventory->in * 1.3);
                     $entry->amount = round($entry->price * 0.9 * $entry->quantity);
                     if ($entry->save()) {
                         echo "--Entry Created! <br/>";
                         $inventory->quantity = $inventory->quantity - $entry->quantity;
                         if ($inventory->save()) {
                             echo "---Inventory Updated! <br/>";
                         } else {
                             $entry->delete();
                             echo "***Inventory Error! Failed to update <br/>";
                         }
                     } else {
                         echo "***Entry Error!  <br/>";
                         print_r($entry->getErrors());
                         echo "<br/>";
                     }
                 } else {
                     echo "*Inventory Error! (invalid randomed inventory id) <br/>";
                 }
             }
             if ($invoice->Amount > 0) {
                 echo "Invoice Created! id=>" . $invoice->id . "<br/>";
             } else {
                 echo "Invoice has no entries! Deleting id=>" . $invoice->id . "<br/>";
                 $invoice->delete();
             }
         } else {
             echo "Invoice Error! <br/>";
             print_r($invoice->getError());
             echo "<br/>";
         }
         echo "<hr/>";
     }
 }
Exemple #19
0
 /**
  * Update an entry
  *
  * @param Entry $entry The Content entry to be updated
  * @param boolean $dryRun Flag for the 'dry-run' parameter
  * @return Entry
  */
 public function updateItem(Entry $entry, $dryRun = false)
 {
     return $entry->save($dryRun);
 }
 public function trigger(Register $ParameterOutput, array $postdata)
 {
     $result = new XMLDocument();
     $result->appendChild($result->createElement($this->parameters()->{'root-element'}));
     $root = $result->documentElement;
     if (isset($postdata['id'])) {
         $entry = Entry::loadFromID($postdata['id']);
         $type = 'edit';
     } else {
         $entry = new Entry();
         $entry->section = $this->parameters()->{'section'};
         if (isset(Frontend::instance()->User) && Frontend::instance()->User instanceof User) {
             $entry->user_id = Frontend::instance()->User->id;
         } else {
             $entry->user_id = (int) Symphony::Database()->query("SELECT `id` FROM `tbl_users` ORDER BY `id` ASC LIMIT 1")->current()->id;
         }
         $type = 'create';
     }
     if (isset($postdata['fields']) && is_array($postdata['fields']) && !empty($postdata['fields'])) {
         $entry->setFieldDataFromFormArray($postdata['fields']);
     }
     $root->setAttribute('type', $type);
     ###
     # Delegate: EntryPreCreate
     # Description: Just prior to creation of an Entry. Entry object provided
     Extension::notify('EntryPreCreate', '/frontend/', array('entry' => &$entry));
     $errors = new MessageStack();
     $status = Entry::save($entry, $errors);
     if ($status == Entry::STATUS_OK) {
         ###
         # Delegate: EntryPostCreate
         # Description: Creation of an Entry. New Entry object is provided.
         Extension::notify('EntryPostCreate', '/frontend/', array('entry' => $entry));
         if ($this->parameters()->{'output-id-on-save'} == true) {
             $ParameterOutput->{sprintf('event-%s-id', $this->parameters()->{'root-element'})} = $entry->id;
         }
         $root->setAttribute('result', 'success');
         $root->appendChild($result->createElement('message', __("Entry %s successfully.", array($type == 'edit' ? __('edited') : __('created')))));
     } else {
         $root->setAttribute('result', 'error');
         $root->appendChild($result->createElement('message', __('Entry encountered errors when saving.')));
         if (!isset($postdata['fields']) || !is_array($postdata['fields'])) {
             $postdata['fields'] = array();
         }
         $element = $result->createElement('values');
         $this->appendValues($element, $postdata['fields']);
         $root->appendChild($element);
         $element = $result->createElement('errors');
         $this->appendMessages($element, $errors);
         $root->appendChild($element);
     }
     return $result;
 }
 public function cloneEntry($sourceEntry, $targetEntry)
 {
     $criteria = $this->getCriteria()->select("idEntry, name, description, nick, idLanguage");
     $criteria->where("entry = '{$sourceEntry}'");
     $criteria->asQuery()->each(function ($row) use($targetEntry) {
         $entry = new Entry();
         $entry->setEntry($targetEntry);
         $entry->setName($row['name']);
         $entry->setDescription($row['description']);
         $entry->setNick($row['nick']);
         $entry->setIdLanguage($row['idLanguage']);
         $entry->save();
     });
 }
 public function trigger(Register $ParameterOutput, array $postdata)
 {
     $result = new XMLDocument();
     $result->appendChild($result->createElement($this->parameters()->{'root-element'}));
     $root = $result->documentElement;
     // Apply default values:
     foreach ($this->parameters()->{'defaults'} as $name => $value) {
         if (!isset($postdata['fields'][$name])) {
             $postdata['fields'][$name] = $value;
         } else {
             if (is_string($postdata['fields'][$name]) and $postdata['fields'][$name] == '') {
                 $postdata['fields'][$name] = $value;
             } else {
                 if (is_array($postdata['fields'][$name]) and empty($postdata['fields'][$name])) {
                     $postdata['fields'][$name] = array($value);
                 }
             }
         }
     }
     // Apply override values:
     foreach ($this->parameters()->{'overrides'} as $name => $value) {
         if (is_array($postdata['fields'][$name])) {
             $postdata['fields'][$name] = array($value);
         } else {
             $postdata['fields'][$name] = $value;
         }
     }
     if (isset($postdata['id'])) {
         $entry = Entry::loadFromID($postdata['id']);
         $type = 'edit';
     } else {
         $entry = new Entry();
         $entry->section = $this->parameters()->{'section'};
         if (isset(Frontend::instance()->User) && Frontend::instance()->User instanceof User) {
             $entry->user_id = Frontend::instance()->User->id;
         } else {
             $entry->user_id = (int) Symphony::Database()->query("SELECT `id` FROM `tbl_users` ORDER BY `id` ASC LIMIT 1")->current()->id;
         }
         $type = 'create';
     }
     if (isset($postdata['fields']) && is_array($postdata['fields']) && !empty($postdata['fields'])) {
         $entry->setFieldDataFromFormArray($postdata['fields']);
     }
     $root->setAttribute('type', $type);
     ###
     # Delegate: EntryPreCreate
     # Description: Just prior to creation of an Entry. Entry object provided
     Extension::notify('EntryPreCreate', '/frontend/', array('entry' => &$entry));
     $errors = new MessageStack();
     $status = Entry::save($entry, $errors);
     if ($status == Entry::STATUS_OK) {
         ###
         # Delegate: EntryPostCreate
         # Description: Creation of an Entry. New Entry object is provided.
         Extension::notify('EntryPostCreate', '/frontend/', array('entry' => $entry));
         if ($this->parameters()->{'output-id-on-save'} == true) {
             $ParameterOutput->{sprintf('event-%s-id', $this->parameters()->{'root-element'})} = $entry->id;
         }
         $root->setAttribute('result', 'success');
         $root->setAttribute('id', $entry->id);
         $root->appendChild($result->createElement('message', __("Entry %s successfully.", array($type == 'edit' ? __('edited') : __('created')))));
     } else {
         $root->setAttribute('result', 'error');
         $root->appendChild($result->createElement('message', __('Entry encountered errors when saving.')));
         if (!isset($postdata['fields']) || !is_array($postdata['fields'])) {
             $postdata['fields'] = array();
         }
         $element = $result->createElement('errors');
         $this->appendMessages($element, $errors);
         $root->appendChild($element);
     }
     $messages = new MessageStack();
     ###
     # Delegate: EventPostSaveFilter
     # Description: After saving entry from the front-end. This delegate will not force the Events to terminate if it populates the error
     #              array reference. Provided with the event, message stack, postdata and entry object.
     Extension::notify('EventPostSaveFilter', '/frontend/', array('event' => $this, 'messages' => $messages, 'fields' => $postdata, 'entry' => $entry));
     if ($messages->valid()) {
         $filter = $result->createElement('filters');
         $this->appendMessages($filter, $messages);
         $root->appendChild($filter);
     }
     $element = $result->createElement('values');
     $this->appendValues($element, is_array($postdata['fields']) ? $postdata['fields'] : array());
     $root->appendChild($element);
     return $result;
 }
 public function __actionEdit()
 {
     $callback = Administration::instance()->getPageCallback();
     $entry_id = (int) $callback['context']['entry_id'];
     if (@array_key_exists('save', $_POST['action']) || @array_key_exists("done", $_POST['action'])) {
         $entry = Entry::loadFromID($entry_id);
         $post = General::getPostData();
         $fields = array();
         if (isset($post['fields']) and !empty($post['fields'])) {
             $fields = $post['fields'];
         }
         $entry->setFieldDataFromFormArray($fields);
         ###
         # Delegate: EntryPreEdit
         # Description: Just prior to editing of an Entry.
         Extension::notify('EntryPreEdit', '/publish/edit/', array('entry' => &$entry));
         $this->errors->flush();
         $status = Entry::save($entry, $this->errors);
         if ($status == Entry::STATUS_OK) {
             // Check if there is a field to prepopulate
             if (isset($_REQUEST['prepopulate']) && strlen(trim($_REQUEST['prepopulate'])) > 0) {
                 $field_handle = key($_REQUEST['prepopulate']);
                 $value = stripslashes(rawurldecode($_REQUEST['prepopulate'][$field_handle]));
                 $prepopulate_filter = "?prepopulate[{$field_handle}]=" . rawurlencode($value);
             } else {
                 $prepopulate_filter = null;
             }
             ###
             # Delegate: EntryPostEdit
             # Description: Editing an entry. Entry object is provided.
             Extension::notify('EntryPostEdit', '/publish/edit/', array('entry' => $entry));
             ## WOOT
             redirect(sprintf('%s/symphony/publish/%s/edit/%d/:saved/%s', URL, $entry->section, $entry->id, $prepopulate_filter));
         }
         // Oh dear
         $this->entry = $entry;
         $this->alerts()->append(__('An error occurred while processing this form. <a href="#error">See below for details.</a> <a class="more">Show a list of errors.</a>'), AlertStack::ERROR);
         return;
     } elseif (@array_key_exists('delete', $_POST['action']) && is_numeric($entry_id)) {
         $callback = Administration::instance()->getPageCallback();
         ###
         # Delegate: Delete
         # Description: Prior to deleting an entry. Entry ID is provided, as an
         # array to remain compatible with other Delete delegate call
         Extension::notify('Delete', '/publish/', array('entry_id' => $entry_id));
         Entry::delete($entry_id);
         redirect(ADMIN_URL . '/publish/' . $callback['context']['section_handle'] . '/');
     }
 }
 public function createentry($authenticated = false)
 {
     try {
         $entry = new Entry($this->db);
         $entry->update('title', $this->title);
         $entry->update('type', $this->type);
         $entry->update('size', $this->size);
         $entry->update('width', $this->width);
         $entry->update('height', $this->height);
         $entry->update('ip', $this->host);
         $entry->update('password', $this->password);
         $entry->update('safe', $this->worksafe);
         $entry->update('hash', $this->hash);
         if ($authenticated) {
             $entry->update('user', $_SESSION['auth_id']);
         }
         $nsid = $_SESSION['namespace_id'] ? $_SESSION['namespace_id'] : DB_PUBNS;
         if ($nsid != DB_PUBNS) {
             $ns = new DBNamespaces($this->db);
             if (!$ns->check_permission($nsid, $_SESSION['auth_id'], ACL_WRITE)) {
                 throw new ImageException('no permission to upload into this namespace');
             }
         }
         $entry->update('namespace', $nsid);
         $entry->save();
         $this->entryid = $entry->get_id();
         return true;
     } catch (Exception $e) {
         throw new ImageException('application error while creating entry', true);
     }
 }
Exemple #25
0
    /**
     * @return void
     */
    public function actionCsv()
    {
        $model = new ImportCsvUploadForm();

        // upload form (first step) was submitted
        if (isset($_POST['ImportCsvUploadForm'])) {
            $model->attributes = $_POST['ImportCsvUploadForm'];

            // validate upload
            if ($model->validate()) {
                $models = array();

                // get file
                $file = CUploadedFile::getInstance($model, 'file');
                $fileContent = trim(file_get_contents($file->tempName));
                $fileLines = explode("\n", $fileContent);

                // relations between CSV and ImportCsvForm
                $csvToObject = array(
                    0 => 'name',
                    1 => 'url',
                    2 => 'comment',
                    3 => 'tags',
                    4 => 'username',
                    5 => 'password'
                );

                // traverse uploaded file per line
                foreach ($fileLines as $index => $line) {
                    // skip first line (header)
                    if ($index == 0) {
                        continue;
                    }

                    // parse line to array
                    $csv = str_getcsv($line);

                    if (count($csv) < 1) {
                        continue;
                    }

                    // create model
                    $tmpModel = new ImportCsvForm();

                    // set array values to model
                    foreach ($csvToObject as $position => $name) {
                        if (!isset($csv[$position])) {
                            break;
                        }

                        $tmpModel->$csvToObject[$position] = $csv[$position];
                    }

                    $models[] = $tmpModel;
                }
            }
        } elseif (isset($_POST['ImportCsvForm'])) { // import
            $models = array();
            $valid = true;

            foreach ($_POST['ImportCsvForm'] as $data) {
                $model = new ImportCsvForm();
                $model->attributes = $data;
                $valid = $model->validate();

                $models[] = $model;

                if (!$valid) {
                    Yii::app()->user->setFlash('hasError', true);
                }
            }

            if ($valid) {
                foreach ($models as $model) {
                    $entry = new Entry('create');
                    $entry->name = $model->name;
                    $entry->url = $model->url;
                    $entry->username = $model->username;
                    $entry->password = $model->password;
                    $entry->tagList = $model->tags;
                    $entry->comment = $model->comment;
                    $entry->save();
                    $entry->resaveTags();
                }

                Yii::app()->user->setFlash('success', 'Your CSV was successfully imported!');
                $this->redirect(array('/entry/index'));
            }
        }
        // render upload form
        if (!isset($models)) {
            $this->render('csv-upload', array('model' => $model, 'maxImport' => ceil(ini_get('max_input_vars') / 6)));
        } else { // render import form
            $this->render('csv-import', array('models' => $models));
        }
    }
 public function sync($contract_guid)
 {
     $this->authenticate($contract_guid);
     $active_tree = Dropbox::find($contract_guid);
     $previous_delta = empty($active_tree->delta) ? null : $active_tree->delta;
     $delta_data = $this->active_client->getDelta($previous_delta);
     foreach (['has_more', 'cursor', 'entries', 'reset'] as $required_key) {
         if (!isset($delta_data[$required_key])) {
             return ['success' => false, 'error_message' => 'Missing ' . $required_key];
         }
     }
     if ($delta_data['reset'] && !is_null($previous_delta)) {
         // Have yet to encounter a 'reset', documentation suggests it only
         // will occur at the initial (null) delta, and if an app folder is
         // renamed. Since we're not in an app folder, it shouldn't occur.
         //
         // That said, if it does occur, we need to know right away!
         error_log("DELTA RESET ENCOUNTERED FOR USER " . $contract_guid . " AT DELTA " . $previous_delta . " NEED TO TEST!");
         // From documentation:
         // https://www.dropbox.com/developers/core/docs#metadata-details
         // reset If true, clear your local state before processing the delta
         // entries. reset is always true on the initial call to /delta (i.e.
         // when no cursor is passed in). Otherwise, it is true in rare
         // situations, such as after server or account maintenance, or if a
         // user deletes their app folder.
         // Supposedly that means we have to reprocess this user's entire
         // dropbox account, from scratch. Very scary prospect.
         dd("Special case, not yet handled!...");
     }
     if (count($delta_data['entries']) < 1 && !$delta_data['has_more'] && !$delta_data['reset']) {
         $active_tree->delta = $delta_data['cursor'];
         $active_tree->save();
         return ['success' => true, 'updated' => false];
     }
     foreach ($delta_data['entries'] as $entry_key => list($entry['original_path'], $entry['update_data'])) {
         $entry_altered = false;
         $entry_created = false;
         $entry_deleted = false;
         // Remove attributes we don't track, are deprecated, etc.
         unset($delta_data['entries'][$entry_key][1]['thumb_exists'], $delta_data['entries'][$entry_key][1]['revision'], $entry['update_data']['icon'], $entry['update_data']['root'], $entry['update_data']['size'], $entry['update_data']['hash'], $entry['update_data']['thumb_exists'], $entry['update_data']['revision']);
         if (is_null($entry['update_data'])) {
             $entry_deleted = true;
         } elseif ($stored_entry = Entry::where('original_path', '=', $entry['original_path'])->where('dropbox_id', $contract_guid)->first()) {
             foreach ($entry['update_data'] as $entry_column => $entry_column_value) {
                 $stored_column_name = ['rev' => 'rev', 'bytes' => 'bytes', 'modified' => 'service_updated_at', 'client_mtime' => 'client_updated_at', 'path' => 'original_path', 'is_dir' => 'is_dir', 'mime_type' => 'mime_type'][$entry_column];
                 if ($entry_column_value !== $stored_entry->{$stored_column_name}) {
                     $stored_entry->{$stored_column_name} = $entry_column_value;
                     $entry_altered = true;
                 }
             }
         } else {
             // Path does not exist in the database
             $stored_entry = new Entry();
             $stored_entry->dropbox_id = $contract_guid;
             if ($entry['original_path'] == '/') {
                 $stored_entry->parent_id = 0;
             } else {
                 $parent_entry = Entry::where('original_path', '=', dirname($entry['original_path']))->where('dropbox_id', $contract_guid)->first();
                 if (!$parent_entry && dirname($entry['original_path']) == '/') {
                     // Generate a root since it is not shown in deltas
                     $parent_entry = new Entry();
                     $parent_entry->original_path = '/';
                     $parent_entry->dropbox_id = $contract_guid;
                     $parent_entry->parent_id = 0;
                     $parent_entry->rev = '';
                     $parent_entry->bytes = 0;
                     $parent_entry->mime_type = '';
                     $parent_entry->service_updated_at = '';
                     $parent_entry->client_updated_at = '';
                     $parent_entry->is_dir = 1;
                     $parent_entry->save();
                 }
                 $stored_entry->parent_id = $parent_entry->id;
             }
             $stored_entry->original_path = $entry['update_data']['path'];
             $stored_entry->rev = $entry['update_data']['rev'];
             $stored_entry->bytes = $entry['update_data']['bytes'];
             $stored_entry->mime_type = isset($entry['update_data']['mime_type']) ? $entry['update_data']['mime_type'] : '';
             $stored_entry->service_updated_at = $entry['update_data']['modified'];
             $stored_entry->client_updated_at = isset($entry['update_data']['client_mtime']) ? $entry['update_data']['client_mtime'] : '';
             $stored_entry->is_dir = $entry['update_data']['is_dir'];
             $entry_created = true;
         }
         if ($entry_altered || $entry_created) {
             $stored_entry->save();
         }
         if ($entry_created) {
             $data = ['action' => 'create', 'entry' => $stored_entry->toArray()];
             if (!$stored_entry->is_dir) {
                 Queue::push('FileHandlerController@create', $data, $this->file_queue_id);
             }
         }
         if ($entry_altered) {
             $data = ['action' => 'update', 'entry' => $stored_entry->toArray()];
             if (!$stored_entry->is_dir) {
                 Queue::push('FileHandlerController@update', $data, $this->file_queue_id);
             }
         }
         if ($entry_deleted) {
             // TODO: Fire off single-file deletion processing for this file, here
             if ($stored_entry = Entry::where('original_path', '=', $entry['original_path'])->where('dropbox_id', $contract_guid)->first()) {
                 // Remove any/all children files and folders to this folder
                 foreach ($stored_entry->children() as $child_entry) {
                     $data = ['action' => 'remove', 'entry' => $child_entry->toArray()];
                     Queue::push('FileHandlerController@remove', $data, $this->file_queue_id);
                     $child_entry->delete();
                 }
                 $data = ['action' => 'remove', 'entry' => $stored_entry->toArray()];
                 if (!$stored_entry->is_dir) {
                     Queue::push('FileHandlerController@remove', $data, $this->file_queue_id);
                 }
                 $stored_entry->delete();
             }
         }
     }
     $active_tree->delta = $delta_data['cursor'];
     $active_tree->save();
     // One delta sync per queue job
     return ['success' => true, 'updated' => true];
 }