       1: <?php
       2: /**
       3:  * DataTables PHP libraries.
       4:  *
       5:  * PHP libraries for DataTables and DataTables Editor, utilising PHP 5.3+.
       6:  *
       7:  *  @author    SpryMedia
       8:  *  @copyright 2012 SpryMedia ( http://sprymedia.co.uk )
       9:  *  @license   http://editor.datatables.net/license DataTables Editor
      10:  *  @link      http://editor.datatables.net
      11:  */
      12:
      13: namespace DataTables\Editor;
      14: if (!defined('DATATABLES')) exit();
      15:
      16: use
      17:     DataTables,
      18:     DataTables\Editor,
      19:     DataTables\Editor\Field;
      20:
      21:
      22: /**
      23:  * Join table class for DataTables Editor.
      24:  *
      25:  * The Join class can be used with {@link Editor::join} to allow Editor to
      26:  * obtain joined information from the database.
      27:  *
      28:  * For an overview of how Join tables work, please refer to the
      29:  * {@link https://editor.datatables.net/manual/php/ Editor manual} as it is
      30:  * useful to understand how this class represents the links between tables,
      31:  * before fully getting to grips with it's API.
      32:  *
      33:  *  @example
      34:  *    Join the parent table (the one specified in the {@link Editor::table}
      35:  *    method) with the table *access*, with a link table *user__access*, which
      36:  *    allows multiple properties to be found for each row in the parent table.
      37:  *    <code>
      38:  *      Join::inst( 'access', 'array' )
      39:  *          ->link( 'users.id', 'user_access.user_id' )
      40:  *          ->link( 'access.id', 'user_access.access_id' )
      41:  *          ->field(
      42:  *              Field::inst( 'id' )->validator( 'Validate::required' ),
      43:  *              Field::inst( 'name' )
      44:  *          )
      45:  *    </code>
      46:  *
      47:  *  @example
      48:  *    Single row join - here we join the parent table with a single row in
      49:  *    the child table, without an intermediate link table. In this case the
      50:  *    child table is called *extra* and the two fields give the columns that
      51:  *    Editor will read from that table.
      52:  *    <code>
      53:  *        Join::inst( 'extra', 'object' )
      54:  *            ->link( 'user.id', 'extra.user_id' )
      55:  *            ->field(
      56:  *                Field::inst( 'comments' ),
      57:  *                Field::inst( 'review' )
      58:  *            )
      59:  *    </code>
      60:  */
      61: class Join extends DataTables\Ext {
      62:     /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
      63:      * Constructor
      64:      */
      65:
      66:     /**
      67:      * Join instance constructor.
      68:      *  @param string $table Table name to get the joined data from.
      69:      *  @param string $type Work with a single result ('object') or an array of
      70:      *    results ('array') for the join.
      71:      */
      72:     function __construct( $table=null, $type='object' )
      73:     {
      74:         $this->table( $table );
      75:         $this->type( $type );
      76:     }
      77:
      78:
      79:     /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
      80:      * Private properties
      81:      */
      82:
      83:     /** @var DataTables\Editor\Field[] */
      84:     private $_fields = array();
      85:
      86:     /** @var array */
      87:     private $_join = array(
      88:         "parent" => null,
      89:         "child" => null,
      90:         "table" => null
      91:     );
      92:
      93:     /** @var string */
      94:     private $_table = null;
      95:
      96:     /** @var string */
      97:     private $_type = null;
      98:
      99:     /** @var string */
     100:     private $_name = null;
     101:
     102:     /** @var boolean */
     103:     private $_get = true;
     104:
     105:     /** @var boolean */
     106:     private $_set = true;
     107:
     108:     /** @var string */
     109:     private $_aliasParentTable = null;
     110:
     111:     /** @var array */
     112:     private $_where = array();
     113:
     114:     /** @var boolean */
     115:     private $_whereSet = false;
     116:
     117:     /** @var array */
     118:     private $_links = array();
     119:
     120:     /** @var string */
     121:     private $_customOrder = null;
     122:
     123:     /** @var callable[] */
     124:     private $_validators = array();
     125:
     126:
     127:     /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     128:      * Public methods
     129:      */
     130:
     131:     /**
     132:      * Get / set parent table alias.
     133:      *
     134:      * When working with a self referencing table (i.e. a column in the table contains
     135:      * a primary key value from its own table) it can be useful to set an alias on the
     136:      * parent table's name, allowing a self referencing Join. For example:
     137:      *   <code>
     138:      *   SELECT p2.publisher
     139:      *   FROM   publisher as p2
     140:      *   JOIN   publisher on (publisher.idPublisher = p2.idPublisher)
     141:      *   <code>
     142:      * Where, in this case, `publisher` is the table that is used by the Editor instance,
     143:      * and you want to use `Join` to link back to the table (resolving a name for example).
     144:      * This method allows that alias to be set. Fields can then use standard SQL notation
     145:      * to select a field, for example `p2.publisher` or `publisher.publisher`.
     146:      *  @param string $_ Table alias to use
     147:      *  @return string|self Table alias set (which is null by default), or self if used as
     148:      *    a setter.
     149:      */
     150:     public function aliasParentTable ( $_=null )
     151:     {
     152:         return $this->_getSet( $this->_aliasParentTable, $_ );
     153:     }
     154:
     155:
     156:     /**
     157:      * Get / set field instances.
     158:      *
     159:      * The list of fields designates which columns in the table that will be read
     160:      * from the joined table.
     161:      *  @param Field $_... Instances of the {@link Field} class, given as a single
     162:      *    instance of {@link Field}, an array of {@link Field} instances, or multiple
     163:      *    {@link Field} instance parameters for the function.
     164:      *  @return Field[]|self Array of fields, or self if used as a setter.
     165:      *  @see {@link Field} for field documentation.
     166:      */
     167:     public function field ( $_=null )
     168:     {
     169:         if ( $_ !== null && !is_array($_) ) {
     170:             $_ = func_get_args();
     171:         }
     172:         return $this->_getSet( $this->_fields, $_, true );
     173:     }
     174:
     175:
     176:     /**
     177:      * Get / set field instances.
     178:      *
     179:      * An alias of {@link field}, for convenience.
     180:      *  @param Field $_... Instances of the {@link Field} class, given as a single
     181:      *    instance of {@link Field}, an array of {@link Field} instances, or multiple
     182:      *    {@link Field} instance parameters for the function.
     183:      *  @return Field[]|self Array of fields, or self if used as a setter.
     184:      *  @see {@link Field} for field documentation.
     185:      */
     186:     public function fields ( $_=null )
     187:     {
     188:         if ( $_ !== null && !is_array($_) ) {
     189:             $_ = func_get_args();
     190:         }
     191:         return $this->_getSet( $this->_fields, $_, true );
     192:     }
     193:
     194:
     195:     /**
     196:      * Get / set get attribute.
     197:      *
     198:      * When set to false no read operations will occur on the join tables.
     199:      *  @param boolean $_ Value
     200:      *  @return boolean|self Name
     201:      */
     202:     public function get ( $_=null )
     203:     {
     204:         return $this->_getSet( $this->_get, $_ );
     205:     }
     206:
     207:
     208:     /**
     209:      * Get / set join properties.
     210:      *
     211:      * Define how the SQL will be performed, on what columns. There are
     212:      * basically two types of join that are supported by Editor here, a direct
     213:      * foreign key reference in the join table to the parent table's primary
     214:      * key, or a link table that contains just primary keys for the parent and
     215:      * child tables (this approach is usually used with a {@link type} of
     216:      * 'array' since you can often have multiple links between the two tables,
     217:      * while a direct foreign key reference will typically use a type of
     218:      * 'object' (i.e. a single entry).
     219:      *
     220:      *  @param string|string[] $parent Parent table's primary key names. If used
     221:      *    with a link table (i.e. third parameter to this method is given, then
     222:      *    an array should be used, with the first element being the pkey's name
     223:      *    in the parent table, and the second element being the key's name in
     224:      *    the link table.
     225:      *  @param string|string[] $child Child table's primary key names. If used
     226:      *    with a link table (i.e. third parameter to this method is given, then
     227:      *    an array should be used, with the first element being the pkey's name
     228:      *    in the child table, and the second element being the key's name in the
     229:      *    link table.
     230:      *  @param string $table Join table name, if using a link table
     231:      *  @returns Join This for chaining
     232:      *  @deprecated 1.5 Please use the {@link link} method rather than this
     233:      *      method now.
     234:      */
     235:     public function join ( $parent=null, $child=null, $table=null )
     236:     {
     237:         if ( $parent === null && $child === null ) {
     238:             return $this->_join;
     239:         }
     240:
     241:         $this->_join['parent'] = $parent;
     242:         $this->_join['child'] = $child;
     243:         $this->_join['table'] = $table;
     244:         return $this;
     245:     }
     246:
     247:
     248:     /**
     249:      * Create a join link between two tables. The order of the fields does not
     250:      * matter, but each field must contain the table name as well as the field
     251:      * name.
     252:      *
     253:      * This method can be called a maximum of two times for an Mjoin instance:
     254:      *
     255:      * * First time, creates a link between the Editor host table and a join
     256:      *   table
     257:      * * Second time creates the links required for a link table.
     258:      *
     259:      * Please refer to the Editor Mjoin documentation for further details:
     260:      * https://editor.datatables.net/manual/php
     261:      *
     262:      * @param  string $field1 Table and field name
     263:      * @param  string $field2 Table and field name
     264:      * @return Join Self for chaining
     265:      * @throws \Exception Link limitations
     266:      */
     267:     public function link ( $field1, $field2 )
     268:     {
     269:         if ( strpos($field1, '.') === false || strpos($field2, '.') === false ) {
     270:             throw new \Exception("Link fields must contain both the table name and the column name");
     271:         }
     272:
     273:         if ( count( $this->_links ) >= 4 ) {
     274:             throw new \Exception("Link method cannot be called more than twice for a single instance");
     275:         }
     276:
     277:         $this->_links[] = $field1;
     278:         $this->_links[] = $field2;
     279:
     280:         return $this;
     281:     }
     282:
     283:
     284:     /**
     285:      * Specify the property that the data will be sorted by.
     286:      *
     287:      * @param  string $order SQL column name to order the data by
     288:      * @return Join Self for chaining
     289:      */
     290:     public function order ( $_=null )
     291:     {
     292:         // How this works is by setting the SQL order by clause, and since the
     293:         // join that is done in PHP is always done sequentially, the order is
     294:         // retained.
     295:         return $this->_getSet( $this->_customOrder, $_ );
     296:     }
     297:
     298:
     299:     /**
     300:      * Get / set name.
     301:      *
     302:      * The `name` of the Join is the JSON property key that is used when
     303:      * 'getting' the data, and the HTTP property key (in a JSON style) when
     304:      * 'setting' data. Typically the name of the db table will be used here,
     305:      * but this method allows that to be overridden.
     306:      *  @param string $_ Field name
     307:      *  @return String|self Name
     308:      */
     309:     public function name ( $_=null )
     310:     {
     311:         return $this->_getSet( $this->_name, $_ );
     312:     }
     313:
     314:
     315:     /**
     316:      * Get / set set attribute.
     317:      *
     318:      * When set to false no write operations will occur on the join tables.
     319:      * This can be useful when you want to display information which is joined,
     320:      * but want to only perform write operations on the parent table.
     321:      *  @param boolean $_ Value
     322:      *  @return boolean|self Name
     323:      */
     324:     public function set ( $_=null )
     325:     {
     326:         return $this->_getSet( $this->_set, $_ );
     327:     }
     328:
     329:
     330:     /**
     331:      * Get / set join table name.
     332:      *
     333:      * Please note that this will also set the {@link name} used by the Join
     334:      * as well. This is for convenience as the JSON output / HTTP input will
     335:      * typically use the same name as the database name. If you want to set a
     336:      * custom name, the {@link name} method must be called ***after*** this one.
     337:      *  @param string $_ Name of the table to read the join data from
     338:      *  @return String|self Name of the join table, or self if used as a setter.
     339:      */
     340:     public function table ( $_=null )
     341:     {
     342:         if ( $_ !== null ) {
     343:             $this->_name = $_;
     344:         }
     345:         return $this->_getSet( $this->_table, $_ );
     346:     }
     347:
     348:
     349:     /**
     350:      * Get / set the join type.
     351:      *
     352:      * The join type allows the data that is returned from the join to be given
     353:      * as an array (i.e. working with multiple possibly results for each record from
     354:      * the parent table), or as an object (i.e. working which one and only one result
     355:      * for each record form the parent table).
     356:      *  @param string $_ Join type ('object') or an array of
     357:      *    results ('array') for the join.
     358:      *  @return String|self Join type, or self if used as a setter.
     359:      */
     360:     public function type ( $_=null )
     361:     {
     362:         return $this->_getSet( $this->_type, $_ );
     363:     }
     364:
     365:
     366:     /**
     367:      * Set a validator for the array of data (not on a field basis)
     368:      *
     369:      * @param string $fieldName Name of the field that any error should be shown
     370:      *   against on the client-side
     371:      * @param callable $fn Callback function for validation
     372:      * @return self Chainable
     373:      */
     374:     public function validator ( $fieldName, $fn )
     375:     {
     376:         $this->_validators[] = array(
     377:             'fieldName' => $fieldName,
     378:             'fn' => $fn
     379:         );
     380:
     381:         return $this;
     382:     }
     383:
     384:
     385:     /**
     386:      * Where condition to add to the query used to get data from the database.
     387:      * Note that this is applied to the child table.
     388:      *
     389:      * Can be used in two different ways:
     390:      *
     391:      * * Simple case: `where( field, value, operator )`
     392:      * * Complex: `where( fn )`
     393:      *
     394:      *  @param string|callable $key   Single field name or a closure function
     395:      *  @param string|string[] $value Single field value, or an array of values.
     396:      *  @param string          $op    Condition operator: <, >, = etc
     397:      *  @return string[]|self Where condition array, or self if used as a setter.
     398:      */
     399:     public function where ( $key=null, $value=null, $op='=' )
     400:     {
     401:         if ( $key === null ) {
     402:             return $this->_where;
     403:         }
     404:
     405:         if ( is_callable($key) && is_object($key) ) {
     406:             $this->_where[] = $key;
     407:         }
     408:         else {
     409:             $this->_where[] = array(
     410:                 "key"   => $key,
     411:                 "value" => $value,
     412:                 "op"    => $op
     413:             );
     414:         }
     415:
     416:         return $this;
     417:     }
     418:
     419:
     420:     /**
     421:      * Get / set if the WHERE conditions should be included in the create and
     422:      * edit actions.
     423:      *
     424:      * This means that the fields which have been used as part of the 'get'
     425:      * WHERE condition (using the `where()` method) will be set as the values
     426:      * given.
     427:      *
     428:      * This is default false (i.e. they are not included).
     429:      *
     430:      *  @param boolean $_ Include (`true`), or not (`false`)
     431:      *  @return boolean Current value
     432:      */
     433:     public function whereSet ( $_=null )
     434:     {
     435:         return $this->_getSet( $this->_whereSet, $_ );
     436:     }
     437:
     438:
     439:
     440:     /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     441:      * Internal methods
     442:      */
     443:
     444:     /**
     445:      * Get data
     446:      *  @param Editor $editor Host Editor instance
     447:      *  @param string[] $data Data from the parent table's get and were we need
     448:      *    to add out output.
     449:      *  @param array $options options array for fields
     450:      *  @internal
     451:      */
     452:     public function data( $editor, &$data, &$options )
     453:     {
     454:         if ( ! $this->_get ) {
     455:             return;
     456:         }
     457:
     458:         $this->_prep( $editor );
     459:         $db       = $editor->db();
     460:         $dteTable = $editor->table();
     461:         $pkey     = $editor->pkey();
     462:         $idPrefix = $editor->idPrefix();
     463:
     464:         $dteTable = $dteTable[0];
     465:         $dteTableLocal = $this->_aliasParentTable ? // Can be aliased to allow a self join
     466:             $this->_aliasParentTable :
     467:             $dteTable;
     468:         $joinField = isset($this->_join['table']) ?
     469:             $this->_join['parent'][0] :
     470:             $this->_join['parent'];
     471:
     472:         // This is something that will likely come in a future version, but it
     473:         // is a relatively low use feature. Please get in touch if this is
     474:         // something you require.
     475:         if ( count( $pkey ) > 1 ) {
     476:             throw new \Exception("MJoin is not currently supported with a compound primary key for the main table", 1);
     477:         }
     478:
     479:         if ( count($data) > 0 ) {
     480:             $pkey = $pkey[0];
     481:             $pkeyIsJoin = $pkey === $joinField || $pkey === $dteTable.'.'.$joinField;
     482:
     483:             // Sanity check that table selector fields are read only, and have an name without
     484:             // a dot (for DataTables mData to be able to read it)
     485:             for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
     486:                 $field = $this->_fields[$i];
     487:
     488:                 if ( strpos( $field->dbField() , "." ) !== false ) {
     489:                     if ( $field->set() !== Field::SET_NONE && $this->_set ) {
     490:                         echo json_encode( array(
     491:                             "sError" => "Table selected fields (i.e. '{table}.{column}') in `Join` ".
     492:                                 "must be read only. Use `set(false)` for the field to disable writing."
     493:                         ) );
     494:                         exit(0);
     495:                     }
     496:
     497:                     if ( strpos( $field->name() , "." ) !== false ) {
     498:                         echo json_encode( array(
     499:                             "sError" => "Table selected fields (i.e. '{table}.{column}') in `Join` ".
     500:                                 "must have a name alias which does not contain a period ('.'). Use ".
     501:                                 "name('---') to set a name for the field"
     502:                         ) );
     503:                         exit(0);
     504:                     }
     505:                 }
     506:             }
     507:
     508:             // Set up the JOIN query
     509:             $stmt = $db
     510:                 ->query( 'select' )
     511:                 ->distinct( true )
     512:                 ->get( $dteTableLocal.'.'.$joinField.' as dteditor_pkey' )
     513:                 ->get( $this->_fields('get') )
     514:                 ->table( $dteTable .' as '. $dteTableLocal );
     515:
     516:             if ( $this->order() ) {
     517:                 $stmt->order( $this->order() );
     518:             }
     519:
     520:             $this->_apply_where( $stmt );
     521:
     522:             if ( isset($this->_join['table']) ) {
     523:                 // Working with a link table
     524:                 $stmt
     525:                     ->join(
     526:                         $this->_join['table'],
     527:                         $dteTableLocal.'.'.$this->_join['parent'][0] .' = '. $this->_join['table'].'.'.$this->_join['parent'][1]
     528:                     )
     529:                     ->join(
     530:                         $this->_table,
     531:                         $this->_table.'.'.$this->_join['child'][0] .' = '. $this->_join['table'].'.'.$this->_join['child'][1]
     532:                     );
     533:             }
     534:             else {
     535:                 // No link table in the middle
     536:                 $stmt
     537:                     ->join(
     538:                         $this->_table,
     539:                         $this->_table.'.'.$this->_join['child'] .' = '. $dteTableLocal.'.'.$this->_join['parent']
     540:                     );
     541:             }
     542:
     543:             // Check that the joining field is available.  The joining key can
     544:             // come from the Editor instance's primary key, or any other field,
     545:             // including a nested value (from a left join). If the instance's
     546:             // pkey, then we've got that in the DT_RowId parameter, so we can
     547:             // use that. Otherwise, the key must be in the field list.
     548:             if ( $this->_propExists( $dteTable.'.'.$joinField, $data[0] ) ) {
     549:                 $readField = $dteTable.'.'.$joinField;
     550:             }
     551:             else if ( $this->_propExists( $joinField, $data[0] ) ) {
     552:                 $readField = $joinField;
     553:             }
     554:             else if ( ! $pkeyIsJoin ) {
     555:                 echo json_encode( array(
     556:                     "sError" => "Join was performed on the field '{$joinField}' which was not "
     557:                         ."included in the Editor field list. The join field must be included "
     558:                         ."as a regular field in the Editor instance."
     559:                 ) );
     560:                 exit(0);
     561:             }
     562:
     563:             // Get list of pkey values and apply as a WHERE IN condition
     564:             // This is primarily useful in server-side processing mode and when filtering
     565:             // the table as it means only a sub-set will be selected
     566:             // This is only applied for "sensible" data sets. It will just complicate
     567:             // matters for really large data sets:
     568:             // https://stackoverflow.com/questions/21178390/in-clause-limitation-in-sql-server
     569:             if ( count($data) < 1000 ) {
     570:                 $whereIn = array();
     571:
     572:                 for ( $i=0 ; $i<count($data) ; $i++ ) {
     573:                     $whereIn[] = $pkeyIsJoin ?
     574:                         str_replace( $idPrefix, '', $data[$i]['DT_RowId'] ) :
     575:                         $this->_readProp( $readField, $data[$i] );
     576:                 }
     577:
     578:                 $stmt->where_in( $dteTableLocal.'.'.$joinField, $whereIn );
     579:             }
     580:
     581:             // Go!
     582:             $res = $stmt->exec();
     583:             if ( ! $res ) {
     584:                 return;
     585:             }
     586:
     587:             // Map to primary key for fast lookup
     588:             $join = array();
     589:             while ( $row=$res->fetch() ) {
     590:                 $inner = array();
     591:
     592:                 for ( $j=0 ; $j<count($this->_fields) ; $j++ ) {
     593:                     $field = $this->_fields[$j];
     594:                     if ( $field->apply('get') ) {
     595:                         $inner[ $field->name() ] = $field->val('get', $row);
     596:                     }
     597:                 }
     598:
     599:                 if ( $this->_type === 'object' ) {
     600:                     $join[ $row['dteditor_pkey'] ] = $inner;
     601:                 }
     602:                 else {
     603:                     if ( !isset( $join[ $row['dteditor_pkey'] ] ) ) {
     604:                         $join[ $row['dteditor_pkey'] ] = array();
     605:                     }
     606:                     $join[ $row['dteditor_pkey'] ][] = $inner;
     607:                 }
     608:             }
     609:
     610:             // Loop over the data and do a join based on the data available
     611:             for ( $i=0 ; $i<count($data) ; $i++ ) {
     612:                 $rowPKey = $pkeyIsJoin ?
     613:                     str_replace( $idPrefix, '', $data[$i]['DT_RowId'] ) :
     614:                     $this->_readProp( $readField, $data[$i] );
     615:
     616:                 if ( isset( $join[$rowPKey] ) ) {
     617:                     $data[$i][ $this->_name ] = $join[$rowPKey];
     618:                 }
     619:                 else {
     620:                     $data[$i][ $this->_name ] = ($this->_type === 'object') ?
     621:                         (object)array() : array();
     622:                 }
     623:             }
     624:         }
     625:
     626:         // Field options
     627:         foreach ($this->_fields as $field) {
     628:             $opts = $field->optionsExec( $db );
     629:
     630:             if ( $opts !== false ) {
     631:                 $name = $this->name().
     632:                     ($this->_type === 'object' ? '.' : '[].').
     633:                     $field->name();
     634:                 $options[ $name ] = $opts;
     635:             }
     636:         }
     637:     }
     638:
     639:
     640:     /**
     641:      * Create a row.
     642:      *  @param Editor $editor Host Editor instance
     643:      *  @param int $parentId Parent row's primary key value
     644:      *  @param string[] $data Data to be set for the join
     645:      *  @internal
     646:      */
     647:     public function create ( $editor, $parentId, $data )
     648:     {
     649:         // If not settable, or the many count for the join was not submitted
     650:         // there we do nothing
     651:         if (
     652:             ! $this->_set ||
     653:             ! isset($data[$this->_name]) ||
     654:             ! isset($data[$this->_name.'-many-count'])
     655:         ) {
     656:             return;
     657:         }
     658:
     659:         $this->_prep( $editor );
     660:         $db = $editor->db();
     661:
     662:         if ( $this->_type === 'object' ) {
     663:             $this->_insert( $db, $parentId, $data[$this->_name] );
     664:         }
     665:         else {
     666:             for ( $i=0 ; $i<count($data[$this->_name]) ; $i++ ) {
     667:                 $this->_insert( $db, $parentId, $data[$this->_name][$i] );
     668:             }
     669:         }
     670:     }
     671:
     672:
     673:     /**
     674:      * Update a row.
     675:      *  @param Editor $editor Host Editor instance
     676:      *  @param int $parentId Parent row's primary key value
     677:      *  @param string[] $data Data to be set for the join
     678:      *  @internal
     679:      */
     680:     public function update ( $editor, $parentId, $data )
     681:     {
     682:         // If not settable, or the many count for the join was not submitted
     683:         // there we do nothing
     684:         if ( ! $this->_set || ! isset($data[$this->_name.'-many-count']) ) {
     685:             return;
     686:         }
     687:
     688:         $this->_prep( $editor );
     689:         $db = $editor->db();
     690:
     691:         if ( $this->_type === 'object' ) {
     692:             // update or insert
     693:             $this->_update_row( $db, $parentId, $data[$this->_name] );
     694:         }
     695:         else {
     696:             // WARNING - this will remove rows and then readd them. Any
     697:             // data not in the field list WILL BE LOST
     698:             // todo - is there a better way of doing this?
     699:             $this->remove( $editor, array($parentId) );
     700:             $this->create( $editor, $parentId, $data );
     701:         }
     702:     }
     703:
     704:
     705:     /**
     706:      * Delete rows
     707:      *  @param Editor $editor Host Editor instance
     708:      *  @param int[] $ids Parent row IDs to delete
     709:      *  @internal
     710:      */
     711:     public function remove ( $editor, $ids )
     712:     {
     713:         if ( ! $this->_set ) {
     714:             return;
     715:         }
     716:
     717:         $that = $this;
     718:         $this->_prep( $editor );
     719:         $db = $editor->db();
     720:
     721:         if ( isset($this->_join['table']) ) {
     722:             $stmt = $db
     723:                 ->query( 'delete' )
     724:                 ->table( $this->_join['table'] )
     725:                 ->or_where( $this->_join['parent'][1], $ids )
     726:                 ->exec();
     727:         }
     728:         else {
     729:             $stmt = $db
     730:                 ->query( 'delete' )
     731:                 ->table( $this->_table )
     732:                 ->where_group( function ( $q ) use ( $that, $ids ) {
     733:                     $q->or_where( $that->_join['child'], $ids );
     734:                 } );
     735:
     736:             $this->_apply_where( $stmt );
     737:
     738:             $stmt->exec();
     739:         }
     740:     }
     741:
     742:
     743:     /**
     744:      * Validate input data
     745:      *
     746:      * @param array $errors Errors array
     747:      * @param Editor $editor Editor instance
     748:      * @param string[] $data Data to validate
     749:      * @param string $action `create` or `edit`
     750:      * @internal
     751:      */
     752:     public function validate ( &$errors, $editor, $data, $action )
     753:     {
     754:         if ( ! $this->_set && ! isset($data[$this->_name.'-many-count']) ) {
     755:             return;
     756:         }
     757:
     758:         $this->_prep( $editor );
     759:
     760:         $joinData = isset($data[$this->_name]) ?
     761:             $data[$this->_name] :
     762:             [];
     763:
     764:         for ( $i=0 ; $i<count($this->_validators) ; $i++ ) {
     765:             $validator = $this->_validators[$i];
     766:             $fn = $validator['fn'];
     767:             $res = $fn( $editor, $action, $joinData );
     768:
     769:             if ( is_string($res) ) {
     770:                 $errors[] = array(
     771:                     "name" => $validator['fieldName'],
     772:                     "status" => $res
     773:                 );
     774:             }
     775:         }
     776:
     777:         if ( $this->_type === 'object' ) {
     778:             $this->_validateFields( $errors, $editor, $joinData, $this->_name.'.' );
     779:         }
     780:         else {
     781:             for ( $i=0 ; $i<count($joinData) ; $i++ ) {
     782:                 $this->_validateFields( $errors, $editor, $joinData[$i], $this->_name.'[].' );
     783:             }
     784:         }
     785:     }
     786:
     787:
     788:
     789:     /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     790:      * Private methods
     791:      */
     792:
     793:     /**
     794:      * Add local WHERE condition to query
     795:      *  @param \DataTables\Database\Query $query Query instance to apply the WHERE conditions to
     796:      *  @private
     797:      */
     798:     private function _apply_where ( $query )
     799:     {
     800:         for ( $i=0 ; $i<count($this->_where) ; $i++ ) {
     801:             if ( is_callable( $this->_where[$i] ) ) {
     802:                 $this->_where[$i]( $query );
     803:             }
     804:             else {
     805:                 $query->where(
     806:                     $this->_where[$i]['key'],
     807:                     $this->_where[$i]['value'],
     808:                     $this->_where[$i]['op']
     809:                 );
     810:             }
     811:         }
     812:     }
     813:
     814:
     815:     /**
     816:      * Create a row.
     817:      *  @param \DataTables\Database $db Database reference to use
     818:      *  @param int $parentId Parent row's primary key value
     819:      *  @param string[] $data Data to be set for the join
     820:      *  @private
     821:      */
     822:     private function _insert( $db, $parentId, $data )
     823:     {
     824:         if ( isset($this->_join['table']) ) {
     825:             // Insert keys into the join table
     826:             $stmt = $db
     827:                 ->query('insert')
     828:                 ->table( $this->_join['table'] )
     829:                 ->set( $this->_join['parent'][1], $parentId )
     830:                 ->set( $this->_join['child'][1], $data[$this->_join['child'][0]] )
     831:                 ->exec();
     832:         }
     833:         else {
     834:             // Insert values into the target table
     835:             $stmt = $db
     836:                 ->query('insert')
     837:                 ->table( $this->_table )
     838:                 ->set( $this->_join['child'], $parentId );
     839:
     840:             for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
     841:                 $field = $this->_fields[$i];
     842:
     843:                 if ( $field->apply( 'set', $data ) ) { // TODO should be create or edit
     844:                     $stmt->set( $field->dbField(), $field->val('set', $data) );
     845:                 }
     846:             }
     847:
     848:             // If the where condition variables should also be added to the database
     849:             // Note that `whereSet` is now deprecated
     850:             if ( $this->_whereSet ) {
     851:                 for ( $i=0, $ien=count($this->_where) ; $i<$ien ; $i++ ) {
     852:                     if ( ! is_callable( $this->_where[$i] ) ) {
     853:                         $stmt->set( $this->_where[$i]['key'], $this->_where[$i]['value'] );
     854:                     }
     855:                 }
     856:             }
     857:
     858:             $stmt->exec();
     859:         }
     860:     }
     861:
     862:
     863:     /**
     864:      * Prepare the instance to be run.
     865:      *
     866:      * @param  Editor $editor Editor instance
     867:      * @private
     868:      */
     869:     private function _prep ( $editor )
     870:     {
     871:         $links = $this->_links;
     872:
     873:         // Were links used to configure this instance - if so, we need to
     874:         // back them onto the join array
     875:         if ( $this->_join['parent'] === null && count($links) ) {
     876:             $editorTable = $editor->table();
     877:             $editorTable = $editorTable[0];
     878:             $joinTable = $this->table();
     879:
     880:             if ( $this->_aliasParentTable ) {
     881:                 $editorTable = $this->_aliasParentTable;
     882:             }
     883:
     884:             if ( count( $links ) === 2 ) {
     885:                 // No link table
     886:                 $f1 = explode( '.', $links[0] );
     887:                 $f2 = explode( '.', $links[1] );
     888:
     889:                 if ( $f1[0] === $editorTable ) {
     890:                     $this->_join['parent'] = $f1[1];
     891:                     $this->_join['child'] = $f2[1];
     892:                 }
     893:                 else {
     894:                     $this->_join['parent'] = $f2[1];
     895:                     $this->_join['child'] = $f1[1];
     896:                 }
     897:             }
     898:             else {
     899:                 // Link table
     900:                 $f1 = explode( '.', $links[0] );
     901:                 $f2 = explode( '.', $links[1] );
     902:                 $f3 = explode( '.', $links[2] );
     903:                 $f4 = explode( '.', $links[3] );
     904:
     905:                 // Discover the name of the link table
     906:                 if ( $f1[0] !== $editorTable && $f1[0] !== $joinTable ) {
     907:                     $this->_join['table'] = $f1[0];
     908:                 }
     909:                 else if ( $f2[0] !== $editorTable && $f2[0] !== $joinTable ) {
     910:                     $this->_join['table'] = $f2[0];
     911:                 }
     912:                 else if ( $f3[0] !== $editorTable && $f3[0] !== $joinTable ) {
     913:                     $this->_join['table'] = $f3[0];
     914:                 }
     915:                 else {
     916:                     $this->_join['table'] = $f4[0];
     917:                 }
     918:
     919:                 $this->_join['parent'] = array( $f1[1], $f2[1] );
     920:                 $this->_join['child'] = array( $f3[1], $f4[1] );
     921:             }
     922:         }
     923:     }
     924:
     925:
     926:     /**
     927:      * Update a row.
     928:      *  @param \DataTables\Database $db Database reference to use
     929:      *  @param int $parentId Parent row's primary key value
     930:      *  @param string[] $data Data to be set for the join
     931:      *  @private
     932:      */
     933:     private function _update_row ( $db, $parentId, $data )
     934:     {
     935:         if ( isset($this->_join['table']) ) {
     936:             // Got a link table, just insert the pkey references
     937:             $db->push(
     938:                 $this->_join['table'],
     939:                 array(
     940:                     $this->_join['parent'][1] => $parentId,
     941:                     $this->_join['child'][1]  => $data[$this->_join['child'][0]]
     942:                 ),
     943:                 array(
     944:                     $this->_join['parent'][1] => $parentId
     945:                 )
     946:             );
     947:         }
     948:         else {
     949:             // No link table, just a direct reference
     950:             $set = array(
     951:                 $this->_join['child'] => $parentId
     952:             );
     953:
     954:             for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
     955:                 $field = $this->_fields[$i];
     956:
     957:                 if ( $field->apply( 'set', $data ) ) {
     958:                     $set[ $field->dbField() ] = $field->val('set', $data);
     959:                 }
     960:             }
     961:
     962:             // Add WHERE conditions
     963:             $where = array($this->_join['child'] => $parentId);
     964:             for ( $i=0, $ien=count($this->_where) ; $i<$ien ; $i++ ) {
     965:                 $where[ $this->_where[$i]['key'] ] = $this->_where[$i]['value'];
     966:
     967:                 // Is there any point in this? Is there any harm?
     968:                 // Note that `whereSet` is now deprecated
     969:                 if ( $this->_whereSet ) {
     970:                     if ( ! is_callable( $this->_where[$i] ) ) {
     971:                         $set[ $this->_where[$i]['key'] ] = $this->_where[$i]['value'];
     972:                     }
     973:                 }
     974:             }
     975:
     976:             $db->push( $this->_table, $set, $where );
     977:         }
     978:     }
     979:
     980:
     981:     /**
     982:      * Create an SQL string from the fields that this instance knows about for
     983:      * using in queries
     984:      *  @param string $direction Direction: 'get' or 'set'.
     985:      *  @returns array Fields to include
     986:      *  @private
     987:      */
     988:     private function _fields ( $direction )
     989:     {
     990:         $fields = array();
     991:
     992:         for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
     993:             $field = $this->_fields[$i];
     994:
     995:             if ( $field->apply( $direction, null ) ) {
     996:                 if ( strpos( $field->dbField() , "." ) === false ) {
     997:                     $fields[] = $this->_table.'.'.$field->dbField() ." as ".$field->dbField();;
     998:                 }
     999:                 else {
    1000:                     $fields[] = $field->dbField();// ." as ".$field->dbField();
    1001:                 }
    1002:             }
    1003:         }
    1004:
    1005:         return $fields;
    1006:     }
    1007:
    1008:
    1009:     /**
    1010:      * Validate input data
    1011:      *
    1012:      * @param array $errors Errors array
    1013:      * @param Editor $editor Editor instance
    1014:      * @param string[] $data Data to validate
    1015:      * @param string $prefix Field error prefix for client-side to show the
    1016:      *   error message on the appropriate field
    1017:      * @internal
    1018:      */
    1019:     private function _validateFields ( &$errors, $editor, $data, $prefix )
    1020:     {
    1021:         for ( $i=0 ; $i<count($this->_fields) ; $i++ ) {
    1022:             $field = $this->_fields[$i];
    1023:             $validation = $field->validate( $data, $editor );
    1024:
    1025:             if ( $validation !== true ) {
    1026:                 $errors[] = array(
    1027:                     "name" => $prefix.$field->name(),
    1028:                     "status" => $validation
    1029:                 );
    1030:             }
    1031:         }
    1032:     }
    1033: }
    1034:
    1035: