sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function setOrder($field, $desc = null) { if (!$field instanceof Field) { if (is_object($field)) { $this->_dsql()->order($field, $desc); return $this; } if (is_string($field) && strpos($field, ',') !== false) { $field = explode(',', $field); } if (is_array($field)) { if (!is_null($desc)) { throw $this->exception('If first argument is array, second argument must not be used'); } foreach (array_reverse($field) as $o) { $this->setOrder($o); } return $this; } if (is_null($desc) && is_string($field) && strpos($field, ' ') !== false) { list($field, $desc) = array_map('trim', explode(' ', trim($field), 2)); } /** @type Field $field */ $field = $this->getElement($field); } $this->_dsql()->order($field, $desc); return $this; }
Sets an order on the field. Field must be properly defined
entailment
public function getRows($fields = null) { /**/$this->app->pr->start('getRows/selecting'); $a = $this->selectQuery($fields); /**/$this->app->pr->next('getRows/fetching'); $a = $a->get(); $this->app->pr->stop(); return $a; }
Loads all matching data into array of hashes
entailment
public function count($alias = null) { // prepare new query $q = $this->dsql()->del('fields')->del('order'); // add expression field to query return $q->field($q->count(), $alias); }
Returns dynamic query selecting number of entries in the database. @param string $alias Optional alias of count expression @return DB_dsql
entailment
public function sum($field) { // prepare new query $q = $this->dsql()->del('fields')->del('order'); // put field in array if it's not already if (!is_array($field)) { $field = array($field); } // add all fields to query foreach ($field as $f) { if (!is_object($f)) { $f = $this->getElement($f); } $q->field($q->sum($f), $f->short_name); } // return query return $q; }
Returns dynamic query selecting sum of particular field or fields. @param string|array|Field $field @return DB_dsql
entailment
public function tryLoadRandom() { // get ID first $id = $this->dsql()->order('rand()')->limit(1)->field($this->getElement($this->id_field))->getOne(); if ($id) { $this->load($id); } return $this; }
Loads random entry into model
entailment
public function tryLoad($id) { if (is_null($id)) { throw $this->exception('Record ID must be specified, otherwise use loadAny()'); } return $this->_load($id, true); }
Try to load a record by specified ID. Will not raise exception if record is not found
entailment
public function loadBy($field, $cond = UNDEFINED, $value = UNDEFINED) { $q = $this->dsql; $this->dsql = $this->dsql(); $this->addCondition($field, $cond, $value); $this->loadAny(); $this->dsql = $q; return $this; }
Similar to loadAny() but will apply condition before loading. Condition is temporary. Fails if record is not loaded.
entailment
public function tryLoadBy($field, $cond = UNDEFINED, $value = UNDEFINED) { $q = $this->dsql; $this->dsql = $this->dsql(); $this->addCondition($field, $cond, $value); $this->tryLoadAny(); $this->dsql = $q; return $this; }
Attempt to load using a specified condition, but will not fail if such record is not found
entailment
public function getBy($field, $cond = UNDEFINED, $value = UNDEFINED) { $data = $this->data; $id = $this->id; $this->tryLoadBy($field, $cond, $value); $row = $this->data; $this->data = $data; $this->id = $id; return $row; }
Loads data record and return array of that data. Will not affect currently loaded record.
entailment
protected function _load($id, $ignore_missing = false) { /**/$this->app->pr->start('load/selectQuery'); $this->unload(); $load = $this->selectQuery(); /**/$this->app->pr->next('load/clone'); $p = ''; if (!empty($this->relations)) { $p = ($this->table_alias ?: $this->table).'.'; } /**/$this->app->pr->next('load/where'); if (!is_null($id)) { $load->where($p.$this->id_field, $id); } /**/$this->app->pr->next('load/beforeLoad'); $this->hook('beforeLoad', array($load, $id)); if (!$this->loaded()) { /**/$this->app->pr->next('load/get'); $s = $load->stmt; $l = $load->args['limit']; $load->stmt = null; $data = $load->limit(1)->getHash(); $load->stmt = $s; $load->args['limit'] = $l; if (!is_null($id)) { array_pop($load->args['where']); } // remove where condition /**/$this->app->pr->next('load/ending'); $this->reset(); if (@!$data) { if ($ignore_missing) { return $this; } else { throw $this->exception('Record could not be loaded', 'Exception_NoRecord') ->addMoreInfo('model', $this) ->addMoreInfo('id', $id); } } $this->data = $data; // avoid using set() for speed and to avoid field checks $this->id = $this->data[$this->id_field]; } $this->hook('afterLoad'); /**/$this->app->pr->stop(); return $this; }
Internal loading funciton. Do not use. OK to override.
entailment
public function saveAndUnload() { $this->_save_as = false; $this->save(); $this->_save_as = null; return $this; }
Save model into database and don't try to load it back
entailment
public function saveAs($model) { if (is_string($model)) { $model = $this->app->normalizeClassName($model, 'Model'); $model = $this->add($model); } $this->_save_as = $model; $res = $this->save(); $this->_save_as = null; return $res; }
Save model into database and try to load it back as a new model of specified class. Instance of new class is returned.
entailment
public function save() { $this->_dsql()->owner->beginTransaction(); $this->hook('beforeSave'); // decide, insert or modify if ($this->loaded()) { $res = $this->modify(); } else { $res = $this->insert(); } $res->hook('afterSave'); $this->_dsql()->owner->commit(); return $res; }
Save model into database and load it back. If for some reason it won't load, whole operation is undone.
entailment
private function insert() { $insert = $this->dsql(); // Performs the actual database changes. Throw exception if problem occurs foreach ($this->elements as $name => $f) { if ($f instanceof Field) { if (!$f->editable() && !$f->system()) { continue; } if (!isset($this->dirty[$name]) && $f->defaultValue() === null) { continue; } $f->updateInsertQuery($insert); } } $this->hook('beforeInsert', array(&$insert)); //delayed is not supported by INNODB, but what's worse - it shows error. //if($this->_save_as===false)$insert->option_insert('delayed'); $id = $insert->insert(); if ($id == 0) { // no auto-increment column present $id = $this->get($this->id_field); if ($id === null && $this->_save_as !== false) { throw $this->exception('Please add auto-increment ID column to your table or specify ID manually'); } } $res = $this->hook('afterInsert', array($id)); if ($res === false) { return $this; } if ($this->_save_as === false) { return $this->unload(); } if ($this->_save_as) { $this->unload(); } $o = $this->_save_as ?: $this; if ($this->fast && !$this->_save_as) { $this[$this->id_field] = $this->id = $id; return $this; } $res = $o->tryLoad($id); if (!$res->loaded()) { throw $this->exception('Saved model did not match conditions. Save aborted.'); } return $res; }
Internal function which performs insert of data. Use save() instead. OK to override. Will return new object if saveAs() is used.
entailment
private function modify() { $modify = $this->dsql()->del('where'); $modify->where($this->getElement($this->id_field), $this->id); if (empty($this->dirty)) { return $this; } foreach ($this->dirty as $name => $junk) { if ($el = $this->hasElement($name)) { if ($el instanceof Field) { $el->updateModifyQuery($modify); } } } // Performs the actual database changes. Throw exceptions if problem occurs $this->hook('beforeModify', array($modify)); if ($modify->args['set']) { $modify->update(); } if ($this->dirty[$this->id_field]) { $this->id = $this->get($this->id_field); } $this->hook('afterModify'); if ($this->_save_as === false) { return $this->unload(); } $id = $this->id; if ($this->_save_as) { $this->unload(); } $o = $this->_save_as ?: $this; return $o->load($id); }
Internal function which performs modification of existing data. Use save() instead. OK to override. Will return new object if saveAs() is used.
entailment
public function unload() { if ($this->_save_later) { $this->_save_later = false; $this->saveAndUnload(); } $this->hook('beforeUnload'); $this->id = null; // parent::unload(); if ($this->_save_later) { $this->_save_later = false; $this->saveAndUnload(); } if ($this->loaded()) { $this->hook('beforeUnload'); } $this->data = $this->dirty = array(); $this->id = null; $this->hook('afterUnload'); // $this->hook('afterUnload'); return $this; }
forget currently loaded record and it's ID. Will not affect database
entailment
public function tryDelete($id = null) { if (!is_null($id)) { $this->tryLoad($id); } if ($this->loaded()) { $this->delete(); } return $this; }
Tries to delete record, but does nothing if not found
entailment
public function delete($id = null) { if (!is_null($id)) { $this->load($id); } if (!$this->loaded()) { throw $this->exception('Unable to determine which record to delete'); } $tmp = $this->dsql; $this->initQuery(); $delete = $this->dsql->where($this->id_field, $this->id); $delete->owner->beginTransaction(); $this->hook('beforeDelete', array($delete)); $delete->delete(); $this->hook('afterDelete'); $delete->owner->commit(); $this->dsql = $tmp; $this->unload(); return $this; }
Deletes record matching the ID
entailment
public function deleteAll() { $delete = $this->dsql(); $delete->owner->beginTransaction(); $this->hook('beforeDeleteAll', array($delete)); $delete->delete(); $this->hook('afterDeleteAll'); $delete->owner->commit(); $this->reset(); return $this; }
Deletes all records matching this model. Use with caution.
entailment
public function set($name, $value = UNDEFINED) { if (is_array($name)) { foreach ($name as $key => $val) { $this->set($key, $val); } return $this; } if ($name === false || $name === null) { return $this->reset(); } // Verify if such a field exists if ($this->strict_fields && !$this->hasElement($name)) { throw $this->exception('No such field', 'Logic') ->addMoreInfo('name', $name); } if ($value !== UNDEFINED && ( is_object($value) || is_object($this->data[$name]) || is_array($value) || is_array($this->data[$name]) || (string) $value != (string) $this->data[$name] // this is not nice.. || $value !== $this->data[$name] // considers case where value = false and data[$name] = null || !isset($this->data[$name]) // considers case where data[$name] is not initialized at all // (for example in model using array controller) ) ) { $this->data[$name] = $value; $this->setDirty($name); } return $this; }
Override all methods to keep back-compatible
entailment
public function _refBind($field_in, $expression, $field_out = null) { if ($this->controller) { return $this->controller->refBind($this, $field, $expression); } list($myref, $rest) = explode('/', $ref, 2); if (!$this->_references[$myref]) { throw $this->exception('No such relation') ->addMoreInfo('ref', $myref) ->addMoreInfo('rest', $rest); } // Determine and populate related model if (is_array($this->_references[$myref])) { $m = $this->_references[$myref][0]; } else { $m = $this->_references[$myref]; } $m = $this->add($m); if ($rest) { $m = $m->_ref($rest); } $this->_refGlue(); if (!isset($this->_references[$ref])) { throw $this->exception('Unable to traverse, no reference defined by this name') ->addMoreInfo('name', $ref); } $r = $this->_references[$ref]; if (is_array($r)) { list($m, $our_field, $their_field) = $r; if (is_string($m)) { $m = $this->add($m); } else { $m = $m->newInstance(); } return $m->addCondition($their_field, $this[$our_field]); } if (is_string($m)) { $m = $this->add($m); } else { $m = $m->newInstance(); } return $m->load($this[$our_field]); }
Strange method. Uses undefined $field variable, undefined refBind() method etc. https://github.com/atk4/atk4/issues/711
entailment
public function send(OutgoingMessage $message) { $from = $message->getFrom(); $composeMessage = $message->composeMessage(); $numbers = $message->getToWithCarriers(); if (count($numbers) > 1) { $endpoint = '/send-sms-multiple'; $data = [ 'sendSmsMultiRequest' => ['sendSmsRequestList' => []], ]; foreach ($numbers as $key => $item) { array_push($data['sendSmsMultiRequest']['sendSmsRequestList'], $this->generateMessageBody($from, $item, $composeMessage)); } } else { $endpoint = '/send-sms'; $data = [ 'sendSmsRequest' => $this->generateMessageBody($from, $numbers[0], $composeMessage), ]; } $this->buildCall($endpoint); $this->buildBody($data); $this->postRequest(); }
Sends a SMS message. @param \SimpleSoftwareIO\SMS\OutgoingMessage $message
entailment
protected function processReceive($rawMessage) { $rawMessage = $rawMessage->getSmsStatusResp; $incomingMessage = $this->createIncomingMessage(); $incomingMessage->setRaw($rawMessage); $incomingMessage->setFrom($rawMessage->shortcode); $incomingMessage->setMessage(null); $incomingMessage->setId($rawMessage->id); $incomingMessage->setTo(null); return $incomingMessage; }
Parse a response from messageId check and returns a Message. @param $rawMessage @return \SimpleSoftwareIO\SMS\IncomingMessage
entailment
public function checkMessages(array $options = []) { $this->buildCall('/received/list'); $this->buildBody($options); $jsonResponse = json_decode($this->postRequest()->getBody()->getContents()); if (!isset($jsonResponse->receivedResponse)) { throw new \Exception('Invalid response from API. Missing mandatory object.'); } $rawMessages = $jsonResponse->receivedResponse; if ($rawMessages->statusCode !== '00') { throw new \Exception( 'Unable to request from API. Status Code: '.$rawMessages->statusCode .' - '.$rawMessages->detailDescription.' ('.$rawMessages->detailCode.')' ); } if ($rawMessages->detailCode === '300') { return $this->makeMessages($rawMessages->receivedMessages); } return []; }
Checks the server for messages and returns their results. @param array $options @throws \Exception @return array
entailment
public function getMessage($messageId) { $this->buildCall('/get-sms-status/'.$messageId); return $this->makeMessage(json_decode($this->getRequest()->getBody()->getContents())); }
Gets a single message by it's ID. @param int|string $messageId @return \SimpleSoftwareIO\SMS\IncomingMessage
entailment
protected function postRequest() { $response = $this->client->post($this->buildUrl(), [ 'auth' => $this->getAuth(), 'json' => $this->getBody(), 'headers' => [ 'Accept' => 'application/json', ], ]); if ($response->getStatusCode() != 201 && $response->getStatusCode() != 200) { throw new \Exception('Unable to request from API. HTTP Error: '.$response->getStatusCode()); } return $response; }
Creates and sends a POST request to the requested URL. @throws \Exception @return mixed
entailment
protected function getRequest() { $url = $this->buildUrl($this->getBody()); $response = $this->client->get($url, [ 'auth' => $this->getAuth(), 'headers' => [ 'Accept' => 'application/json', ], ]); if ($response->getStatusCode() != 201 && $response->getStatusCode() != 200) { throw new \Exception('Unable to request from API.'); } return $response; }
Creates and sends a GET request to the requested URL. @throws \Exception @return mixed
entailment
private function generateMessageBody($from, $number, $composeMessage) { $aux = [ 'from' => $from, 'to' => $number['number'], 'msg' => $composeMessage, 'callbackOption' => $this->callbackOption, ]; if (!is_null($number['carrier'])) { $aux['id'] = $number['carrier']; } return $aux; }
Message body generator based on the attributes. @param $from @param $number @param $composeMessage @return array
entailment
public function parseRequestedURL() { // This is the re-constructions of teh proper URL. // 1. Schema $url = $this->app->getConfig('atk/base_url', null); if (is_null($url)) { // Detect it $url = 'http'; $https = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || $_SERVER['SERVER_PORT'] == 443; if ($https) { $url .= 's'; } // 2. Continue building. We are adding hostname next and port. $url .= '://'.$_SERVER['SERVER_NAME']; //if($_SERVER["SERVER_PORT"]!="80")$url .= ":".$_SERVER['SERVER_PORT']; if (($_SERVER['SERVER_PORT'] == '80' && !$https) || ($_SERVER['SERVER_PORT'] == '443' && $https)) { ; } else { $url .= ':'.$_SERVER['SERVER_PORT']; } } // We have now arrived at base_url as defined $this->base_url = $url; // 3. Next we need a base_part of our URL. There are many different // variables and approaches we tried it, REDIRECT_URL_ROOT, REDIRECT_URL, // etc, however most reliable is $this->unix_dirname(SCRIPT_NAME) $path = $this->unix_dirname($_SERVER['SCRIPT_NAME']); if (substr($path, -1) != '/') { $path .= '/'; } // We have now arrived at base_path as defined $this->base_path = $path; // 4. We now look at RequestURI and extract base_path from the beginning if (isset($_GET['page'])) { $page = $_GET['page']; $this->page = $page; } else { $request_uri = $this->getRequestURI(); if (strpos($request_uri, $path) !== 0) { throw $this->exception('URL matching problem') ->addMoreInfo('RequestURI', $request_uri) ->addMoreInfo('BasePath', $path); } $page = substr($request_uri, strlen($path)); if (!$page) { $page = 'index'; } // Preserve actual page $this->page = $page; // Remove postfix from page if any $page = preg_replace('/\..*$/', '', $page); $page = preg_replace('/\/$/', '', $page); $page = str_replace('/', '_', $page); if (substr($page, -1) == '_') { $page = substr($page, 0, -1); } } if (strpos($page, '.') !== false) { throw $this->exception('Page may not contain periods (.)') ->addMoreInfo('page', $page); } // We have now arrived at the page as per specification. $this->app->page = str_replace('/', '_', $page); $this->template_filename = $this->app->page; if (substr($this->template_filename, -1) == '/') { $this->template_filename .= 'index'; } }
Detect server environment and tries to guess absolute and relative URLs to your application. See docs: doc/application/routing/parsing
entailment
public function init() { parent::init(); // first let's see if we authenticate if ($this->authenticate === true || ( $this->authenticate !== false && ($this->hasMethod('authenticate') || $this->app->hasMethod('authenticate')) ) ) { $result = false; if ($this->hasMethod('authenticate')) { $result = $this->authenticate(); } if (!$result && $this->app->hasMethod('authenticate')) { $result = $this->app->authenticate(); } if (!$result) { throw $this->exception('Authentication Failed', null, 403); } if (is_object($result)) { $this->user = $result; } } $m = $this->_model(); if ($m) { $this->setModel($m); } }
init.
entailment
protected function _model() { // Based od authentication data, return a valid model if (!$this->model_class) { return false; } /** @type Model $m */ //$m=$this->app->add('Model_'.$this->model_class); $m = $this->setModel($this->model_class); if ($this->user_id_field && $m->hasField($this->user_id_field) && $this->authenticate !== false && $this->user ) { // if not authenticated, blow up $m->addCondition($this->user_id_field, $this->user->id); } $id = $_GET['id']; if (!is_null($id)) { if ($this->id_field) { $m->loadBy($this->id_field, $id); } else { $m->load($id); } } return $m; }
Method returns new instance of the model we will operate on. Instead of using this method, you can use $this->model instead. @return Model
entailment
protected function outputOne($data) { if (is_object($data)) { $data = $data->get(); } if ($data['_id']) { $data = array('id' => (string) $data['_id']) + $data; } unset($data['_id']); foreach ($data as $key => $val) { if ($val instanceof MongoID) { $data[$key] = (string) $val; } } return $data; }
Generic method for returning single record item of data, which can be used for filtering or cleaning up. @param object|array $data @return array
entailment
protected function outputMany($data) { if (is_object($data)) { $data = $data->getRows(); } $output = array(); foreach ($data as $row) { $output[] = $this->outputOne($row); } return $output; }
Generic outptu filtering method for multiple records of data. @param object|array $data @return array
entailment
protected function _input($data, $filter = true) { // validates input if (is_array($filter)) { $data = array_intersect_key($data, array_flip($filter)); } unset($data['id']); unset($data['_id']); unset($data['user_id']); unset($data['user']); return $data; }
Filtering input data. @param array $data @param bool $filter @return array
entailment
public function get() { $m = $this->model; if (!$m) { throw $this->exception('Specify model_class or define your method handlers'); } if ($m->loaded()) { if (!$this->allow_list_one) { throw $this->exception('Loading is not allowed'); } return $this->outputOne($m->get()); } if (!$this->allow_list) { throw $this->app->exception('Listing is not allowed'); } return $this->outputMany($m->setLimit(100)->getRows()); }
[get description]. @return array
entailment
public function put_post($data) { $m = $this->model; if ($m->loaded()) { if (!$this->allow_edit) { throw $this->exception('Editing is not allowed'); } $data = $this->_input($data, $this->allow_edit); } else { if (!$this->allow_add) { throw $this->exception('Adding is not allowed'); } $data = $this->_input($data, $this->allow_add); } return $this->outputOne($m->set($data)->save()->get()); }
Because it's not really defined which of the two is used for updating the resource, Agile Toolkit will support put_post identically. Both of the requests are idempotent. As you extend this class and redefine methods, you should properly use POST or PUT. See http://stackoverflow.com/a/2691891/204819 @param array $data @return array
entailment
public function delete() { if (!$this->allow_delete) { throw $this->exception('Deleting is not allowed'); } $m = $this->model; if (!$m->loaded()) { throw $this->exception('Cowardly refusing to delete all records'); } $m->delete(); return true; }
[delete description]. @return bool
entailment
public function render($view = null, $layout = null) { $content = parent::render($view, $layout); if ($this->response->type() == 'text/html') { return $content; } $this->Blocks->set('content', $this->output()); $this->response->download($this->getFilename()); return $this->Blocks->get('content'); }
Render method @param string $view The view being rendered. @param string $layout The layout being rendered. @return string The rendered view.
entailment
protected function output() { ob_start(); $writer = PHPExcel_IOFactory::createWriter($this->PhpExcel, 'Excel2007'); if (!isset($writer)) { throw new Exception('Excel writer not found'); } $writer->setPreCalculateFormulas(false); $writer->setIncludeCharts(true); $writer->save('php://output'); $output = ob_get_clean(); return $output; }
Generates the binary excel data @return string @throws CakeException If the excel writer does not exist
entailment
public function getFilename() { if (isset($this->viewVars['_filename'])) { return $this->viewVars['_filename'] . '.xlsx'; } return Inflector::slug(str_replace('.xlsx', '', $this->request->url)) . '.xlsx'; }
Gets the filename @return string filename
entailment
protected function makeMessages($rawMessages) { $incomingMessages = []; foreach ($rawMessages as $rawMessage) { $incomingMessages[] = $this->processReceive($rawMessage); } return $incomingMessages; }
Creates many IncomingMessage objects. @param string $rawMessages @return array
entailment
public function addColumn($width = 'auto') { /** @type View $c */ $c = $this->add('View'); if (is_numeric($width)) { $this->mode = 'grid'; $c->addClass('atk-col-'.$width); return $c; } elseif (substr($width, -1) == '%') { $this->mode = 'pct'; $c->addStyle('width', $width); } $this->template->trySet('row_class', 'atk-cells'); $c->addClass('atk-cell'); return $c; }
Adds new column to the set. Argument can be numeric for 12GS, percent for flexi design or omitted for equal columns. @param int|string $width @return View
entailment
public function init() { parent::init(); $this->app->router = $this; $this->app->addHook('buildURL', array($this, 'buildURL')); }
}}}
entailment
public function link($page, $args = array()) { if ($this->links[$page]) { throw $this->exception('This page is already linked') ->addMoreInfo('page', $page); } $this->links[$page] = $args; return $this; }
Link method creates a bi-directional link between a URL and a page along with some GET parameters. This method is entirely tranpsarent and can be added for pages which are already developed at any time. Example: $this->link('profile',array('user_id'));
entailment
public function addRule($regex, $target = null, $params = null) { $this->rules[] = array($regex, $target, $params); return $this; }
Add new rule to the pattern router. If $regexp is matched, then page is changed to $target and arguments returned by preg_match are stored inside GET as per supplied params array.
entailment
public function setModel($model) { /** @type Model $model */ $model = parent::setModel($model); foreach ($model as $rule) { $this->addRule($rule['rule'], $rule['target'], explode(',', $rule['params'])); } // @todo Consider to return $model instead of $this like we do in setModel method of all other classes return $this; }
Allows use of models. Define a model with fields: - rule - target - params (comma separated). and content of that model will be used to auto-fill routing
entailment
public function route() { $this->app->page_orig = $this->app->page; foreach ($this->links as $page => $args) { $page = str_replace('/', '_', $page); // Exact match, no more routing needed if ($this->app->page == $page) { return $this; } $page .= '_'; if (substr($this->app->page, 0, strlen($page)) == $page) { $rest = explode('_', substr($this->app->page, strlen($page))); reset($args); foreach ($rest as $arg) { list($key, $match) = @each($args); if (is_numeric($key) || is_null($key)) { $key = $match; } else { if (!preg_match($match, $arg)) { break 2; } } $_GET[$key] = $arg; } $this->app->page = substr($page, 0, -1); return $this; } //$misc=explode()$this->app->page = substr } $r = $_SERVER['REQUEST_URI']; foreach ($this->rules as $rule) { if (preg_match('/'.$rule[0].'/', $r, $t)) { $this->app->page = $rule[1]; if ($rule[2]) { foreach ($rule[2] as $k => $v) { $_GET[$v] = $t[$k + 1]; } } } } }
Perform the necessary changes in the APP's page. After this you can still get the orginal page in app->page_orig.
entailment
public function init() { parent::init(); if (@$this->app->jui) { throw $this->exception('Do not add jUI twice'); } $this->app->jui = $this; $this->addDefaultIncludes(); $this->atk4_initialised = true; }
Initialization
entailment
public function addDefaultIncludes() { $this->addInclude('start-atk4'); /* $config['js']['jqueryui']='https://code.jquery.com/ui/1.11.4/jquery-ui.min.js'; // to use CDN */ if ($v = $this->app->getConfig('js/versions/jqueryui', null)) { $v = 'jquery-ui-'.$v; } else { $v = $this->app->getConfig('js/jqueryui', 'jquery-ui-1.11.4.min'); // bundled jQueryUI version } $this->addInclude($v); $this->addInclude('ui.atk4_loader'); $this->addInclude('ui.atk4_notify'); $this->addInclude('atk4_univ_basic'); $this->addInclude('atk4_univ_jui'); }
Adds default includes
entailment
public function addInclude($file, $ext = '.js') { if (strpos($file, 'http') === 0) { parent::addOnReady('$.atk4.includeJS("'.$file.'")'); return $this; } $url = $this->app->locateURL('js', $file.$ext); if (!$this->atk4_initialised) { return parent::addInclude($file, $ext); } parent::addOnReady('$.atk4.includeJS("'.$url.'")'); return $this; }
Adds includes @param string $file @param string $ext @return $this
entailment
public function addStylesheet($file, $ext = '.css', $template = false) { if (strpos($file, 'http') === 0) { parent::addOnReady('$.atk4.includeCSS("'.$file.'")'); return $this; } $url = $this->app->locateURL('css', $file.$ext); if (!$this->atk4_initialised || $template) { return parent::addStylesheet($file, $ext); } parent::addOnReady('$.atk4.includeCSS("'.$url.'")'); }
Adds stylesheet @param string $file @param string $ext @param bool $template @return $this
entailment
public function addOnReady($js) { if ($js instanceof jQuery_Chain) { $js = $js->getString(); } if (!$this->atk4_initialised) { return parent::addOnReady($js); } $this->app->template->appendHTML('document_ready', "$.atk4(function(){ ".$js."; });\n"); return $this; }
Adds JS chain to DOM onReady event @param jQuery_Chain|string $js @return $this
entailment
public function connect() { if ($this->config->dsn === null && $this->config->db !== null) { trigger_error('Config::$db is deprecated, see Config::$dsn.', E_USER_DEPRECATED); $this->config->dsn("mysql:dbname={$this->config->db};host={$this->config->host}"); } try { $this->pdo = new \PDO( $this->config->dsn, $this->config->user, $this->config->pass ); $this->pdo->exec('SET NAMES '.$this->config->encoding); foreach ($this->config->attributes as $name => $value) { $this->pdo->setAttribute($name, $value); } $sth = $this->pdo->query('SELECT DATABASE() FROM DUAL'); $database = $sth->fetch(); $this->database = end($database); $this->version = (string) $this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION); } catch (\PDOException $e) { throw new Exception('Connecting to database failed with message: '.$e->getMessage()); } }
{@inheritdoc}
entailment
protected function lock() { $this->tables->execute(); $table = array(); while ($a = $this->tables->fetch(\PDO::FETCH_ASSOC)) { $table[] = current($a); } return !$table || $this->pdo->exec('LOCK TABLES `'.implode('` WRITE, `', $table).'` WRITE'); }
Locks all tables. @return bool
entailment
protected function open($filename, $flags) { if (is_file($filename) === false || ($this->file = fopen($filename, $flags)) === false) { throw new Exception('Unable to open the target file.'); } }
Opens a file for writing. @param string $filename The filename @param string $flags Flags @throws Exception
entailment
protected function write($string, $format = true) { if ($format) { $string .= $this->delimiter; } $string .= "\n"; if (fwrite($this->file, $string, strlen($string)) === false) { throw new Exception('Unable to write '.strlen($string).' bytes to the dumpfile.'); } }
Writes a line to the file. @param string $string The string to write @param bool $format Format the string
entailment
protected function move() { if ($this->compress) { $gzip = new Compress($this->config); $gzip->pack($this->temp, $this->config->file); unlink($this->temp); return true; } if (@rename($this->temp, $this->config->file)) { return true; } if (@copy($this->temp, $this->config->file) && unlink($this->temp)) { return true; } throw new Exception('Unable to move the temporary file.'); }
Moves a temporary file to the final location. @return bool @throws Exception
entailment
protected function getDelimiter($delimiter = ';', $query = null) { while (1) { if ($query === null || strpos($query, $delimiter) === false) { return $delimiter; } $delimiter .= $delimiter; } }
Gets a SQL delimiter. Gives out a character sequence that isn't in the given query. @param string $delimiter Delimiter character @param string|null $query The query to check @return string Unique delimiter character sequence @since 2.7.0
entailment
public function init() { parent::init(); $this->js_reload = $this->js()->reload(); // Virtual Page would receive 3 types of requests - add, delete, edit $this->virtual_page = $this->add('VirtualPage', array( 'frame_options' => $this->frame_options, )); /** @type VirtualPage $this->virtual_page */ $name_id = $this->virtual_page->name.'_id'; /* if ($_GET['edit'] && !isset($_GET[$name_id])) { $_GET[$name_id] = $_GET['edit']; } */ if (isset($_GET[$name_id])) { $this->app->stickyGET($name_id); $this->id = $_GET[$name_id]; } if ($this->isEditing()) { $this->form = $this ->virtual_page ->getPage() ->add($this->form_class, $this->form_options) //->addClass('atk-form-stacked') ; /** @type Form $this->form */ $this->grid = new Dummy(); /** @type Grid $this->grid */ return; } $this->grid = $this->add($this->grid_class, $this->grid_options); /** @type Grid $this->grid */ $this->form = new Dummy(); /** @type Form $this->form */ // Left for compatibility $this->js('reload', $this->grid->js()->reload()); if ($this->allow_add) { $this->add_button = $this->grid->addButton('Add'); } }
{@inheritdoc} CRUD's init() will create either a grid or form, depending on isEditing(). You can then do the necessary changes after Note, that the form or grid will not be populated until you call setModel()
entailment
public function isEditing($mode = null) { $page_mode = $this->virtual_page->isActive(); // Requested edit, but not allowed if ($page_mode == 'edit' && !$this->allow_edit) { throw $this->exception('Editing is not allowed'); } // Requested add but not allowed if ($page_mode == 'add' && !$this->allow_add) { throw $this->exception('Adding is not allowed'); } // Request matched argument exactly if (!is_null($mode)) { return $mode === $page_mode; } // Argument was blank, then edit/add is OK return (boolean) $page_mode; }
Returns if CRUD is in editing mode or not. It's preferable over checking if($grid->form). @param string $mode Specify which editing mode you expect @return bool true if editing.
entailment
public function setModel($model, $fields = null, $grid_fields = null) { $model = parent::setModel($model); if (!isset($this->entity_name)) { if (!isset($model->caption)) { // Calculates entity name $class = get_class($this->model); $class = substr(strrchr($class, '\\') ?: ' '.$class, 1); // strip namespace $this->entity_name = str_replace( array('Model_', '_'), array('', ' '), $class ); } else { $this->entity_name = $model->caption; } } if (!$this->isEditing()) { $this->configureGrid(is_null($grid_fields) ? $fields : $grid_fields); } if ($this->allow_add) { if ($this->configureAdd($fields)) { return $model; } } elseif (isset($this->add_button)) { $this->add_button->destroy(); } if ($this->allow_edit) { if ($this->configureEdit($fields)) { return $model; } } if ($this->allow_del) { $this->configureDel(); } return $model; }
Assign model to your CRUD and specify list of fields to use from model. {@inheritdoc} @param string|Model $model Same as parent @param array $fields Specify list of fields for form and grid @param array $grid_fields Overide list of fields for the grid @return AbstractModel $model
entailment
public function addRef($name, $options = array()) { if (!$this->model) { throw $this->exception('Must set CRUD model first'); } if (!is_array($options)) { throw $this->exception('Must be array'); } // if(!$this->grid || $this->grid instanceof Dummy)return; $s = $this->app->normalizeName($name); if ($this->isEditing('ex_'.$s)) { $n = $this->virtual_page->name.'_'.$s; if ($_GET[$n]) { $this->id = $_GET[$n]; $this->app->stickyGET($n); } $idfield = $this->model->table.'_'.$this->model->id_field; if ($_GET[$idfield]) { $this->id = $_GET[$idfield]; $this->app->stickyGET($idfield); } $view_class = (is_null($options['view_class'])) ? get_class($this) : $options['view_class']; $subview = $this->virtual_page->getPage()->add( $view_class, $options['view_options'] ); $this->model->load($this->id); $subview->setModel( $options['view_model'] ? (is_callable($options['view_model']) ? call_user_func($options['view_model'], $this->model) : $options['view_model'] ) : $this->model->ref($name), $options['fields'], $options['grid_fields'] ?: $options['extra_fields'] ); return $subview; } elseif ($this->grid instanceof Grid) { $this->grid->addColumn('expander', 'ex_'.$s, $options['label'] ?: $s); $this->grid->columns['ex_'.$s]['page'] = $this->virtual_page->getURL('ex_'.$s); // unused: $idfield = $this->grid->columns['ex_'.$s]['refid'].'_'.$this->model->id_field; } if ($this->isEditing()) { return; } }
Assuming that your model has a $relation defined, this method will add a button into a separate column. When clicking, it will expand the grid and will present either another CRUD with related model contents (one to many) or a form preloaded with related model data (many to one). Adds expander to the crud, which edits references under the specified name. Returns object of nested CRUD when active, or null The format of $options is the following: array ( 'view_class' => 'CRUD', // Which View to use inside expander 'view_options' => .. // Second arg when adding view. 'view_model' => model or callback // Use custom model for sub-View, by default ref($name) will be used 'fields' => array() // Used as second argument for setModel() 'extra_fields' => array() // Third arguments to setModel() used by CRUDs 'label'=> 'Click Me' // Label for a button inside a grid ) @param string $name Name of the reference. If you leave blank adds all @param array $options Customizations, see above @return View_CRUD|null Returns crud object, when expanded page is rendered
entailment
public function addFrame($name, $options = array()) { if (!$this->model) { throw $this->exception('Must set CRUD model first'); } if (!is_array($options)) { throw $this->exception('Must be array'); } $s = $this->app->normalizeName($name); if ($this->isEditing('fr_'.$s)) { $n = $this->virtual_page->name.'_'.$s; if ($_GET[$n]) { $this->id = $_GET[$n]; $this->app->stickyGET($n); } return $this->virtual_page->getPage(); } if ($this->isEditing()) { return false; } $this ->virtual_page ->addColumn( 'fr_'.$s, $options['title'] ?: $name, array( 'descr' => $options['label'] ?: null, 'icon' => $options['icon'] ?: null, ), $this->grid ); }
Adds button to the crud, which opens a new frame and returns page to you. Add anything into the page as you see fit. The ID of the record will be inside $crud->id. The format of $options is the following: array ( 'title'=> 'Click Me' // Header for the column 'label'=> 'Click Me' // Text to put on the button 'icon' => 'click-me' // Icon for button ) @param string $name Unique name, also button and title default @param array $options Options @return Page|bool Returns object if clicked on popup.
entailment
public function addAction($method_name, $options = array()) { if (!$this->model) { throw $this->exception('Must set CRUD model first'); } if ($options == 'toolbar') { $options = array('column' => false, 'toolbar' => true); } if ($options == 'column') { $options = array('toolbar' => false, 'column' => true); } $descr = isset($options['descr']) ? $options['descr'] : ucwords(str_replace('_', ' ', $method_name)); $icon = isset($options['icon']) ? $options['icon'] : 'target'; $show_toolbar = isset($options['toolbar']) ? $options['toolbar'] : true; $show_column = isset($options['column']) ? $options['column'] : true; if ($this->isEditing($method_name)) { /** @type View_Console $c */ $c = $this->virtual_page->getPage()->add('View_Console'); $self = $this; // Callback for the function $c->set(function ($c) use ($show_toolbar, $show_column, $options, $self, $method_name) { if ($show_toolbar && !$self->id) { $self->model->unload(); } elseif ($show_column && $self->id) { $c->out('Loading record '.$self->id, array('class' => 'atk-effect-info')); $self->model->load($self->id); } else { return; } $ret = $self->model->$method_name(); $c->out('Returned: '.json_encode($ret, JSON_UNESCAPED_UNICODE), array('class' => 'atk-effect-success')); /* if (isset($options['args'])) { $params = $options['args']; } elseif (!method_exists($self->model, $method_name)) { // probably a dynamic method $params = array(); } else { $reflection = new ReflectionMethod($self->model, $method_name); $params = $reflection->getParameters(); } */ }); return; /* unused code below $has_parameters = (bool) $params; foreach ($params as $i => $param) { $this->form->addField($param->name); $this->has_parameters = true; } if (!$has_parameters) { $this->form->destroy(); $ret = $this->model->$method_name(); if (is_object($ret) && $ret == $this->model) { $this->virtual_page->getPage()->add('P')->set('Executed successfully'); $this->virtual_page->getPage()->js(true, $this->js_reload); } else { $this->virtual_page->getPage()->js(true, $this->js_reload); if (is_object($ret)) { $ret = (string) $ret; } $this->virtual_page->getPage() ->add('P')->set('Returned: '.json_encode($ret, JSON_UNESCAPED_UNICODE)); } $this->virtual_page->getPage() ->add('Button')->set(array('Close', 'icon' => 'cross', 'swatch' => 'green')) ->js('click')->univ()->closeDialog(); return true; } $this->form->addSubmit('Execute'); if ($this->form->isSubmitted()) { $ret = call_user_func_array(array($this->model, $method_name), array_values($this->form->get())); if (is_object($ret)) { $ret = (string) $ret; } $this->js(null, $this->js()->reload())->univ() ->successMessage('Returned: '.json_encode($ret, JSON_UNESCAPED_UNICODE)) ->closeDialog() ->execute(); } return true; */ } elseif ($this->isEditing()) { return; } $frame_options = array_merge(array(), $this->frame_options ?: array()); if ($show_column) { $this ->virtual_page ->addColumn( $method_name, $descr.' '.$this->entity_name, array('descr' => $descr, 'icon' => $icon), $this->grid ); } if ($show_toolbar) { $button = $this->addButton(array($descr, 'icon' => $icon)); // Configure Add Button on Grid and JS $button->js('click')->univ() ->frameURL( $this->app->_($this->entity_name.'::'.$descr), $this->virtual_page->getURL($method_name), $frame_options ); } }
Assuming that your model contains a certain method, this allows you to create a frame which will pop you a new frame with a form representing model method arguments. Once the form is submitted, the action will be evaluated. @param string $method_name @param array $options
entailment
protected function configureAdd($fields = null) { // We are actually in the frame! if ($this->isEditing('add')) { $this->model->unload(); $m = $this->form->setModel($this->model, $fields); $this->form->addSubmit('Add'); $this->form->onSubmit(array($this, 'formSubmit')); return $m; } elseif ($this->isEditing()) { return; } // Configure Add Button on Grid and JS $this->add_button->js('click')->univ() ->frameURL( $this->app->_( $this->entity_name === false ? 'New Record' : 'Adding new '.$this->entity_name ), $this->virtual_page->getURL('add'), $this->frame_options ); if ($this->entity_name !== false) { $this->add_button->setIcon('plus')->setHTML('Add '.htmlspecialchars($this->entity_name)); } }
Configures necessary components when CRUD is in the adding mode. @param array $fields List of fields for add form @return void|Model If model, then bail out, no greed needed
entailment
protected function configureEdit($fields = null) { // We are actually in the frame! if ($this->isEditing('edit')) { $m = $this->form->setModel($this->model, $fields); $m->load($this->id); $this->form->addSubmit(); $this->form->onSubmit(array($this, 'formSubmit')); return $m; } elseif ($this->isEditing()) { return; } $this ->virtual_page ->addColumn( 'edit', 'Editing '.$this->entity_name, array('descr' => 'Edit', 'icon' => 'pencil'), $this->grid ); }
Configures necessary components when CRUD is in the editing mode. @param array $fields List of fields for add form @return void|Model If model, then bail out, no greed needed
entailment
protected function formSubmit($form) { try { $form->save(); $self = $this; $this->app->addHook('pre-render', function () use ($self) { $self->formSubmitSuccess()->execute(); }); } catch (Exception_ValidityCheck $e) { $form->displayError($e->getField(), $e->getMessage()); } }
Called after on post-init hook when form is submitted. @param Form $form Form which was submitted
entailment
public function formSubmitSuccess() { return $this->form->js(null, $this->js()->trigger('reload')) ->univ()->closeDialog(); }
Returns JavaScript action which should be executed on form successfull submission. @return jQuery_Chain to be executed on successful submit
entailment
public function setSource($model, $table = null) { if (!$table) { $table = $model->table; } if (@!$this->app->mongoclient) { $m = new MongoClient($this->app->getConfig('mongo/url', null)); $db = $this->app->getConfig('mongo/db'); $this->app->mongoclient = $m->$db; } parent::setSource($model, array( 'db' => $this->app->mongoclient->$table, 'conditions' => array(), 'collection' => $table, )); $model->addMethod('incr,decr', $this); //$model->data=$model->_table[$this->short_name]['db']->get($id); }
'='=>true,'>'=>true,'>='=>true,'<='=>true,'<'=>true,'!='=>true,'like'=>true);
entailment
public function init() { parent::init(); $this->tab_template = $this->template->cloneRegion('tabs'); $this->template->del('tabs'); }
Initialization
entailment
public function addTab($title, $name = null) { $container = $this->add('View_HtmlElement', $name); $this->tab_template->set(array( 'url' => '#'.$container->name, 'tab_name' => $title, 'tab_id' => $container->short_name, )); $this->template->appendHTML('tabs', $this->tab_template->render()); return $container; }
/* Add tab and returns it so that you can add static content
entailment
public function addTabURL($page, $title = null) { if (is_null($title)) { $title = ucwords(preg_replace('/[_\/\.]+/', ' ', $page)); } $this->tab_template->set(array( 'url' => $this->app->url($page, array('cut_page' => 1)), 'tab_name' => $title, 'tab_id' => basename($page), )); $this->template->appendHTML('tabs', $this->tab_template->render()); return $this; }
/* Add tab which loads dynamically. Returns $this for chaining
entailment
public function addGlobalMethod($name, $callable) { if ($this->hasMethod($name)) { throw $this->exception('Registering method twice') ->addMoreInfo('name', $name); } $this->addHook('global-method-'.$name, $callable); }
Agile Toolkit objects allow method injection. This is quite similar to technique used in JavaScript:. obj.test = function() { .. } All non-existant method calls on all Agile Toolkit objects will be tried against local table of registered methods and then against global registered methods. addGlobalmethod allows you to register a globally-recognized for all agile toolkit object. PHP is not particularly fast about executing methods like that, but this technique can be used for adding backward-compatibility or debugging, etc. @see AbstractObject::hasMethod() @see AbstractObject::__call() @param string $name Name of the method @param callable $callable Calls your function($object, $arg1, $arg2)
entailment
public function addLocation($contents, $obsolete = UNDEFINED) { if ($obsolete !== UNDEFINED) { throw $this->exception('Use a single argument for addLocation'); } return $this->pathfinder->addLocation($contents); }
Add new location with additional resources. @param array $contents @param mixed $obsolete @return PathFinder_Location
entailment
public function url($page = null, $arguments = array()) { if (is_object($page) && $page instanceof URL) { // we receive URL return $page->setArguments($arguments); } if (is_array($page)) { $p = $page[0]; unset($page[0]); $arguments = $page; $page = $p; } /** @type URL $url */ $url = $this->add('URL'); unset($this->elements[$url->short_name]); // garbage collect URLs if (strpos($page, 'http://') === 0 || strpos($page, 'https://') === 0) { $url->setURL($page); } else { $url->setPage($page); } return $url->setArguments($arguments); }
Generates URL for specified page. Useful for building links on pages or emails. Returns URL object. @param mixed $page @param array $arguments @return URL
entailment
public function getLogger($class_name = UNDEFINED) { if (is_null($this->logger)) { $this->logger = $this->add($class_name === UNDEFINED ? $this->logger_class : $class_name); } return $this->logger; }
Initialize logger or return existing one. @param string $class_name @return Logger
entailment
public function caughtException($e) { $this->hook('caught-exception', array($e)); echo get_class($e), ': '.$e->getMessage(); exit; }
Is executed if exception is raised during execution. Re-define to have custom handling of exceptions system-wide. @param Exception $e
entailment
public function readAllConfig() { // If configuration files are not there - will silently ignore foreach ($this->config_files as $file) { $this->readConfig($file); } $tz = $this->getConfig('timezone', null); if (!is_null($tz) && function_exists('date_default_timezone_set')) { // with seting default timezone date_default_timezone_set($tz); } else { if (!ini_get('date.timezone')) { ini_set('date.timezone', 'UTC'); } } }
Will include all files as they are defined in $this->config_files from folder $config_location.
entailment
public function readConfig($file = 'config.php') { $orig_file = $file; if (strpos($file, '.php') != strlen($file) - 4) { $file .= '.php'; } if (strpos($file, '/') === false) { $file = getcwd().'/'.$this->config_location.'/'.$file; } if (file_exists($file)) { // some tricky thing to make config be read in some cases it could not in simple way unset($config); $config = &$this->config; $this->config_files_loaded[] = $file; include $file; unset($config); return true; } return false; }
Read config file and store it in $this->config. Use getConfig() to access. @param string $file Filename @return bool
entailment
public function setConfig($config = array(), $val = UNDEFINED) { if ($val !== UNDEFINED) { return $this->setConfig(array($config => $val)); } $this->config = array_merge($this->config ?: array(), $config ?: array()); }
Manually set configuration option. @param array $config @param mixed $val
entailment
public function getConfig($path, $default_value = UNDEFINED) { /* * For given path such as 'dsn' or 'logger/log_dir' returns * corresponding config value. Throws ExceptionNotConfigured if not set. * * To find out if config is set, do this: * * $var_is_set = true; * try { $app->getConfig($path); } catch ExceptionNotConfigured($e) { $var_is_set=false; } */ $parts = explode('/', $path); $current_position = $this->config; foreach ($parts as $part) { if (!array_key_exists($part, $current_position)) { if ($default_value !== UNDEFINED) { return $default_value; } throw $this->exception('Configuration parameter is missing in config.php', 'NotConfigured') ->addMoreInfo('config_files_loaded', $this->config_files_loaded) ->addMoreInfo('missign_line', " \$config['".implode("']['", explode('/', $path))."']"); } else { $current_position = $current_position[$part]; } } return $current_position; }
Load config if necessary and look up corresponding setting. @param string $path @param mixed $default_value @return string
entailment
public function getVersion($of = 'atk') { // TODO: get version of add-on if (!$this->version_cache) { $f = $this->app->pathfinder->atk_location->base_path.DIRECTORY_SEPARATOR.'VERSION'; if (file_exists($f)) { $this->version_cache = trim(file_get_contents($f)); } else { $this->version_cache = '4.0.1'; } } return $this->version_cache; }
Determine version of Agile Toolkit or specified plug-in. @param string $of @return string
entailment
public function requires($addon = 'atk', $v, $location = null) { $cv = $this->getVersion($addon); if (version_compare($cv, $v) < 0) { if ($addon == 'atk') { $e = $this->exception('Agile Toolkit version is too old'); } else { $e = $this->exception('Add-on is outdated') ->addMoreInfo('addon', $addon); } $e->addMoreInfo('required', $v) ->addMoreInfo('you have', $cv); if ($location !== null) { $e->addMoreInfo('download_location', $location); } throw $e; } // Possibly we need to enable compatibility version if ($addon == 'atk') { if (version_compare($v, '4.2') < 0 && version_compare($v, '4.1.4') >= 0) { $this->add('Controller_Compat'); return true; } } return true; }
Verifies version. Should be used by addons. For speed improvement, redefine this into empty function. @param string $addon @param string $v @param string $location @return bool
entailment
public function dbConnect($dsn = null) { $this->db = $this->add('DB'); /** @type DB $this->db */ return $this->db->connect($dsn); }
Use database configuration settings from config file to establish default connection. @param mixed $dsn @return DB
entailment
public function normalizeName($name, $separator = '_') { if (strlen($separator) == 0) { return preg_replace('|[^a-z0-9]|i', '', $name); } $s = $separator[0]; $name = preg_replace('|[^a-z0-9\\'.$s.']|i', $s, $name); $name = trim($name, $s); $name = preg_replace('|\\'.$s.'{2,}|', $s, $name); return $name; }
Normalize field or identifier name. Can also be used in URL normalization. This will replace all non alpha-numeric characters with separator. Multiple separators in a row is replaced with one. Separators in beginning and at the end of name are removed. Sample input: "Hello, Dear Jon!" Sample output: "Hello_Dear_Jon" @param string $name String to process @param string $separator Character acting as separator @return string Normalized string
entailment
public function normalizeClassName($name, $prefix = null) { if (!is_string($name)) { return $name; } $name = str_replace('/', '\\', $name); if ($prefix !== null) { $class = ltrim(strrchr($name, '\\'), '\\') ?: $name; $prefix = ucfirst($prefix); if (strpos($class, $prefix) !== 0) { $name = preg_replace('|^(.*\\\)?(.*)$|', '\1'.$prefix.'_\2', $name); } } return $name; }
First normalize class name, then add specified prefix to class name if it's passed and not already added. Class name can have namespaces and they are treated prefectly. If object is passed as $name parameter, then same object is returned. Example: normalizeClassName('User','Model') == 'Model_User'; @param string|object $name Name of class or object @param string $prefix Optional prefix for class name @return string|object Full, normalized class name or received object
entailment
public function encodeHtmlChars($s, $flags = null, $encode = null, $double_encode = false) { if ($flags === null) { $flags = ENT_COMPAT; } if ($encode === null) { $encode = ini_get('default_charset') ?: 'UTF-8'; } return htmlspecialchars($s, $flags, $encode, $double_encode); }
Encodes HTML special chars. By default does not encode already encoded ones. @param string $s @param int $flags @param string $encode @param bool $double_encode @return string
entailment
public function migrate() { // find migrations $folders = $this->app->pathfinder->search('dbupdates', '', 'path'); // todo - sort files in folders foreach ($folders as $dir) { $files = scandir($dir); sort($files); foreach ($files as $name) { if (strtolower(substr($name, -4)) != '.sql') { continue; } $q = $this->db->dsql() ->table('_db_update') ->where('name', strtolower($name)) ->field('status'); if ($q->getOne() === 'ok') { continue; } $migration = file_get_contents($dir.'/'.$name); $q->set('name', strtolower($name)); try { $this->db->dbh->exec($migration); $q->set('status', 'ok')->replace(); } catch (Exception $e) { $q->set('status', 'fail')->replace(); if (!$e instanceof BaseException) { $e = $this->exception() ->addMoreInfo('Original error', $e->getMessage()); } throw $e->addMoreInfo('file', $name); } } } return $this; }
Find migrations and execute them in order. .. warning:: Use ";" semicolon between full statements. If you leave empty statement between two semilocons MySQL ->exec() seems to fail.
entailment
public function getStatusModel() { /** @type SQL_Model $m */ $m = $this->add('SQL_Model', ['table' => '_db_update']); $m->addField('name'); $m->addField('status')->enum(['ok', 'fail']); $m->setSource('SQL'); return $m; }
Produces and returns a generic model you can supply to your Grid if you want show migration status.
entailment
public function routePages($prefix, $ns = null) { $this->namespace_routes[$prefix] = $this->normalizeClassName($ns ?: $prefix); }
Pages with a specified prefix will loaded from a specified namespace. @param string $prefix @param string $ns
entailment
protected function loadStaticPage($page) { $layout = $this->layout ?: $this; try { $t = 'page/'.str_replace('_', '/', strtolower($page)); $this->template->findTemplate($t); $this->page_object = $layout->add($this->page_class, $page, 'Content', array($t)); } catch (Exception_PathFinder $e2) { $t = 'page/'.strtolower($page); $this->template->findTemplate($t); $this->page_object = $layout->add($this->page_class, $page, 'Content', array($t)); } return $this->page_object; }
Attempts to load static page. Raises exception if not found. @param string $page @return Page
entailment
public function caughtException($e) { if ($e instanceof Exception_Migration) { try { // The mesage is for user. Let's display it nicely. $this->app->pathfinder->addLocation(array('public' => '.')) ->setCDN('http://www.agiletoolkit.org/'); /** @type Layout_Basic $l */ $l = $this->app->add('Layout_Basic', null, null, array('layout/installer')); /** @type View $i */ $i = $l->add('View'); $i->addClass('atk-align-center'); /** @type H1 $h */ $h = $i->add('H1'); $h->set($e->getMessage()); if ($e instanceof Exception_Migration) { /** @type P $p */ $p = $i->add('P'); $p->set('Hello and welcome to Agile Toolkit 4.3. '. 'Your project may require some minor tweaks before you can use 4.3.'); } /** @type Button $b */ $b = $i->add('Button'); $b->addClass('atk-swatch-green') ->set(array('Migration Guide', 'icon' => 'book')) ->link('https://github.com/atk4/docs/blob/master/articles/migration42/index.md'); if ($this->app->template && $this->app->template->hasTag('Layout')) { $t = $this->app->template; } else { /** @type GiTemplate $t */ $t = $this->add('GiTemplate'); $t->loadTemplate('html'); } $t->setHTML('Layout', $l->getHTML()); $t->trySet('css', 'http://css.agiletoolkit.org/framework/css/installer.css'); echo $t->render(); exit; } catch (BaseException $e) { echo 'here'; $this->app->add('Logger'); return parent::caughtException($e); } } return parent::caughtException($e); }
@todo Description @param Exception $e
entailment
public function send(OutgoingMessage $message) { $from = $message->getFrom(); $composeMessage = $message->composeMessage(); //Convert to callfire format. $numbers = implode(',', $message->getTo()); $data = [ 'from' => $from, 'to' => $numbers, 'text' => $composeMessage, 'api_key' => $this->apiKey, 'api_secret' => $this->apiSecret, ]; $this->buildCall('/sms/json'); $this->buildBody($data); $response = $this->postRequest(); $body = json_decode($response->getBody(), true); if ($this->hasError($body)) { $this->handleError($body); } return $response; }
Sends a SMS message. @param \SimpleSoftwareIO\SMS\OutgoingMessage $message
entailment
protected function hasError($body) { if ($this->hasAResponseMessage($body) && $this->hasProperty($this->getFirstMessage($body), 'status')) { $firstMessage = $this->getFirstMessage($body); return (int) $firstMessage['status'] !== 0; } return false; }
Checks if the transaction has an error. @param $body @return bool
entailment
protected function handleError($body) { $firstMessage = $this->getFirstMessage($body); $error = 'An error occurred. Nexmo status code: '.$firstMessage['status']; if ($this->hasProperty($firstMessage, 'error-text')) { $error = $firstMessage['error-text']; } $this->throwNotSentException($error, $firstMessage['status']); }
Log the error message which ocurred. @param $body
entailment
public function checkMessages(array $options = []) { $this->buildCall('/search/messages/'.$this->apiKey.'/'.$this->apiSecret); $this->buildBody($options); $rawMessages = json_decode($this->getRequest()->getBody()->getContents()); return $this->makeMessages($rawMessages->items); }
Checks the server for messages and returns their results. @param array $options @return array
entailment
public function init() { parent::init(); $this->app->jquery = $this; if (!$this->app->template) { return; } if (!$this->app->template->is_set('js_include')) { throw $this->exception('Tag js_include must be defined in shared.html'); } if (!$this->app->template->is_set('document_ready')) { throw $this->exception('Tag document_ready must be defined in shared.html'); } $this->app->template->del('js_include'); /* $config['js']['jquery']='https://code.jquery.com/jquery-2.1.4.min.js'; // to use CDN */ if ($v = $this->app->getConfig('js/versions/jquery', null)) { $v = 'jquery-'.$v; } else { $v = $this->app->getConfig('js/jquery', 'jquery-2.2.1.min'); // bundled jQuery version } $this->addInclude($v); // Controllers are not rendered, but we need to do some stuff manually $this->app->addHook('pre-render-output', array($this, 'postRender')); $this->app->addHook('cut-output', array($this, 'cutRender')); }
Initialization
entailment
public function addStaticInclude($file, $ext = '.js') { if (@$this->included['js-'.$file.$ext]++) { return $this; } if (strpos($file, 'http') !== 0 && $file[0] != '/') { $url = $this->app->locateURL('js', $file.$ext); } else { $url = $file; } $this->app->template->appendHTML( 'js_include', '<script type="text/javascript" src="'.$url.'"></script>'."\n" ); return $this; }
Adds static includes @param string $file @param string $ext @return $this
entailment
public function addStaticStylesheet($file, $ext = '.css', $locate = 'css') { //$file=$this->app->locateURL('css',$file.$ext); if (@$this->included[$locate.'-'.$file.$ext]++) { return; } if (strpos($file, 'http') !== 0 && $file[0] != '/') { $url = $this->app->locateURL($locate, $file.$ext); } else { $url = $file; } $this->app->template->appendHTML( 'js_include', '<link type="text/css" href="'.$url.'" rel="stylesheet" />'."\n" ); return $this; }
Adds static stylesheet @param string $file @param string $ext @param string $locate @return $this
entailment
public function addOnReady($js) { if (is_object($js)) { $js = $js->getString(); } $this->app->template->appendHTML('document_ready', $js.";\n"); return $this; }
Add custom code into onReady section. Will be executed under $(function(){ .. }) @param jQuery_Chain|string $js @return $this
entailment